Datasets:
Modalities:
Text
Size:
10K - 100K
branch_name
stringclasses 22
values | content
stringlengths 18
81.8M
| directory_id
stringlengths 40
40
| languages
sequencelengths 1
36
| num_files
int64 1
7.38k
| repo_language
stringclasses 151
values | repo_name
stringlengths 7
101
| revision_id
stringlengths 40
40
| snapshot_id
stringlengths 40
40
|
---|---|---|---|---|---|---|---|---|
refs/heads/master | <repo_name>kirenewardainijoas/rest-server<file_sep>/SI_PEGADAIAN/application/controllers/api/Nasabah.php
<?php
use Restserver\Libraries\REST_Controller;
defined('BASEPATH') or exit('No direct script access allowed');
require APPPATH . 'libraries/REST_Controller.php';
require APPPATH . 'libraries/Format.php';
class Nasabah extends REST_Controller
{
public function __construct()
{
parent::__construct();
$this->load->model('Nasabah_model');
}
public function index_get()
{
$id = $this->get('id');
if ($id === null) {
$data_nasabah = $this->Nasabah_model->getNasabah();
} else {
$data_nasabah = $this->Nasabah_model->getNasabah($id);
}
if ($data_nasabah) {
$this->response([
'status' => true,
'data' => $data_nasabah
], REST_Controller::HTTP_OK);
} else {
$this->response([
'status' => false,
'message' => 'id not found'
], REST_Controller::HTTP_NOT_FOUND);
}
}
public function index_delete()
{
$id = $this->delete('id');
if ($id === null) {
$this->response([
'status' => false,
'message' => 'provide an id!'
], REST_Controller::HTTP_BAD_REQUEST);
} else {
if ($this->Nasabah_model->deleteNasabah($id) > 0) {
$this->response([
'status' => true,
'id' => $id,
'message' => 'deleted.'
], REST_Controller::HTTP_NO_CONTENT);
} else {
$this->response([
'status' => false,
'message' => 'id not found'
], REST_Controller::HTTP_BAD_REQUEST);
}
}
}
public function index_post()
{
$data = [
'first_name' => $this->post('first_name'),
'last_name' => $this->post('last_name'),
'email' => $this->post('email'),
'gender' => $this->post('gender')
];
if ($this->Nasabah_model->createNasabah($data) > 0) {
$this->response([
'status' => true,
'message' => 'new data nasabah has been created.'
], REST_Controller::HTTP_CREATED);
} else {
$this->response([
'status' => false,
'message' => 'failed to created new data'
], REST_Controller::HTTP_BAD_REQUEST);
}
}
public function index_put()
{
$id = $this->put('id');
$data = [
'first_name' => $this->post('first_name'),
'last_name' => $this->post('last_name'),
'email' => $this->post('email'),
'gender' => $this->post('gender')
];
if ($this->Nasabah_model->updateNasabah($data, $id) > 0) {
$this->response([
'status' => true,
'message' => 'new data nasabah has been update.'
], REST_Controller::HTTP_NO_CONTENT);
} else {
$this->response([
'status' => false,
'message' => 'failed to update data'
], REST_Controller::HTTP_BAD_REQUEST);
}
}
}
<file_sep>/SI_PEGADAIAN/application/models/Nasabah_model.php
<?php
class Nasabah_model extends CI_Model
{
public function getNasabah($id = null)
{
if ($id === null) {
return $this->db->get('data_nasabah')->result_array();
} else {
return $this->db->get_where('data_nasabah', ['id' => $id])->result_array();
}
}
public function deleteNasabah($id)
{
$this->db->delete('data_nasabah', ['id' => $id]);
return $this->db->affected_rows();
}
public function createNasabah($data)
{
$this->db->insert('data_nasabah', $data);
return $this->db->affected_rows();
}
public function updateNasabah($data, $id)
{
$this->db->update('data_nasabah', $data, ['id' => $id]);
return $this->db->affected_rows();
}
}
| f971b1fcc3f9f6f0bb64e87f72e04ce2b30361be | [
"PHP"
] | 2 | PHP | kirenewardainijoas/rest-server | fc06b985eadc0678d72751945dffc599cbacbe5c | 4f8790707e8f8f0421295c15b59985b50a006c11 |
refs/heads/master | <file_sep>class AddCostPerSoldToCoins < ActiveRecord::Migration[5.2]
def change
add_column :coins, :cost_per_sold, :decimal
end
end
<file_sep>class Coin < ApplicationRecord
belongs_to :person
before_validation :make_only_symbol_for_coin
private
def make_only_symbol_for_coin
self.symbol = symbol.split.first
end
end
<file_sep>class RemoveIsItSoldFromCoins < ActiveRecord::Migration[5.2]
def change
remove_column :coins, :is_it_sold
end
end
<file_sep>json.partial! "cryptos/crypto", crypto: @crypto
<file_sep>
<% for x in @show_coins %>
<% if @coin.symbol.upcase == x["symbol"] %>
<% coin_name = x["name"] %>
<% rank = x["rank"] %>
<% price_usd = x["price_usd"] %>
<% price_btc = x["price_btc"] %>
<% market_cap_usd = x["market_cap_usd"] %>
<% available_supply = x["available_supply"] %>
<% total_supply = x["total_supply"] %>
<% max_supply = x["max_supply"] %>
<% percent_change_1h = x["percent_change_1h"] %>
<% percent_change_24h = x["percent_change_24h"] %>
<% percent_change_7d = x["percent_change_7d"] %>
<% else %>
<% end %>
<% end %>
<div class="container">
<div class="card">
<div class="card-body">
<h3 class="text-uppercase text-center mt-4">Detailed statistics</h3>
<table data-toggle="table">
<thead>
<tr>
<th>Title</th>
<th>Value</th>
</tr>
</thead>
<tbody>
<tr>
<td>Coin name:</td>
<td><%= coin_name %></td>
</tr>
<tr>
<td>Rank:</td>
<td><%= rank %></td>
</tr>
<tr>
<td>Price usd:</td>
<td><%= price_usd %></td>
</tr>
<tr>
<td>Price btc:</td>
<td><%= price_btc %></td>
</tr>
<tr>
<td>Market cap usd:</td>
<td><%= market_cap_usd %></td>
</tr>
<tr>
<td>Available supply:</td>
<td><%= available_supply %></td>
</tr>
<tr>
<td>Total supply:</td>
<td> <%= total_supply %></td>
</tr>
<tr>
<td>Max supply:</td>
<td>
<%= max_supply %>
</td>
</tr>
<tr>
<td>Percent change 1h:</td>
<td>
<%= percent_change_1h %>
</td>
</tr>
<tr>
<td>Percent change 24h:</td>
<td>
<%= percent_change_24h %>
</td>
</tr>
<tr>
<td>Percent change 7d:</td>
<td>
<%= percent_change_7d %>
</td>
</tr>
</tbody>
</table>
<div class="pt-4 pb-2 text-right">
<%= link_to 'Edit', edit_coin_path(@coin), class:"btn btn-info"%>
<%= link_to 'Back', coins_path, class:"btn btn-info" %>
</div>
</div>
</div>
</div>
<file_sep><!-- If user login -->
<div class="row">
<div class="col-md-12">
<section class="jumbotron text-center">
<div class="container">
<h3 class="jumbotron-heading">
<%= t('portfolio_empty') %>
</h3>
<p>
<%= link_to t('add_new_coin'), new_coin_path, class: "btn btn-success" %>
</p>
</div>
</section>
</div>
</div><file_sep># README
* Ruby version ruby 2.3.1
* Rails 5.2.0
* Internationalization (I18n) API
<file_sep>class HomeController < ApplicationController
before_action :set_coin, only: [:show, :edit, :update, :destroy]
before_action :correct_person, only: [:show, :edit, :update, :destroy]
def index
@coins = Coin.all
require 'net/http'
require 'json'
@url = 'https://api.coinmarketcap.com/v1/ticker/?limit=1000'
@uri = URI(@url)
@response = Net::HTTP.get(@uri)
@lookup_coins = JSON.parse(@response)
@profit_lost = 0
@profit_summ = 0
end
private
# Use callbacks to share common setup or constraints between actions.
def set_coin
@coin = Coin.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def coin_params
params.require(:coin).permit(:symbol, :person_id, :cost_per, :amount_owned)
end
def correct_person
@correct = current_person.coins.find_by(id: params[:id])
redirect_to coins_path, notice: "Пользователи не могут просматривать монеты других участников" if @correct.nil?
end
end
<file_sep>PassengerRuby /opt/rubies/ruby-2.3/bin/ruby
PassengerUploadBufferDir /home/a/artpes57/bitcoinbtn.ru/tmp
SetENV GEM_HOME /home/a/artpes57/.gem/ruby/2.3.1
SetENV GEM_PATH /home/a/artpes57/.gem/ruby/2.3.1:/opt/ruby/2.3/lib/ruby/gems/2.3.0
RAILSENV development
<file_sep>require 'test_helper'
class CryptosControllerTest < ActionDispatch::IntegrationTest
setup do
@crypto = cryptos(:one)
end
test "should get index" do
get cryptos_url
assert_response :success
end
test "should get new" do
get new_crypto_url
assert_response :success
end
test "should create crypto" do
assert_difference('Crypto.count') do
post cryptos_url, params: { crypto: { amount_owner: @crypto.amount_owner, cost_per: @crypto.cost_per, symbol: @crypto.symbol, user_id: @crypto.user_id } }
end
assert_redirected_to crypto_url(Crypto.last)
end
test "should show crypto" do
get crypto_url(@crypto)
assert_response :success
end
test "should get edit" do
get edit_crypto_url(@crypto)
assert_response :success
end
test "should update crypto" do
patch crypto_url(@crypto), params: { crypto: { amount_owner: @crypto.amount_owner, cost_per: @crypto.cost_per, symbol: @crypto.symbol, user_id: @crypto.user_id } }
assert_redirected_to crypto_url(@crypto)
end
test "should destroy crypto" do
assert_difference('Crypto.count', -1) do
delete crypto_url(@crypto)
end
assert_redirected_to cryptos_url
end
end
<file_sep><br>
<h2 class="w-100 text-center"><%= t('history_h') %> </h2>
<h3 class="w-100 text-center"> <%= t('history_p') %> </h3>
<div class="card card-profile ml-auto mr-auto" style="max-width: 500px">
<div class="card-body ">
<h3 class="card-category text-dark">
1. <%= t('history_instr1') %>
</h3>
</div>
<div class="card-header card-header-image">
<%= image_tag("/img/1.jpg", class: " img") %>
</div>
</div>
<br>
<br>
<div class="card card-profile ml-auto mr-auto" style="max-width: 500px">
<div class="card-body ">
<h3 class="card-category text-dark">
2. <%= t('history_instr2') %>
</h3>
</div>
<div class="card-header card-header-image">
<%= image_tag("/img/2.jpg", class: " img") %>
</div>
</div>
<file_sep>class StaticPagesController < ApplicationController
def about
end
def history
@coins = Coin.all
require 'net/http'
require 'json'
@url = 'https://api.coinmarketcap.com/v1/ticker/?limit=1000'
@uri = URI(@url)
@response = Net::HTTP.get(@uri)
@lookup_coins = JSON.parse(@response)
@profit_lost = 0
@profit_summ = 0
end
end
<file_sep>json.array! @cryptos, partial: 'cryptos/crypto', as: :crypto
<file_sep><% if !person_signed_in? %>
<table class="table__for__center" >
<tbody>
<tr>
<td class="align-middle">
<div class="text-center">
<h3 class="jumbotron-heading"><%= t('problem1') %>. <%= t('problem2') %></h3>
<div class="col-12 text-center">
<%= t('free') %>
</div>
<p>
<%= link_to t('sign_up'), new_person_registration_path, class: 'btn btn-primary' %>
<%= link_to t('login'), new_person_session_path, class: "btn btn-info" %>
</p>
</div>
</td>
</tr>
</tbody>
</table>
<% else %>
<!-- Render content -->
<% if 0 < (Coin.where(person_id: current_person.id).count) %>
<!-- If User have coin -->
<%= render 'static_pages/home_have_coin' %>
<% else %>
<!-- If User did't coin -->
<%= render 'static_pages/home_have_not_coin' %>
<% end %>
<% end %><file_sep><div class="card">
<div class="card-body">
<% @soldcount = 0 %>
<% @coins.each do |coin| %>
<% if coin.person_id == current_person.id %>
<% if coin.cost_per_sold.blank? %>
<% else %>
<% @soldcount += 1 %>
<% end %>
<% end %>
<% end %>
<!-- Render content -->
<% if (@soldcount >= 1) %>
<%= render 'static_pages/if_history_not_empty' %>
<% else %>
<%= render 'static_pages/history_empty' %>
<% end %>
<br>
</div>
</div>
<!-- Close MainCart (Wrap) -->
<script>
jQuery(document).ready(function ($) {
// Paste info about portolio value
var profitLost = 0;
$('.proit__lost').each(function () {
profitLost += parseFloat($(this).text());
});
console.log(">>>>>" + profitLost);
$('#historyProfLost').text(profitLost.toFixed(2));
$(".coin__item__wrap a.btn-info").html('<i class="material-icons">subject</i>');
$(".coin__item__wrap a.btn-success").html('<i class="material-icons">mode_edit</i>');
$(".coin__item__wrap a.btn-danger").html('<i class="material-icons">delete</i>');
$("#cardAddNewCoin a").html('<i class="material-icons">add</i>');
// Change color depends value
$(".change__value .badge").each(function () {
var value = $(this).find(".change__val");
var value = value.text();
if (value >= 0) {
$(this).addClass('badge-success');
} else {
$(this).addClass('badge-danger');
$(this).find(".material-icons").text('trending_down');
}
});
// Change color Summary
var value = $("#wrapPortfSumm #moneyPortfLost");
var value = value.text();
if (value >= 0) {
$('#wrapPortfSumm').addClass('bg-success');
} else {
$('#wrapPortfSumm').addClass('bg-danger');
}
});
</script>
<file_sep>
<h1>Cryptos</h1>
<table>
<thead>
<tr>
<th>Symbol</th>
<th>User</th>
<th>Cost per</th>
<th>Amount owner</th>
<th colspan="3"></th>
</tr>
</thead>
<%= current_person.id %>
<tbody>
<% @cryptos.each do |crypto| %>
<% if crypto.user_id == current_person.id %>
<tr>
<td><%= crypto.symbol %></td>
<td><%= crypto.user_id %></td>
<td><%= crypto.cost_per %></td>
<td><%= crypto.amount_owner %></td>
<td><%= link_to 'Show', crypto %></td>
<td><%= link_to 'Edit', edit_crypto_path(crypto) %></td>
<td><%= link_to 'Destroy', crypto, method: :delete, data: { confirm: 'Are you sure?' } %></td>
</tr>
<% end %>
<% end %>
</tbody>
</table>
<br>
<%= link_to 'New Crypto', new_crypto_path %>
<file_sep>class ApplicationController < ActionController::Base
before_action :set_locale
def set_locale
logger.debug "* Accept-Language: #{request.env['HTTP_ACCEPT_LANGUAGE']}"
if extract_locale_from_accept_language_header == 'en' || extract_locale_from_accept_language_header == 'ru'
I18n.locale = extract_locale_from_accept_language_header
else
I18n.locale = 'en'
end
logger.debug "* Locale set to '#{I18n.locale}'"
end
def lookup
require 'net/http'
require 'json'
@url = 'https://api.coinmarketcap.com/v1/ticker/'
@uri = URI(@url)
@response = Net::HTTP.get(@uri)
@lookup_coins = JSON.parse(@response)
@symbol = params[:sym]
if @symbol
@symbol = @symbol.upcase
end
if @symbol == ""
@symbol = "Вы забыли выбрать валюту, пожалуйста сделайте выбор"
end
end
def about
end
private
def extract_locale_from_accept_language_header
request.env['HTTP_ACCEPT_LANGUAGE'].scan(/^[a-z]{2}/).first
end
end
<file_sep><div id="wrapEditForm">
<%= render 'form', coin: @coin %>
<br>
<nav aria-label="Page navigation example">
<ul class="pagination justify-content-center">
<li class="page-item"><%= link_to 'Back', coins_path, class:'page-link' %></li>
<li class="page-item"><%= link_to 'Show detail', @coin, class:'page-link' %></li>
</ul>
</nav>
<script>
jQuery(document).ready(function($) {
var inputCoinName = $("#formCoinName input").val();
console.log('inputCoinName' + inputCoinName);
$( "#wrapEditForm #formTextHeader" ).text( "Edit: " + inputCoinName );
});
</script>
</div>
<file_sep>
<div class="row">
<div class="col-md-3">
</div>
<div class="col-md-6 text-center">
<br>
<div class="card card-signup p-5">
<%= form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %>
<%= devise_error_messages! %>
<div class="form-signin">
<%= image_tag("/img/bitcoin.svg", class: "mb-2", height: '72', width: '72') %>
<h3 class="h3 mb-3 font-weight-normal"><%= t('sign_up') %></h3>
</div>
<div class="form-label-group">
<!-- <input type="email" id="inputEmail" class="form-control" placeholder="Email address" required="" autofocus=""> -->
<%= f.email_field :email, autofocus: true, autocomplete: "email", :class => 'form-control', placeholder: t('email') %>
</div>
<br>
<div class="form-label-group">
<%= f.password_field :password, autocomplete: "off", :class => 'form-control', placeholder: t('password') %>
</div>
<br>
<div class="form-label-group">
<%= f.password_field :password_confirmation, autocomplete: "off", :class => 'form-control', placeholder: t('confirm_password') %>
</div>
<br>
<%= f.submit t('sign_up'), :class => 'btn btn-lg btn-primary btn-block' %>
</div>
<!-- <button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button> -->
<% end %>
</form>
</div>
<div class="col-md-3">
</div>
</div>
<file_sep># Files in the config/locales directory are used for internationalization
# and are automatically loaded by Rails. If you want to use locales other
# than English, add the necessary files in this directory.
#
# To use the locales, use `I18n.t`:
#
# I18n.t 'hello'
#
# In views, this is aliased to just `t`:
#
# <%= t('hello') %>
#
# To use a different locale, set it with `I18n.locale`:
#
# I18n.locale = :es
#
# This would use the information in config/locales/es.yml.
#
# The following keys must be escaped otherwise they will not be retrieved by
# the default I18n backend:
#
# true, false, on, off, yes, no
#
# Instead, surround them with single quotes.
#
# en:
# 'true': 'foo'
#
# To learn more, please read the Rails Internationalization guide
# available at http://guides.rubyonrails.org/i18n.html.
en:
hello: 'Hello world'
header: 'Keep track of your crypto coins'
sub_header: 'Create an account and add your coins. And watch in real time. How much do they cost in sum and separately'
free: 'The service is absolutely free, you can delete the account anytime'
header: 'Service will solve at least 2 problems'
problem1: 'Buying currency at different sites is difficult to calculate how much money you have at the moment'
problem2: 'The service saves the history of the sale of the currency and shows the result in the amount.'
read_more: 'Read more'
sign_up: 'Register'
login: 'Login'
portfolio: 'portfolio'
confirm_password: '<PASSWORD>'
password: '<PASSWORD>'
email: 'Your email'
portfolio: 'Your coins'
add_new_coin: 'Add a coin'
history: 'Sales history'
logout: 'Exit'
setting_account: 'Account settings'
descr_after_login_home: 'You can add a new coin to the portfolio or see the status of the current coins'
descr_after_login_home_p: 'To start creating a Crypto-currency portfolio, you need to add a coin'
portfolio_detail: 'Details'
individual_cost: 'The cost of your pock for each of the crypto currency:'
money_amount: 'The total value of your portfolio'
profit_lost: 'Profit / loss'
change: 'Change'
d: 'days'
hs: 'hours'
h: 'hour'
history_h: 'The history is empty. You did not sell coins'
history_p: 'To sell a coin, follow the instructions below'
history_instr1: 'Go to the "Your coins" section, then click on the "edit" icon'
history_instr2: 'In the lowest form, indicate the rate at which the coin'
name_cur: 'Enter the name of the crypto'
name_cur_plh: 'Start typing the name'
cur_price: 'The rate at the time of buying coins'
cur_price_plh: 'Price for one monetu'
amount: 'Total number of coins'
edit_profile: 'Edit profile'
leave: 'Leave the field blank if you do not want to change the password'
confirm: 'Enter your current password to confirm'
minimum: 'minimum characters'
unhappy: 'Dissatisfied'
cancel_acc: 'Delete account'
back: 'back'
update: 'Update'
portfolio_empty: 'There are no coins in your portfolio, please add a coin'
activerecord:
errors:
messages:
record_invalid: "Validation failed: %{errors}"
restrict_dependent_destroy:
has_one: "Cannot delete record because a dependent %{record} exists"
has_many: "Cannot delete record because dependent %{record} exist"
date:
abbr_day_names:
- Sun
- Mon
- Tue
- Wed
- Thu
- Fri
- Sat
abbr_month_names:
-
- Jan
- Feb
- Mar
- Apr
- May
- Jun
- Jul
- Aug
- Sep
- Oct
- Nov
- Dec
day_names:
- Sunday
- Monday
- Tuesday
- Wednesday
- Thursday
- Friday
- Saturday
formats:
default: "%Y-%m-%d"
long: "%B %d, %Y"
short: "%b %d"
month_names:
-
- January
- February
- March
- April
- May
- June
- July
- August
- September
- October
- November
- December
order:
- :year
- :month
- :day
datetime:
distance_in_words:
about_x_hours:
one: about 1 hour
other: about %{count} hours
about_x_months:
one: about 1 month
other: about %{count} months
about_x_years:
one: about 1 year
other: about %{count} years
almost_x_years:
one: almost 1 year
other: almost %{count} years
half_a_minute: half a minute
less_than_x_minutes:
one: less than a minute
other: less than %{count} minutes
less_than_x_seconds:
one: less than 1 second
other: less than %{count} seconds
over_x_years:
one: over 1 year
other: over %{count} years
x_days:
one: 1 day
other: "%{count} days"
x_minutes:
one: 1 minute
other: "%{count} minutes"
x_months:
one: 1 month
other: "%{count} months"
x_years:
one: 1 year
other: "%{count} years"
x_seconds:
one: 1 second
other: "%{count} seconds"
prompts:
day: Day
hour: Hour
minute: Minute
month: Month
second: Seconds
year: Year
errors:
format: "%{attribute} %{message}"
messages:
accepted: must be accepted
blank: can't be blank
present: must be blank
confirmation: doesn't match %{attribute}
empty: can't be empty
equal_to: must be equal to %{count}
even: must be even
exclusion: is reserved
greater_than: must be greater than %{count}
greater_than_or_equal_to: must be greater than or equal to %{count}
inclusion: is not included in the list
invalid: is invalid
less_than: must be less than %{count}
less_than_or_equal_to: must be less than or equal to %{count}
model_invalid: "Validation failed: %{errors}"
not_a_number: is not a number
not_an_integer: must be an integer
odd: must be odd
required: must exist
taken: has already been taken
too_long:
one: is too long (maximum is 1 character)
other: is too long (maximum is %{count} characters)
too_short:
one: is too short (minimum is 1 character)
other: is too short (minimum is %{count} characters)
wrong_length:
one: is the wrong length (should be 1 character)
other: is the wrong length (should be %{count} characters)
other_than: must be other than %{count}
template:
body: 'There were problems with the following fields:'
header:
one: 1 error prohibited this %{model} from being saved
other: "%{count} errors prohibited this %{model} from being saved"
helpers:
select:
prompt: Please select
submit:
create: Create %{model}
submit: Save %{model}
update: Update %{model}
number:
currency:
format:
delimiter: ","
format: "%u%n"
precision: 2
separator: "."
significant: false
strip_insignificant_zeros: false
unit: "$"
format:
delimiter: ","
precision: 3
separator: "."
significant: false
strip_insignificant_zeros: false
human:
decimal_units:
format: "%n %u"
units:
billion: Billion
million: Million
quadrillion: Quadrillion
thousand: Thousand
trillion: Trillion
unit: ''
format:
delimiter: ''
precision: 3
significant: true
strip_insignificant_zeros: true
storage_units:
format: "%n %u"
units:
byte:
one: Byte
other: Bytes
gb: GB
kb: KB
mb: MB
tb: TB
percentage:
format:
delimiter: ''
format: "%n%"
precision:
format:
delimiter: ''
support:
array:
last_word_connector: ", and "
two_words_connector: " and "
words_connector: ", "
time:
am: am
formats:
default: "%a, %d %b %Y %H:%M:%S %z"
long: "%B %d, %Y %H:%M"
short: "%d %b %H:%M"
pm: pm<file_sep>json.extract! crypto, :id, :symbol, :user_id, :cost_per, :amount_owner, :created_at, :updated_at
json.url crypto_url(crypto, format: :json)
<file_sep>json.extract! coin, :id, :symbol, :person_id, :cost_per, :amount_owned, :created_at, :updated_at
json.url coin_url(coin, format: :json)
<file_sep><div class="card">
<div class="card-body">
<h3 class="text-uppercase text-center mt-4"><%= t('portfolio') %></h3>
<div class="row">
<div class="col-md-6 pb-5">
<div class="card p-3">
<p> <%= t('individual_cost') %>
</p>
<canvas id="myChart" width="100%" height="100%"></canvas>
</div>
</div>
<div class="col-md-6">
<div class="card p-3">
<div class="rounded bg-info m-3 p-2">
<div class="card-body">
<h5 class="text-uppercase font-weight-bold text-white mt-3 mb-3">
<%= t('money_amount') %>
<br>
<span class="portfSummText"> $ </span>
<span class="portfSummText" id="moneyPortfAmount"></span>
</h5>
</div>
</div>
<div id='wrapPortfSumm' class="rounded m-3 p-2">
<div class="card-body">
<h5 class="text-uppercase font-weight-bold text-white mt-3 mb-3">
<%= t('profit_lost') %>
<br>
<span class="portfSummText" id="moneyPortfLost"></span>
<span class="portfSummText">$</span>
</h5>
</div>
</div>
</div>
<!-- close card p-3 -->
</div>
<!-- close col-md-6 -->
</div>
<!-- close col-md-6 -->
<script>
jQuery(document).ready(function ($) {
var profitLost = 0;
var curientVal = 0;
$('.proit__lost').each(function () {
profitLost += parseFloat($(this).text());
});
$('.curientValue').each(function () {
curientVal += parseFloat($(this).text());
});
$('#moneyPortfAmount').text(curientVal.toFixed(2));
$('#moneyPortfLost').text(profitLost.toFixed(2));
});
</script>
<div class="row">
<div class="col-12 mt-4 mb-1">
<h3 class="text-uppercase text-center"><%= t('portfolio_detail') %></h3>
</div>
</div>
<div class="row">
<% @coins.each do |coin| %>
<!-- *** -->
<!-- If the coin does not matter in the cost_per_sold field, then it is not sold. And you need to show it here -->
<!-- *** -->
<% if coin.person_id == current_person.id && coin.cost_per_sold.blank? %>
<% if coin.symbol %>
<% coin.symbol = coin.symbol.upcase %>
<% end %>
<% for x in @lookup_coins %>
<% if coin.symbol == x["symbol"] %>
<div class="col-md-6 wrap__each__coin">
<div class="card card-nav-tabs">
<h3 class="card-header card-header-primary text-uppercase coin__name">
<%= x["name"] %> =
<%= number_with_precision(x["price_usd"].to_d, precision: 2) %>$
</h3>
<div class="card-body">
<div class="row">
<div class="col-12 col-md-4">
<div class="change__value">
<span class="badge badge-success w-100 mb-3 mb-md-0">
<p> <%= t('change') %> 7<%= t('d') %> </p>
<p class="change__val">
<%= x["percent_change_7d"] %>
</p>
<i class="material-icons">trending_up</i>
</span>
</div>
</div>
<div class="col-12 col-md-4">
<div class="change__value">
<span class="badge badge-success w-100 mb-3 mb-md-0">
<p> <%= t('change') %> 24<%= t('hs') %> </p>
<p class="change__val">
<%= x["percent_change_24h"] %>
</p>
<i class="material-icons">trending_up</i>
</span>
</div>
</div>
<div class="col-12 col-md-4">
<div class="change__value">
<span class="badge badge-success w-100 mb-3 mb-md-0">
<p> <%= t('change') %> 1<%= t('h') %> </p>
<p class="change__val">
<%= x["percent_change_1h"] %>
</p>
<i class="material-icons">trending_up</i>
</span>
</div>
</div>
</div>
<!-- END row -->
<div class="row static2row mt-2 mb-2">
<div class="col-12">
<div class="change__value">
<span class="badge w-100">
<p class="m-3"> <%= t('profit_lost') %> </p>
<p class="change__val proit__lost m-3">
<% curval = (x["price_usd"].to_d * coin.amount_owned) - (coin.cost_per * coin.amount_owned) %>
<%= number_with_precision(curval.to_d, precision: 2) %>
</p>
</span>
</div>
</div>
</div>
<!-- END row -->
<div class="text-white bg-info p-2 mt-2 curr__value__coin">
<h5 class="text-white text-uppercase text-center font-weight-bold m-0 align-middle pt-3 pb-3"> <%= t('money_amount') %>: $
<span class="curientValue">
<%= number_with_precision(x["price_usd"].to_d * coin.amount_owned, precision: 2) %>
</span>
</h5>
</div>
<br>
<div class="footer text-center coin__item__wrap">
<%= link_to 'Show', coin, class: "btn btn-info btn-just-icon btn-fill btn-round animated fadeIn" %>
<%= link_to 'Edit', edit_coin_path(coin), class: "btn btn-success btn-just-icon btn-fill btn-round btn-wd animated fadeIn" %>
<%= link_to 'Destroy', coin, method: :delete, data: { confirm: 'Are you sure?' }, class: "btn btn-danger btn-just-icon btn-fill btn-round animated fadeIn" %>
</div>
</div>
</div>
</div>
<% end %>
<% end %>
<% end %>
<% end %>
<!-- Add new coin -->
<div class="col-md-6">
<div class="card card-nav-tabs">
<h3 class="card-header card-header-primary text-uppercase ">
<%= t('add_new_coin') %>
</h3>
<div class="card-body">
<div class="row">
<div class="col-12">
<div id="cardAddNewCoin" class="p-4 text-center">
<span class="">
<%= link_to 'New Coin', new_coin_path, class: "btn btn-success btn-just-icon btn-fill btn-round btn-wd animated fadeIn" %>
</span>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- End Add new coin -->
</div> <!-- Close row tag -->
</div>
</div>
<!-- Close MainCart (Wrap) -->
<script>
jQuery(document).ready(function ($) {
$(".coin__item__wrap a.btn-info").html('<i class="material-icons">subject</i>');
$(".coin__item__wrap a.btn-success").html('<i class="material-icons">mode_edit</i>');
$(".coin__item__wrap a.btn-danger").html('<i class="material-icons">delete</i>');
$("#cardAddNewCoin a").html('<i class="material-icons">add</i>');
// Change color depends value
$(".change__value .badge").each(function () {
var value = $(this).find(".change__val");
var value = value.text();
if (value >= 0) {
$(this).addClass('badge-success');
} else {
$(this).addClass('badge-danger');
$(this).find(".material-icons").text('trending_down');
}
});
// Change color Summary
var value = $("#wrapPortfSumm #moneyPortfLost");
var value = value.text();
if (value >= 0) {
$('#wrapPortfSumm').addClass('bg-success');
} else {
$('#wrapPortfSumm').addClass('bg-danger');
}
});
</script>
<script>
jQuery(document).ready(function ($) {
// Chart #1 Start
var coinsNames = [];
var coinsSummary = [];
$(".wrap__each__coin").each(function () {
// For Name
var coinName = $(this).find(".coin__name");
var coinName = coinName.text();
coinsNames.push(coinName);
// For value
var coinSumm = $(this).find(".curr__value__coin .curientValue").text();
coinsSummary.push(coinSumm);
});
var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {
type: 'pie',
data: {
labels: coinsNames,
datasets: [{
label: '# of Votes',
data: coinsSummary,
backgroundColor: [
'#99B2DD',
'#F9DEC9',
'rgba(153, 102, 255, 1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 99, 132, 1)',
'rgba(255, 159, 64, 1)'
],
borderColor: [
'#99B2DD',
'#F9DEC9',
'rgba(153, 102, 255, 1)',
'rgba(54, 162, 235, 1)',
'rgba(255,99,132,1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
},
});
// Chart #1 End
});
</script><file_sep>
<div class="row">
<div class="col-md-3">
</div>
<div class="col-md-6 text-center">
<br>
<div class="card card-signup p-5">
<%= form_with(model: coin, local: true, :html => {:class => 'form-signin'}) do |form| %>
<% if coin.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(coin.errors.count, "error") %> prohibited this coin from being saved:</h2>
<ul>
<% coin.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="form-signin">
<%= image_tag("/img/bitcoin.svg", class: "mb-4", height: '72', width: '72') %>
<h2 id="formTextHeader" class="h3 mb-4 mt-0 font-weight-normal text-uppercase"><%= t('add_new_coin') %></h2>
</div>
<div id="formCoinName" class="form-label-group mb-3 text-left">
<label for="exampleInputEmail1 text-dark" ><%= t('name_cur') %></label>
<%= form.text_field :symbol, placeholder: t('name_cur_plh'), :required => 'required', :class => 'form-control' %>
</div>
<div class="form-label-group d-none">
<%= form.number_field :person_id, value: current_person.id, type: "hidden" %>
</div>
<div class="form-label-group mb-3 text-left">
<label for="exampleInputEmail1 text-dark" ><%= t('cur_price') %></label>
<%= form.text_field :cost_per, placeholder: t('cur_price_plh'), :required => 'required', :class => 'form-control' %>
</div>
<div class="form-label-group mb-3 text-left">
<label for="exampleInputEmail1 text-dark" ><%= t('amount') %></label>
<%= form.text_field :amount_owned, placeholder: t('amount'), :required => 'required', :class => 'form-control' %>
</div>
<br>
<!-- <button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button> -->
<%= form.submit t('add_new_coin'), :class => 'btn btn-lg btn-primary btn-block form__button' %>
</form>
</div>
</div>
<div class="col-md-3">
</div>
</div>
<% end %>
<file_sep><% if !person_signed_in? %>
<nav class="navbar navbar-expand-lg bg-primary">
<div class="container">
<div class="navbar-translate">
<a class="navbar-brand" href="/">BITCOINBTN.ru</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
<span class="navbar-toggler-icon"></span>
<span class="navbar-toggler-icon"></span>
</button>
</div>
<div class="collapse navbar-collapse">
<ul class="navbar-nav ml-auto">
<li class="nav-item">
<%= link_to t('sign_up'), new_person_registration_path, class: 'nav-link nav__sign-up' %>
</li>
<li class="nav-item">
<%= link_to t('login'), new_person_session_path, class: "nav-link nav__login" %>
</li>
</ul>
</div>
</div>
</nav>
<script>
jQuery(document).ready(function ($) {
$("a.nav__sign-up").prepend('<i class="material-icons">person_add</i> ');
$("a.nav__login").prepend('<i class="material-icons">person</i> ');
});
</script>
<% else %>
<nav class="navbar navbar-expand-lg bg-primary">
<div class="container">
<div class="navbar-translate">
<a class="navbar-brand" href="/">BITCOINBTN.ru</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
<span class="navbar-toggler-icon"></span>
<span class="navbar-toggler-icon"></span>
</button>
</div>
<div class="collapse navbar-collapse">
<ul class="navbar-nav ml-auto">
<li class="nav-item">
<%= link_to t('portfolio'), coins_path, class: 'nav-link nav__portfolio' %>
</li>
<li class="nav-item">
<%= link_to t('history'), history_path, class: 'nav-link nav__history' %>
</li>
<li class="nav-item">
<%= link_to t('add_new_coin'), new_coin_path, class: 'nav-link nav__add-coin' %>
</li>
<li class="nav-item">
<%= link_to t('setting_account'), edit_person_registration_path, class: 'nav-link nav__setting-account' %>
</li>
<li class="nav-item">
<%= link_to t('logout'), destroy_person_session_path, method: :delete, class: 'nav-link nav__logout' %>
</li>
</ul>
</div>
</div>
</nav>
<script>
jQuery(document).ready(function ($) {
$("a.nav__portfolio").prepend('<i class="material-icons">work</i> ');
$("a.nav__history").prepend('<i class="material-icons">history</i> ');
$("a.nav__add-coin").prepend('<i class="material-icons">add_circle_outline</i> ');
$("a.nav__setting-account").prepend('<i class="material-icons">settings</i> ');
$("a.nav__logout").prepend('<i class="material-icons">exit_to_app</i> ');
});
</script>
<% end %>
<file_sep><div class="row">
<div class="col-md-3">
</div>
<div class="col-md-6 text-center">
<br>
<div class="card card-signup p-5">
<%= form_for(resource, as: resource_name, url: registration_path(resource_name), html: { method: :put }) do |f| %>
<%= devise_error_messages! %>
<div class="form-signin">
<%= image_tag("/img/computer.svg", class: "mb-2", height: '72', width: '72') %>
<h3 class="h3 mb-2 font-weight-normal"><%= t('edit_profile') %></h3>
</div>
<div class="form-label-group text-left">
<%= f.label :email, :class => 'text-left' %><br />
<%= f.email_field :email, autofocus: true, autocomplete: "email", :class => 'form-control', placeholder: "Email" %>
</div>
<% if devise_mapping.confirmable? && resource.pending_reconfirmation? %>
<div>Currently waiting confirmation for: <%= resource.unconfirmed_email %></div>
<% end %>
<br>
<div class="form-label-group text-left">
<%= f.label :password, :class => 'text-left' %> <i><%= t('leave') %></i><br />
<%= f.password_field :password, autocomplete: "off", :class => 'form-control', placeholder: "<PASSWORD>" %>
<% if @minimum_password_length %>
<em><%= @minimum_password_length %><%= t('minimum') %></em>
<% end %>
</div>
<br>
<div class="form-label-group text-left">
<%= f.label :password_confirmation, :class => 'text-left' %><br />
<%= f.password_field :password_confirmation, autocomplete: "off", :class => 'form-control', placeholder: "<PASSWORD> confirmation" %>
</div>
<br>
<div class="form-label-group text-left">
<%= f.label :current_password, :class => 'text-left' %> <i> <%= t('confirm') %></i><br />
<%= f.password_field :current_password, autocomplete: "off", :class => 'form-control', placeholder: "<PASSWORD>" %>
</div>
<br>
<div class="actions">
<%= f.submit t('update'), :class => 'btn btn-lg btn-primary btn-block form__button' %>
</div>
<% end %>
<br>
<h5><%= t('unhappy') %>? <%= button_to t('cancel_acc'), registration_path(resource_name), data: { confirm: "Are you sure?" }, method: :delete, :class => 'btn btn-lg btn-block form__button' %></h5>
</div>
<div class="row">
<div class="col-md-4">
</div>
<div class="col-md-4">
<%= link_to t('back'), :back, :class => 'btn btn-lg btn-info btn-block form__button' %>
</div>
<div class="col-md-4">
</div>
</div>
</div>
<div class="col-md-3">
</div>
</div>
<file_sep>class AddSoldInfoToCoins < ActiveRecord::Migration[5.2]
def change
remove_column :coins, :is_it_sold, :boolean
end
end
<file_sep> <h3 class="text-uppercase text-center mt-4"><%= t('history') %></h3>
<div class="row pb-5">
<div class="col-12">
<div class="change__value">
<span class="badge w-100 badge-success">
<p class="m-3"><%= t('profit_lost') %> </p>
<p id="historyProfLost" class="change__val m-3"></p>
</span>
</div>
</div>
</div>
<div class="row">
<% @coins.each do |coin| %>
<!-- *** -->
<!-- If the coin does not matter in the cost_per_sold field, then it is not sold. And you need to show it here -->
<!-- *** -->
<% if coin.person_id == current_person.id && coin.cost_per_sold %>
<% if coin.symbol %>
<% coin.symbol = coin.symbol.upcase %>
<% end %>
<% for x in @lookup_coins %>
<% if coin.symbol == x["symbol"] %>
<div class="col-md-6 wrap__each__coin">
<div class="card card-nav-tabs">
<h3 class="card-header card-header-primary text-uppercase coin__name">
<%= x["name"] %>
</h3>
<div class="card-body">
<!-- END row -->
<div class="row static2row mt-2 mb-2">
<div class="col-12">
<div class="change__value">
<span class="badge w-100">
<p class="m-3"> <%= t('profit_lost') %> </p>
<p class="change__val proit__lost m-3">
<% profit_lost_coin = (coin.cost_per_sold * coin.amount_owned).to_i - (coin.cost_per * coin.amount_owned).to_i %>
<%= profit_lost_coin %>
</p>
</span>
</div>
</div>
</div>
<br>
<div class="footer text-center coin__item__wrap">
<%= link_to 'Destroy', coin, method: :delete, data: { confirm: 'Are you sure?' }, class: "btn btn-danger btn-just-icon btn-fill btn-round animated fadeIn" %>
</div>
</div>
</div>
</div>
<% end %>
<% end %>
<% end %>
<% end %>
</div> <!-- Close row tag --><file_sep>class Crypto < ApplicationRecord
belongs_to :person
end
<file_sep># Additional translations at https://github.com/plataformatec/devise/wiki/I18n
ru:
devise:
confirmations:
confirmed: "Ваш адрес электронной почты успешно подтвержден."
send_instructions: "Вы получите электронное письмо с инструкциями о том, как подтвердить свой адрес электронной почты в течение нескольких минут."
send_paranoid_instructions: "Если ваш адрес электронной почты существует в нашей базе данных, вы получите электронное письмо с инструкциями о том, как подтвердить свой адрес электронной почты за несколько минут."
failure:
already_authenticated: "Вы уже вошли в систему."
inactive: "Ваша учетная запись еще не активирована."
invalid: "Неправильный %{authentication_keys} или пароль."
locked: "Ваш аккаунт заблокирован."
last_attempt: "У вас есть еще одна попытка, прежде чем ваша учетная запись будет заблокирована."
not_found_in_database: "Неправильный %{authentication_keys} или пароль."
timeout: "Срок действия вашей сессии истек. Повторите попытку, чтобы продолжить."
unauthenticated: "Прежде чем продолжить, вам нужно войти в систему или зарегистрироваться."
unconfirmed: "Прежде чем продолжить, вы должны подтвердить свой адрес электронной почты."
mailer:
confirmation_instructions:
subject: "Инструкции по подтверждению"
reset_password_instructions:
subject: "Сбросить инструкции для пароля"
unlock_instructions:
subject: "Инструкции по разблокировке"
email_changed:
subject: "Изменено сообщение электронной почты"
password_change:
subject: "Пароль изменен"
omniauth_callbacks:
failure: "Не удалось аутентифицировать вас %{kind} потому как \"%{reason}\"."
success: "Успешно завершена %{kind} аккаунт."
passwords:
no_token: "Вы не можете получить доступ к этой странице, не используя пароль для сброса пароля. Если вы пришли из пароля для сброса пароля, убедитесь, что вы использовали полный URL-адрес."
send_instructions: "Вы получите электронное письмо с инструкциями о том, как сбросить пароль за несколько минут."
send_paranoid_instructions: "Если ваш адрес электронной почты существует в нашей базе данных, вы получите ссылку на восстановление пароля на свой адрес электронной почты через несколько минут."
updated: "Ваш пароль был успешно изменен. Теперь вы вошли в систему."
updated_not_active: "Ваш пароль был успешно изменен."
registrations:
destroyed: "До свидания! Ваша учетная запись успешно отменена. Мы надеемся увидеть Вас снова скоро."
signed_up: "Поздравляем! Вы успгешно зарегистрировались!"
signed_up_but_inactive: "Вы успешно зарегистрировались. Однако мы не смогли подписать вас, потому что ваша учетная запись еще не активирована."
signed_up_but_locked: "Вы успешно зарегистрировались. Однако мы не смогли подписать вас, потому что ваша учетная запись заблокирована."
signed_up_but_unconfirmed: "На ваш адрес электронной почты отправлено сообщение с ссылкой для подтверждения. Перейдите по ссылке, чтобы активировать свою учетную запись."
update_needs_confirmation: "Вы успешно обновили свою учетную запись, но нам нужно подтвердить ваш новый адрес электронной почты. Проверьте свой адрес электронной почты и подтвердите свой новый адрес электронной почты."
updated: "Ваша учетная запись успешно обновлена."
sessions:
signed_in: "Поздравляем! Вход выполнен успешно!"
signed_out: "Вы успешно вышли"
already_signed_out: "Вы успешно вышли"
unlocks:
send_instructions: "Вы получите электронное письмо с инструкциями о том, как разблокировать свою учетную запись через несколько минут."
send_paranoid_instructions: "Если ваша учетная запись существует, вы получите электронное письмо с инструкциями о том, как разблокировать его через несколько минут."
unlocked: "Ваша учетная запись была разблокирована успешно. Войдите в систему, чтобы продолжить."
errors:
messages:
already_confirmed: "было подтверждено, пожалуйста, войдите в систему"
confirmation_period_expired: "необходимо подтвердить в %{period}, пожалуйста, запросите новый"
expired: "истек, пожалуйста, запросите новый"
not_found: "не найдено"
not_locked: "не было заблокировано"
not_saved:
one: "1 ошибка при создании пользователя:"
other: "%{count} ошибки запретили создать пользователя:"
<file_sep>
<div class="row">
<div class="col-md-3">
</div>
<div class="col-md-6 text-center">
<br>
<div class="card card-signup p-5">
<%= form_with(model: coin, local: true, :html => {:class => 'form-signin'}) do |form| %>
<% if coin.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(coin.errors.count, "error") %> prohibited this coin from being saved:</h2>
<ul>
<% coin.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="form-signin">
<%= image_tag("/img/bitcoin.svg", class: "mb-4", height: '72', width: '72') %>
<h2 id="formTextHeader" class="h3 mb-4 mt-0 font-weight-normal text-uppercase">Add coin </h2>
</div>
<div id="formCoinName" class="form-label-group mb-3 text-left">
<label for="exampleInputEmail1 text-dark" >Enter the name of the currency</label>
<%= form.text_field :symbol, placeholder: "Start type name of currency", :required => 'required', :class => 'form-control' %>
</div>
<div class="form-label-group d-none">
<%= form.number_field :person_id, value: current_person.id, type: "hidden" %>
</div>
<div class="form-label-group mb-3 text-left">
<label for="exampleInputEmail1 text-dark" >The cost of one coin at the time of purchase</label>
<%= form.text_field :cost_per, placeholder: "Price per coin", :required => 'required', :class => 'form-control' %>
</div>
<div class="form-label-group mb-3 text-left">
<label for="exampleInputEmail1 text-dark" >Amount owned</label>
<%= form.text_field :amount_owned, placeholder: "Amount owned", :required => 'required', :class => 'form-control' %>
</div>
<div class="form-label-group mb-3 text-left">
<label for="exampleInputEmail1 text-dark" >Coin Was it sold?</label><br>
<label for="exampleInputEmail1 text-dark" >Please, add Cost Per Sold: </label>
<%= form.text_field :cost_per_sold, placeholder: "The value of the currency at the time of sale", :class => 'form-control' %>
</div>
<br>
<!-- <button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button> -->
<%= form.submit "submit", :class => 'btn btn-lg btn-primary btn-block form__button' %>
</form>
</div>
</div>
<div class="col-md-3">
</div>
</div>
<% end %>
<file_sep>require "application_system_test_case"
class CryptosTest < ApplicationSystemTestCase
setup do
@crypto = cryptos(:one)
end
test "visiting the index" do
visit cryptos_url
assert_selector "h1", text: "Cryptos"
end
test "creating a Crypto" do
visit cryptos_url
click_on "New Crypto"
fill_in "Amount Owner", with: @crypto.amount_owner
fill_in "Cost Per", with: @crypto.cost_per
fill_in "Symbol", with: @crypto.symbol
fill_in "User", with: @crypto.user_id
click_on "Create Crypto"
assert_text "Crypto was successfully created"
click_on "Back"
end
test "updating a Crypto" do
visit cryptos_url
click_on "Edit", match: :first
fill_in "Amount Owner", with: @crypto.amount_owner
fill_in "Cost Per", with: @crypto.cost_per
fill_in "Symbol", with: @crypto.symbol
fill_in "User", with: @crypto.user_id
click_on "Update Crypto"
assert_text "Crypto was successfully updated"
click_on "Back"
end
test "destroying a Crypto" do
visit cryptos_url
page.accept_confirm do
click_on "Destroy", match: :first
end
assert_text "Crypto was successfully destroyed"
end
end
<file_sep>ru:
hello: 'Hello world'
free: 'Сервис абсолютно бесплатный, аккаунт можно удалить'
header: 'Сервис поможет решить минимум 2 проблемы'
problem1: 'Покупая валюту на разных площадках сложно посчитать сколько на данный момент у вас денег'
problem2: 'Сервис сохраняет историю продажи валюты и показывает результат в сумме.'
read_more: 'Подробнее'
sign_up: 'Зарегистрироваться'
login: 'Войти'
portfolio: 'портфолио'
confirm_password: '<PASSWORD>'
password: '<PASSWORD>'
email: 'Ваш email'
portfolio: 'Ваши монеты'
add_new_coin: 'Добавить монету'
history: 'История продаж'
logout: 'Выйти'
setting_account: 'Настройки аккаунта'
descr_after_login_home: 'Вы можете добавить новую монету в портфолио или посмотреть состояние текущих монет'
descr_after_login_home_p: 'Для начала создания портфеля криптовалют, вам нужно добавить монету'
portfolio_detail: 'Подробная информация'
individual_cost: 'Стоимоть вашего порфеля по каждой из криптовалют:'
money_amount: 'Общая стоимость вашего портфеля'
profit_lost: 'Прибыль/убыток'
change: 'Изменение'
d: 'дней'
hs: 'часов'
h: 'час'
history_h: 'История пуста. Вы не продавали монеты'
history_p: 'Что бы продать монету, следуйте инструкции ниже'
history_instr1: 'Перейдите в раздел "Ваши монеты", затем нажмите на иконку "редактировать"'
history_instr2: 'В самой нижней форме укажите курс по которому была продана монета'
name_cur: 'Введите название криптовалюты'
name_cur_plh: 'Начните вводить название'
cur_price: 'Курс на момент покупки монет'
cur_price_plh: 'Цена за одну монeту'
amount: 'Общее количество монет'
edit_profile: 'Изменение профиля'
leave: 'Оставьте поле пустым если не хотите менять пароль'
confirm: 'Введите ваш текущий пароль для подтверждения'
minimum: ' символов минимум'
unhappy: 'Недовольны'
cancel_acc: 'Удалить аккаунт'
back: 'назад'
update: 'Обновить'
portfolio_empty: 'В вашем портфеле нет монет, пожалуйста добавьте монету'
activerecord:
errors:
messages:
record_invalid: "Validation failed: %{errors}"
restrict_dependent_destroy:
has_one: "Cannot delete record because a dependent %{record} exists"
has_many: "Cannot delete record because dependent %{record} exist"
date:
abbr_day_names:
- Sun
- Mon
- Tue
- Wed
- Thu
- Fri
- Sat
abbr_month_names:
-
- Jan
- Feb
- Mar
- Apr
- May
- Jun
- Jul
- Aug
- Sep
- Oct
- Nov
- Dec
day_names:
- Sunday
- Monday
- Tuesday
- Wednesday
- Thursday
- Friday
- Saturday
formats:
default: "%Y-%m-%d"
long: "%B %d, %Y"
short: "%b %d"
month_names:
-
- January
- February
- March
- April
- May
- June
- July
- August
- September
- October
- November
- December
order:
- :year
- :month
- :day
datetime:
distance_in_words:
about_x_hours:
one: about 1 hour
other: about %{count} hours
about_x_months:
one: about 1 month
other: about %{count} months
about_x_years:
one: about 1 year
other: about %{count} years
almost_x_years:
one: almost 1 year
other: almost %{count} years
half_a_minute: half a minute
less_than_x_minutes:
one: less than a minute
other: less than %{count} minutes
less_than_x_seconds:
one: less than 1 second
other: less than %{count} seconds
over_x_years:
one: over 1 year
other: over %{count} years
x_days:
one: 1 day
other: "%{count} days"
x_minutes:
one: 1 minute
other: "%{count} minutes"
x_months:
one: 1 month
other: "%{count} months"
x_years:
one: 1 year
other: "%{count} years"
x_seconds:
one: 1 second
other: "%{count} seconds"
prompts:
day: Day
hour: Hour
minute: Minute
month: Month
second: Seconds
year: Year
errors:
format: "%{attribute} %{message}"
messages:
accepted: must be accepted
blank: can't be blank
present: must be blank
confirmation: doesn't match %{attribute}
empty: can't be empty
equal_to: must be equal to %{count}
even: must be even
exclusion: is reserved
greater_than: must be greater than %{count}
greater_than_or_equal_to: must be greater than or equal to %{count}
inclusion: is not included in the list
invalid: is invalid
less_than: must be less than %{count}
less_than_or_equal_to: must be less than or equal to %{count}
model_invalid: "Validation failed: %{errors}"
not_a_number: is not a number
not_an_integer: must be an integer
odd: must be odd
required: must exist
taken: has already been taken
too_long:
one: is too long (maximum is 1 character)
other: is too long (maximum is %{count} characters)
too_short:
one: is too short (minimum is 1 character)
other: is too short (minimum is %{count} characters)
wrong_length:
one: is the wrong length (should be 1 character)
other: is the wrong length (should be %{count} characters)
other_than: must be other than %{count}
template:
body: 'There were problems with the following fields:'
header:
one: 1 error prohibited this %{model} from being saved
other: "%{count} errors prohibited this %{model} from being saved"
helpers:
select:
prompt: Please select
submit:
create: Create %{model}
submit: Save %{model}
update: Update %{model}
number:
currency:
format:
delimiter: ","
format: "%u%n"
precision: 2
separator: "."
significant: false
strip_insignificant_zeros: false
unit: "$"
format:
delimiter: ","
precision: 3
separator: "."
significant: false
strip_insignificant_zeros: false
human:
decimal_units:
format: "%n %u"
units:
billion: Billion
million: Million
quadrillion: Quadrillion
thousand: Thousand
trillion: Trillion
unit: ''
format:
delimiter: ''
precision: 3
significant: true
strip_insignificant_zeros: true
storage_units:
format: "%n %u"
units:
byte:
one: Byte
other: Bytes
gb: GB
kb: KB
mb: MB
tb: TB
percentage:
format:
delimiter: ''
format: "%n%"
precision:
format:
delimiter: ''
support:
array:
last_word_connector: ", and "
two_words_connector: " and "
words_connector: ", "
time:
am: am
formats:
default: "%a, %d %b %Y %H:%M:%S %z"
long: "%B %d, %Y %H:%M"
short: "%d %b %H:%M"
pm: pm<file_sep>Rails.application.routes.draw do
resources :coins
resources :cryptos
devise_for :people
devise_for :users
get '/about' => 'static_pages#about'
get '/history' => 'static_pages#history'
get '/lookup' => 'static_pages#lookup'
post '/lookup' => 'static_pages#lookup'
root to: "home#index"
end
| d9a2ab45f6b86045d05a39833e07ddb2d9602e85 | [
"HTML+ERB",
"Markdown",
"Ruby",
"YAML",
"ApacheConf"
] | 34 | HTML+ERB | pestovpvl/bitcoinbtn | cfae601fd760a705dcd8e01e5d1e36fe143202e9 | 630b9d9b40dbc2f700d5977943f372d2680315b1 |
refs/heads/master | <file_sep># USFS-ForestInventoryAnalysis
This repository contains data management/wrangling scripts I wrote while employed as a post-graduate research associate at N.C. State University in Fall 2017.
| 6ccaccdd80af3f7939f20cb591cfb93e5be9d9f4 | [
"Markdown"
] | 1 | Markdown | tghays/USFS-ForestInventoryAnalysis | f9e9045d06e45b5f541a05866dc1a2abf126eaef | 2bff4cb386a51f2a3ecf9e6a48a37cc99ff06cbb |
refs/heads/master | <file_sep>import os
import socket
import sys
import threading
from select import select
with socket.socket() as socket:
socket.connect(('localhost', os.environ['PORT']))
def read_input(socket):
while True:
message = input('> ')
socket.send(message.encode('utf-8'))
read_input_thread = threading.Thread(target=read_input, args=(socket,))
read_input_thread.start()
while True:
data = socket.recv(1024)
if not data:
break
print(data.decode('utf-8'))
<file_sep>import socket
import threading
clients = []
def broadcast_msg(msg, conn):
for c in clients:
if c is not conn:
try:
c.send(msg.encode('utf-8'))
except:
c.close()
if c in clients:
clients.remove(c)
with socket.socket() as socket:
address, port = 'localhost', 9999
socket.bind((address, port))
print(f'bound ({address}, {port})')
print('accepting connection')
socket.listen()
while True:
conn, client_address = socket.accept()
clients.append(conn)
def handle_client_connection(conn, addr):
with conn:
while True:
data = conn.recv(1024)
if not data:
break
msg = f'> {addr}: {data.decode("utf-8")}'
print(msg)
broadcast_msg(msg, conn)
threading.Thread(target=handle_client_connection, args=(conn, client_address)).start()
<file_sep>altgraph 0.17
atomicwrites 1.3.0
attrs 19.3.0
autopep8 1.4.4
certifi 2020.4.5.1
click 7.1.1
colorama 0.4.3
cycler 0.10.0
entrypoints 0.3
flake8 3.7.9
Flask 1.1.1
future 0.18.2
itsdangerous 1.1.0
Jinja2 2.11.1
kiwisolver 1.0.1
macholib 1.11
MarkupSafe 1.1.1
matplotlib 3.1.3
mccabe 0.6.1
mkl-fft 1.0.15
mkl-random 1.1.0
mkl-service 2.3.0
more-itertools 8.2.0
numpy 1.18.1
packaging 20.3
pefile 2019.4.18
pip 20.0.2
pluggy 0.13.1
psutil 5.7.0
py 1.8.1
pycodestyle 2.5.0
pycryptodome 3.8.2
pyflakes 2.1.1
PyInstaller 3.6
pyparsing 2.4.6
pytest 5.3.5
python-dateutil 2.8.1
pywin32 227
pywin32-ctypes 0.2.0
setuptools 44.0.0.post20200106
sip 4.19.13
six 1.14.0
tornado 6.0.4
wcwidth 0.1.8
Werkzeug 1.0.1
wheel 0.34.2
wincertstore 0.2 | 3f21ee8fc74abedde92ae37de63a4923b560aab3 | [
"Text",
"Python"
] | 3 | Text | zvikfir/python-course-chat | a5827c10218a50831d8df52c96636403d7591fc1 | f777882988b23aab3b97ea98d293f4bd38c9a834 |
refs/heads/master | <repo_name>ysh3940/v2ray<file_sep>/README.md
## 搭建v2ray的步骤大体如下:<br>
1、购买一个VPS,购买后你会获得VPS的IP、root用户及密码、SSH端口等信息。<br>
2、登录VPS,可以借助Xshell这个工具。<br>
3、安装v2ray,使用xshell成功登录VPS后,开始搭建。<br>
4、在你的设备上配置与VPS对应的v2ray信息,就可以成功使用了。<br>
## 一、环境信息<br>
服务器系统: 搬瓦工(BandwagonHost) Centos 7 x86_64 bbr<br>
v2ray版本:v4.20.0<br>
客户端系统:Windows 10<br>
VPS:我使用的是BandwagonHost 基本套餐 CN2<br>
## 二、购买VPS及使用xshell进行远程连接<br>
使用xshell进行远程连接需要VPS的IP、端口、用户密码等信息,这些信息在成功购买VPS后会获得这些信息。<br>
## 三、搭建v2ray<br>
假设你已经使用root用户登录成功了。下面开始安装:<br>
1.安装wget<br>
在登录完成的窗口输入下面命令并回车进行wget安装:yum -y install wget<br>
2.下载脚本<br>
安装完wget之后就可以进行下载安装v2ray的脚本了,输入如下命令并回车:wget https://install.direct/go.sh<br>
3.安装unzip<br>
因为centos不支持apt-get,我们需要安装unzip:yum install -y zip unzip <br>
4.执行安装<br>
bash go.sh<br>
5.相关命令<br>
在首次安装完成之后,V2Ray不会自动启动,需要手动运行上述启动命令。而在已经运行V2Ray的VPS上再次执行安装脚本,安装脚本会自动停止V2Ray 进程,升级V2Ray程序,然后自动运行V2Ray。在升级过程中,配置文件不会被修改。<br>
# 启动<br>
systemctl start v2ray<br>
# 停止<br>
systemctl stop v2ray<br>
# 重启<br>
systemctl restart v2ray<br>
# 开机自启<br>
systemctl enable v2ray<br>
关于软件更新:更新 V2Ray 的方法是再次执行安装脚本!再次执行安装脚本!再次执行安装脚本!<br>
6.配置<br>
如果你按照上面的命令执行安装完成之后,服务端其实是不需要再进行任何配置的,配置文件位于/etc/v2ray/config.json,使用cat /etc/v2ray/config.json查看配置信息。接下来进行客户端配置就行了。<br>
说明:<br>
配置文件中的id、端口、alterId需要和客户端的配置保持一致。<br>
服务端使用脚本安装成功之后默认就是vmess协议。<br>
配置完成之后重启v2ray。<br>
7.防火墙开放端口<br>
有的vps端口默认不开放,可能导致连接不成功,如果有这种情况。<br>
# 查看已开放端口<br>
firewall-cmd --zone=public --list-ports<br>
# 添加开放端口<br>
firewall-cmd --zone=public --add-port=80/tcp --permanent<br>
可能上面设置后还是没用,简单粗暴就是直接关闭防火墙,我就是这么操作的!
## 四、Windows 客户端<br>
1.下载<br>
这里使用的是Windows图形界面v2rayN,当前版本(2020年2月9日)是3.5版本,下载地址:https://github.com/2dust/v2rayN/releases<br>
也可以去这个地址下载:https://tlanyan.me/v2ray-clients-download/<br>
iPhone客户端下载:链接:https://pan.baidu.com/s/1CSt5evmETg4DYsqgjrLFKw 密码:<PASSWORD><br>
注: 如果你用的是旧版本的v2rayN,可能还需要下载 v2ray-windows-64.zip ,并将v2ray-windows-64.zip和v2rayN.zip解压到同一文件夹。<br>
然后运行V2RayN.exe即可。<br>
2.配置<br>
运行V2RayN.exe,然后进行配置,下图中的配置信息,需要和你VPS搭建的时候的配置信息对应,VPS的v2ray配置信息位于/etc/v2ray/config.json文件里。<br>
如果采用上面的默认方式安装,服务端配置是协议vmess,则配置如下:<br>
https://img.snailshub.com/images/2019/02/10/new-vmess-config.jpg<br>
https://img.snailshub.com/images/2019/02/10/vmess-windows-client.jpg<br>
账号:私信我
| b88bbacb4efd5ade979fb0d04bf8a4bfd94212cb | [
"Markdown"
] | 1 | Markdown | ysh3940/v2ray | 93cc5d0b28054906b16da27a71fae3208ee690a3 | 32a964553cc73a1a2a0831738faa05fdb9175714 |
refs/heads/master | <file_sep>#!/bin/bash
rm -rf deploy/ && hyde gen && find deploy && git status deploy/ && git diff deploy && echo -e '\033[32mTEST PASSED\033[0m' || echo -e '\033[31mTEST FAILED\033[0m'
<file_sep>---
id: 2012-12-03-comments-disabled
title: Comments disabled
comments: False
---
This post has 'comments' metadata attribute set to False.
It won't display any comment related information.
<file_sep>---
title: Disqus comments
id: disqus-based-post
extends: disqusblog.j2
disqus: canvoki
---
You can combine in the same blog post based on static comments with posts managed with Disqus.
Just switch the extended template and provide a Disqus account as metadata.
This way you can still run your existing disqus comments without migrating data to the static way.
<file_sep>from hyde.plugin import Plugin
import re
import hashlib
import urllib
"""
This plugin enables the rendering of static comments,
by making available, as metadata, comment info
stored as independent source files for each comment.
"""
# TOTEST:
# - If inreplyto and thread defined, takes inreplyto as replyto
# - Neither inreplyto nor thread available -> AttributeError
# - Just inreplyto -> thread = inreplyto
# - Just thead -> inreplyto = thread
# - inreplyto and thead -> no change
# - Repeated comment id
# - nested comments
# - ncomments in nested comments
# - meta.comments = True enables them
# - avatar when
# - valid email
# - invalid email
# - explicit image provided
# - changing default via meta
# - Sorting comments by date
# - Threads
# - Counting despite the threads
class CommentsPlugin(Plugin) :
def __init__(self, site) :
super(CommentsPlugin, self).__init__(site)
self._stripMetaRE = re.compile(
r"^\s*(?:---|===)\s*\n((?:.|\n)+?)\n\s*(?:---|===)\s*\n*",
re.MULTILINE)
def begin_site(self) :
def contentWithoutMeta(r) :
text = r.source_file.read_all()
match = re.match(self._stripMetaRE, text)
return text[match.end():]
def commentAvatar(c) :
if hasattr(c.meta, 'avataruri') and c.meta.avataruri :
return c.meta.avataruri
if hasattr(c.meta, 'image') and c.meta.image :
return c.meta.image
gravatar_default = c.node.meta.gravatar_default if 'gravatar_default' in c.node.meta else 'mm'
return gravatarFromEmail(c.meta.authoremail, gravatar_default) or None
def gravatarFromEmail(email, default='mm', size=32) :
"""Given an email address composes the gravatar image uri.
default says which strategy use when not found.
https://en.gravatar.com/site/implement/images/
"""
md5 = hashlib.md5(email.lower().encode("utf-8")).hexdigest()
return ( "http://www.gravatar.com/avatar/" + md5 + "?"
+ urllib.urlencode({
'd':default,
's':str(32)
}))
# compile dicts of posts and comments by id
comments = {}
posts = {}
for r in self.site.content.walk_resources() :
if r.source_file.kind == 'comment' :
if 'id' not in r.meta.to_dict() :
self.logger.debug("Not id for comment %s"%r)
id = str(r.meta.id)
if id in comments :
raise ValueError(
"Repeated comment id '%s' in comments %s and %s" %(
id, r, comments[id]))
comments[id] = r
else :
if 'id' not in r.meta.to_dict() : continue
id = str(r.meta.id)
if id in posts :
raise ValueError(
"Repeated post id '%s' in comments %s and %s" %(
id, r, posts[id]))
posts[id] = r
# Initialize comment related fields on posts
for post in posts.values() :
post.ncomments = 0
post.comments = []
# Setting computed fields on comments
for comment in comments.values() :
comment.thread_children = []
comment.is_processable = False
comment.meta.listable=False
comment.uses_template=False
comment.text = contentWithoutMeta(comment)
comment.meta.avataruri = commentAvatar(comment)
def connectComment(comment, inreplyto) :
self.logger.debug("Comment found: %s replying %s"%(r,inreplyto))
if inreplyto in comments :
comments[inreplyto].thread_children.append(comment)
elif inreplyto in posts :
posts[inreplyto].comments.append(comment)
else:
raise ValueError(
"Comment %s refering to an invalid resource '%s'" %(
r, inreplyto))
# Build the thread tree
for comment in comments.values() :
if 'inreplyto' in comment.meta.to_dict() :
inreplyto = str(comment.meta.inreplyto)
connectComment(comment, inreplyto)
elif 'thread' in comment.meta.to_dict() :
thread = str(comment.meta.thread)
connectComment(comment, thread)
comment.meta.inreplyto = thread
else :
raise ValueError(
"Comment %s is missing either a 'thread' or 'inreplyto' meta attribute to be related"%(
comment))
# Sort by date and count comments
def recursiveSort(comments) :
for comment in comments :
recursiveSort(comment.thread_children)
comments.sort(key=lambda x : x.meta.published)
def recursiveCount(comments) :
return sum((recursiveCount(c.thread_children) for c in comments), len(comments))
def recursiveDepend(post, comments) :
post.depends.extend( (
comment.relative_path
for comment in comments
if comment.relative_path not in post.depends
))
for comment in comments :
recursiveDepend(post, comment.thread_children)
for post in posts.values() :
recursiveSort(post.comments)
post.ncomments = recursiveCount(post.comments)
if not hasattr(post, 'depends'):
post.depends = []
recursiveDepend(post, post.comments)
<file_sep><?php
$debug = 0;
$from_address = "<EMAIL>";
$to_address = "<EMAIL>";
$subject = "[Hyde comments] New comment received";
$debug and ini_set('display_errors', 'On');
$debug and error_reporting(E_ALL | E_STRICT);
function badRequest($message = "Error 400: Bad Request")
{
header("HTTP/1.1 400 Bad Request");
echo $message;
exit();
}
if (! isset($_SERVER['HTTP_REFERER'])) badRequest();
$referrer = $_SERVER['HTTP_REFERER'];
if ($debug)
{
echo '<pre>';
var_dump($_POST);
}
class MissingField extends Exception
{
function __construct($field)
{
parent::__construct("Missing field '$field'");
}
};
/// Safely retrieves post data or throws unless a default value is provided
function post($field, $default=Null)
{
if (!isset($_POST[$field]))
{
if (!is_null($default)) return $default;
throw new MissingField($field);
}
if (empty($_POST[$field]) and !is_null($default))
return $default;
return $_POST[$field];
}
function sluggify($string)
{
$result = preg_replace('/[^A-Za-z0-9-]+/', '-', $string); // Weird into '-'
$result = preg_replace('/--*/', '-', $result); // Collapse multiple '-'
$result = preg_replace('/-$/', '', $result); // Remove '-' at ending
$result = preg_replace('/^-/', '', $result); // Remove '-' at begining
return $result;
}
date_default_timezone_set("UTC");
$time = date("Y-m-d H:i:s");
$slug_time = date("Ymd-His");
$title_excerpt_size=20;
$random_hash = md5(rand());
try
{
$comment = post('comment');
$title_excerpt = substr($comment, 0, strpos(wordwrap($comment, $title_excerpt_size), "\n"));
$thread = post('thread');
$inreplyto = post('inreplyto');
$author = post('name');
$authoremail = post('email');
// Optional params
$authoruri = post('website', "");
$title = post('title', $title_excerpt);
}
catch (MissingField $e)
{
badRequest($e->getMessage());
}
$short_hash = substr($random_hash,-6);
$id = sluggify("$thread-$slug_time-$short_hash-$title");
$comment_file = <<<EOF
---
id: '$id'
thread: '$thread'
inreplyto: '$inreplyto'
title: '$title'
published: !!timestamp '$time'
updated: !!timestamp '$time'
author: "$author"
authoruri: $authoruri
authoremail: $authoremail
---
$comment
EOF;
if ($debug)
{
echo $comment_file;
echo '</pre>';
}
$message = <<<EOF
--Multipart-boundary-$random_hash
Content-Type: text/plain; charset="utf-8
Someone commented you post at:
$referrer
To incorporate such comment into your blog,
save the attached file into the content folder
and regenerate the blog with Hyde.
Author: $author
Email: $authoremail
Website: $authoruri
Title: $title
Content:
------------------
$comment
------------------
Sincerely,
your PHP backend for the Hyde static comments plugin.
--Multipart-boundary-$random_hash
Content-Type: text/yaml; name="$id.comment"; charset="utf-8"
Content-Disposition: attachment
$comment_file
EOF;
if (! $debug )
{
$ok = @mail(
$to_address,
$subject,
$message,
join("\r\n",array(
"From: $from_address",
"Reply-To: $from_address",
"Content-Type: multipart/mixed; boundary=\"Multipart-boundary-$random_hash\""
))
);
if ($ok)
{
echo <<<EOF
<html>
<head> <meta charset="utf-8" /> </head>
<body>
<p>Thanks. Your comment was properly submitted.
</p><p>
Do not expect the comments to appear immediately in the post
as they have to wait for author's moderation.</p>
<p><a href='$referrer'>Back to the post</a></p>
</body>
</html>
EOF;
}
else
{
echo <<<EOF
<html>
<head> <meta charset="utf-8" /> </head>
<body>
<p>We are sorry. There was a problem submiting your comment.
</p><p>
Below you have the content of your comment so that you can copy it and submit it later.</p>
<pre>
Title: $title
------------------
$comment
------------------
</pre>
<p><a href='$referrer'>Back to the post</a></p>
</body>
</html>
EOF;
}
}
?>
<file_sep>hyde-comments: Static comments for Hyde static web generator
============================================================
What?
-----
This is an extension of [Hyde] static web generator to incorporate
comments into your blog post while retaining both data and
simple server requirements.
The idea is that comments are stored as plain text files along
with your post text files and they are combined either on
generation time or in rendering time using JavaScript.
This extension is in early stage and many things are to be defined.
You can participate on the decisions by contributing.
Why?
----
Most people using static blog generators either don't have comments
or they have to rely on external services such as [Disqus].
Such services allow hosting comments and display them by
adding an static javascript code to your template.
So, why that approach is not enough?
You should read the following [post][JeckyllStaticCommentsPost] by <NAME>
the author of an equivalent extension for [Jeckyll][Jeckyll] (Ruby based alter ego of Hyde).
In summary:
* I want to have control over my data. I don't want to rely on an external service.
* I want my blogging tools be free software (as in freedom, not gratis)
Documentation
-------------
Currently, the behaviour of the extension is not yet well-defined.
Please, meanwhile rely on the examples which are pretty explanatory and on (glups!) the code.
Status
------
What works:
- Posts include comments information provided as separate comment files
- Comment files (.comment) can be placed anywhere in the content folder.
- They are related to their post assigning 'comment.meta.thread' to 'post.meta.id'
- Templates can acces the list of post comments by accessing 'post.comments'
- Nested comments:
- Comments are nested assigning 'child.meta.inreplyto' to 'parent.meta.id'
- Top level comments just set 'child.meta.inreplyto' to the post id.
- Children comments are available as 'parent.meta.children'
- Comment template with stylable classes
- Disabling or enabling comments in a post via meta.comment = True/False
- Author avatars
- Gravatar based on 'authoremail' if available.
- Configurable [fallback gravatar](http://en.gravatar.com/site/implement/images/)
- Explicit avatar from either 'image' or 'avataruri' metas.
- Comment submission form (a web 1.0 one :-( )
- Comment submission backend in php, that sends the comment file back to the author.
- The author has to save it and regenerate the web site.
- You can place the backend in a different hosting if you want. Just change the submission URI in 'meta.comment_handler_uri':.
- Light-coupled: It is easily reimplementable in whatever language/framework your hosting allows.
- If you want to automate more things, like regeneration or comment storage, all futs under the same API.
- Post generation depends on its comments.
- Fixed: Links are not generated when no author website is provided.
What is to be implemented (TO-DO's):
- AJAX based comment submission form
- Generation can be threaded but there is no means yet to submit threaded comments by replying a given comment
- Adding optional avatar field (upload or uri?)
- Disabling comments submission via 'meta.commentsclosed' = True
- Security concerns on comment content
- Strip html tags
- Spam links
- Email addresses
- Spam tools
- Moderation by accepting a checksum
- Pre-moderation with akismet
- Unassisted automatic generation
- Client side rendering
- Generation of json data for comments
- Regeneration of comment index json files when moderated
- Dynamically building comments with javascript
- Combine it with existing comments
- JSON data tolerance (don't destroy existing comments when JSON data is missing)
- Pingback
- Likes
Want to help? [Fork it in GitHub][GitHupHydeComments].
Design forces
-------------
### Comment rendering
How/when to render the comments within a post?
* During blog generation
* On browser via JavaScript
The first option can be implemented by adding special files to the site content,
that can be detected by extension or metadata.
Building the comments as part of the site structure
and rendering them by a template
The second option could be implemented
by placing static [JSON] files for comments on a given URL
and querying them from the post page.
There could be an index JSON file for each post with the URL's of the related comments which could be independent files.
The first option has the drawback that it has to be generated each time a comment is added.
The second option has the drawback that it requires JavaScript and that the crawlers (Google) cannot index comments content.
Also, the JavaScript option can add a feature to auto-reload the comments for updates.
This feature indeed opens a third hybrid option:
* Statically generating comments which are available on generation time and updating them on browser.
This way if there is no JavaScript you still have the comments
crawlers have the static content available for rendering
and users can see the comments without waiting for the site to be regenerated.
### Comment submission
This part of the comment system requires server side scripting at least to receive the comments.
But the use of static web generators is often motivated by reasons such as:
* Reducing the server load.
* Being able to place the web whatever the languages provided by a given hosting.
The first motivation discourages the use of heavy duty server scripts.
The second one discourages from attaching the user to a given language and framework setup.
Nevertheless many users that are happy with that if some tasks are being conveniently automated.
We are not that constrained if we realize that:
- Adding a comment is an infrequent task compared to page views, so the load is less than the one of a dynamic website if you want to compare with that.
- We can place the submission script in a different host than the static website. Hosting restrictions and load can be reduced that way.
- If they are simple enough, we can provide, with the same API, different back-ends that do different things using different technologies.
So what kind of things could do a back-end:
- Sending an attached comment file by mail to the author so that she can store it and regenerate the website by hand.
- Storing the comment on the site and notifying the author so that she can regenerate the blog.
- Storing and regenerating the blog (convenient but dangerous)
- Validating the author email (sending an email to the author so she can confirm the comment via a confirmation url)
- Filtering for spam with Akismet or similar
- Log-in, account management...
[Hyde]: http://ringce.com/hyde
[Disqus]: http://disqus
[JeckyllStaticCommentsPost]: http://hezmatt.org/~mpalmer/blog/2011/07/19/static-comments-in-jekyll.html
[Jeckyll]: http://jekyllrb.com/
[JSON]: http://json.org
[GitHupHydeComments]: https://github.com/vokimon/hyde-comments
<file_sep>{% extends "blog.j2" %}
{% block css %}
{{ super() }}
<link rel="stylesheet" href="{{ media_url('css/comments.css') }}">
{% endblock css %}
{%- macro renderThread(comments) %}
{% if comments %}
<ul class='comment-thread'>
{% for comment in comments | sort(attribute='meta.published') %}
<li class='comment' id='{{ comment.meta.id }}'>
<div class='comment-head'>
{% if comment.meta.authoruri %}
<a class='comment-avatar' target='_'
href='{{comment.meta.authoruri|default("#")}}'>
<img
style='max-height:32px;max-width:32px;'
src='{{comment.meta.avataruri}}' /></a>
<a class='comment-author' target='_'
href='{{comment.meta.authoruri}}'>{{
comment.meta.author
}}</a>
{% else %}
<span class='comment-avatar'><img style='max-height:32px;max-width:32px;' src='{{comment.meta.avataruri}}' /></span>
<span class='comment-author'>{{ comment.meta.author }}</span>
{% endif %}
<div class='comment-title'>{{comment.meta.title}}</div>
<div class='comment-reply'><a href='#commentform' onclick='setCurrentReply("{{comment.meta.id}}", "{{comment.meta.title}}");'>Reply</a></div>
<div class='comment-timestamp'>{{comment.meta.published}}</div>
</div>
<div class='comment-text'>
{{ comment.text | markdown }}
</div>
{{- renderThread(comment.thread_children) }}
</li>
{% endfor%}
</ul>
{% endif %}
{% endmacro %}
{% block comments %}
{%- if resource.meta.comments %}{# comments enabled in metadata? #}
<h2>Comments</h2>
<script>
<!--
function setCurrentReply(comment,title)
{
document.getElementById("inreplyto").setAttribute("value",comment);
document.getElementById("comment-title").setAttribute("value","Re: "+title);
}
-->
</script>
<h3>{{ resource.ncomments }} comments.</h3>
{{ renderThread(resource.comments) }}
<h3>Leave a comment</h3>
<div class='comment-form'>
<form id="commentform" method="POST" accept-charset='utf-8' action="{{ resource.meta.comment_handler_uri|default("/commentsubmit.php") }}">
<input type="hidden" name="thread" value="{{resource.meta.id}}" />
<input type="hidden" name="inreplyto" value="{{resource.meta.id}}" id='inreplyto' />
<input type="hidden" name="return_url" value="{{ site.full_url(resource.get_relative_deploy_path()) }}" />
<div class='comment-form-content'>
<div class='comment-form-title'>
<input
type="text"
placeholder='A subject'
size="25"
name="title"
id='comment-title'
/>
<label for='title'>Subject</label> (optional)
</div>
<div class='comment-form-text'>
<textarea
name="comment"
placeholder='Leave a comment...'
rows="6" cols="60"
required='yes'
>
</textarea>
</div>
</div>
<div class='comment-form-identify'>
<div class='comment-form-name'>
<input
type="text"
placeholder='Your name'
size="25"
required="yes"
name="name"
/>
<label for='name'>Name</label>
</div>
<div class='comment-form-email'>
<input
type="email"
placeholder='<EMAIL>'
size="25"
name="email"
required="yes"
/>
<label for='email'>E-mail</label> (not published)
</div>
<div class='comment-form-website'>
<input type="url" placeholder='http://yourdomain.com' size="25" name="website" />
<label for='website'>Website</label> (optional)
</div>
{# Should be display:none so that just bots fill it #}
<div id='yuemail'>
<input
type="email"
placeholder='<EMAIL>'
size="25"
name="yuemail"
id='yuemail'
/>
</div>
<div class='comment-form-submit'>
<input type="submit" name="submit" value="Submit Comment" />
</div>
</div>
</form>
<div class='clear'></div>
</div>
{%- endif %}
{% endblock comments %}
| 7513ed165c542079c55f2d18fe2b389969fe7c17 | [
"Shell",
"HTML",
"Markdown",
"Jinja",
"Python",
"PHP"
] | 7 | Shell | vokimon/hyde-comments | 8099da7da23616f8676876f8fc2ef204848dd89a | aeb93aea2392c5ae45df8f18befcf01d78b51413 |
refs/heads/master | <file_sep>hello-world2
============
My first repository on GitHub
c'est le fichier sur lequel je travail je peut même metre du code dans le fichier ?
| 7a9051f5a2657800a555d11ef2491699873af850 | [
"Markdown"
] | 1 | Markdown | Ouddy/hello-world2 | 04e933d4d2b3cc6ec2ab878ffa756c7bfaf3b7f7 | cc607fe427ee514789ac31f4439511de134a53a6 |
refs/heads/master | <file_sep>//
// ViewController.h
// MyQRCodeReader
//
// Created by <NAME> on 26/05/14.
// Copyright (c) 2014 <NAME>. All rights reserved.
//
#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>
@interface ViewController : UIViewController <AVCaptureMetadataOutputObjectsDelegate>
@end
<file_sep>//
// ViewController.m
// MyQRCodeReader
//
// Created by <NAME> on 26/05/14.
// Copyright (c) 2014 <NAME>. All rights reserved.
//
#import "ViewController.h"
#import <AVFoundation/AVFoundation.h>
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIView *previewUIView;
@property (weak, nonatomic) IBOutlet UILabel *readStatusLabel;
@property (weak, nonatomic) IBOutlet UIBarButtonItem *StartBarButton;
@property (strong, nonatomic) AVCaptureSession * captureSession;
@property (strong, nonatomic) AVCaptureVideoPreviewLayer * videoPreviewLayer;
@property (strong, nonatomic) AVAudioPlayer * audioPlayer;
@property (nonatomic) BOOL isReading;
@end
@implementation ViewController
#pragma mark -
#pragma mark View Life Cycle
- (void)viewDidLoad
{
[super viewDidLoad];
self.isReading = NO;
self.captureSession = nil;
[self loadBeepSoundWhenFinishReadQRCode];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
#pragma mark -
#pragma mark Start Read QR Code
- (BOOL)startReading
{
NSError *error;
// add device camera
AVCaptureDevice *captureDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
return YES;
AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:captureDevice error:&error];
if (!input) {
NSLog(@"%@", [error localizedDescription]);
return NO;
}
self.captureSession = [[AVCaptureSession alloc] init];
[self.captureSession addInput:input];
AVCaptureMetadataOutput * captureMetadataOutput = [[AVCaptureMetadataOutput alloc] init];
[self.captureSession addOutput:captureMetadataOutput];
// create dispatch queue totally used by this task
dispatch_queue_t dispatchQueue;
dispatchQueue = dispatch_queue_create("myQueue", NULL);
[captureMetadataOutput setMetadataObjectsDelegate:self
queue:dispatchQueue];
[captureMetadataOutput setMetadataObjectTypes:[NSArray arrayWithObject:AVMetadataObjectTypeQRCode]];
self.videoPreviewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:self.captureSession];
[self.videoPreviewLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
[self.videoPreviewLayer setFrame:self.previewUIView.layer.bounds];
[self.previewUIView.layer addSublayer:self.videoPreviewLayer];
[self.captureSession startRunning];
}
-(void)stopReading
{
[self.captureSession stopRunning];
self.captureSession = nil;
[self.videoPreviewLayer removeFromSuperlayer];
}
- (void)loadBeepSoundWhenFinishReadQRCode
{
NSString * beepFilePath = [[NSBundle mainBundle] pathForResource:@"beep" ofType:@"mp3"];
NSURL * beepURL = [NSURL URLWithString:beepFilePath];
NSError * error;
self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:beepURL
error:&error];
if (error) {
NSLog(@"Could not play beep mp3 file.");
NSLog(@"%@",[error localizedDescription]);
}
else {
[self.audioPlayer prepareToPlay];
}
}
#pragma mark-
#pragma mark AVCaptureMetadataOutputObjects Delegate
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection
{
if ((metadataObjects !=nil) && [metadataObjects count] > 0) {
AVMetadataMachineReadableCodeObject * metadataObj = [metadataObjects objectAtIndex:0];
if ([[metadataObj type]isEqualToString:AVMetadataObjectTypeQRCode])
{
// since we preform on secondary thread so here need to perform on main thread
[self.readStatusLabel performSelectorOnMainThread:@selector(setText:) withObject:[metadataObj stringValue] waitUntilDone:NO];
[self performSelectorOnMainThread:@selector(stopReading)
withObject:nil
waitUntilDone:NO];
[self.StartBarButton performSelectorOnMainThread:@selector(setText:)
withObject:@"Srart!!"
waitUntilDone:NO];
self.isReading = NO;
if (self.audioPlayer) {
[self.audioPlayer play];
}
}
}
}
#pragma mark-
#pragma mark Actions
- (IBAction)startStopReadQRCode:(id)sender
{
if (!self.isReading) {
if ([self startReading]) {
[self.StartBarButton setTitle:@"Stop"];
[self.readStatusLabel setText:@"Scanning QR Code..."];
}
} else {
[self stopReading];
[self.StartBarButton setTitle:@"Start"];
[self.readStatusLabel setText:@"QR Code is not Running yet ><"];
}
self.isReading = !self.isReading;
}
@end
| 3b0a42d33f0ddd9c12101d5e802e584caebd732a | [
"Objective-C"
] | 2 | Objective-C | shanshan33/MyQRCodeReader | eb0b660f6ef043bf1e3fc95fac38f6fd2d9d814e | d5d96c051853871c58dee684959a0acfbf698af9 |
refs/heads/master | <file_sep># hello-world
Just another respository
This is a test document
| 3e6f17701cc3dc1371c8c0f73b07c4b5313e1208 | [
"Markdown"
] | 1 | Markdown | kumradhika/hello-world | d7c038110459029be9006c88dc5a1a5de04e86db | 5816cd44411d639dac2d4437a8bcd85643ec730f |
refs/heads/master | <file_sep>set -x
aws lambda update-function-code --function-name greeting-function --zip-file fileb://target/lambda-demo-1.0-SNAPSHOT.jar
<file_sep>set -x
aws lambda delete-function --function-name quarkus-greeting-native-function
<file_sep>set -x
aws lambda delete-function --function-name quarkus-spring-greeting-function
<file_sep>set -x
aws lambda delete-function --function-name quarkus-spring-greeting-native-function
<file_sep>aws lambda delete-function --function-name greeting-native-function<file_sep>if [ -z "$LAMBDA_ROLE" ]
then
echo "You must set LAMBDA_ROLE env var. Exiting..."
exit
fi
set -x
aws lambda create-function --function-name quarkus-greeting-native-function --zip-file fileb://target/function.zip --handler any.name.not.used --runtime provided --role $LAMBDA_ROLE --environment Variables="{DISABLE_SIGNAL_HANDLERS=true}"
<file_sep>aws lambda delete-function --function-name greeting-function<file_sep>set -x
aws lambda delete-function --function-name greeting-function
<file_sep>set -x
aws lambda update-function-code --function-name quarkus-spring-greeting-native-function --zip-file fileb://target/function.zip
<file_sep>set -x
aws lambda update-function-code --function-name quarkus-spring-greeting-function --zip-file fileb://target/spring-lambda-demo-quarkus-1.0-SNAPSHOT-runner.jar
<file_sep>if [ -z "$LAMBDA_ROLE" ]
then
echo "You must set LAMBDA_ROLE env var. Exiting..."
exit
fi
set -x
aws lambda create-function --function-name quarkus-spring-greeting-function --zip-file fileb://target/spring-lambda-demo-quarkus-1.0-SNAPSHOT-runner.jar --handler io.quarkus.amazon.lambda.runtime.QuarkusStreamHandler::handleRequest --runtime java8 --role $LAMBDA_ROLE
<file_sep>if [ -z "$LAMBDA_ROLE" ]
then
echo "You must set LAMBDA_ROLE env var. Exiting..."
exit
fi
set -x
aws lambda create-function --function-name greeting-function --zip-file fileb://target/lambda-demo-1.0-SNAPSHOT.jar --handler org.demo.GreetingLambda::handleRequest --runtime java8 --role $LAMBDA_ROLE
| e3602ae4c654b577ba9e4d10bc140dc0a755a530 | [
"Shell"
] | 12 | Shell | patriot1burke/quarkus-serverless-demos | 3b91b894aaa0293c812613eea0b8d8859240afa2 | ecd5711d4ee90618781463bffed5ba78f92d1cda |
refs/heads/main | <repo_name>Zhanadil1509/store-on-nuxt<file_sep>/pages/index.vue
<template>
<NuxtLink to="/">Home</NuxtLink>
</template>
<template>
<main class="container">
<h1>Home Page</h1>
<NuxtLink to="/about">About</NuxtLink>
</main>
</template>
<script>
export default {}
</script>
<style>
.container {
margin: 0 auto;
min-height: 100vh;
display: flex;
justify-content: center;
align-items: center;
text-align: center;
}
</style>
<file_sep>/components/Header.vue
<template>
<nav @click="navSlide">
<ul class="nav-links">
<li><NuxtLink to="/">Home</NuxtLink></li>
<li><NuxtLink to="/about">About</NuxtLink></li>
<li><NuxtLink to="/work">Work</NuxtLink></li>
<li><NuxtLink to="/projects">Projects</NuxtLink></li>
</ul>
<div class="burger">
<div class="line1"></div>
<div class="line2"></div>
<div class="line3"></div>
</div>
</nav>
</template>
<script>
export default {
methods: {
navSlide: () => {
const burger = document.querySelector('.burger');
const nav = document.querySelector('.nav-links');
const navLinks = document.querySelectorAll('.nav-links li')
burger.addEventListener('click', () => {
// Toggle Nav
nav.classList.toggle('nav-active');
// Animate links
navLinks.forEach( (links, index) => {
if(links.style.animation) {
links.style.animation = '';
} else {
links.style.animation = `navLinkFade .5s ease forwards ${index / 7 + .3}s`;
}
});
// Burger animation
burger.classList.toggle('toggle');
});
}
}
}
</script>
<style scoped>
nav {
display: flex;
font-family: 'Poppins', sans-serif;
justify-content: space-around;
align-items: center;
background-color: #5D4954;
min-height: 8vh;
overflow-x: hidden;
}
.nav-links {
display: flex;
justify-content: space-around;
width: 30%;
overflow-x: hidden;
}
.nav-links li {
list-style: none;
}
.nav-links a {
color: rgb(219, 219, 219);
text-decoration: none;
letter-spacing: 3px;
font-weight: bold;
font-size: 14px;
}
.burger {
display: none;
}
.burger div{
width: 25px;
height: 3px;
background-color: rgb(219, 219, 219);
margin: 5px;
transition: all 0.3s ease;
}
@media screen and (max-width: 1024px) {
/* Increase space between nav elements */
.nav-links {
width: 40%;
}
}
@media screen and (max-width: 768px) {
body {
overflow-x: hidden;
}
/* Nav for mobile */
.nav-links {
position: absolute;
right: 0px;
height: 92vh;
top: 8vh;
background-color: #5D4954;
flex-direction: column;
align-items: center;
width: 40%;
transform: translateX(100%);
transition: transform 0.5s ease-in;
}
.nav-links li {
opacity: 0;
}
.burger {
display: block;
cursor: pointer;
}
}
/* Classes deactivated by default */
.nav-active {
transform: translateX(0%);
}
@keyframes navLinkFade {
from {
opacity: 0;
}
to {
opacity: 1;
transform: translateX(0px);
}
}
</style>
| caa9f790b81fce247881b7eb1328fb47c82b7d84 | [
"Vue"
] | 2 | Vue | Zhanadil1509/store-on-nuxt | 63ba2c69f5c7f306aac0d64e567140b2076b777c | 1e90567e2c8e339b8dc0f35ba52ed1d77efe6111 |
refs/heads/main | <repo_name>uc-ahmednu/it3038c-scripts<file_sep>/lab9/lab9.py
import json
import requests
r = requests.get('http://localhost:3000')
data = r.json()
first =(data[0]["name"])
first_ = (data[0]["color"])
print(first + " is " + first_)
second =(data[1]["name"])
second_ = (data[1]["color"])
print(second + " is " + second_)
third =(data[2]["name"])
third_ = (data[2]["color"])
print(third + " is " + third_)
fourth =(data[3]["name"])
fourth_ = (data[3]["color"])
print(fourth + " is " + fourth_)
#Widget is blue
#Widget is green
#Widget whatever is whatever<file_sep>/Labs/Lab5.py
#Input birthday date and print out how many seconds old
import datetime
print("Lets See How Many Days, Hours, and Second you lived in Mother Earth")
print("Enter Your Birthday Year")
Years =int(input("Years: "))
print("Enter Your Birthday Month")
Months = int(input("Months: "))
print("Enter Your Day of Birth")
Days = int(input("Days: "))
Seconds = Years * 24 *60 *60 *365 + Months * 30 *60 + Days *60
print("You have lived in mother earth", Seconds, "Seconds chilling in this pandemic life")<file_sep>/Project1/README.md
My APP
=====
# Hello professor and git hub community. This is my my first project 1 for my scripting class and I tried to create a script that outputs my workstation stoarge space. For your reference I used shutil module from the global API which has a disk usage function. I hope you all enjoyed my code and if you have any questions or concerns let me know.
```javascript
Javascript code block to highlight whats happening in my code<file_sep>/Project2/snake_game1.py
# Simple Snake Game in Python 3 for Beginners
# Prepared by Nur with the refrence of TokyoEdTech
# Part 1: Getting Starting
import turtle
import time
import random
delay = 0.1
# Score
score= 0
high_score = 0
# Set up the screen
wn = turtle.Screen()
wn.title("Snake hero by Nur AKA Legiontroy")
wn.bgcolor("Red")
wn.setup(width=600, height=600)
wn.tracer(0) # Turns off screen updates
# Snake head
head = turtle.Turtle()
head.speed(0)
head.shape("square")
head.color("black")
head.penup()
head.goto(0,0)
head.direction = "stop"
# Snake food
# Snake head
food = turtle.Turtle()
food.speed(0)
food.shape("circle")
food.color("green")
food.penup()
food.goto(0,100)
segments = []
# Pen
pen = turtle.Turtle()
pen.speed(0)
pen.shape("square")
pen.color("white")
pen.penup
pen.hideturtle()
pen.goto(0, 260)
pen.write("Score: 0 High Score: 0", align="center", font=("Courier", 24, "normal"))
# Functions
def go_up():
if head.direction != "down":
head.direction = "up"
def go_down():
if head.direction != "up":
head.direction = "down"
def go_right():
if head.direction != "left":
head.direction = "right"
def go_left():
if head.direction != "right":
head.direction = "left"
def move():
if head.direction == "up":
y = head.ycor()
head.sety(y + 20)
if head.direction == "down":
y = head.ycor()
head.sety(y - 20)
if head.direction == "left":
x = head.xcor()
head.setx(x - 20)
if head.direction == "right":
x = head.xcor()
head.setx(x + 20)
# Keyboard bindings
wn.listen()
wn.onkeypress(go_up, "w")
wn.onkeypress(go_down, "s")
wn.onkeypress(go_right, "d")
wn.onkeypress(go_left, "a")
# Main game loop
while True:
wn.update()
# Check for a collision with the border
if head.xcor()>290 or head.xcor()<-290 or head.ycor()>290 or head.ycor()<-290:
time.sleep(1)
head.goto(0.0)
head.direction = "stop"
# Hide the segments
for segment in segments:
segment.goto(1000,1000)
# Clear the segments list
segments.clear()
#Reset score
score = 0
pen.clear()
pen.write("Score: {} High Score: {}".format(score, high_score), align="center", font=("Courier", 24, "normal"))
# Cehck for a collision with the food
if head.distance(food) < 20:
# Move the food to a random spot
x = random.randint(-290, 290)
y = random.randint(-290, 290)
food.goto(x,y)
# Add a segment
new_segment = turtle.Turtle()
new_segment.speed(0)
new_segment.shape("square")
new_segment.color("grey")
new_segment.penup()
segments.append(new_segment)<file_sep>/FinalProject3.py
import random
# Creates variables for random numbers
odd_number = random.randint(1,10)
tries = 1
# Users will input their name to play a game
name = input("Hi, Tell me your Name ")
print("Hello", name+",", )
question = input("Would you Like Play a Number Guessing Game ? [Y/N] ")
if question == "n":
print("no worries")
# Creates loop for the main game
if question == "y":
print("Say A Number Between 1 & 10")
guess = int(input("Do you want to give a try : "))
if guess > odd_number:
print("Guess Lower than ", guess)
if guess < odd_number:
print("Guess Higher than ", guess)
# Do while loop that continues to check for the correct answer
while guess != odd_number:
tries += 1
guess = int(input("Try Again : "))
if guess == odd_number:
print("Yay, correct! It Was", odd_number, "and it only", tries, "tries!")
<file_sep>/Project2/README.md
My APP
=====
# Hello professor and git hub community. This is my second project 2 for my scripting class and I tried to create a snake game with the help of TokyoEdTech and my peer classmates that outputs the game. For your reference I used module from the global API which has a function. I hope you all enjoyed my code and if you have any questions or concerns let me know.
```javascript
Javascript code block to highlight whats happening in my code<file_sep>/Lab8/stawrs.py
# import of non-built=in modules to make http requests
import requests
from bs4 import BeautifulSoup
# get html from site
url ='https://www.starwars.com/news/15-star-wars-quotes-to-use-in-everyday-life'
response = requests.get(url)
headers = response.headers
body = response.text[:2000]
# drill down into html to grab desired info -- quotes and "authors" of said quoteshtml = BeautifulSoup(response.text, 'html.parser')
quotes = html.findAll('strong')
#print (quotes)
# clean up data -- remove unwanted html and make it more readable
for quote in quotes:
text_only_quote = quote.text
print(text_only_quote)<file_sep>/Powershell/sysinfo.ps1
$Hello = "Hello, powershell"
Write-Host($Hello)
function getIP {
(Get-NetIPAddress).IPv4Address | Select-String "192"
}
write-host(getIP)
$IP = getIP
$Date = Get-Date
$Body = "This machine's IP is $IP. user is $env:username. Hostname is $env:COMPUTERNAME. PowerShell Version. Today's date is $DATE"
write-host($Body)
| e339247e4a4575acfdcb0627ac741506878b71ae | [
"Markdown",
"PowerShell",
"Python"
] | 8 | Markdown | uc-ahmednu/it3038c-scripts | 13d78957f1bf1880621d12fce1d37bd71a36e27a | 44a421d7b26beda15df4975e393490b49130ba87 |
refs/heads/master | <file_sep>'''
Created on 2017.1.8
@author: lq
'''
import sys
import time
import uuid
import json
import logging
import Queue
import threading
from config import load_config
from logging.handlers import RotatingFileHandler
from flask import Flask, request
app = Flask(__name__)
config = load_config()
mutex = threading.Lock()
class master():
def __init__(self, num = 10):
self.threadNum = num
self.timeout = 30
self.threadList = []
self.availableAccQu= Queue.Queue()
self.queueInUse = Queue.Queue()
self.accountInfo = {}
self.infoList = config.accounts_list
self.addAccountsInQueue(self.accountInfo, self.availableAccQu, self.infoList)
#add acc in queue
def addAccountsInQueue(self, ac, qu, li):
for item in li:
#ac available dict
if item not in ac.values():
# set accounts, only
if item in self.infoList:
logging.info("-------------add acc to available queue------------")
logging.info(str(item))
guuid = uuid.uuid1()
qu.put(guuid)
ac[guuid] = item
#polling interface
def waitCondition(self, delayTime, timeOut, condition, msg = ""):
tm = 0
assert(delayTime > 0)
assert(timeOut > delayTime)
while tm < timeOut:
if condition(tm):
if msg != "":
logging.info(msg)
return True
tm = tm + delayTime
time.sleep(delayTime)
return False
def run(self):
#start thread
for i in range(self.threadNum):
print i
self.threadList.append(threading.Thread(target=self.timeoutProcessThreadFunc, args = ()))
for p in self.threadList:
p.start()
p = threading.Thread(target=self.infoReportThread, args=())
p.start()
app.add_url_rule('/account', 'account', self.msgTransformFunc, methods = ['GET', 'POST'])
app.run(host='0.0.0.0', port='12345')
def infoReportThread(self):
logging.info("------info report thread start------ ")
while True:
logging.info("--------------available accounts------------------")
for item in self.accountInfo.values():
logging.info(item)
time.sleep(10)
#timeout thread
def timeoutProcessThreadFunc(self):
logging.info("------timeout thread start------")
while True:
acc = self.queueInUse.get()
condition = lambda s:acc in self.accountInfo.values()
result = self.waitCondition(1, self.timeout, condition)
if not result:
li = []
logging.warning("----------Timeout,release accounts-------------")
logging.warning(acc["admin"])
li.append(acc)
self.addAccountsInQueue(self.accountInfo, self.availableAccQu, li)
li.remove(acc)
#data process func
def msgTransformFunc(self):
if request.method == 'GET':
acc = {}
if self.availableAccQu.empty():
logging.warning('all accounts are in ues[msgTransformFunc]')
return json.dumps({"error": "all accounts are in use"})
#get acc from local dict
guuid = self.availableAccQu.get()
acc = self.accountInfo[guuid]
#add to in use que
logging.info("----------------------get acc---------------------")
logging.info(acc["admin"])
self.accountInfo.pop(guuid)
self.queueInUse.put(acc)
return json.dumps(acc)
elif request.method == 'POST':
li = []
li.append(json.loads(request.data))
print type(json.loads(request.data))
logging.info("---------------------release acc-----------------------")
logging.info(json.loads(request.data)["admin"])
self.addAccountsInQueue(self.accountInfo, self.availableAccQu, li)
return request.data
return json.dumps({"error": "request error"})
if __name__ == '__main__':
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
datefmt='%a, %d %b %Y %H:%M:%S',
filename=sys.path[0] + '/log.log',
filemode='w')
Rthandler = RotatingFileHandler('log.log', maxBytes=2*1024*1024,backupCount=5)
Rthandler.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
Rthandler.setFormatter(formatter)
logging.getLogger('').addHandler(Rthandler)
streamHandler = logging.StreamHandler()
streamHandler.setLevel(logging.DEBUG)
streamHandler.setFormatter(formatter)
logging.getLogger('').addHandler(streamHandler)
obj = master()
obj.run()
<file_sep># -*- coding: utf-8 -*-
import json
import sys
from requests import post as requests_post
from config import load_config
config = load_config()
access_token = config.access_token
class DingTalk(object):
url = 'https://oapi.dingtalk.com/robot/send'
headers = {'Content-type': 'application/json', 'Accept': 'application/json'}
def __init__(self, access_token, url=None):
if url is not None:
self.url = url
self.access_token = access_token
def send(self, json_data):
req = requests_post(self.url, data=json.dumps(json_data),
headers=self.headers,
params={'access_token': self.access_token})
return req.json()
def text_message(self, text, at=[], at_all=False):
json_data = {
"msgtype": "text",
"text": {
"content": text
}
}
if at or at_all:
if not isinstance(at, list):
at = [at]
json_data['at'] = {
"atMobiles": at,
"isAtAll": at_all
}
return self.send(json_data)
def link_message(self, title='', text='', message_url='', pic_url=''):
json_data = {
"msgtype": "link",
"link": {
"title": title,
"text": text,
"picUrl": pic_url,
"messageUrl": message_url
}
}
return self.send(json_data)
def markdown_message(self, title, text):
json_data = {
"msgtype": "markdown",
"markdown": {
"title": title,
"text": text
}
}
return self.send(json_data)
def usage():
return '''1. dingtalk "content for output"
2. dingtalk "content for output" warn|info telephone
3. dingtalk "content for output" critical'''
def Ding(content, lvl='warn', tel=''):
if tel == '' and lvl != 'critical':
ding_talk = DingTalk(access_token)
ding_talk.text_message(content)
elif tel != '' and lvl != 'critical':
ding_talk = DingTalk(access_token)
ding_talk.text_message(content, at=[tel])
elif lvl == 'critical':
ding_talk = DingTalk(access_token)
ding_talk.text_message(content, at_all=True)
else:
print usage()
if __name__ == '__main__':
#Ding("a s & *", lvl='error')
Ding("i have a pen,")
#Ding("下雨了", tel='')
#Ding("下雨了*", lvl='critical')
<file_sep>class Config(object):
accounts_list = [{"admin":"", "password":""}]
acc_timeout = 610
access_token = ''
<file_sep>'''
Created on 2017.1.8
@author: lq
'''
import sys
import time
import uuid
import json
import logging
import Queue
import threading
from config import load_config
from logging.handlers import RotatingFileHandler
from flask import Flask, request
from ding_talk import Ding
app = Flask(__name__)
config = load_config()
mutex = threading.Lock()
class master():
def __init__(self):
self.threadList = []
self.timeoutPollList = []
self.availableAccQu= Queue.Queue()
self.accountInfo = {}
self.infoList = config.accounts_list
self.timeout = config.acc_timeout
self.addAccountsInQueue(self.accountInfo, self.availableAccQu, self.infoList)
def byteify(self, obj):
if isinstance(obj, dict):
res = {}
for key, value in obj.iteritems():
res = dict(res, **{self.byteify(key): self.byteify(value)})
return res
#return {self.byteify(key): self.byteify(value) for (key, value) in obj.iteritems()}
elif isinstance(obj, list):
res = []
for i in obj:
res.append(self.byteify(i))
return res
#return [self.byteify(element) for element in obj]
elif isinstance(obj, unicode):
return obj.encode('utf-8')
else:
return obj
#add acc in queue
def addAccountsInQueue(self, ac, qu, li):
for item in li:
item = self.byteify(item)
acc = dict(admin=item['admin'], password=item['password'])
#ac available dict
global mutex
try:
if mutex.acquire():
if acc not in ac.values():
# set accounts, only
if acc in self.infoList:
logging.info("-------------add acc to available queue------------")
logging.info(str(acc))
guuid = uuid.uuid1()
ac[guuid] = acc
qu.put(guuid)
mutex.release()
except Exception as e:
logging,info(e)
mutex.release()
def run(self):
#start thread
pf = threading.Thread(target=self.addAccInPollListFunc, args = ())
p = threading.Thread(target=self.infoReportThread, args=())
p.start()
pf.start()
app.add_url_rule('/account', 'account', self.msgTransformFunc, methods = ['GET', 'POST'])
app.add_url_rule('/bindAcc', 'bindAcc', self.bindFunc, methods = ['POST'])
app.run(host='0.0.0.0', port='12345')
def infoReportThread(self):
logging.info("------info report thread start------ ")
while True:
logging.info("--------------available accounts------------------")
for item in self.accountInfo.values():
logging.info(item)
time.sleep(120)
#timeout thread
def addAccInPollListFunc(self):
logging.info("------timeout thread start------")
while True:
time.sleep(1)
try:
for index, item in enumerate(self.timeoutPollList):
if item["timeout"]<1:
self.timeoutPollList.remove(item)
acc = item["account"]
warnStr = "Account occupancy timeout, case:{0}, acc:{1}".format(item.get('case', 'invalued'), acc['admin'])
Ding(warnStr)
li = []
li.append(acc)
logging.warning("------Timeout------")
logging.warning(acc)
self.addAccountsInQueue(self.accountInfo, self.availableAccQu, li)
self.timeoutPollList[index]["timeout"] = self.timeoutPollList[index]["timeout"] -1
except IndexError:
pass
except Exception as e:
logging.warning(e)
#bind func
def bindFunc(self):
logging.info("---------------------bind acc and case ---------------------")
if request.method == 'POST':
res = {}
flag = False
res = json.loads(request.data)
res = self.byteify(res)
for i, item in enumerate(self.timeoutPollList):
if item['account']['admin']==res['admin']:
try:
self.timeoutPollList[i]["case"] = res['case']
flag = True
break
except IndexError:
pass
if flag:
logging.info('bind success! case info:{0}, acc info: {1}'.format(res['case'], res['admin']))
else:
logging.warning('bing failed! case info:{0}, acc info: {1}'.format(res['case'], res['admin']))
return json.dumps({'code': 500, 'msg': "acc {0} not exist in polling list".format(res['admin'])})
return json.dumps({'code': 200, 'msg': ""})
else:
return json.dumps({'code':400,'msg':'request error'})
#data process func
def msgTransformFunc(self):
if request.method == 'GET':
acc = {}
if self.availableAccQu.empty():
logging.warning('all accounts are in ues[msgTransformFunc]')
return json.dumps({"error": "all accounts are in use"})
#get acc from local dict
guuid = self.availableAccQu.get()
acc = self.accountInfo[guuid]
#add to in use que
logging.info("----------------------get acc---------------------")
logging.info(acc["admin"])
self.accountInfo.pop(guuid)
self.timeoutPollList.append(dict(timeout=self.timeout, account=acc))
return json.dumps(acc)
elif request.method == 'POST':
li = []
res = {}
res = json.loads(request.data)
res = self.byteify(res)
li.append(res)
logging.info("---------------------release acc-----------------------")
logging.info(res)
for item in self.timeoutPollList:
if res['admin'] == item["account"]['admin']:
self.timeoutPollList.remove(item)
break
self.addAccountsInQueue(self.accountInfo, self.availableAccQu, li)
return request.data
return json.dumps({"error": "request error"})
if __name__ == '__main__':
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
datefmt='%a, %d %b %Y %H:%M:%S',
filename=sys.path[0] + '/log.log',
filemode='w')
Rthandler = RotatingFileHandler('log.log', maxBytes=2*1024*1024,backupCount=5)
Rthandler.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
Rthandler.setFormatter(formatter)
logging.getLogger('').addHandler(Rthandler)
streamHandler = logging.StreamHandler()
streamHandler.setLevel(logging.DEBUG)
streamHandler.setFormatter(formatter)
logging.getLogger('').addHandler(streamHandler)
obj = master()
obj.run()
<file_sep>accounts distribute policy
python for accounts distribute policy
Config
you should touch a default.py for config,
# default.py
class Config(object):
accounts_list = [{"admin":"XXXX", "password":"<PASSWORD>"},{"admin":"XXXX", "password":"<PASSWORD>"}]
acc_timeout = 620
#acc_timeout : account is in use, when the timeout is reach, acc is forced to release
there are two policy
| c0d19313eecfbef5ee189b4486a41dc01593e7d7 | [
"Markdown",
"Python"
] | 5 | Markdown | liuqiang2017/myproject | 8e7bb62173640fe28c52c586542b833f5f818fb4 | 5a60fb38cdcf0c027dd6a7f9f73f398361e68070 |
refs/heads/master | <file_sep>[{"descripcion":"jugar","completado":true},{"descripcion":"dormir","completado":false}]<file_sep>## Aplicación de comandos
Es necesario aplicar el siguiente comando antes de correr la aplicación:
```
npm install
``` | 21c15117a4c707c9a95de8acd3cb6e202815fd26 | [
"Markdown",
"JSON"
] | 2 | Markdown | jesusamaro25/node-to-do | 2e3bdf83855997aedb943d4e5f0359e8db6860e6 | 9a74abe22ffe5e9ce3012692e010600e8223ee5b |
refs/heads/master | <repo_name>carloszapata/CRUD---extjs<file_sep>/README.md
CRUD---extjs
============
CRUD DEMO
| 7ebc6d0b0d69e661f38e30506d14d15ab8b9e1d1 | [
"Markdown"
] | 1 | Markdown | carloszapata/CRUD---extjs | c7ae66e3fea9c67b20f9be13742a48724ec568f9 | 2d3ca13fa5ec86af456b8620fc45a66a0f6a9f79 |
refs/heads/master | <file_sep>#!/bin/sh
SettingsFile=/home/CouchBot/BotSettings.json
rm $SettingsFile
echo "" > $SettingsFile
echo "{" >> $SettingsFile
echo " \"Keys\": {" >> $SettingsFile
echo " \"DiscordToken\": \"DIS<PASSWORD>\"," >> $SettingsFile
echo " \"TwitchClientId\": \"TWITCHID\"," >> $SettingsFile
echo " \"YouTubeApiKey\": \"YOUTUBEAPI\"," >> $SettingsFile
echo " \"ApiAiKey\": \"APIAIKEY\"" >> $SettingsFile
echo " }," >> $SettingsFile
echo " \"BotConfiguration\": {" >> $SettingsFile
echo " \"CouchBotId\": 0," >> $SettingsFile
echo " \"Prefix\": \"\"," >> $SettingsFile
echo " \"TotalShards\": 1," >> $SettingsFile
echo " \"OwnerId\": 0" >> $SettingsFile
echo " }," >> $SettingsFile
echo " \"Directories\": {" >> $SettingsFile
echo " \"ConfigRootDirectory\": \"/home/CouchBot/Data/\"," >> $SettingsFile
echo " \"UserDirectory\": \"Users\"," >> $SettingsFile
echo " \"GuildDirectory\": \"Guilds\"," >> $SettingsFile
echo " \"LiveDirectory\": \"Live\"," >> $SettingsFile
echo " \"MixerDirectory\": \"Mixer\"," >> $SettingsFile
echo " \"PicartoDirectory\": \"Picarto\"," >> $SettingsFile
echo " \"SmashcastDirectory\": \"/Smashcast/\"," >> $SettingsFile
echo " \"TwitchDirectory\": \"/Twitch/\"," >> $SettingsFile
echo " \"YouTubeDirectory\": \"/YouTube/\"" >> $SettingsFile
echo " }," >> $SettingsFile
echo " \"Platforms\": {" >> $SettingsFile
echo " \"EnableMixer\": true," >> $SettingsFile
echo " \"EnableSmashcast\": true," >> $SettingsFile
echo " \"EnableTwitch\": true," >> $SettingsFile
echo " \"EnableYouTube\": true," >> $SettingsFile
echo " \"EnablePicarto\": true," >> $SettingsFile
echo " \"EnableVidMe\": true" >> $SettingsFile
echo " }," >> $SettingsFile
echo " \"Intervals\": {" >> $SettingsFile
echo " \"Picarto\": 120," >> $SettingsFile
echo " \"Smashcast\": 120," >> $SettingsFile
echo " \"Twitch\": 300," >> $SettingsFile
echo " \"TwitchFeed\": 300," >> $SettingsFile
echo " \"YouTubePublished\": 900," >> $SettingsFile
echo " \"YouTubeLive\": 300," >> $SettingsFile
echo " \"VidMe\": 900" >> $SettingsFile
echo " }" >> $SettingsFile
echo "}" >> $SettingsFile
| 58e54b0f60add7cc2f8742a729a94b96c4868103 | [
"Shell"
] | 1 | Shell | DeltaC99/CouchBot-Directory-Fixer | 313b136ac6d87230af57f7c7199539b7e36a96fc | 4138a0b38869ff14324a1b55e68b05fb73b48b3a |
refs/heads/main | <repo_name>myujjawal/CourseraWebD_JH<file_sep>/module2/README.md
# Coursera-WebD-JH | b281c4fc0bcaccdaff9a3210675101ae3dab740a | [
"Markdown"
] | 1 | Markdown | myujjawal/CourseraWebD_JH | e9679753adeaafabbf728cd44dafc0ec9606e8ad | 428cb9813b393c611ab4d6160f889dc590ee35da |
refs/heads/master | <file_sep>#This part is intened for further programming. They are not supposed to be used as I now only set up the informal partial workflow. When the formal overall flow is desired to be implemented, this part should be used as global virables setting
flagPE='' #pair end or single end
dir_output='/'
dir_samtool='/hwfssz1/ST_META/CD/zhujie/program/bioenv/bin/samtools/bwa'
dir_clean=''
dir_IDBA_fq2fa='/zfssz3/ST_META/ST_META/USER/wangzhifeng1/software/idba-master/bin/fq2fa'
dir_IDBA_ud='/hwfssz1/ST_META/F15HQSB1SY2332_Chicken_LSS/06.profile/Abundance/depth/IDBA-Meta/idba-master/bin/idba_ud'
dir_Metabat='/hwfssz1/ST_META/PN/zhangsuyu/Monkeys/metabat/bin/runMetaBat.sh'
dir_Checkm-'/hwfssz1/ST_META/PN/zhangsuyu/Monkeys/CheckM-master/bin/checkm'
#This is the main of the program. To configure the list of sample,create a samplelist in the same directory of the script, or give absolute dir. One line per sample name.
#1.clean data 2.IDBA 3.METABETA 4.Checkm 5.Refinem
def main():
file=open('sampleconfigure','r')
listtemp=file.readlines()
samplelist=[]
datalist=[]
for each in listtemp:
samplelist.append(each.split(' ')[0])
datalist.append(each.split(' ')[1][:-1])
for i in range(len(samplelist)):
file=open(str(str(samplelist[i])+'.sh'),'w')
file.write('source activate Bacgenome')
file.write('\n')
file.write(bam_index(str(samplist[i]),str(datalist[i])))
file.write(iden_genome(str(samplist[i]),str(datalist[i])))
file.write(outliers(str(samplist[i]),str(datalist[i])))
file.write(gene_filter(str(samplist[i]),str(datalist[i])))
file.write(callgene(str(samplist[i]),str(datalist[i])))
file.write(tax_pro(str(samplist[i]),str(datalist[i])))
file.write(iden_tax(str(samplist[i]),str(datalist[i])))
file.write(tax_filter(str(samplist[i]),str(datalist[i])))
file.write(iden_16s(str(samplist[i]),str(datalist[i])))
file.write(filter_16s(str(samplist[i]),str(datalist[i])))
file.close()
file=open('qsub.sh','w')
for each in samplelist:
file.write('qsub -cwd -P F15HQSB1SY2332 -q st.q -l vf = 16G, num_proc =16 ')
file.write(str(str(each)+'.sh'))
file.write('\n')
file.close()
#create contigs with IDBA
def IDBA(samplename,directory,flagPE):
if flagPE=='Yes' or flagPE=='yes' or flagPE=='YES':
temp=dir_IDBA_fq2fa+' --merge ' + directory[0] +'/clean/'+samplename+'.clean.1.fa'+ ' ' + directory[1]+'/clean/'+samplename+'.clean.2.fa' + ' ' + dir_output +'IDBA/'+ samplename +'.fa\n'
temp+=dir_IDBA_ud+' -r '+ dir_output+'IDBA/' + samplename +'.fa'+ ' -o ' + dir_output +'IDBA/'+ samplename + ' --mink 20 --num_threads 10'
else:
temp=dir_IDBA_ud+' -r '+ dir_output +'IDBA/'+ samplename +'.fa'+ ' -o ' + dir_output+'IDBA/' + samplename + ' --mink 20 --num_threads 10'
return temp
def bwa(samplename,directory,flagPE):
if flagPE=='Yes' or flagPE=='yes' or flagPE=='YES':
temp=dir_samtool+ ' index ' + dir_output +'IDBA/'+ samplename +'/contig.fa\n'
temp+=dir_samtool + ' mem -t -5 '+ dir_output+'IDBA/' + samplename +'/contig.fa' + ' ' + directory[0]+'/clean/'+samplename+'.clean.1.fa'+' ' + directory[1]+'/clean/'+samplename+'.clean.2.fa' + ' > ' + dir_output +'/bwa/'+ samplename+'_mem-pe.sam\n'
temp+=dir_samtool[:-4] +' view -bS ' + dir_output +'/bwa/'+ samplename+'_mem-pe.sam' + ' > ' + dir_output +'/bwa/'+ samplename+'_mem-pe.bam\n'
temp+=dir_samtool[:-4] +' sort ' + dir_output +'/bwa/'+ samplename+'_mem-pe.bam' + ' > ' + dir_output +'/bwa/'+ samplename+'_mem-pe.sort.bam\n'
temp+='rm '+ dir_output +'/bwa/'+ samplename+'_mem-pe.sam\n'
temp+='rm '+dir_output +'/bwa/'+ samplename+'_mem-pe.bam\n'
else:
temp=dir_samtool+ ' index ' + dir_output+'IDBA/' + samplename +'/contig.fa\n'
temp+=dir_samtool + ' mem -t -5 '+ dir_output+'IDBA/' + samplename +'/contig.fa' + ' ' + directory+'/clean/'+samplename+'.clean.fa' ' > ' + dir_output +'/bwa/'+ samplename+'_mem-se.sam\n'
temp+=dir_samtool[:-4] +' view -bS ' + dir_output +'/bwa/'+ samplename+'_mem-se.sam' + ' > ' + dir_output +'/bwa/'+ samplename+'_mem-se.bam\n'
temp+=dir_samtool[:-4] +' sort ' + dir_output +'/bwa/'+ samplename+'_mem-se.bam' + ' > ' + dir_output +'/bwa/'+ samplename+'_mem-se.sort.bam\n'
temp+='rm '+ dir_output +'/bwa/'+ samplename+'_mem-se.sam\n'
temp+='rm '+dir_output +'/bwa/'+ samplename+'_mem-se.bam\n'
return temp
#This part is the dirtectories for MetaBeta the auto binning of contigs. At this time dirlist should be included with '{}'
def dirmaker(dirlist):
temp='mkdir '+ dirlist + ' -p\n'
return temp
#This part is the dirtectories for MetaBeta the auto binning of contigs
def Metabat(samplename,directory):
temp=dir_Metabat+' '+directory+'/IDBA/'+samplename+'/contig.fa'+' '+directory+'/bwa/'+samplename+'_mem-se.sort.bam'
return temp
#This is the Checkm part of the program.
def Checkm(samplename,metadir,domain,datatype,ckmoutput):
temp=dir_Checkm+' lineage_wf '+ ' -x '+datatype + ' -t '+'8 '+metadir+samplename +' '+ckmoutput+'/linage\n'
#/hwfssz1/ST_META/CD/zhujie/program/bioenv/bin/samtools index bam.file
def bam_index(samplename, directory):
temp=dir_samtool+' index '+directory
temp+=dir_output+ 'bwa/' + samplename+'_mem-pe.sort.bam\n'
return temp
#>refinem scaffold_stats -c 16 <scaffold_file> <bin_dir> <stats_output_dir> <bam_files>
def iden_genome(samplename, directory):
temp=''
temp+='refinem scaffold_stats -c 16 -x fa ' + directory + 'IDBA_'+samplename+'/contig.fa '
temp+=directory+'checkm_dir_all/'+samplename+'.contig.fa.metabat-bins '
temp+='/ldfssz1/ST_META/P17Z10200N0048_PRO_ZYQ/zhangsuyu/haoyunze/overallflow/'+samplename+'/scaffold '
temp+=dir_output + 'bwa/'+samplename+'_mem-pe.sort.bam'
temp+='\n'
return temp
#>refinem outliers <stats_output_dir>/scaffold_stats.tsv <outlier_output_dir>
def outliers(samplename):
directory='/ldfssz1/ST_META/P17Z10200N0048_PRO_ZYQ/zhangsuyu/haoyunze/overallflow/'
temp='refinem outliers '+ directory+samplename+'/scaffold/scaffold_stats.tsv '+ directory+samplename+'/outliers\n '
return temp
#>refinem filter_bins <bin_dir> <outlier_output_dir>/outliers.tsv <filtered_output_dir>
def gene_filter(samplename):
temp='refinem filter_bins -x fa '
temp += '/ldfssz1/ST_META/P17Z10200N0048_PRO_ZYQ/zhangsuyu/Recovery8000/eightsamples/checkm_dir_all/'+samplename+'.contig.fa.metabat-bins '
temp += '/ldfssz1/ST_META/P17Z10200N0048_PRO_ZYQ/zhangsuyu/haoyunze/overallflow/'+samplename+'/outliers/outliers.tsv '
temp += '/ldfssz1/ST_META/P17Z10200N0048_PRO_ZYQ/zhangsuyu/haoyunze/overallflow/'+samplename+'/filtergene\n '
return temp
#>refinem call_genes -c 40 bins <bin_dir> <gene_output_dir>
def callgene(samplename):
temp='refinem call_genes -c 16 -x fa ' + '/ldfssz1/ST_META/P17Z10200N0048_PRO_ZYQ/zhangsuyu/Recovery8000/eightsamples/checkm_dir_all/'+samplename+'.contig.fa.metabat-bins '
temp += '/ldfssz1/ST_META/P17Z10200N0048_PRO_ZYQ/zhangsuyu/haoyunze/overallflow/'+samplename+'/calledgenes\n'
return temp
#>refinem taxon_profile -c 40 <gene_output_dir> <stats_output_dir>/scaffold_stats.tsv <reference_db> <reference_taxonomy> <taxon_profile_output_dir>
def tax_pro(samplename):
temp='refinem taxon_profile -c 16 ' + '/ldfssz1/ST_META/P17Z10200N0048_PRO_ZYQ/zhangsuyu/haoyunze/overallflow/'+samplename+'/calledgenes '
temp+='/ldfssz1/ST_META/P17Z10200N0048_PRO_ZYQ/zhangsuyu/haoyunze/overallflow/'+samplename+'/scaffold/scaffold_stats.tsv '
temp+='/hwfssz1/ST_META/PN/haoyunze/Database/genome_db.2017-11-09.genes.faa /hwfssz1/ST_META/PN/haoyunze/Database/gtdb_r80_taxonomy.2017-12-15.tsv '
temp+='/ldfssz1/ST_META/P17Z10200N0048_PRO_ZYQ/zhangsuyu/haoyunze/overallflow/'+samplename+'/taxpro\n'
return temp
#>refinem taxon_filter -c 40 <taxon_profile_dir> taxon_filter.tsv
def iden_tax(samplename):
temp='refinem taxon_filter -c 16 '+ '/ldfssz1/ST_META/P17Z10200N0048_PRO_ZYQ/zhangsuyu/haoyunze/overallflow/'+samplename+'/taxpro /ldfssz1/ST_META/P17Z10200N0048_PRO_ZYQ/zhangsuyu/haoyunze/overallflow/'+samplename+'/taxpro/taxon_filter.tsv\n'
return temp
#>refinem filter_bins <bin_dir> <taxon_output_dir>/taxon_filter.tsv <filtered_output_dir>
def tax_filter(samplename):
temp='refinem filter_bins -x fa '
temp += '/ldfssz1/ST_META/P17Z10200N0048_PRO_ZYQ/zhangsuyu/haoyunze/overallflow/'+samplename+'/filtergene '
temp += '/ldfssz1/ST_META/P17Z10200N0048_PRO_ZYQ/zhangsuyu/haoyunze/overallflow/'+samplename+'/taxpro/taxon_filter.tsv '
temp += '/ldfssz1/ST_META/P17Z10200N0048_PRO_ZYQ/zhangsuyu/haoyunze/overallflow/'+samplename+'/filtertax \n'
return temp
#>refinem ssu_erroneous <bin_dir> <taxon_profile_dir> <ssu_db> <reference_taxonomy> <ssu_output_dir>
def iden_16s(samplename):
temp='refinem ssu_erroneous -x fa '
temp+='/ldfssz1/ST_META/P17Z10200N0048_PRO_ZYQ/zhangsuyu/haoyunze/overallflow/'+samplename+'/filtertax '
temp+='/ldfssz1/ST_META/P17Z10200N0048_PRO_ZYQ/zhangsuyu/haoyunze/overallflow/'+samplename+'/taxpro '
temp+='/hwfssz1/ST_META/PN/haoyunze/Database/gtdb_r80_ssu_db.2018-01-18.fna /hwfssz1/ST_META/PN/haoyunze/Database/gtdb_r80_taxonomy.2017-12-15.tsv '
temp+='/ldfssz1/ST_META/P17Z10200N0048_PRO_ZYQ/zhangsuyu/haoyunze/overallflow/'+samplename+'/16s\n'
return temp
#>refinem filter_bins <bin_dir> <16s_output_dir>/ssu_erroneous.tsv <filtered_output_dir>
def filter_16s(samplename):
temp='refinem filter_bins -x fa '
temp += '/ldfssz1/ST_META/P17Z10200N0048_PRO_ZYQ/zhangsuyu/haoyunze/overallflow/'+samplename+'/filtertax '
temp+='/ldfssz1/ST_META/P17Z10200N0048_PRO_ZYQ/zhangsuyu/haoyunze/overallflow/'+samplename+'/16s/ssu_erroneous.tsv '
temp+='/ldfssz1/ST_META/P17Z10200N0048_PRO_ZYQ/zhangsuyu/haoyunze/overallflow/'+samplename+'/filter16s\n '
return temp
main()
<file_sep>dir_samtool='/hwfssz1/ST_META/CD/zhujie/program/bioenv/bin/samtools/bwa'
dir_clean='/hwfssz1/ST_META/F15HQSB1SY2332_Chicken_LSS/01.filter/bin/bin/readsFilter.dev.pl'
dir_IDBA_fq2fa='/zfssz3/ST_META/ST_META/USER/wangzhifeng1/software/idba-master/bin/fq2fa'
dir_IDBA_ud='/hwfssz1/ST_META/F15HQSB1SY2332_Chicken_LSS/06.profile/Abundance/depth/IDBA-Meta/idba-master/bin/idba_ud'
dir_Metabat='/hwfssz1/ST_META/PN/zhangsuyu/Monkeys/metabat/bin/'
def bwa(SampleID,fqID,fqPath):
print("SampleID",SampleID)
print("fqID",fqID)
print("fqPath",fqPath)
return None
dir_clean='/hwfssz1/ST_META/F15HQSB1SY2332_Chicken_LSS/01.filter/bin/bin/readsFilter.dev.pl'
def clean(fq,prefix):
#fq1,fq2 <prefix> <qt> <limit> <N num> <qf> <lf>
temp='perl '+dir_clean+' '+fq+'1.fq.gz,'+fq+'2.fq.gz '+prefix+' 20 10 1 15 15 30'
return temp
dir_rmhost='/hwfssz1/ST_META/F15HQSB1SY2332_Chicken_LSS/01.filter/bin/bin/rmhost_v1.2.pl'
def rmhost(fq,work_DIR,host_database):
temp='perl '+dir_rmhost+' -a '+fq+'1.fq.gz -b '+fq+'2.fq.gz -c '+fq+'.single.fq.gz -d '+host_database+' -D 4 -s 30 -r 1 -m 100 -x 600 -v 7 -i 0.9 -t 6 -f Y -q 1 -p '+work_DIR['02.rmhost']+'/'+fq
return temp
#create contigs with IDBA
dir_IDBA_fq2fa='/zfssz3/ST_META/ST_META/USER/wangzhifeng1/software/idba-master/bin/fq2fa'
dir_IDBA_ud='/hwfssz1/ST_META/F15HQSB1SY2332_Chicken_LSS/06.profile/Abundance/depth/IDBA-Meta/idba-master/bin/idba_ud'
def IDBA(samplename,work_DIR,flagPE):
if flagPE=='Yes' or flagPE=='yes' or flagPE=='YES':
temp=dir_IDBA_fq2fa+' --merge ' + work_DIR['02.rmhost']+'/'+samplename+'.clean.1.fa'+ ' ' + work_DIR['02.rmhost']+'/'+samplename+'.rmhost.2.fa' + ' ' + work_DIR['03.assembly'] +'/'+ samplename +'.fa\n'
temp+=dir_IDBA_ud+' -r '+ work_DIR['03.assembly'] + '/' + samplename +'.fa'+ ' -o ' + work_DIR['03.assembly'] + '/' + samplename + ' --mink 20 --num_threads 10\n'
temp+='cd '+work_DIR['03.assembly']+'\n'
temp+="ls |grep -vE '(contig.fa|scaffold.fa)'|xargs rm\n"
else:
temp=dir_IDBA_ud+' -r '+ work_DIR['03.assembly'] + '/' + samplename +'.fa' + ' -o ' + work_DIR['03.assembly'] + '/' + samplename + ' --mink 20 --num_threads 10\n'
temp+='cd '+work_DIR['03.assembly']+'\n'
temp+="ls |grep -vE '(contig.fa|scaffold.fa)'|xargs rm\n"
return temp
dir_bwa='/zfssz3/ST_META/ST_META/USER/xuxiaoqiang/xuxiaoqiang/software/bwa-master/bwa-master/bwa'
dir_samtools='/hwfssz1/ST_META/CD/zhujie/program/bioenv/bin/samtools'
def bwa(samplename,work_DIR,flagPE):
if flagPE=='Yes' or flagPE=='yes' or flagPE=='YES':
temp='cd '+ work_DIR['02.rmhost']+'\n'
temp+='gunzip ' + work_DIR['02.rmhost'] + samplename + '.rmhost.1.fq \n'
temp+='gunzip ' + work_DIR['02.rmhost'] + samplename + '.rmhost.2.fq \n'
temp+='cd '+ work_DIR['041.bwa']+'\n'
temp+=dir_bwa + ' index ' + work_DIR['03.assembly'] + '/' + samplename +'/contig.fa\n'
temp+=dir_bwa + ' mem -t -5 '+ work_DIR['03.assembly'] + '/' + samplename +'/contig.fa ' + work_DIR['02.rmhost'] + '/' + samplename + '.rmhost.1.fq ' + ' ' + work_DIR['02.rmhost'] + '/' + samplename+'.rmhost.2.fq '+ ' > ' + work_DIR['041.bwa'] +'/'+ samplename+'_mem-pe.sam\n'
temp+=dir_samtools +' view -bS ' + work_DIR['041.bwa'] +'/'+ samplename+'_mem-pe.sam' + ' > ' + work_DIR['041.bwa'] +'/'+ samplename+'_mem-pe.bam\n'
temp+=dir_samtools +' sort ' + work_DIR['041.bwa'] +'/'+ samplename+'_mem-pe.bam' + ' > ' + work_DIR['041.bwa'] +'/'+ samplename+'_mem-pe.sort.bam\n'
temp+='rm '+work_DIR['041.bwa'] +'/'+ samplename+'_mem-pe.sam\n'
temp+='rm '+work_DIR['041.bwa'] +'/'+ samplename+'_mem-pe.bam\n'
else:
pass
return temp
#filter and remove host by programs from fangchao
# def clean(fq1,fq2,prefix):
# #fq1,fq2 <prefix> <qt> <limit> <N num> <qf> <lf>
# temp=dir_clean+' '+fq1+' '+fq2+' '+prefix+' 20 10 1 15 15 30'
# return temp
#create contigs with IDBA
#>refinem scaffold_stats -c 16 <scaffold_file> <bin_dir> <stats_output_dir> <bam_files>
def iden_genome(samplename,work_DIR,flagPE):
if flagPE=='Yes' or flagPE=='yes' or flagPE=='YES':
temp+='refinem scaffold_stats -c 16 -x fa ' + work_DIR['03.assembly'] + '/'+samplename+'/contig.fa '
temp+=work_DIR['043.checkm']+'/'+samplename+'.contig.fa.metabat-bins '
temp+=work_DIR['05.refine']+'/'+samplename+'/scaffold '
temp+=work_DIR['041.bwa'] +'/'+ samplename+'_mem-pe.sort.bam'
temp+='\n'
return temp
#>refinem outliers <stats_output_dir>/scaffold_stats.tsv <outlier_output_dir>
def outliers(samplename,work_DIR):
temp='refinem outliers '+ work_DIR['05.refine']+'/'+samplename+'/scaffold/scaffold_stats.tsv '+ work_DIR['051.iden_genome']+'/'+samplename+'/outliers\n '
return temp
#>refinem filter_bins <bin_dir> <outlier_output_dir>/outliers.tsv <filtered_output_dir>
def gene_filter(samplename,work_DIR):
temp='refinem filter_bins -x fa '
temp += work_DIR['043.checkm']+'/'+samplename+'.contig.fa.metabat-bins '
temp += work_DIR['05.refine']+'/'+samplename+'/outliers/outliers.tsv '
temp += work_DIR['05.refine']+'/'+samplename+'/filtergene\n '
return temp
#>refinem call_genes -c 40 bins <bin_dir> <gene_output_dir>
def callgene(samplename,work_DIR):
temp='refinem call_genes -c 16 -x fa ' + work_DIR['043.checkm']+'/'+samplename+'.contig.fa.metabat-bins '
temp += work_DIR['05.refine']+'/'+samplename+'/calledgenes '
return temp
#>refinem taxon_profile -c 40 <gene_output_dir> <stats_output_dir>/scaffold_stats.tsv <reference_db> <reference_taxonomy> <taxon_profile_output_dir>
def tax_pro(samplename,work_DIR):
temp='refinem taxon_profile -c 16 ' + work_DIR['05.refine']+'/'+samplename+'/calledgenes ''
temp+=work_DIR['05.refine']+'/'+samplename+'/scaffold/scaffold_stats.tsv '
temp+='/hwfssz1/ST_META/PN/haoyunze/Database/genome_db.2017-11-09.genes.faa /hwfssz1/ST_META/PN/haoyunze/Database/gtdb_r80_taxonomy.2017-12-15.tsv '
temp+=work_DIR['05.refine']+'/'+samplename+'/taxpro\n'
return temp
#>refinem taxon_filter -c 40 <taxon_profile_dir> taxon_filter.tsv
def iden_tax(samplename,work_DIR):
temp='refinem taxon_filter -c 16 '+ work_DIR['05.refine']+'/'+samplename+'/taxpro '+work_DIR['05.refine']+'/'+samplename+'/taxpro/taxon_filter.tsv\n'
return temp
#>refinem filter_bins <bin_dir> <taxon_output_dir>/taxon_filter.tsv <filtered_output_dir>
def tax_filter(samplename,work_DIR):
temp='refinem filter_bins -x fa '
temp += work_DIR['05.refine']+'/'+samplename+'/filtergene '
temp += work_DIR['05.refine']+'/'+samplename+'/taxpro/taxon_filter.tsv '
temp +=work_DIR['05.refine']+'/'+samplename+'/filtertax \n'
return temp
#>refinem ssu_erroneous <bin_dir> <taxon_profile_dir> <ssu_db> <reference_taxonomy> <ssu_output_dir>
def iden_16s(samplename,work_DIR):
temp='refinem ssu_erroneous -x fa '
temp+=work_DIR['05.refine']+'/'+samplename+'/filtertax '
temp+=work_DIR['05.refine']+'/'+samplename+'/taxpro '
temp+='/hwfssz1/ST_META/PN/haoyunze/Database/gtdb_r80_ssu_db.2018-01-18.fna /hwfssz1/ST_META/PN/haoyunze/Database/gtdb_r80_taxonomy.2017-12-15.tsv '
temp+=work_DIR['05.refine']+'/'+samplename+'/16s\n'
return temp
#>refinem filter_bins <bin_dir> <16s_output_dir>/ssu_erroneous.tsv <filtered_output_dir>
def filter_16s(samplename,work_DIR):
temp='refinem filter_bins -x fa '
temp +=work_DIR['05.refine']+'/'+samplename+'/filtertax '
temp+=work_DIR['05.refine']+'/'+samplename+'/16s/ssu_erroneous.tsv '
temp+=work_DIR['05.refine']+'/'+samplename+'/filter16s\n '
return temp
| 607a67884bcd776a69403335d826a4a0ce225ab7 | [
"Python"
] | 2 | Python | Feverdreams/BacGenoReconstruct | 9fdcbd98394370f4a221f96c35620a0aa2f341d8 | b83dceb0d520fcfd835d4f4c72dccf0b4fa530f6 |
refs/heads/main | <repo_name>beaumontyun/portfolio<file_sep>/src/views/BlogList.vue
<template>
<div class="container md:w-8/12 mb-20 md:mr-80 dark:bg-black">
<p class="font-semibold md:text-4xl dark:text-white">blog</p>
<br>
<div v-if="blogs.length">
<div v-for="blog in blogs" :key="blog.id" class="blog">
<router-link
:to="{ name: 'blog', params: { id: blog.id } }"
class="text-xl md:text-4xl dark:text-white"
>
<h2>{{ blog.title }}</h2>
<br>
</router-link>
</div>
</div>
<div v-else>I am loading stuff or the server is taking a snooze... plz come back after 6am GMT</div>
</div>
</template>
<script>
export default {
name: "BlogList",
data() {
return {
blogs: [],
};
},
created() {
fetch("https://beaumont-awesome-blog.herokuapp.com/blogs")
.then((res) => res.json())
.then((data) => (this.blogs = data))
.catch((err) => console.log(err.message));
},
};
</script>
<style scoped>
h2:hover {
color: #2194e0;
}
</style><file_sep>/src/views/About.vue
<template>
<div class="container md:w-8/12 mb-20 md:mr-80 dark:bg-black">
<p class="font-semibold md:text-4xl dark:text-white">Got some stuff on your chest?</p>
<br>
<p class="text-xl md:text-4xl dark:text-white">Could be a hair, could be ketchup, or it could be your next great idea -
come <a href="https://calendly.com/b-yun/say-hi-to-beaumont" class="text-blue-450 dark:text-red-500">say hi</a> and don't be shy, I always have a cup of coffee in hand to hear your thoughts</p>
<br>
<p class="text-xl md:text-4xl dark:text-white">Some topics we could discuss:</p>
<ul class="md:text-3xl dark:text-white">
<li>- Sailing</li>
<li>- Movies</li>
<li>- Video games</li>
<li>- Web development</li>
<li>- Books and hobbies</li>
<li>- THE WORLD!</li>
</ul>
<br>
<p class="text-xl md:text-4xl dark:text-white">But just in case you feel like conversing the old fashion way, you can always <a href="mailto:<EMAIL>" class="text-blue-450 dark:text-red-500">email me</a> or follow my on <a href="https://www.instagram.com/hsf_beaumont/" class="text-blue-450 dark:text-red-500">isntagram</a></p>
<br>
</div>
</template>
<file_sep>/src/components/HelloWorld.vue
<template>
<div class="container md:w-8/12 md:mr-80 dark:bg-black">
<p class="font-bold md:text-5xl dark:text-white">{{ msg }}</p>
<br>
<p class="text-xl md:text-4xl dark:text-white">I make websites with laravel and vueJS</p>
<br>
<p class="text-xl md:text-4xl dark:text-white">I am working on <a href="https://github.com/beaumontyun/vue-mysitio" class="text-blue-450 dark:text-red-500">mysitio</a>, a home decor social media / secondhand furniture store</p>
<br>
<p class="text-xl md:text-4xl dark:text-white">I have a map-based social media prototype-app called <a href="https://gitlab.com/Tarey/project3" class="text-blue-450 dark:text-red-500">mapper</a>, you can share funny icons & gifs to your friend on the map</p>
<br>
<p class="text-xl md:text-4xl dark:text-white">In my downtime, I am creating <a href="https://github.com/beaumontyun/timing" class="text-blue-450 dark:text-red-500">timing</a>, a fun stopwatch app to track my daily routines</p>
<br>
<p class="text-xl md:text-4xl dark:text-white">On the side, I am a qualified solicitor in England and Wales, sometimes I speak English, Cantonese, Mandarin and Spanish together uncontrollably</p>
<br>
<p class="text-xl md:text-4xl dark:text-white">Come <a href="https://calendly.com/b-yun/say-hi-to-beaumont" class="text-blue-450 dark:text-red-500">say hi</a> whenever you are free!</p>
<br>
</div>
</template>
<script>
export default {
name: 'HelloWorld',
props: {
msg: String
}
}
</script>
<file_sep>/src/views/Home.vue
<template>
<div id="home">
<HelloWorld class="bg-transparent" msg="Hello, I am Beaumont"/>
</div>
</template>
<script>
// @ is an alias to /src
import HelloWorld from '@/components/HelloWorld.vue'
export default {
name: 'Home',
components: {
HelloWorld
}
}
</script>
<style scoped>
#home {
background-size: 300px 350px;
background-repeat: no-repeat;
background-position: right top;
/* background-image: url('~@/assets/02.09.png') */
}
</style><file_sep>/src/views/Blog.vue
<template>
<div class="container md:w-8/12 mb-20 md:mr-80 dark:bg-black">
<div v-if="blog">
<p class="font-semibold md:text-4xl dark:text-white">{{ blog.title }}</p>
<p>{{blog.date}}</p>
<br>
<p>{{blog.image}}</p>
<p>{{blog.body}}</p>
</div>
<div v-else>
<p>I am loading stuff or the server is taking a snooze... plz come back after 6am GMT</p>
</div>
</div>
</template>
<script>
export default {
props: ['id'],
name: "Blog",
data() {
return {
blog: null,
};
},
mounted() {
fetch("https://beaumont-awesome-blog.herokuapp.com/blogs/" + this.id)
.then((res) => res.json())
.then((data) => (this.blog = data))
.catch((err) => console.log(err.message));
},
};
</script>
<style>
</style> | 39cf668b6209475172f980a324a009cd87a7ee5f | [
"Vue"
] | 5 | Vue | beaumontyun/portfolio | 759c77e9f5b4a893c161def9d1f297f2cac18c0d | 977af6bc7712a26c9ac8930da89c4da237b67e34 |
refs/heads/master | <file_sep># tungdv
practive HTML using <div>
| 15bf5cdf3c2e7b0814e03f637db804bbdb6fe7ed | [
"Markdown"
] | 1 | Markdown | anhtung96nb/tungdv | 9a0e37589d08bf74f6f6a1a60bb9dcefa6e1a311 | 7fcf8ff07fa1dbd3558e272edb5a197c69846fbc |
refs/heads/master | <repo_name>abdullahalrifat959/psd-project-2<file_sep>/css/main.css
/*! HTML5 Boilerplate v8.0.0 | MIT License | https://html5boilerplate.com/ */
.* {
margin: 0;
padding: 0;
overflow: hidden;
clear: both;
}
body {
background-color: #f2f2f2!important;
}
.header_topo_area {
margin: 0;
padding: 0;
overflow: hidden;
clear: both;
}
.row.section_row {
display: flex;
}
.row.ok {
display: flex;
}
.top_left {
text-align: end;
padding: 26px 45px;
}
.top_right {
text-align: end;
margin: 0;
padding: 0;
line-height: 72px;
}
.top_right ul {
list-style: none;
display: block;
}
.top_right ul li {
display: inline-block;
}
.top_right ul li a {
text-decoration: none;
color: #000;
padding-left: 30px;
padding-top: 50px;
display: block;
text-transform: uppercase;
font-size: 19px;
}
.banner_area {
background: url(../img/banner.jpg) no-repeat center center;
background-size: cover;
min-height: 1000px;
}
.banner_text {
color: #fff;
padding-top: 400px;
padding-left: 140px;
/* font-size: 35px; */
font-size: 22px;
}
.banner_text h2 {
font-size: 51px;
margin-bottom: 27px;
}
.searchbar {
background: white;
width: 396px;
color: black;
padding: 10px;
border-radius: 24px;
}
.searchbar input {
border:none;
}
.section_left_text {
display: block;
text-align: center;
padding: 64px;
font-size: 18px;
line-height: 38px;
}
.col-md-6.left {
background: url(../img/slider2.jpg) no-repeat center center;
background-size: cover;
margin: 0;
padding: 0;
}
.section_row_right {
padding: 93px 60px;
display: block;
font-size: 18px;
line-height: 33px;
background: white;
}
a.btn {
background: goldenrod;
border-radius: 12px;
}
.service_top {
display: block;
text-align: center;
margin: 0;
padding:30px;
font-size: 19px;
}
.content_area {
overflow: hidden;
padding: 0;
margin-top: 55px;
}
.service_text {
box-sizing: border-box;
display: block;
border: 2px solid white;
margin: 7px 0;
background: white;
border-radius: 20px;
line-height: 33px;
padding: 10px;
}
.service_text h2 {
font-size: 17px;
margin: 0;
padding-top: 4px;
color: #8ac9e4;
}
.footer-area {
background: #262626;
margin: 0;
padding: 0;
color: white;
padding-bottom: 200px;
line-height: 20px;
padding-top: 30px;
}
.service_text p {
margin: 0;
padding: 0;
font-size: 12px;
font-weight: 500;
}
.col-md-6.content_left {
background: url(../img/slider1.jpg) repeat-x center center;
background-size: cover;
min-height: 498px;
}
.content_right h2 {
color: #a3bf1c;
font-size: 37px;
color: #;
}
.content_right {
padding-top: 68px;
padding-left: 35px;
padding-right: 25px;
padding-bottom: 107px;
background: #fff;
font-size:18px;
}
.content_right a {
background: #a3bf1c;
padding: 10px 30px;
border-radius: 13px;
margin-top: 10px;
display: inline-block;
text-decoration: none;
}
.content_right p {
margin-bottom: 15px;
display: block;
}
ul.footer_ul {
margin: 0;
padding: 0;
list-style: none;
display: block;
}
ul.footer_ul li {
display: inline-block;
margin: 0;
padding: 0;
}
ul.footer_ul li a {
padding-right: 17px;
font-size: 21px;
}
.footer-bottom {
color: gray;
background: #000;
text-align: center;
line-height: 48px;
font-size: 12px;
}
.service_left {
margin-left: 57px;
margin-right: 15px;
}
}
a.ser {
text-align: end;
display: block;
text-decoration: none;
position: relative;
}
.footer_right h3 {
margin-bottom: 30px;
font-size:32px;
}
.footer_left h3 {
margin-bottom: 27px;
font-size: 30px;
}
.col-md-6 {
padding: 0 0;
}
.service_text.sevice-right {
margin-right: 44px;
padding: 22px;
}
.service_text.service_left p.ok {
float: left;
background: white;
width: 80%;
}
.service_text.service_left p.okk {
float: left;
background: white;
width: 19%;
margin: 0;
padding: 0;
}
.service_text.service_left p.okk a.ser {
color: red;
background: #a3bf1c;
padding: 8px 29px;
border-radius: 7px;
}
.service_text.service_right p.ok {
float: left;
background: white;
width: 80%;
}
.service_text.service_right p.okk {
float: left;
background: white;
width: 19%;
margin: 0;
padding: 0;
}
.service_text.service_right p.okk a.ser {
color: red;
background: #a3bf1c;
padding: 8px 29px;
border-radius: 7px;
}
.secondp{
color:#a3bf1c;
}
.third{
float:left;
width:70%;
position:relative;
}
.fourth{
float:right;
width:30%;
background:#a3bf1c;
text-align:center;
position:absolute;
padding: 9px;
font-size: 22px;
border-radius: 0 0 19px 0;
bottom:0;
right:0;
margin:0;
}
.main{
background:white;
border-radius:15px;
margin:0;
padding:0;
display:block;
overflow:hidden;
clear:both;
padding-bottom: 0px;
padding-left: 25px;
}
.col-md-6.row_left {
padding-top: 55px;
margin-left: 0px;
box-sizing: border-box;
position: relative;
display: block;
padding-left: 60px;
padding-bottom: 5px;
padding-right: 5px;
}
.col-md-6.row_right {
padding-top: 55px;
margin-left: 0px;
box-sizing: border-box;
position: relative;
display: block;
padding-right: 40px;
padding-bottom: 5px;
padding-left: 10px;
}
.main h2 {
color: #8ac9e4;
font-size: 21px;
}
.section_left_text h2 {
color: #8ac9e4;
font-size: 46px;
font-weight: 600;
}
.section_row_right h2 {
color: #b8cd63;
font-size: 42px;
line-height: 61px;
}
a.btn {
background: #a3bf1c;
padding: 8px 13px;
font-size: 20px;
}
.service_top h2 {
font-size: 39px;
line-height: 47px;
margin-top: 60px;
}
.footer_left {
overflow: hidden;
clear: both;
font-size: 24px;
line-height: 34px;
}
.footer_right {
font-size: 21px;}
.footer_left h2 {
font-size: 42px;
margin-bottom: 25px;
}
.footer_right h2 {
font-size: 38px;
margin-bottom: 15px;
}
.header_topo_area .col-md-9 {
padding: 0;
margin: 0;
overflow: hidden;
} | 6a8e5ac500e1cccdf42fe3da437eeb1946d805be | [
"CSS"
] | 1 | CSS | abdullahalrifat959/psd-project-2 | ebd93433290b9e6a223434f75f63de733f8a88fe | e9959fe9a9f01b56e8b34a6de010111ffe59a7f2 |
End of preview. Expand
in Dataset Viewer.
No dataset card yet
- Downloads last month
- 2