branch_name
stringclasses
22 values
content
stringlengths
18
81.8M
directory_id
stringlengths
40
40
languages
sequence
num_files
int64
1
7.38k
repo_language
stringlengths
1
23
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>&nbsp;(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>&nbsp;(not&nbsp;published) </div> <div class='comment-form-website'> <input type="url" placeholder='http://yourdomain.com' size="25" name="website" /> <label for='website'>Website</label>&nbsp;(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 &lt;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
refs/heads/master
<repo_name>zhaoguohan123/CppDemo<file_sep>/2. 访问控件的七种方式/DemoDialog/DemoDialog/DemoDialogDlg.cpp // DemoDialogDlg.cpp : 实现文件 // #include "stdafx.h" #include "DemoDialog.h" #include "DemoDialogDlg.h" #include "afxdialogex.h" #ifdef _DEBUG #define new DEBUG_NEW #endif // 用于应用程序“关于”菜单项的 CAboutDlg 对话框 class CAboutDlg : public CDialogEx { public: CAboutDlg(); // 对话框数据 enum { IDD = IDD_ABOUTBOX }; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持 // 实现 protected: DECLARE_MESSAGE_MAP() }; CAboutDlg::CAboutDlg() : CDialogEx(CAboutDlg::IDD) { } void CAboutDlg::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx) END_MESSAGE_MAP() // CDemoDialogDlg 对话框 CDemoDialogDlg::CDemoDialogDlg(CWnd* pParent /*=NULL*/) : CDialogEx(CDemoDialogDlg::IDD, pParent) , m_num1(0) , m_num2(0) , m_num3(0) { m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); } void CDemoDialogDlg::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); DDX_Text(pDX, IDC_EDIT1, m_num1); DDX_Text(pDX, IDC_EDIT2, m_num2); DDX_Text(pDX, IDC_EDIT3, m_num3); DDX_Control(pDX, IDC_EDIT1, m_edit1); DDX_Control(pDX, IDC_EDIT2, m_edit2); DDX_Control(pDX, IDC_EDIT3, m_edit3); } BEGIN_MESSAGE_MAP(CDemoDialogDlg, CDialogEx) ON_WM_SYSCOMMAND() ON_WM_PAINT() ON_WM_QUERYDRAGICON() ON_BN_CLICKED(IDC_BUTTON1, &CDemoDialogDlg::OnBnClickedButton1) ON_BN_CLICKED(IDC_BUTTON2, &CDemoDialogDlg::OnBnClickedButton2) ON_BN_CLICKED(IDC_BUTTON3, &CDemoDialogDlg::OnBnClickedButton3) ON_BN_CLICKED(IDC_BUTTON4, &CDemoDialogDlg::OnBnClickedButton4) ON_BN_CLICKED(IDC_BUTTON5, &CDemoDialogDlg::OnBnClickedButton5) ON_BN_CLICKED(IDC_BUTTON6, &CDemoDialogDlg::OnBnClickedButton6) ON_BN_CLICKED(IDC_BUTTON7, &CDemoDialogDlg::OnBnClickedButton7) END_MESSAGE_MAP() // CDemoDialogDlg 消息处理程序 BOOL CDemoDialogDlg::OnInitDialog() { CDialogEx::OnInitDialog(); // 将“关于...”菜单项添加到系统菜单中。 // IDM_ABOUTBOX 必须在系统命令范围内。 ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX); ASSERT(IDM_ABOUTBOX < 0xF000); CMenu* pSysMenu = GetSystemMenu(FALSE); if (pSysMenu != NULL) { BOOL bNameValid; CString strAboutMenu; bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX); ASSERT(bNameValid); if (!strAboutMenu.IsEmpty()) { pSysMenu->AppendMenu(MF_SEPARATOR); pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu); } } // 设置此对话框的图标。当应用程序主窗口不是对话框时,框架将自动 // 执行此操作 SetIcon(m_hIcon, TRUE); // 设置大图标 SetIcon(m_hIcon, FALSE); // 设置小图标 // TODO: 在此添加额外的初始化代码 return TRUE; // 除非将焦点设置到控件,否则返回 TRUE } void CDemoDialogDlg::OnSysCommand(UINT nID, LPARAM lParam) { if ((nID & 0xFFF0) == IDM_ABOUTBOX) { CAboutDlg dlgAbout; dlgAbout.DoModal(); } else { CDialogEx::OnSysCommand(nID, lParam); } } // 如果向对话框添加最小化按钮,则需要下面的代码 // 来绘制该图标。对于使用文档/视图模型的 MFC 应用程序, // 这将由框架自动完成。 void CDemoDialogDlg::OnPaint() { if (IsIconic()) { CPaintDC dc(this); // 用于绘制的设备上下文 SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0); // 使图标在工作区矩形中居中 int cxIcon = GetSystemMetrics(SM_CXICON); int cyIcon = GetSystemMetrics(SM_CYICON); CRect rect; GetClientRect(&rect); int x = (rect.Width() - cxIcon + 1) / 2; int y = (rect.Height() - cyIcon + 1) / 2; // 绘制图标 dc.DrawIcon(x, y, m_hIcon); } else { CDialogEx::OnPaint(); } } //当用户拖动最小化窗口时系统调用此函数取得光标 //显示。 HCURSOR CDemoDialogDlg::OnQueryDragIcon() { return static_cast<HCURSOR>(m_hIcon); } void CDemoDialogDlg::OnBnClickedButton1() { // TODO: 在此添加控件通知处理程序代码 int num1,num2,num3; TCHAR ch1[12],ch2[12],ch3[12]; GetDlgItem(IDC_EDIT1)->GetWindowTextW(ch1, 12); GetDlgItem(IDC_EDIT2)->GetWindowTextW(ch2, 12); num1 = _ttoi(ch1); num2 = _ttoi(ch2); num3 = num1 + num2; _itot(num3,ch3,10); GetDlgItem(IDC_EDIT3)->SetWindowTextW(ch3); } void CDemoDialogDlg::OnBnClickedButton2() { // TODO: 在此添加控件通知处理程序代码 int num1,num2,num3; TCHAR ch1[12],ch2[12],ch3[12]; GetDlgItemText(IDC_EDIT1,ch1,12); GetDlgItemText(IDC_EDIT2,ch2, 12); num1 = _ttoi(ch1); num2 = _ttoi(ch2); num3 = num1 + num2; _itot(num3,ch3,10); SetDlgItemText(IDC_EDIT3,ch3); } void CDemoDialogDlg::OnBnClickedButton3() { // TODO: 在此添加控件通知处理程序代码 int num1,num2,num3; num1 = GetDlgItemInt(IDC_EDIT1); num2 = GetDlgItemInt(IDC_EDIT2); num3 = num1 + num2; SetDlgItemInt(IDC_EDIT3,num3); } void CDemoDialogDlg::OnBnClickedButton4() { // TODO: 在此添加控件通知处理程序代码 UpdateData(TRUE); //从控件的值更新到变量 m_num3 = m_num1 + m_num2; UpdateData(FALSE); //把变量更新到控件的值 } void CDemoDialogDlg::OnBnClickedButton5() { // TODO: 在此添加控件通知处理程序代码 int num1,num2,num3; TCHAR ch1[12],ch2[12],ch3[12]; m_edit1.GetWindowTextW(ch1,12); m_edit2.GetWindowTextW(ch2,12); num1 = _ttoi(ch1); num2 = _ttoi(ch2); num3 = num1 + num2; _itot(num3, ch3, 10); m_edit3.SetWindowTextW(ch3); } void CDemoDialogDlg::OnBnClickedButton6() { // TODO: 在此添加控件通知处理程序代码 int num1,num2,num3; TCHAR ch1[12],ch2[12],ch3[12]; ::SendMessage(GetDlgItem(IDC_EDIT1)->m_hWnd, WM_GETTEXT, 12, (LPARAM) ch1); ::SendMessage(GetDlgItem(IDC_EDIT2)->m_hWnd, WM_GETTEXT, 12, (LPARAM) ch2); num1 = _ttoi(ch1); num2 = _ttoi(ch2); num3 = num1 + num2; _itot(num3, ch3 ,10); ::SendMessage(GetDlgItem(IDC_EDIT3)->m_hWnd, WM_SETTEXT, 0, (LPARAM)ch3); } void CDemoDialogDlg::OnBnClickedButton7() { // TODO: 在此添加控件通知处理程序代码 int num1,num2,num3; TCHAR ch1[12],ch2[12],ch3[12]; SendDlgItemMessage(IDC_EDIT1, WM_GETTEXT, 12, (LPARAM)ch1); SendDlgItemMessage(IDC_EDIT2, WM_GETTEXT, 12, (LPARAM)ch2); num1 = _ttoi(ch1); num2 = _ttoi(ch2); num3 = num1 + num2; _itot(num3, ch3 ,10); SendDlgItemMessage(IDC_EDIT3, WM_SETTEXT ,12 , (LPARAM)ch3); } <file_sep>/Pro1_ThreadFuncMustBeStatic/Demo/Demo/DemoDlg.cpp // DemoDlg.cpp : 实现文件 // #include "stdafx.h" #include "Demo.h" #include "DemoDlg.h" #include "CommonTool.h" #include "afxdialogex.h" #ifdef _DEBUG #define new DEBUG_NEW #endif // 用于应用程序“关于”菜单项的 CAboutDlg 对话框 class CAboutDlg : public CDialogEx { public: CAboutDlg(); // 对话框数据 #ifdef AFX_DESIGN_TIME enum { IDD = IDD_ABOUTBOX }; #endif protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持 // 实现 protected: DECLARE_MESSAGE_MAP() }; CAboutDlg::CAboutDlg() : CDialogEx(IDD_ABOUTBOX) { } void CAboutDlg::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx) END_MESSAGE_MAP() // CDemoDlg 对话框 CDemoDlg::CDemoDlg(CWnd* pParent /*=NULL*/) : CDialogEx(IDD_DEMO_DIALOG, pParent) , m_ServIp(_T("")) { m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); } void CDemoDlg::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); DDX_Text(pDX, IDC_SRVIP_EDIT, m_ServIp); DDV_MaxChars(pDX, m_ServIp, 255); } BEGIN_MESSAGE_MAP(CDemoDlg, CDialogEx) ON_WM_SYSCOMMAND() ON_WM_PAINT() ON_WM_QUERYDRAGICON() ON_BN_CLICKED(IDOK, &CDemoDlg::OnBnClickedOk) END_MESSAGE_MAP() // CDemoDlg 消息处理程序 BOOL CDemoDlg::OnInitDialog() { CDialogEx::OnInitDialog(); // 将“关于...”菜单项添加到系统菜单中。 // IDM_ABOUTBOX 必须在系统命令范围内。 ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX); ASSERT(IDM_ABOUTBOX < 0xF000); CMenu* pSysMenu = GetSystemMenu(FALSE); if (pSysMenu != NULL) { BOOL bNameValid; CString strAboutMenu; bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX); ASSERT(bNameValid); if (!strAboutMenu.IsEmpty()) { pSysMenu->AppendMenu(MF_SEPARATOR); pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu); } } // 设置此对话框的图标。 当应用程序主窗口不是对话框时,框架将自动 // 执行此操作 SetIcon(m_hIcon, TRUE); // 设置大图标 SetIcon(m_hIcon, FALSE); // 设置小图标 // TODO: 在此添加额外的初始化代码 return TRUE; // 除非将焦点设置到控件,否则返回 TRUE } void CDemoDlg::OnSysCommand(UINT nID, LPARAM lParam) { if ((nID & 0xFFF0) == IDM_ABOUTBOX) { CAboutDlg dlgAbout; dlgAbout.DoModal(); } else { CDialogEx::OnSysCommand(nID, lParam); } } // 如果向对话框添加最小化按钮,则需要下面的代码 // 来绘制该图标。 对于使用文档/视图模型的 MFC 应用程序, // 这将由框架自动完成。 void CDemoDlg::OnPaint() { if (IsIconic()) { CPaintDC dc(this); // 用于绘制的设备上下文 SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0); // 使图标在工作区矩形中居中 int cxIcon = GetSystemMetrics(SM_CXICON); int cyIcon = GetSystemMetrics(SM_CYICON); CRect rect; GetClientRect(&rect); int x = (rect.Width() - cxIcon + 1) / 2; int y = (rect.Height() - cyIcon + 1) / 2; // 绘制图标 dc.DrawIcon(x, y, m_hIcon); } else { CDialogEx::OnPaint(); } } //当用户拖动最小化窗口时系统调用此函数取得光标 //显示。 HCURSOR CDemoDlg::OnQueryDragIcon() { return static_cast<HCURSOR>(m_hIcon); } void CDemoDlg::OnBnClickedOk() { UpdateData(TRUE); //获取编辑框的值到变量,false则反之 //MessageBox(m_ServIp, "测试值", MB_OK); //DataToThread * ptmp = (DataToThread * )malloc(sizeof(DataToThread)); // 这里有new和malloc的区别,如果是malloc,不会调用构造函数对CString进行初始化 DataToThread * ptmp = new DataToThread(); ptmp->_ServIp = m_ServIp; UINT idThread = 0; HANDLE hThread = (HANDLE)_beginthreadex(NULL, 0, CDemoDlg::ConnectWithServ, ptmp, 0, &idThread); //HANDLE hThreadAndEvent[1]; //hThreadAndEvent[0] = hThread; //MsgWaitForMultipleObjects(1, hThreadAndEvent, 2000, QS_ALLEVENTS, MWMO_INPUTAVAILABLE); WaitForSingleObject(hThread, INFINITE); // 这里可以做适当改进,以免卡死 //CDialogEx::OnOK(); } unsigned __stdcall CDemoDlg::ConnectWithServ(void * pthis) { DataToThread * pDataToThread = (DataToThread *)pthis; DWORD dwReadSize = 0; char *pData = NULL; char pReq[4096] = { 0 }; HANDLE hInternet = NULL; HANDLE hSession = NULL; HANDLE hRequest = NULL; const char * apiCsp = "/sangfor/testp"; OutputDebugStringA("### ConnectServ start."); if (!ConnectServ(apiCsp, hInternet, hSession, hRequest, pDataToThread->_ServIp, 80)) { OutputDebugStringA("### ConnectServ failed."); return 0; } OutputDebugStringA("### CreateJsonReqData start."); if (CreateJsonReqData(pReq) == FALSE) { OutputDebugStringA("CreateJsonReqData failed."); return 0; } OutputDebugStringA("### SendRequestToServ start."); if (!SendRequestToServ(hRequest, pReq, strlen(pReq))) { OutputDebugStringA("SendRequestToServer failed."); return 0; } OutputDebugStringA("### ReadServBackData start."); if (!ReadServBackData(hRequest, pData, dwReadSize, FALSE)) { OutputDebugStringA("ReadServerBackData failed."); return 0; } OutputDebugStringA("### AnalyzeRecvData start."); if (AnalyzeRecvData(pData) == FALSE) { OutputDebugStringA("AnalyzeRecvData failed."); return 0; } return 1; }<file_sep>/4. CppPro/Memory/注意:线程启动的参数传递.md 1. 规则: 绝不能用启动函数的内部变量给线程传参: 函数启动一个线程,很多时候需要向线程传参数,但是线程是异步启动的,即很可能启动函数已经退出了,而线程函数都还没有正式开始运行。 2. 深层原因: 道理很简单,函数的内部变量在浮动栈,但函数退出时,浮动栈自动拆除,内存空间已经被释放了。 当线程启动时,按照给的参数指针去查询变量,实际上是在读一块无效的内存区域,程序会因此而崩溃。 3. 解决方法: 应该直接用malloc函数给需要传递的参数分配一块内存区域,将指针传入线程,线程收到后使用,最后线程退出时,free释放。 代码详细见demo中。 如果在CallBackFun函数调用线程函数之前,不给使用malloc给td分配堆内存空间,那么当CallBackFun函数返回时; 在内存栈区的td就会被清除,此时线程函数中访问的地址就会变得不存在; <file_sep>/4. CppPro/README.md # CppDemo 1. 这里存放每一个与cpp相关的知识点 2. 常见的bug的收集 <file_sep>/4. CppPro/extern_Pro/extern_Pro/a.cpp #include <Windows.h> #include <stdio.h> extern int b; extern const DWORD a; void fun_a(){ DWORD cpp_a = a; printf("a.cpp a= %d, b = %d \n",cpp_a,b); }<file_sep>/Pro1_ThreadFuncMustBeStatic/Demo/Demo/CommonTool.cpp #include "stdafx.h" #include "CommonTool.h" #define REQ_JSON "{}" #define PUT_PUT_DEBUG_BUF_LEN 1024 void OutputDebugVal(const char * strOutputString, ...) { char strBuffer[PUT_PUT_DEBUG_BUF_LEN] = { 0 }; va_list vlArgs; va_start(vlArgs, strOutputString); _vsnprintf_s(strBuffer, sizeof(strBuffer) - 1, strOutputString, vlArgs); va_end(vlArgs); OutputDebugStringA(strBuffer); } BOOL ClearHandle(HINTERNET &hInternet, HINTERNET &hSession, HINTERNET &hRequest) { if (hInternet != NULL) { InternetCloseHandle(hInternet); hInternet = NULL; } if (hSession != NULL) { InternetCloseHandle(hSession); hSession = NULL; } if (hRequest != NULL) { InternetCloseHandle(hRequest); hRequest = NULL; } return TRUE; } BOOL ConnectServ(const char *pURL, HANDLE &hInternet, HANDLE &hSession, HANDLE &hRequest, const char *pSERVAddress, WORD wPort = 0) { if (pURL == NULL) { OutputDebugStringA("### [ConnectServer] falied, pURL is NULL"); return FALSE; } hInternet = NULL; hSession = NULL; hRequest = NULL; hInternet = InternetOpenA("TestCS",INTERNET_OPEN_TYPE_DIRECT, NULL,NULL,0); if (hInternet == NULL) { OutputDebugStringA("### [ConnectServer] InternetOpenA falied"); return FALSE; } DWORD dwTimeOut = 1000 * 6 * 2; InternetSetOption(hInternet, INTERNET_OPTION_CONNECT_TIMEOUT, &dwTimeOut, sizeof(DWORD)); InternetSetOption(hInternet, INTERNET_OPTION_SEND_TIMEOUT, &dwTimeOut, sizeof(DWORD)); InternetSetOption(hInternet, INTERNET_OPTION_DATA_SEND_TIMEOUT, &dwTimeOut, sizeof(DWORD)); InternetSetOption(hInternet, INTERNET_OPTION_RECEIVE_TIMEOUT, &dwTimeOut, sizeof(DWORD)); hSession = InternetConnectA(hInternet, pSERVAddress, wPort, "", "", INTERNET_SERVICE_HTTP, 0, 0); if (hSession == NULL) { OutputDebugStringA("### [ConnectServer] InternetConnectA falied"); ClearHandle(hInternet, hSession, hRequest); return FALSE; } //DWORD secureFlags = INTERNET_FLAG_RELOAD | INTERNET_FLAG_KEEP_CONNECTION | INTERNET_FLAG_NO_CACHE_WRITE | // INTERNET_FLAG_SECURE | INTERNET_FLAG_IGNORE_CERT_CN_INVALID; DWORD secureFlags = SECURITY_FLAG_IGNORE_UNKNOWN_CA | SECURITY_FLAG_IGNORE_CERT_DATE_INVALID | SECURITY_FLAG_IGNORE_CERT_CN_INVALID; const char *pAccept = NULL; hRequest = HttpOpenRequestA(hSession, "POST", pURL, NULL, NULL, &pAccept, secureFlags, 0); if (hRequest == NULL) { OutputDebugStringA("### [ConnectServer] HttpOpenRequestA falied"); ClearHandle(hInternet, hSession, hRequest); return FALSE; } OutputDebugStringA("### [ConnectServer] ConnectServ success"); return TRUE; } BOOL SendRequestToServ(HINTERNET hRequest, const char*pData, int iDataLen) { if (hRequest == NULL ) { OutputDebugStringA("### [SendRequestToServ] falied, hRequest is NULL"); return FALSE; } CHAR hdrs[] = "Content-Type: application/json"; DWORD dwTryTime = 5; //尝试5次 BOOL bSendSucc = FALSE; while (dwTryTime--) { bSendSucc = HttpSendRequestA(hRequest, hdrs, strlen(hdrs), (void *)pData, iDataLen); DWORD dwErrCode = GetLastError(); // 根据 返回值,处理链接失败的情况 if (bSendSucc == TRUE) { break; } if (dwErrCode == ERROR_INTERNET_CLIENT_AUTH_CERT_NEEDED)//客户端需要提交证书 { OutputDebugStringA("### [SendRequestToServ][HttpSendRequestA] falied 客户端需要提交证书"); } else if (dwErrCode == ERROR_INTERNET_INVALID_CA)//服务器证书无效 { OutputDebugStringA("### [SendRequestToServ][HttpSendRequestA] falied 服务器证书无效"); } else { OutputDebugVal("### [SendRequestToServ][HttpSendRequestA] falied. %u\n", dwErrCode); break; } } return bSendSucc; } BOOL ReadServBackData(HINTERNET hRequest, char *&pData, DWORD &Len, BOOL bNeedReport) { if (hRequest == NULL) { OutputDebugStringA("[ReadServBackData] falied, hRequest is NULL"); return FALSE; } DWORD dwResourceSize = 0; DWORD dwIndex = 0; char strSize[1024] = { 0 }; DWORD dwSize = sizeof(strSize); DWORD dwBufflen = 64 * 1024;//64k BOOL bRet = HttpQueryInfo(hRequest, HTTP_QUERY_STATUS_CODE, strSize, &dwSize, &dwIndex);//获取头部状态 if (bRet == NULL) { OutputDebugStringA("[ReadServBackData] HttpQueryInfo falied, bRet is NULL"); return FALSE; } else { int ret = atoi(strSize); if (ret != HTTP_STATUS_OK) { OutputDebugStringA("[ReadServBackData] HttpQueryInfo falied, bRet is not HTTP_STATUS_OK"); return FALSE; } } dwSize = sizeof(strSize); bRet = HttpQueryInfo(hRequest, HTTP_QUERY_CONTENT_LENGTH, strSize, &dwSize, &dwIndex);//获取头部大小 if (bRet == TRUE) { dwResourceSize = atoi(strSize); } if (dwResourceSize != 0) { dwBufflen = dwResourceSize + 1; } char * pReadData = new char[dwBufflen]; if (pReadData == NULL) { OutputDebugStringA("[ReadServBackData] pReadData is NULL"); return FALSE; } memset(pReadData, 0, dwBufflen); BOOL bSucc = FALSE; DWORD dwTotalReadLen = 0; while (true) { DWORD dwReadLen = 0; BOOL bRet = InternetReadFile(hRequest, pReadData + dwTotalReadLen, dwBufflen - dwTotalReadLen, &dwReadLen); DWORD dwErrCode = GetLastError(); if (bRet == TRUE)//成功 { dwTotalReadLen += dwReadLen;//累加计数器 if ((dwReadLen == 0) || (dwTotalReadLen == dwResourceSize))//读完 { bSucc = TRUE; break; } if (bNeedReport == TRUE) { //需要进行回调 } } else if ((dwErrCode != ERROR_INSUFFICIENT_BUFFER) && (dwErrCode != ERROR_NO_MORE_ITEMS)) { OutputDebugStringA("[ReadServBackData] InternetReadFile Fail %u"); break; } //执行到这里,表明读取数据成功,或者错误,但是错误原因是没有缓冲区了 if ((dwBufflen - dwTotalReadLen == 0) || ((bRet == FALSE) && (dwErrCode == ERROR_INSUFFICIENT_BUFFER || dwErrCode == ERROR_NO_MORE_ITEMS))) { dwBufflen *= 2;//扩张一倍大小 char *pNewData = new char[dwBufflen]; if (pNewData == NULL) { delete[] pReadData; break; } memset(pNewData, 0, dwBufflen); memcpy(pNewData, pReadData, dwTotalReadLen); delete[] pReadData; pReadData = pNewData; } } if (bSucc == TRUE) { pData = pReadData; Len = dwTotalReadLen; } else { delete[] pReadData; pReadData = NULL; } return bSucc; } void ClearJson(cJSON* json) { if (json) { cJSON_free(json); json = NULL; } } BOOL CreateJsonReqData(char * pReq) { const int dataLen = 32; BOOL bRet = FALSE; cJSON *pPostData = NULL; char *pJsonReqData = NULL; pPostData = cJSON_Parse(REQ_JSON); if (pPostData == NULL) { OutputDebugStringA("### [CreateJsonReqData] pPostData is NULL"); return FALSE; } // 添加json节点数据 char username[dataLen] = "zgh"; if (cJSON_AddStringToObject(pPostData, "username", username) == NULL) { goto clean; } char password[dataLen] = "<PASSWORD>"; if (cJSON_AddStringToObject(pPostData, "password", password) == NULL) { goto clean; } pJsonReqData = cJSON_Print(pPostData); if (pJsonReqData == NULL) { OutputDebugStringA("### [CreateJsonReqData] JsonReqData is NULL"); } else { bRet = TRUE; StringCchCopy(pReq, 1024, pJsonReqData); } OutputDebugStringA("### [CreateJsonReqData] success"); clean: ClearJson(pPostData); return bRet; } BOOL AnalyzeRecvData(char* pData) { BOOL bRet = NULL; cJSON *pRecvData = NULL; cJSON *pResult = NULL; cJSON *pChildData = NULL; cJSON *pAccessToken = NULL; //将返回信息转换为JSON格式 pRecvData = cJSON_Parse(pData); if (pRecvData == NULL) { goto clean; } //判断是否成功获取accesstoken pResult = cJSON_GetObjectItem(pRecvData, "success"); if (pResult == NULL) { goto clean; } //读取子节点data pChildData = cJSON_GetObjectItem(pRecvData, "data"); if (pChildData == NULL) { goto clean; } //读取出accesstoken pAccessToken = cJSON_GetObjectItem(pChildData, "access_token"); if (pAccessToken == NULL) { goto clean; } char ret[512] = { 0 }; StringCchCopyA(ret, 512, cJSON_GetStringValue(pAccessToken)); OutputDebugStringA("### [AnalyzeRecvData] success"); OutputDebugVal("##### access_token : %s", cJSON_GetStringValue(pAccessToken)); OutputDebugStringA("### [AnalyzeRecvData] print success"); clean: ClearJson(pRecvData); ClearJson(pResult); ClearJson(pAccessToken); ClearJson(pChildData); return bRet; }<file_sep>/Pro1_ThreadFuncMustBeStatic/Demo/Demo/DemoDlg.h // DemoDlg.h : 头文件 // #pragma once #include "afxwin.h" typedef struct _DataToThread { CString _ServIp; // 服务的IP,不包括https:// }DataToThread, *pPataToThread; // CDemoDlg 对话框 class CDemoDlg : public CDialogEx { // 构造 public: CDemoDlg(CWnd* pParent = NULL); // 标准构造函数 static unsigned __stdcall ConnectWithServ(void * pthis); // 对话框数据 #ifdef AFX_DESIGN_TIME enum { IDD = IDD_DEMO_DIALOG }; #endif protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持 // 实现 protected: HICON m_hIcon; // 生成的消息映射函数 virtual BOOL OnInitDialog(); afx_msg void OnSysCommand(UINT nID, LPARAM lParam); afx_msg void OnPaint(); afx_msg HCURSOR OnQueryDragIcon(); DECLARE_MESSAGE_MAP() public: afx_msg void OnBnClickedOk(); // 服务器的IP CString m_ServIp; }; <file_sep>/README.md # CppDemo 1. Cpp Prime学习记录以及demo验证 <file_sep>/4. CppPro/extern_Pro/注意:Cpp声明变量与定义变量.md 1. extern: 声明 (1)所有以内置类型名开头+空格+变量名; 的句子都是定义句。 如 int x; (2)所有 extern+空格+内置类型名+空格+变量名; 形式的句子都是声明句。 如 extern int x; (3)所有 extern+空格+内置类型名+空格+变量名=常量; 形式的句子都是定义句。 如 extern int x = 10; 2. extern与const联合使用需要注意: const仅仅在本文件内有效<file_sep>/1. 显示本地IP和MAC、以及字符数的计算/DemoDialog/DemoDialogDlg.h // DemoDialogDlg.h : 头文件 // #pragma once //#include <WinSock2.h> //#include <Iphlpapi.h> //#pragma comment(lib,"Iphlpapi.lib") // CDemoDialogDlg 对话框 class CDemoDialogDlg : public CDialogEx { // 构造 public: CDemoDialogDlg(CWnd* pParent = NULL); // 标准构造函数 // 对话框数据 enum { IDD = IDD_DEMODIALOG_DIALOG }; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持 // 实现 protected: HICON m_hIcon; // 生成的消息映射函数 virtual BOOL OnInitDialog(); afx_msg void OnSysCommand(UINT nID, LPARAM lParam); afx_msg void OnPaint(); afx_msg HCURSOR OnQueryDragIcon(); DECLARE_MESSAGE_MAP() public: afx_msg void OnBnClickedButton1(); afx_msg void OnStnClickedStaticOutput(); afx_msg void OnBnClickedCount(); afx_msg void OnEnChangeEditInput(); afx_msg void OnBnClickedShowIpmac(); }; <file_sep>/4. CppPro/Memory/Client/Client/Client.cpp // Client.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #pragma comment(lib,"ws2_32.lib") using namespace std; int main() { WORD sockVersion = MAKEWORD(2, 2); WSADATA data; if (WSAStartup(sockVersion, &data) != 0) { return 0; } SOCKET sclient = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (sclient == INVALID_SOCKET) { printf("invalid socket !"); return 0; } struct sockaddr_in serAddr; serAddr.sin_family = AF_INET; serAddr.sin_port = htons(8888); //serAddr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1"); inet_pton(AF_INET, "127.0.0.1", &(serAddr.sin_addr.S_un.S_addr)); // vs2013后不使用inet_addr if (connect(sclient, (struct sockaddr *)&serAddr, sizeof(serAddr)) == SOCKET_ERROR) { printf("connect error !"); closesocket(sclient); return 0; } char * sendData = "csi接收 二进制文件未解析\n"; send(sclient, sendData, strlen(sendData), 0); /*char recData[255]; int ret = recv(sclient, recData, 255, 0); if (ret > 0) { recData[ret] = 0x00; //printf(recData); printf("%d%s",i,recData); } */ while(1) { printf("请输入要发送的数据:\n"); char senddata[128] = { 0 }; cin.getline(senddata,20); send(sclient, senddata, strlen(senddata), 0); } getchar(); closesocket(sclient); WSACleanup(); return 0; } <file_sep>/4. CppPro/Memory/README.md Demo对于的文章地址:https://juejin.cn/post/6931701607226687501 <file_sep>/Pro1_ThreadFuncMustBeStatic/Demo/Demo/ReadMe.txt 1. 在MFC程序中发送http请求,使用多线程。这里验证了_beginThreadex传入多线程函数必须是全局函数或者静态成员函数。 原因是如果线程函数不是静态成员函数,那么会给线程函数传入表示当前对象的this指针,这显然不符合线程函数使用的规定 <file_sep>/4. CppPro/Memory/Server/Server/Server.cpp // Server.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #define _WINSOCK_DEPRECATED_NO_WARNINGS #pragma comment(lib,"ws2_32.lib") int main() { WORD sockVersion = MAKEWORD(2, 2); // 指定winsock版本 WSAData wsaData; if (WSAStartup(sockVersion, &wsaData)!=0) //只调用一次,该函数成功后再调用进一步的Windows Sockets API函数 { printf("WSAStartup error"); return 0; } // 1. 创建套接字 socket //AF_INET表示IPv4,SOCK_STREAM数据传输方式,IPPROTO_TCP传输协议; SOCKET listenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (listenSocket == INVALID_SOCKET) { printf("套接字创建失败"); WSACleanup(); return 0; } // 2. 绑定套接字到一个IP地址和一个端口上 bind sockaddr_in addrListen; addrListen.sin_family = AF_INET; addrListen.sin_port = htons(8888); addrListen.sin_addr.S_un.S_addr = INADDR_ANY; //表示任何IP service.sin_addr.s_addr = inet_addr("127.0.0.1"); if (bind(listenSocket, (SOCKADDR*)&addrListen, sizeof(addrListen)) == SOCKET_ERROR) { printf("绑定失败"); closesocket(listenSocket); return 0; } //3. 监听指定端口 listen if (listen(listenSocket, 5) == SOCKET_ERROR) // 5: 等待连接队列的最大长度。 { printf("监听出错"); closesocket(listenSocket); return 0; } //4. 等待连接, 连接后建立一个新的套接字 accept SOCKET revSocket; //对应此时所建立连接的套接字的句柄 sockaddr_in remoteAddr; //接收连接到服务器上的地址信息 int remoteAddrLen = sizeof(remoteAddr); printf("等待连接...\n"); /*等待客户端请求,服务器接收请求*/ revSocket = accept(listenSocket, (SOCKADDR*)&remoteAddr, &remoteAddrLen); //等待客户端接入,直到有客户端连接上来为止 if (revSocket == INVALID_SOCKET) { printf("客户端发出请求,服务器接收请求失败:%d \n", WSAGetLastError()); closesocket(listenSocket); WSACleanup(); return 0; } else { printf("客服端与服务器建立连接成功\n"); } // 5. recv和send while (1) { char revData[255] = ""; /*通过建立的连接进行通信*/ int res = recv(revSocket, revData, 255, 0); if (res > 0) { printf("Bytes received: %d\n", res); printf("客户端发送的数据: %s\n", revData); } else if (res == 0) printf("Connection closed\n"); else printf("recv failed: %d\n", WSAGetLastError()); } closesocket(revSocket); closesocket(listenSocket); WSACleanup(); getchar(); return 0; } <file_sep>/4. CppPro/extern_Pro/extern_Pro/main.cpp #include <stdio.h> #include <Windows.h> int b = 9; extern const DWORD a = 10; // const 对象尽在文件内有效 extern void fun_a(); int main(){ fun_a(); printf("main a = %d ,b = %d\n",a,b); getchar(); }<file_sep>/4. CppPro/Memory/Demo/Demo/Demo.cpp // Demo.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #define NUM_THREADS 5 using namespace std; struct thread_data { int thread_id; char * message; }; void * PrintHello(void * threadarg) // 线程函数用来输出被传入的参数 { struct thread_data * my_data; my_data = (struct thread_data *)threadarg; cout<< "Thread ID: \t"<<my_data->thread_id; cout<< "Message: "<<my_data->message<<endl; pthread_exit(NULL); return 0; } void CallBackFun() // 生成要传入线程的参数 { pthread_t threads[NUM_THREADS] = {0}; struct thread_data td[NUM_THREADS] = {0}; //struct thread_data *td[NUM_THREADS]; // 使用结构体指针数组,方便分配堆内存 int rc; int i; for( i=0; i < NUM_THREADS; i++ ){ // td[i] = (struct thread_data *)malloc(sizeof(struct thread_data)); // 给结构体分配堆内存 cout <<"main() : creating thread, " << i << endl; td[i].thread_id = i; td[i].message = (char * )"This is message"; rc = pthread_create(&threads[i], NULL, PrintHello, (void *)&td[i]); /* td[i]->thread_id = i; td[i]->message = (char * )"This is message"; rc = pthread_create(&threads[i], NULL, PrintHello, (void *)td[i]);*/ if (rc){ cout << "Error:unable to create thread," << rc << endl; exit(-1); } } //Sleep(1000); } int _tmain(int argc, _TCHAR* argv[]) { CallBackFun(); getchar(); return 0; } <file_sep>/1. 显示本地IP和MAC、以及字符数的计算/DemoDialog/DemoDialogDlg.cpp // DemoDialogDlg.cpp : 实现文件 // #include "stdafx.h" #include "DemoDialog.h" #include "DemoDialogDlg.h" #include "afxdialogex.h" #pragma comment(lib,"iphlpapi.lib") #ifdef _DEBUG #define new DEBUG_NEW #endif // 用于应用程序“关于”菜单项的 CAboutDlg 对话框 class CAboutDlg : public CDialogEx { public: CAboutDlg(); // 对话框数据 enum { IDD = IDD_ABOUTBOX }; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持 // 实现 protected: DECLARE_MESSAGE_MAP() }; CAboutDlg::CAboutDlg() : CDialogEx(CAboutDlg::IDD) { } void CAboutDlg::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx) END_MESSAGE_MAP() // CDemoDialogDlg 对话框 CDemoDialogDlg::CDemoDialogDlg(CWnd* pParent /*=NULL*/) : CDialogEx(CDemoDialogDlg::IDD, pParent) { m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); } void CDemoDialogDlg::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(CDemoDialogDlg, CDialogEx) ON_WM_SYSCOMMAND() ON_WM_PAINT() ON_WM_QUERYDRAGICON() ON_BN_CLICKED(IDC_COUNT, &CDemoDialogDlg::OnBnClickedCount) ON_EN_CHANGE(IDC_EDIT_INPUT, &CDemoDialogDlg::OnEnChangeEditInput) ON_BN_CLICKED(IDC_SHOW_IPMAC, &CDemoDialogDlg::OnBnClickedShowIpmac) END_MESSAGE_MAP() // CDemoDialogDlg 消息处理程序 BOOL CDemoDialogDlg::OnInitDialog() { CDialogEx::OnInitDialog(); // 将“关于...”菜单项添加到系统菜单中。 // IDM_ABOUTBOX 必须在系统命令范围内。 ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX); ASSERT(IDM_ABOUTBOX < 0xF000); CMenu* pSysMenu = GetSystemMenu(FALSE); if (pSysMenu != NULL) { BOOL bNameValid; CString strAboutMenu; bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX); ASSERT(bNameValid); if (!strAboutMenu.IsEmpty()) { pSysMenu->AppendMenu(MF_SEPARATOR); pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu); } } // 设置此对话框的图标。当应用程序主窗口不是对话框时,框架将自动 // 执行此操作 SetIcon(m_hIcon, TRUE); // 设置大图标 SetIcon(m_hIcon, FALSE); // 设置小图标 // TODO: 在此添加额外的初始化代码 return TRUE; // 除非将焦点设置到控件,否则返回 TRUE } void CDemoDialogDlg::OnSysCommand(UINT nID, LPARAM lParam) { if ((nID & 0xFFF0) == IDM_ABOUTBOX) { CAboutDlg dlgAbout; dlgAbout.DoModal(); } else { CDialogEx::OnSysCommand(nID, lParam); } } // 如果向对话框添加最小化按钮,则需要下面的代码 // 来绘制该图标。对于使用文档/视图模型的 MFC 应用程序, // 这将由框架自动完成。 void CDemoDialogDlg::OnPaint() { if (IsIconic()) { CPaintDC dc(this); // 用于绘制的设备上下文 SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0); // 使图标在工作区矩形中居中 int cxIcon = GetSystemMetrics(SM_CXICON); int cyIcon = GetSystemMetrics(SM_CYICON); CRect rect; GetClientRect(&rect); int x = (rect.Width() - cxIcon + 1) / 2; int y = (rect.Height() - cyIcon + 1) / 2; // 绘制图标 dc.DrawIcon(x, y, m_hIcon); } else { CDialogEx::OnPaint(); } } //当用户拖动最小化窗口时系统调用此函数取得光标 //显示。 HCURSOR CDemoDialogDlg::OnQueryDragIcon() { return static_cast<HCURSOR>(m_hIcon); } void CDemoDialogDlg::OnBnClickedCount() { // TODO: 在此添加控件通知处理程序代码 CString strInput; GetDlgItemText(IDC_EDIT_INPUT, strInput); int nLen = strInput.GetLength(); CString strOutput; strOutput.Format(TEXT("字符串长度: %d, 字符个数 : %d"), nLen, nLen); SetDlgItemText(IDC_STATIC_OUTPUT, strOutput); } void CDemoDialogDlg::OnEnChangeEditInput() { // TODO: 如果该控件是 RICHEDIT 控件,它将不 // 发送此通知,除非重写 CDialogEx::OnInitDialog() // 函数并调用 CRichEditCtrl().SetEventMask(), // 同时将 ENM_CHANGE 标志“或”运算到掩码中。 // TODO: 在此添加控件通知处理程序代码 } void CDemoDialogDlg::OnBnClickedShowIpmac() { // TODO: 在此添加控件通知处理程序代码 CString myIP, myMAC, Show_addInfo_buf; ULONG outBufLen = 0; DWORD dwRetVal = 0; PIP_ADAPTER_INFO pAdapterInfo; PIP_ADAPTER_INFO pAdapterInfoTmp = NULL; pAdapterInfo = (IP_ADAPTER_INFO *)GlobalAlloc(GMEM_ZEROINIT, sizeof(IP_ADAPTER_INFO)); //异常处理 if (GetAdaptersInfo(pAdapterInfo, &outBufLen)!= ERROR_SUCCESS) { GlobalFree(pAdapterInfo); pAdapterInfo = (IP_ADAPTER_INFO *)GlobalAlloc(GMEM_ZEROINIT, outBufLen); } if ((dwRetVal = GetAdaptersInfo(pAdapterInfo, &outBufLen)) == NO_ERROR) { pAdapterInfoTmp = pAdapterInfo; myIP = ""; while (pAdapterInfoTmp) { if (pAdapterInfoTmp->Type == MIB_IF_TYPE_ETHERNET) { if (pAdapterInfoTmp->CurrentIpAddress) { myIP = pAdapterInfoTmp->CurrentIpAddress->IpAddress.String; } else { myIP = pAdapterInfoTmp->IpAddressList.IpAddress.String; } } if (!myIP.IsEmpty() && myIP.CompareNoCase(TEXT("0.0.0.0"))!=0) { myMAC.Format(TEXT("%02X-%02X-%02X-%02X-%02X-%02X"), pAdapterInfoTmp->Address[0], pAdapterInfoTmp->Address[1], pAdapterInfoTmp->Address[2], pAdapterInfoTmp->Address[3], pAdapterInfoTmp->Address[4], pAdapterInfoTmp->Address[5]); break; } pAdapterInfoTmp = pAdapterInfoTmp->Next; } } //得到了Cstring类型的 IP和mac信息 Show_addInfo_buf.Format(TEXT("IP: %s \n\n mac: %s"), myIP, myMAC); SetDlgItemText(IDC_STATIC_OUTPUT2, Show_addInfo_buf); GlobalFree(pAdapterInfo); } <file_sep>/Pro1_ThreadFuncMustBeStatic/Demo/Demo/CommonTool.h #pragma once #include <windows.h> #include <WinInet.h> //#include <winhttp.h> #include <strsafe.h> #include "cJSON.h" #include <process.h> /* 函数作用:连接服务器 参数: pURL [in] 请求页面路径,如"/por/login_psw.csp?type=cs" hInternet [out] 返回Internet句柄 hSession [out] Internet连接句柄 hRequest [out] Internet 请求句柄 返回值: TRUE 表示成功,FALSE表示失败 */ BOOL ConnectServ(const char *pURL, HANDLE &hInternet, HANDLE &hSession, HANDLE &hRequest, const char *pVPNAddress , WORD wPort ); /* 函数作用:发送请求到服务器 参数: hRequest [in] 该请求句柄,为ConnectSERV函数第4个返回参数 pData [in] 附带的数据,一般为post请求的参数 iDataLen [in] pData长度,字节 返回值: TRUE 表示成功,FALSE表示失败 */ BOOL SendRequestToServ(HINTERNET hRequest, const char*pData, int iDataLen); /* 函数作用:关闭Internet句柄 参数: hInternet [in] Internet句柄 hSession [in] Internet连接句柄 hRequest [in] Internet 请求句柄 返回值:成功返回TRUE,失败返回FALSE */ BOOL ClearHandle(HINTERNET &hInternet, HINTERNET &hSession, HINTERNET &hRequest); /* 函数作用:发送请求到服务器 参数: hRequest [in] 该请求句柄,为ConnectServ函数第4个返回参数 pData [in] 附带的数据,一般为post请求的参数 iDataLen [in] pData长度,字节 返回值: TRUE 表示成功,FALSE表示失败 */ BOOL ReadServBackData(HINTERNET hRequest, char *&pData, DWORD &Len, BOOL bNeedReport); // 清理JSON数据 void ClearJson(cJSON* json); // 创建请求的JSON数据 BOOL CreateJsonReqData(char * pReq); // 解析JSON数据 BOOL AnalyzeRecvData(char* pData); void OutputDebugVal(const char * strOutputString, ...);
a3eb072bb9428541ee8e5f9704c543d786e89445
[ "Text", "Markdown", "C++", "C" ]
18
Text
zhaoguohan123/CppDemo
1101d089dfede2eb041f29e0df700f5d97388729
77c82f56bac016245da3c995d6e2b2bf5a4db593
refs/heads/master
<file_sep> define(function (require, exports, module) { require("jquery"); var Global = require("global") var ObjectJS = {}; //登陆初始化 ObjectJS.init = function (status) { ObjectJS.bindEvent(); } //绑定事件 ObjectJS.bindEvent = function () { $("#iptPwd").on("keypress", function (e) { if (e.keyCode == 13) { $("#btnLogin").click(); $("#iptPwd").blur(); } }); //登录 $("#btnLogin").click(function () { if (!$("#iptUserName").val()) { $(".registerErr").html("请输入账号").slideDown(); return; } if (!$("#iptPwd").val()) { $(".registerErr").html("请输入密码").slideDown(); return; } $(this).html("登录中...").attr("disabled", "disabled"); Global.post("/Manage/Home/UserLogin", { userName: $("#iptUserName").val(), pwd: $("#iptPwd").val() }, function (data) { $("#btnLogin").html("登录").removeAttr("disabled"); if (data.result == 1) { location.href = "Index"; } else if (data.result == 2) { $(".registerErr").html("用户名不存在").slideDown(); } else if (data.result == 3) { $(".registerErr").html("账号或密码有误").slideDown(); } else if (data.result == 4) { $(".registerErr").html("您的账户已注销,请切换其他账户登录").slideDown(); } }); }); } module.exports = ObjectJS; });<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using WinWarEntity; namespace WinWarWeb.Controllers { public class BaseController : Controller { public Dictionary<string, Object> jsonResult = new Dictionary<string, object>(); public Passport currentPassport { get { if (Session["WinWarUser"] == null) { //Session["WinWarUser"] = new Passport() { UserID = 5 }; //return new Passport() { UserID = 5 }; return new Passport(); } else { return (Passport)Session["WinWarUser"]; } } } } } <file_sep>Use [WinWar] GO IF EXISTS (SELECT * FROM sysobjects WHERE type = 'P' AND name = 'M_AddNews') BEGIN DROP Procedure M_AddNews END GO /*********************************************************** 过程名称: M_AddNews 功能描述: 添加评论 参数说明: 编写日期: 2016/6/6 程序作者: Allen 调试记录: exec M_AddNews 100000002,1,6128258538 ************************************************************/ CREATE PROCEDURE [dbo].[M_AddNews] @ID bigint, @Title nvarchar(500), @TitleSub nvarchar(500)='', @TitleApp nvarchar(500)='', @NewsSum nvarchar(500)='', @Author nvarchar(100)='', @Source nvarchar(100)='', @PicUrl nvarchar(200)='', @PosiPar int=3, @Important int=2, @IsIssue int=0, @TypeID bigint, @Content text AS declare @NEWS_UNI_CODE bigint select @NEWS_UNI_CODE=max(NEWS_UNI_CODE) from NEWS_MAIN if(@NEWS_UNI_CODE is null) set @NEWS_UNI_CODE=0 set @NEWS_UNI_CODE+=1 insert into NEWS_MAIN(NEWS_UNI_CODE,TITLE_MAIN,TITLE_SUB,TITLE_APP,NEWS_SUM,NEWS_AUTHOR,REAL_SOURCE_NAME,Pic_URL,NEGA_POSI_PAR,IMPT_PAR,IS_ISSUE,NEWS_TYPE) values(@NEWS_UNI_CODE,@Title,@TitleSub,@TitleApp,@NewsSum,@Author,@Source,@PicUrl,@PosiPar,@Important,@IsIssue,@TypeID) insert into NEWS_CONTENT(NEWS_UNI_CODE,HTML_TXT) values(@NEWS_UNI_CODE,@Content) <file_sep>define(function (require, exports, module) { var Global = require("global"); var DoT = require("dot"); var Paras = { lastFavoriteID: 0, pageSize:5 }; var ObjectJS = {}; ObjectJS.init = function () { ObjectJS.bindEvent(); ObjectJS.getNewsCollect(); }; ObjectJS.bindEvent = function () { //加载更多新闻讨论 $(".load-more").click(function () { ObjectJS.getNewsCollect(); }); }; ObjectJS.getNewsCollect = function () { $(".data-loading").show(); Global.post("/User/GetNewsFavorites", Paras, function (data) { $(".data-loading").hide(); Paras.lastFavoriteID = data.lastFavoriteID; var items = data.items; var len=items.length; if (len > 0) { $(".content ul li.no-data").remove(); DoT.exec("template/home/news-list.html", function (template) { var innerhtml = template(items); innerhtml = $(innerhtml); $(".content ul").append(innerhtml); innerhtml.fadeIn(400); $(".content ul").find(".news").click(function () { var id = $(this).data("id"); location.href = "/home/detail/" + id; //$("#iframe-news-detail").attr("src", "/home/detail/" + id); //$(".news-detail").fadeIn(); //$("#news_" + id + " .news-title").addClass("news-read"); }); }); } if (len == Paras.pageSize) { $(".load-more").show(); } else { $(".load-more").hide(); } }); } module.exports = ObjectJS; });<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WinWarEntity { [Serializable] public class Passport { private int _autoid; private string _userid; private string _loginname; private string _loginpwd; private string _name=""; private string _email=""; private string _mobilephone=""; private string _officephone=""; private string _citycode=""; private string _address=""; private DateTime _birthday; private int? _age=0; private int? _sex=0; private int? _education=0; private string _jobs=""; private string _avatar=""; private string _parentid; private int? _allocation=0; private int? _status=0; private string _description=""; private DateTime _effecttime; private DateTime _turnovertime; private DateTime _createtime= DateTime.Now; private string _createuserid; public List<Menu> Menus { get; set; } /// <summary> /// /// </summary> public int AutoID { set{ _autoid=value;} get{return _autoid;} } /// <summary> /// /// </summary> [Property("Lower")] public long UserID { set; get; } /// <summary> /// /// </summary> public string LoginName { set{ _loginname=value;} get{return _loginname;} } /// <summary> /// /// </summary> public string BindMobilePhone { set; get; } /// <summary> /// /// </summary> public string LoginPWD { set{ _loginpwd=value;} get{return _loginpwd;} } /// <summary> /// /// </summary> public string Name { set{ _name=value;} get{return _name;} } /// <summary> /// /// </summary> public string Email { set{ _email=value;} get{return _email;} } /// <summary> /// /// </summary> public string MobilePhone { set{ _mobilephone=value;} get{return _mobilephone;} } /// <summary> /// /// </summary> public string OfficePhone { set{ _officephone=value;} get{return _officephone;} } /// <summary> /// /// </summary> public string CityCode { set{ _citycode=value;} get{return _citycode;} } /// <summary> /// /// </summary> public string Address { set{ _address=value;} get{return _address;} } /// <summary> /// /// </summary> public DateTime Birthday { set{ _birthday=value;} get{return _birthday;} } /// <summary> /// /// </summary> public int? Age { set{ _age=value;} get{return _age;} } /// <summary> /// /// </summary> public int? Sex { set{ _sex=value;} get{return _sex;} } /// <summary> /// /// </summary> public int? Education { set{ _education=value;} get{return _education;} } /// <summary> /// /// </summary> public string Jobs { set{ _jobs=value;} get{return _jobs;} } /// <summary> /// /// </summary> public string Avatar { set{ _avatar=value;} get{return _avatar;} } /// <summary> /// /// </summary> [Property("Lower")] public string ParentID { set{ _parentid=value;} get{return _parentid;} } /// <summary> /// /// </summary> public int? Allocation { set{ _allocation=value;} get{return _allocation;} } /// <summary> /// /// </summary> public int? Status { set{ _status=value;} get{return _status;} } /// <summary> /// /// </summary> public string Description { set{ _description=value;} get{return _description;} } /// <summary> /// /// </summary> public DateTime EffectTime { set{ _effecttime=value;} get{return _effecttime;} } /// <summary> /// /// </summary> public DateTime TurnoverTime { set{ _turnovertime=value;} get{return _turnovertime;} } /// <summary> /// /// </summary> public DateTime CreateTime { set{ _createtime=value;} get{return _createtime;} } /// <summary> /// /// </summary> [Property("Lower")] public string CreateUserID { set{ _createuserid=value;} get{return _createuserid;} } [Property("Lower")] public string TeamID { get; set; } [Property("Lower")] public string DepartID { get; set; } public string BindWeiXinID { get; set; } /// <summary> /// 填充数据 /// </summary> /// <param name="dr"></param> public void FillData(System.Data.DataRow dr) { dr.FillData(this); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data; using WinWarEntity; using WinWarDAL; namespace WinWarBusiness { public class OrganizationBusiness { #region Cache private static Dictionary<string, List<Users>> _cacheUsers; private static Dictionary<string, List<Role>> _cacheRoles; /// <summary> /// 缓存用户信息 /// </summary> private static Dictionary<string, List<Users>> Users { get { if (_cacheUsers == null) { _cacheUsers = new Dictionary<string, List<Users>>(); } return _cacheUsers; } set { _cacheUsers = value; } } /// <summary> /// 缓存角色信息 /// </summary> private static Dictionary<string, List<Role>> Roles { get { if (_cacheRoles == null) { _cacheRoles = new Dictionary<string, List<Role>>(); } return _cacheRoles; } set { _cacheRoles = value; } } #endregion #region 查询 public static bool IsExistLoginName(string loginName) { if (string.IsNullOrEmpty(loginName)) return false; object count = CommonBusiness.Select("Users", "count(0)", " Status=1 and (LoginName='" + loginName + "' or BindMobilePhone='" + loginName + "')"); return Convert.ToInt32(count) > 0; } public static Users GetUserByUserName(string loginname, string pwd,out int result, string operateip) { pwd = WinWarTool.Encrypt.GetEncryptPwd(pwd, loginname); DataSet ds = new OrganizationDAL().GetUserByUserName(loginname, pwd, out result); Users model = null; if (ds.Tables.Contains("User") && ds.Tables["User"].Rows.Count > 0) { model = new Users(); model.FillData(ds.Tables["User"].Rows[0]); model.LogGUID = Guid.NewGuid().ToString(); model.Role = GetRoleByID(model.RoleID); //权限 if (model.Role != null && model.Role.IsDefault == 1) { model.Menus = CommonBusiness.ClientMenus; } else { model.Menus = new List<Menu>(); foreach (DataRow dr in ds.Tables["Permission"].Rows) { Menu menu = new Menu(); menu.FillData(dr); model.Menus.Add(menu); } } } return model; } public static bool ConfirmLoginPwd(string loginname, string pwd) { pwd = WinWarTool.Encrypt.GetEncryptPwd(pwd, loginname); int result; DataSet ds = new OrganizationDAL().GetUserByUserName(loginname, pwd,out result); if (ds.Tables.Contains("User") && ds.Tables["User"].Rows.Count > 0) { return true; } return false; } public static Users GetUserByMDUserID(string mduserid, string operateip) { DataSet ds = new OrganizationDAL().GetUserByMDUserID(mduserid); Users model = null; if (ds.Tables.Contains("User") && ds.Tables["User"].Rows.Count > 0) { model = new Users(); model.FillData(ds.Tables["User"].Rows[0]); model.LogGUID = Guid.NewGuid().ToString(); model.Role = GetRoleByID(model.RoleID); //处理缓存 if (!Users.ContainsKey(model.AgentID)) { GetUsers(model.AgentID); } if (Users[model.AgentID].Where(u => u.UserID == model.UserID).Count() == 0) { Users[model.AgentID].Add(model); } else { var user = Users[model.AgentID].Where(u => u.UserID == model.UserID).FirstOrDefault(); user.LogGUID = model.LogGUID; } //权限 if (model.Role != null && model.Role.IsDefault == 1) { model.Menus = CommonBusiness.ClientMenus; } else { model.Menus = new List<Menu>(); foreach (DataRow dr in ds.Tables["Permission"].Rows) { Menu menu = new Menu(); menu.FillData(dr); model.Menus.Add(menu); } } } if (string.IsNullOrEmpty(operateip)) { operateip = ""; } return model; } public static Users GetUserByAliMemberID(string aliMemberID, string operateip) { DataSet ds = new OrganizationDAL().GetUserByAliMemberID(aliMemberID); Users model = null; if (ds.Tables.Contains("User") && ds.Tables["User"].Rows.Count > 0) { model = new Users(); model.FillData(ds.Tables["User"].Rows[0]); model.LogGUID = Guid.NewGuid().ToString(); model.Role = GetRoleByID(model.RoleID); //处理缓存 if (!Users.ContainsKey(model.AgentID)) { GetUsers(model.AgentID); } if (Users[model.AgentID].Where(u => u.UserID == model.UserID).Count() == 0) { Users[model.AgentID].Add(model); } else { var user = Users[model.AgentID].Where(u => u.UserID == model.UserID).FirstOrDefault(); user.LogGUID = model.LogGUID; } //权限 if (model.Role != null && model.Role.IsDefault == 1) { model.Menus = CommonBusiness.ClientMenus; } else { model.Menus = new List<Menu>(); foreach (DataRow dr in ds.Tables["Permission"].Rows) { Menu menu = new Menu(); menu.FillData(dr); model.Menus.Add(menu); } } } if (string.IsNullOrEmpty(operateip)) { operateip = ""; } return model; } public static Users GetUserByUserID(string userid) { if (string.IsNullOrEmpty(userid)) { return null; } userid = userid.ToLower(); DataTable dt = new OrganizationDAL().GetUserByUserID(userid); Users model = new Users(); if (dt.Rows.Count > 0) { model.FillData(dt.Rows[0]); model.Role = GetRoleByID(model.RoleID); } return model; } public static List<Users> GetUsers(string keyWords, string departID, string roleID, int pageSize, int pageIndex, ref int totalCount, ref int pageCount) { string whereSql =" Status<>9"; if (!string.IsNullOrEmpty(keyWords)) whereSql += " and ( Name like '%" + keyWords + "%' or MobilePhone like '%" + keyWords + "%' or Email like '%" + keyWords + "%')"; if (!string.IsNullOrEmpty(departID)) whereSql += " and DepartID='" + departID + "'"; if (!string.IsNullOrEmpty(roleID)) whereSql += " and RoleID='" + roleID + "'"; DataTable dt = CommonBusiness.GetPagerData("Users", "*", whereSql, "AutoID", pageSize, pageIndex, out totalCount, out pageCount); List<Users> list = new List<Users>(); Users model; foreach (DataRow item in dt.Rows) { model = new Users(); model.FillData(item); model.CreateUser = GetUserByUserID(model.CreateUserID); model.Role = GetRoleByID(model.RoleID); list.Add(model); } return list; } public static List<Users> GetUsers(string agentid) { if (string.IsNullOrEmpty(agentid)) { return new List<Users>(); } if (!Users.ContainsKey(agentid)) { List<Users> list = new List<WinWarEntity.Users>(); DataTable dt = OrganizationDAL.BaseProvider.GetUsers(agentid); foreach (DataRow dr in dt.Rows) { Users model = new Users(); model.FillData(dr); model.Role = GetRoleByID(model.RoleID); list.Add(model); } Users.Add(agentid, list); return list; } return Users[agentid].ToList(); } public static List<Users> GetUsersByParentID(string parentid, string agentid) { var users = GetUsers(agentid).Where(m => m.ParentID == parentid && m.Status == 1).ToList(); return users; } public static List<Users> GetStructureByParentID(string parentid, string agentid) { var users = GetUsersByParentID(parentid, agentid); foreach (var user in users) { user.ChildUsers = GetStructureByParentID(user.UserID, agentid); } return users; } public static List<Role> GetRoles() { DataTable dt = new OrganizationDAL().GetRoles(); List<Role> list = new List<Role>(); foreach (DataRow dr in dt.Rows) { Role model = new Role(); model.FillData(dr); list.Add(model); } return list; } public static Role GetRoleByID(string roleid) { Role model = null; DataSet ds = OrganizationDAL.BaseProvider.GetRoleByID(roleid); if (ds.Tables.Contains("Role") && ds.Tables["Role"].Rows.Count > 0) { model = new Role(); model.FillData(ds.Tables["Role"].Rows[0]); model.Menus = new List<Menu>(); foreach (DataRow dr in ds.Tables["Menus"].Rows) { Menu menu = new Menu(); menu.FillData(dr); model.Menus.Add(menu); } } return model; } #endregion #region 添加 public string CreateRole(string name, string parentid, string description, string operateid, string agentid, string clientid) { string roleid = Guid.NewGuid().ToString(); bool bl = OrganizationDAL.BaseProvider.CreateRole(roleid, name, parentid, description, operateid, agentid, clientid); if (bl) { return roleid; } return ""; } public static Users CreateUser(string loginname, string loginpwd, string name, string mobile, string email, string citycode, string address, string jobs, string roleid, string operateid, out int result) { string userid = Guid.NewGuid().ToString(); loginpwd = WinWarTool.Encrypt.GetEncryptPwd(loginpwd, loginname); Users user = null; DataTable dt = OrganizationDAL.BaseProvider.CreateUser(userid, loginname, loginpwd, name, mobile, email, citycode, address, jobs, roleid, operateid, out result); if (dt.Rows.Count > 0) { user = new Users(); user.FillData(dt.Rows[0]); } return user; } #endregion #region 编辑/删除 public static bool UpdateUserAccount(string userid, string loginName, string loginPwd, string agentid) { loginPwd = WinWarTool.Encrypt.GetEncryptPwd(loginPwd, loginName); bool flag = OrganizationDAL.BaseProvider.UpdateUserAccount(userid, loginName, loginPwd); if (flag) { if (Users.ContainsKey(agentid)) { List<Users> users = Users[agentid]; Users u = users.Find(m => m.UserID == userid); u.LoginName = loginName; } } return flag; } public static bool UpdateUserPass(string userid, string loginPwd, string agentid) { loginPwd = WinWarTool.Encrypt.GetEncryptPwd(loginPwd, ""); bool flag = OrganizationDAL.BaseProvider.UpdateUserPass(userid, loginPwd); return flag; } public static bool UpdateUserAccountPwd(string loginName, string loginPwd) { loginPwd = WinWarTool.Encrypt.GetEncryptPwd(loginPwd, loginName); bool flag = OrganizationDAL.BaseProvider.UpdateUserAccountPwd(loginName, loginPwd); return flag; } public static bool UpdateUserInfo(string userid, string name, string jobs, DateTime birthday, int age, string departID, string email, string mobilePhone, string officePhone, string agentid) { bool flag = OrganizationDAL.BaseProvider.UpdateUserInfo(userid, name, jobs, birthday, age, departID, email, mobilePhone, officePhone); //清除缓存 if (flag) { if (Users.ContainsKey(agentid)) { List<Users> users = Users[agentid]; Users u = users.Find(m => m.UserID == userid); u.Name = name; u.Jobs = jobs; u.Birthday = birthday; u.Age = age; u.DepartID = departID; u.Email = email; u.MobilePhone = mobilePhone; u.OfficePhone = officePhone; } } return flag; } public static bool UpdateAccountAvatar(string userid, string avatar, string agentid) { bool flag = OrganizationDAL.BaseProvider.UpdateAccountAvatar(userid, avatar); //清除缓存 if (flag) { if (Users.ContainsKey(agentid)) { List<Users> users = Users[agentid]; Users u = users.Find(m => m.UserID == userid); u.Avatar = avatar; } } return flag; } public static bool UpdateAccountBindMobile(string userid, string bindMobile, string agentid) { bool flag = OrganizationDAL.BaseProvider.UpdateAccountBindMobile(userid, bindMobile); //清除缓存 if (flag) { if (Users.ContainsKey(agentid)) { List<Users> users = Users[agentid]; Users u = users.Find(m => m.UserID == userid); u.BindMobilePhone = bindMobile; } } return flag; } public static bool BindAccountAliMember(string userid, string memberid, string agentid) { bool flag = OrganizationDAL.BaseProvider.BindAccountAliMember(userid, memberid); //清除缓存 if (flag) { if (Users.ContainsKey(agentid)) { List<Users> users = Users[agentid]; Users u = users.Find(m => m.UserID == userid); u.AliMemberID = memberid; } } return flag; } public static bool ClearAccountBindMobile(string userid, string agentid) { bool flag = OrganizationDAL.BaseProvider.ClearAccountBindMobile(userid); //清除缓存 if (flag) { if (Users.ContainsKey(agentid)) { List<Users> users = Users[agentid]; Users u = users.Find(m => m.UserID == userid); u.BindMobilePhone = string.Empty; } } return flag; } public bool UpdateRole(string roleid, string name, string description, string operateid, string ip) { bool bl = OrganizationDAL.BaseProvider.UpdateRole(roleid, name, description); return bl; } public bool DeleteRole(string roleid, string operateid, string ip, out int result) { bool bl = OrganizationDAL.BaseProvider.DeleteRole(roleid, out result); return bl; } public bool UpdateRolePermission(string roleid, string permissions, string operateid, string ip) { return OrganizationDAL.BaseProvider.UpdateRolePermission(roleid, permissions, operateid); } public bool UpdateUserParentID(string userid, string parentid, string agentid, string operateid, string ip) { bool bl = OrganizationDAL.BaseProvider.UpdateUserParentID(userid, parentid, agentid); if (bl) { var user = GetUserByUserID(userid); user.ParentID = parentid; } return bl; } public bool ChangeUsersParentID(string userid, string olduserid, string agentid, string operateid, string ip) { bool bl = OrganizationDAL.BaseProvider.ChangeUsersParentID(userid, olduserid, agentid); if (bl) { //新员工 var user = GetUserByUserID(userid); //被替换员工 var oldUser = GetUserByUserID(olduserid); user.ParentID = oldUser.ParentID; oldUser.ParentID = ""; var list = GetUsersByParentID(olduserid, agentid); foreach (var model in list) { model.ParentID = userid; } } return bl; } public bool DeleteUserByID(string userid, string operateid, string ip, out int result) { bool bl = OrganizationDAL.BaseProvider.DeleteUserByID(userid, out result); return bl; } public bool UpdateUserRole(string userid, string roleid, string operateid, string ip) { var user = GetUserByUserID(userid); if (user.RoleID.ToLower() != roleid.ToLower()) { bool bl = OrganizationDAL.BaseProvider.UpdateUserRole(userid, roleid, operateid); return bl; } return true; } #endregion } } <file_sep>Use [WinWar] GO IF EXISTS (SELECT * FROM sysobjects WHERE type = 'P' AND name = 'P_AddNewsComment') BEGIN DROP Procedure P_AddNewsComment END GO /*********************************************************** 过程名称: P_AddNewsComment 功能描述: 添加评论 参数说明: 编写日期: 2016/6/6 程序作者: Allen 调试记录: exec P_AddNewsComment 100000002,1,6128258538 ************************************************************/ CREATE PROCEDURE [dbo].[P_AddNewsComment] @NewsCode bigint, @Content nvarchar(500)='', @UserID bigint, @UserName nvarchar(100)='', @ReplyID bigint=0, @ReplyUserID bigint, @ReplyUserName nvarchar(100)='' AS if(@ReplyID=0) begin insert into NEWS_Comment([User_ID],[User_Name],NEWS_UNI_CODE,[Type],Content,Praise_Count,Reply_Count,Reply_ID,Reply_User_ID,Reply_User_Name,Create_Date) values(@UserID,@UserName,@NewsCode,1,@Content,0,0,0,0,'',getdate()) end else begin insert into NEWS_Comment([User_ID],[User_Name],NEWS_UNI_CODE,[Type],Content,Praise_Count,Reply_Count,Reply_ID,Reply_User_ID,Reply_User_Name,Create_Date) select @UserID,@UserName,@NewsCode,2,@Content,0,0,@ReplyID,@ReplyUserID,@ReplyUserName,getdate() from NEWS_Comment where ID=@ReplyID Update NEWS_Comment set Reply_Count=Reply_Count+1 where ID=@ReplyID end Update NEWS_MAIN set Comment_Count=Comment_Count+1 where NEWS_UNI_CODE=@NewsCode <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; namespace WeiXin.Sdk { public enum ApiOption { [Description("/sns/oauth2/access_token")] access_token, [Description("/sns/userinfo")] userinfo, [DescriptionAttribute("erp.manufacture.pullFentGoodsCodes")] pullFentGoodsCodes, [Description("erp.manufacture.pullFentDataList")] pullFentDataList, [Description("erp.manufacture.batchUpdateFent")] batchUpdateFent, [Description("erp.manufacture.pullBulkGoodsCodes")] pullBulkGoodsCodes, [Description("erp.manufacture.pullBulkDataList")] pullBulkDataList, [Description("erp.manufacture.batchUpdateBulk")] batchUpdateBulk, [Description("erp.manufacture.pushProductionPlan")] pushProductionPlan } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WinWarEntity { public class NewsCommentEntity { public long ID { get; set; } public long User_ID { get; set; } public string User_Name { get; set; } public long News_Uni_Code { get; set; } public int Type { get; set; } public string Content { get; set; } public long Praise_Count { get; set; } public long Reply_Count { get; set; } public long Reply_ID { get; set; } public long Reply_User_ID { get; set; } public string Reply_User_Name { get; set; } public DateTime Create_Date { get; set; } /// <summary> /// 大于0都等于点赞 /// </summary> public long Is_Praise { get; set; } public Passport CreateUser { get; set; } /// <summary> /// 填充数据 /// </summary> /// <param name="dr"></param> public void FillData(System.Data.DataRow dr) { dr.FillData(this); } } } <file_sep>Use [WinWar] GO IF EXISTS (SELECT * FROM sysobjects WHERE type = 'P' AND name = 'M_EditNews') BEGIN DROP Procedure M_EditNews END GO /*********************************************************** 过程名称: M_EditNews 功能描述: 添加评论 参数说明: 编写日期: 2016/6/6 程序作者: Allen 调试记录: exec M_EditNews 100000002,1,6128258538 ************************************************************/ CREATE PROCEDURE [dbo].[M_EditNews] @ID bigint, @Title nvarchar(500), @TitleSub nvarchar(500)='', @TitleApp nvarchar(500)='', @NewsSum nvarchar(500)='', @Author nvarchar(100)='', @Source nvarchar(100)='', @PicUrl nvarchar(200)='', @PosiPar int=3, @Important int=2, @IsIssue int=0, @TypeID bigint, @Content text AS update NEWS_MAIN set TITLE_MAIN=@Title,TITLE_SUB=@TitleSub,TITLE_APP=@TitleApp,Pic_URL=@PicUrl, NEWS_SUM=@NewsSum,NEWS_AUTHOR=@Author,REAL_SOURCE_NAME=@Source,NEGA_POSI_PAR=@PosiPar,IMPT_PAR=@Important,IS_ISSUE=@IsIssue,NEWS_TYPE=@TypeID where NEWS_UNI_CODE=@ID update NEWS_CONTENT set HTML_TXT=@Content where NEWS_UNI_CODE=@ID <file_sep>define(function (require, exports, module) { var ObjectJS = {}; ObjectJS.init = function () { ObjectJS.bindEvent(); } ObjectJS.bindEvent = function () { //窗体滚动 置顶头部 $(window).scroll(function () { if ($(window).scrollTop() > 70) { $(".back-top").fadeIn(500); } else { $(".back-top").fadeOut(1000); } }); //返回顶部 $(".back-top").click(function () { $('body,html').animate({ scrollTop: 0 }, 300); return false; }); } module.exports = ObjectJS; });<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using WinWarBusiness; namespace WinWarWeb.Controllers { public class UserController : BaseController { public ActionResult Index() { if (Session["WinWarUser"] == null){ return Redirect("/user/login"); } ViewBag.Passport = currentPassport; return View(); } public ActionResult Login(string returnUrl) { var authorizeUrl = WeiXin.Sdk.Token.GetAuthorizeUrl(Server.UrlEncode(WeiXin.Sdk.AppConfig.CallBackUrl), returnUrl, YXERP.Common.Common.IsMobileDevice()); return Redirect(authorizeUrl); } public ActionResult WeiXinCallBack(string code, string state) { if (!string.IsNullOrEmpty(code)) { var token = WeiXin.Sdk.Token.GetAccessToken(code); if (!string.IsNullOrEmpty(token.access_token)) { string unionid = token.unionid??string.Empty; string openid = token.openid; var passport=new WeiXin.Sdk.PassportEntity(); if (string.IsNullOrEmpty(unionid)) { passport = WeiXin.Sdk.Passport.GetUserInfo(token.access_token, openid); unionid=passport.unionid; } WinWarEntity.Passport user=PassportBusiness.GetPassportByWeiXinID(unionid); if(user.UserID==0) { if(string.IsNullOrEmpty(passport.unionid)) { passport = WeiXin.Sdk.Passport.GetUserInfo(token.access_token, openid); } PassportBusiness.BindWeiXinID(passport.nickname,passport.headimgurl,passport.unionid); user = PassportBusiness.GetPassportByWeiXinID(unionid); } Session["WinWarUser"]=user; if (!string.IsNullOrEmpty(state)) { return Redirect(state); } } } return Redirect("/Home/Index"); } public ActionResult Logout() { Session["WinWarUser"] = null; return Redirect("/home/index"); } #region ajax public JsonResult GetNewsFavorites(int pageSize, long lastFavoriteID) { if (Session["WinWarUser"] == null) { jsonResult.Add("result", -1); } else { var items = NewsBusiness.BaseBusiness.GetNewsFavorites(currentPassport.UserID, pageSize, ref lastFavoriteID); jsonResult.Add("items", items); jsonResult.Add("lastFavoriteID", lastFavoriteID); jsonResult.Add("result", -1); } return new JsonResult() { Data = jsonResult, JsonRequestBehavior = JsonRequestBehavior.AllowGet }; } #endregion } } <file_sep>Use [WinWar] GO IF EXISTS (SELECT * FROM sysobjects WHERE type = 'P' AND name = 'P_GetNewsDetail') BEGIN DROP Procedure P_GetNewsDetail END GO /*********************************************************** 过程名称: P_GetNewsDetail 功能描述: 获取新闻详情 参数说明: 编写日期: 2016/6/9 程序作者: Mu 调试记录: exec P_GetNewsDetail 6128258538 ************************************************************/ CREATE PROCEDURE [dbo].[P_GetNewsDetail] @NewsCode bigint, @UserID bigint=0 AS if(@UserID<>0) select n.*,isnull(f.Is_Praise,0) Is_Praise,isnull(Is_Collect,0) Is_Collect,c.HTML_TXT from NEWS_MAIN n left join NEWS_CONTENT c on n.News_Uni_Code=c.News_Uni_Code left join NEWS_Favorite f on n.News_Uni_Code=f.News_Uni_Code and f.[User_ID]=@UserID where n.News_Uni_Code=@NewsCode else select n.*,c.HTML_TXT from NEWS_MAIN n left join NEWS_CONTENT c on n.News_Uni_Code=c.News_Uni_Code where n.News_Uni_Code=@NewsCode update NEWS_MAIN set View_Count=View_Count+1 where News_Uni_Code=@NewsCode <file_sep>Use [WinWar] GO IF EXISTS (SELECT * FROM sysobjects WHERE type = 'P' AND name = 'M_DeleteUserByID') BEGIN DROP Procedure M_DeleteUserByID END GO /*********************************************************** 过程名称: M_DeleteUserByID 功能描述: 删除员工 参数说明: 编写日期: 2015/10/24 程序作者: Allen 调试记录: exec M_DeleteUserByID ************************************************************/ CREATE PROCEDURE [dbo].[M_DeleteUserByID] @UserID nvarchar(64), @Result int output --0:失败,1:成功 AS begin tran set @Result=0 declare @Err int=0,@RoleID nvarchar(64) --防止自杀式删除用户,管理员至少保留一个 select @RoleID=RoleID from Users where UserID=@UserID if exists (select AutoID from Role where RoleID=@RoleID and IsDefault=1) begin if not exists(select UserID from Users where RoleID=@RoleID and Status=1 and UserID<>@UserID) begin set @Result=0 rollback tran return end end Update Users set Status=9,ParentID='',RoleID='' where UserID=@UserID Update UserRole set Status=9 where UserID=@UserID and Status=1 set @Err+=@@error if(@Err>0) begin set @Result=0 rollback tran end else begin set @Result=1 commit tran end<file_sep>Use [WinWar] GO IF EXISTS (SELECT * FROM sysobjects WHERE type = 'P' AND name = 'P_AddNewsPraiseCount') BEGIN DROP Procedure P_AddNewsPraiseCount END GO /*********************************************************** 过程名称: P_AddNewsPraiseCount 功能描述: 收藏新闻 参数说明: 编写日期: 2016/6/6 程序作者: Allen 调试记录: exec P_AddNewsPraiseCount 100000002,1,6128258090 ************************************************************/ CREATE PROCEDURE [dbo].[P_AddNewsPraiseCount] @UserID bigint, @IsAdd int=1, @NewsCode bigint AS if(@UserID>0 and @NewsCode>0) begin if exists(select ID from NEWS_Favorite where NEWS_UNI_CODE=@NewsCode and [User_ID]=@UserID) begin Update NEWS_Favorite set Is_Praise=@IsAdd where NEWS_UNI_CODE=@NewsCode and [User_ID]=@UserID end else begin insert into NEWS_Favorite([User_ID],NEWS_UNI_CODE,Is_Praise,Is_Collect,Create_Date) values(@UserID,@NewsCode,@IsAdd,0,getdate()) end if(@IsAdd=1) begin Update NEWS_MAIN set Praise_Count=Praise_Count+1 where NEWS_UNI_CODE=@NewsCode end else begin Update NEWS_MAIN set Praise_Count=Praise_Count-1 where NEWS_UNI_CODE=@NewsCode and Praise_Count>=1 end end <file_sep>Use [WinWar] GO IF EXISTS (SELECT * FROM sysobjects WHERE type = 'P' AND name = 'P_AddNewsCollectCount') BEGIN DROP Procedure P_AddNewsCollectCount END GO /*********************************************************** 过程名称: P_AddNewsCollectCount 功能描述: 收藏新闻 参数说明: 编写日期: 2016/6/6 程序作者: Allen 调试记录: exec P_AddNewsCollectCount 100000002,1,6128258538 ************************************************************/ CREATE PROCEDURE [dbo].[P_AddNewsCollectCount] @UserID bigint, @IsAdd int=1, @NewsCode bigint AS if(@UserID>0 and @NewsCode>0) begin if exists(select ID from NEWS_Favorite where NEWS_UNI_CODE=@NewsCode and [User_ID]=@UserID) begin Update NEWS_Favorite set Is_Collect=@IsAdd,Create_Date=getdate() where NEWS_UNI_CODE=@NewsCode and [User_ID]=@UserID end else begin insert into NEWS_Favorite([User_ID],NEWS_UNI_CODE,Is_Praise,Is_Collect,Create_Date) values(@UserID,@NewsCode,0,@IsAdd,getdate()) end if(@IsAdd=1) begin Update NEWS_MAIN set Collect_Count=Collect_Count+1 where NEWS_UNI_CODE=@NewsCode end else begin Update NEWS_MAIN set Collect_Count=Collect_Count-1 where NEWS_UNI_CODE=@NewsCode and Collect_Count>=1 end end <file_sep>Use [WinWar] GO IF EXISTS (SELECT * FROM sysobjects WHERE type = 'P' AND name = 'M_GetUserToLogin') BEGIN DROP Procedure M_GetUserToLogin END GO /*********************************************************** 过程名称: M_GetUserToLogin 功能描述: 验证云销系统登录并返回信息 参数说明: 编写日期: 2015/4/22 程序作者: Allen 调试记录: exec M_GetUserToLogin 'Admin','ADA9D527563353B415575BD5BAAE0469' ************************************************************/ CREATE PROCEDURE [dbo].[M_GetUserToLogin] @LoginName nvarchar(200), @LoginPWD nvarchar(64), @Result int output --1:查询正常;2:用户名不存在;3:用户密码有误;4:用户被注销 AS declare @UserID nvarchar(64),@ClientID nvarchar(64),@AgentID nvarchar(64),@RoleID nvarchar(64) set @UserID='' IF EXISTS(select UserID from Users where LoginName=@LoginName and Status<>9) begin select @UserID = UserID,@ClientID=ClientID,@AgentID=AgentID,@RoleID=RoleID from Users where LoginName=@LoginName and LoginPWD=@LoginPWD if(@UserID<>'') begin set @UserID='' select @UserID = UserID,@ClientID=ClientID,@AgentID=AgentID,@RoleID=RoleID from Users where LoginName=@LoginName and LoginPWD=@LoginPWD and Status<>9 if(@UserID<>'') begin --会员信息 select * from Users where UserID=@UserID --权限信息 select m.* from Menu m left join RolePermission r on r.MenuCode=m.MenuCode where (RoleID=@RoleID or IsLimit=0 ) set @Result=1 end else set @Result=4 end else set @Result=3 end else set @Result=2 <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace WinWarWeb.Areas.Manage.Controllers { [WinWarWeb.Manage.Common.UserAuthorize] public class BaseController : Controller { // // GET: /Manage/Base/ public Dictionary<string, Object> jsonResult = new Dictionary<string, object>(); /// <summary> /// 默认分页Size /// </summary> protected int PageSize = 10; /// <summary> /// 登录IP /// </summary> protected string OperateIP { get { return string.IsNullOrEmpty(Request.Headers.Get("X-Real-IP")) ? Request.UserHostAddress : Request.Headers["X-Real-IP"]; } } /// <summary> /// 当前登录用户 /// </summary> protected WinWarEntity.Users CurrentUser { get { if (Session["ClientManager"] == null) { return null; } else { return (WinWarEntity.Users)Session["ClientManager"]; } } set { Session["ClientManager"] = value; } } /// <summary> /// 返回数据集合 /// </summary> protected Dictionary<string, object> JsonDictionary = new Dictionary<string, object>(); } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WinWarEntity { public class NewsEntity { public long News_Uni_Code { get; set; } public DateTime Pub_Time { get; set; } public string News_Author { get; set; } public int Nega_Posi_Par { get; set; } public string Title_Main { get; set; } public string Title_Sub { get; set; } public string Title_App { get; set; } public int News_Type { get; set; } public int Source_Uni_Code { get; set; } public string News_Sum { get; set; } public string Is_Headline_Par { get; set; } public int Impt_Par { get; set; } public string Is_Main_News { get; set; } public string Is_Issue { get; set; } public string Real_Source_Name { get; set; } /// <summary> /// 图片 /// </summary> public string Pic_URL { get; set; } /// <summary> /// 浏览数 /// </summary> public long View_Count { get; set; } /// <summary> /// 评论数 /// </summary> public long Comment_Count { get; set; } /// <summary> /// 点赞数 /// </summary> public long Praise_Count { get; set; } /// <summary> /// 收藏数 /// </summary> public long Collect_Count { get; set; } public string Txt_Content { get; set; } public string Html_Txt { get; set; } /// <summary> /// 是否点赞 /// </summary> public int Is_Praise { get; set; } /// <summary> /// 是否收藏 /// </summary> public int Is_Collect { get; set; } public string NEWS_TYPE_NAME2 { get; set; } public NewsTypeEntity NewsType { get; set; } /// <summary> /// 填充数据 /// </summary> /// <param name="dr"></param> public void FillData(System.Data.DataRow dr) { dr.FillData(this); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace WinWarWeb.Areas.Manage.Controllers { public class HomeController : Controller { // // GET: /Manage/Home/ public ActionResult Index() { if (Session["ClientManager"] == null) { return Redirect("/manage/home/Login"); } return View(); } public ActionResult Login() { return View(); } public ActionResult Logout() { Session["ClientManager"] = null; return Redirect("/manage/home/Login"); } public JsonResult UserLogin(string userName, string pwd) { int result = 0; Dictionary<string, object> resultObj = new Dictionary<string, object>(); string operateip = string.Empty; int outResult; WinWarEntity.Users model = WinWarBusiness.OrganizationBusiness.GetUserByUserName(userName, pwd, out outResult, operateip); if (model != null) { Session["ClientManager"] = model; } result = outResult; resultObj.Add("result", result); return new JsonResult { Data = resultObj, JsonRequestBehavior = JsonRequestBehavior.AllowGet }; } } } <file_sep>Use [WinWar] GO IF EXISTS (SELECT * FROM sysobjects WHERE type = 'P' AND name = 'M_InsterUser') BEGIN DROP Procedure M_InsterUser END GO /*********************************************************** 过程名称: M_InsterUser 功能描述: 添加云销用户 参数说明: 编写日期: 2015/4/10 程序作者: Allen 调试记录: exec M_InsterUser ************************************************************/ CREATE PROCEDURE [dbo].[M_InsterUser] @UserID nvarchar(64), @LoginName nvarchar(200)='', @LoginPWD nvarchar(64)='', @Name nvarchar(200), @Mobile nvarchar(64)='', @Email nvarchar(200)='', @CityCode nvarchar(10)='', @Address nvarchar(200)='', @Jobs nvarchar(200)='', @RoleID nvarchar(64)='', @CreateUserID nvarchar(64)='', @Result int output --0:失败,1:成功,2 账号已存在 3:人数超限 AS begin tran set @Result=0 declare @Err int=0,@MaxCount int=0,@Count int --账号已存在 if(@LoginName<>'' and exists(select UserID from Users where LoginName=@LoginName and Status=1) ) begin set @Result=2 rollback tran return end insert into Users(UserID,LoginName,LoginPWD,Name,MobilePhone,Email,CityCode,Address,Jobs,Allocation,Status,IsDefault,RoleID,CreateUserID) values(@UserID,@LoginName,@LoginPWD,@Name,@Mobile,@Email,@CityCode,@Address,@Jobs,1,1,0,@RoleID,@CreateUserID) --角色关系 if(@RoleID<>'') begin insert into UserRole(UserID,RoleID,CreateUserID) values(@UserID,@RoleID,@CreateUserID) set @Err+=@@error end if(@Err>0) begin set @Result=0 rollback tran end else begin select * from Users where UserID=@UserID set @Result=1 commit tran end<file_sep><%@ Application Codebehind="Global.asax.cs" Inherits="WinWarWeb.MvcApplication" Language="C#" %> <file_sep>using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; using WinWarEntity; using WinWarDAL; namespace WinWarBusiness { public class NewsBusiness { public static NewsBusiness BaseBusiness = new NewsBusiness(); #region Cache private static List<NewsTypeEntity> _types { get; set; } private static List<NewsTypeEntity> CacheNewsType { get { if (_types == null) { _types = new List<NewsTypeEntity>(); DataTable dt = NewsDAL.BaseDAL.GetNewsTypes(); foreach (DataRow dr in dt.Rows) { NewsTypeEntity model = new NewsTypeEntity(); model.FillData(dr); _types.Add(model); } } return _types; } set { _types = value; } } #endregion #region 查询 public NewsTypeEntity GetNewsTypeByCode(int code) { if (CacheNewsType.Where(m => m.Cls_Code == code).Count() > 0) { return CacheNewsType.Where(m => m.Cls_Code == code).FirstOrDefault(); } NewsTypeEntity model = new NewsTypeEntity(); DataTable dt = NewsDAL.BaseDAL.GetNewsTypeByID(code); if ( dt.Rows.Count>0) { model.FillData(dt.Rows[0]); CacheNewsType.Add(model); } return model; } public List<NewsTypeEntity> GetNewsTypeByParentID(int id) { if (id > 0) { return CacheNewsType.FindAll(m => m.News_Type_1 == id && m.News_Type_2 > 0); } else { return CacheNewsType.FindAll(m => m.News_Type_2 <= 0); } } /// <summary> /// 获取新闻 /// </summary> /// <param name="keyWords">关键词</param> /// <param name="typeid">新闻类型</param> /// <param name="pageSize">每页新闻数</param> /// <param name="newsCode">最大新闻Code,第一页传 0</param> /// <returns></returns> public List<NewsEntity> GetNews(string keyWords, int typeid, int pageSize, long userid, ref long newsCode) { List<NewsEntity> list = new List<NewsEntity>(); DataTable dt = NewsDAL.BaseDAL.GetNews(keyWords, typeid, pageSize, userid, ref newsCode); foreach (DataRow dr in dt.Rows) { NewsEntity model = new NewsEntity(); model.FillData(dr); list.Add(model); } return list; } public List<NewsEntity> GetNewNews_Mains(int typeid, int pageSize, long maxNewsCode, long userid) { List<NewsEntity> list = new List<NewsEntity>(); DataTable dt = NewsDAL.BaseDAL.GetNewNews_Mains(typeid, pageSize, maxNewsCode, userid); foreach (DataRow dr in dt.Rows) { NewsEntity model = new NewsEntity(); model.FillData(dr); list.Add(model); } return list; } public List<NewsEntity> GetNewsFavorites(long userid, int pageSize, ref long favoriteid) { List<NewsEntity> list = new List<NewsEntity>(); DataTable dt = NewsDAL.BaseDAL.GetNewsFavorites(userid, pageSize, ref favoriteid); foreach (DataRow dr in dt.Rows) { NewsEntity model = new NewsEntity(); model.FillData(dr); list.Add(model); } return list; } public NewsEntity GetNewsDetail(long newsCode, long userid) { NewsEntity item =null; DataTable dt = NewsDAL.BaseDAL.GetNewsDetail(newsCode, userid); if(dt.Rows.Count>0) { item = new NewsEntity(); item.FillData(dt.Rows[0]); item.NewsType = GetNewsTypeByCode(item.News_Type); } return item; } /// <summary> /// 获取新闻评论 /// </summary> /// <param name="newsCode"></param> /// <param name="pageSize"></param> /// <param name="pageIndex"></param> /// <param name="userid"></param> /// <returns></returns> public List<NewsCommentEntity> GetNewsComments(long newsCode, int pageSize, long userid, ref long id) { List<NewsCommentEntity> list = new List<NewsCommentEntity>(); DataTable dt = NewsDAL.BaseDAL.GetNewsComments(newsCode, pageSize, userid, ref id); foreach (DataRow dr in dt.Rows) { NewsCommentEntity model = new NewsCommentEntity(); model.FillData(dr); model.CreateUser = PassportBusiness.GetPassportByID(model.User_ID); list.Add(model); } return list; } #endregion #region 添加 /// <summary> /// 增加新闻浏览数 /// </summary> /// <param name="newsCode"></param> /// <returns></returns> public bool AddNewsViewCount(int newsCode) { return NewsDAL.BaseDAL.AddNewsViewCount(newsCode); } /// <summary> /// 点赞评论 /// </summary> /// <param name="newsCode">新闻编码</param> /// <param name="isAdd">true 点赞;false 取消点赞</param> /// <param name="userid">用户ID</param> /// <returns></returns> public bool AddNewsCommentPraiseCount(long id, bool isAdd, long userid) { return NewsDAL.BaseDAL.AddNewsCommentPraiseCount(id, isAdd, userid); } /// <summary> /// 点赞新闻 /// </summary> /// <param name="newsCode">新闻编码</param> /// <param name="isAdd">true 点赞;false 取消点赞</param> /// <param name="userid">用户ID</param> /// <returns></returns> public bool AddNewsPraiseCount(long newsCode, bool isAdd, long userid) { return NewsDAL.BaseDAL.AddNewsPraiseCount(newsCode, isAdd, userid); } /// <summary> /// 收藏新闻 /// </summary> /// <param name="newsCode">新闻编码</param> /// <param name="isAdd">true 点赞;false 取消点赞</param> /// <param name="userid">用户ID</param> /// <returns></returns> public bool AddNewsCollectCount(long newsCode, bool isAdd, long userid) { return NewsDAL.BaseDAL.AddNewsCollectCount(newsCode, isAdd, userid); } /// <summary> /// 评论或回复 /// </summary> /// <param name="content"></param> /// <param name="newsCode"></param> /// <param name="userid"></param> /// <param name="userName"></param> /// <param name="replyid"></param> /// <param name="replyUserID"></param> /// <param name="replyUserName"></param> /// <returns></returns> public bool AddNewsComment(string content, long newsCode, long userid, string userName, long replyid, long replyUserID, string replyUserName) { return NewsDAL.BaseDAL.AddNewsComment(content, newsCode, userid,userName,replyid,replyUserID,replyUserName); } #endregion #region manage public List<NewsEntity> GetNews(string keyWords, int bigTypeID, int typeid, int publishStatus, int pageSize, int pageIndex, ref int totalCount, ref int pageCount) { List<NewsEntity> list = new List<NewsEntity>(); DataTable dt = NewsDAL.BaseDAL.GetNews(keyWords, bigTypeID, typeid, publishStatus, pageSize, pageIndex, ref totalCount, ref pageCount); foreach (DataRow dr in dt.Rows) { NewsEntity model = new NewsEntity(); model.FillData(dr); if (model.News_Type > 0) { model.NewsType = GetNewsTypeByCode(model.News_Type); } list.Add(model); } return list; } public bool AddNews(NewsEntity news) { return NewsDAL.BaseDAL.AddNews(news.News_Uni_Code, news.Title_Main, news.Title_Sub, news.Title_App, news.News_Sum, news.News_Author, news.Real_Source_Name, news.Pic_URL, news.Nega_Posi_Par, news.Impt_Par,news.Is_Issue, news.News_Type, news.Html_Txt); } public bool EditNews(NewsEntity news) { return NewsDAL.BaseDAL.EditNews(news.News_Uni_Code, news.Title_Main, news.Title_Sub, news.Title_App, news.News_Sum, news.News_Author, news.Real_Source_Name, news.Pic_URL, news.Nega_Posi_Par, news.Impt_Par, news.Is_Issue, news.News_Type, news.Html_Txt); } public bool PublishNews(long newsCode, int isPublish) { return NewsDAL.BaseDAL.PublishNews(newsCode, isPublish); } #endregion } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Script.Serialization; using WinWarBusiness; using WinWarEntity; namespace WinWarWeb.Controllers { public class HomeController : BaseController { public ActionResult Index(string id) { if (currentPassport.UserID == 0) { var authorizeUrl = WeiXin.Sdk.Token.GetAuthorizeUrl(Server.UrlEncode(WeiXin.Sdk.AppConfig.CallBackUrl), string.Empty, YXERP.Common.Common.IsMobileDevice()); return Redirect(authorizeUrl); } else { ViewBag.ID = id ?? "6"; ViewBag.Passport = currentPassport; } //ViewBag.ID = id ?? "6"; //ViewBag.Passport = currentPassport; return View(); } public ActionResult Detail(long id=0) { if (id == 0) { return Redirect("/Home/Index"); } var item = NewsBusiness.BaseBusiness.GetNewsDetail(id, currentPassport.UserID); ViewBag.Item = item; ViewBag.Passport = currentPassport; return View(); } public ActionResult NewsDetail() { return View(); } #region ajax public JsonResult GetNewsTypeByParentID(int id) { var items = NewsBusiness.BaseBusiness.GetNewsTypeByParentID(id); jsonResult.Add("items", items); return new JsonResult() { Data=jsonResult, JsonRequestBehavior=JsonRequestBehavior.AllowGet }; } public JsonResult GetNews(string keywords, int typeID, long lastNewsCode, int pageSize) { var items = NewsBusiness.BaseBusiness.GetNews(keywords, typeID, pageSize, currentPassport.UserID, ref lastNewsCode); jsonResult.Add("items", items); jsonResult.Add("lastNewsCode", lastNewsCode); return new JsonResult() { Data = jsonResult, JsonRequestBehavior = JsonRequestBehavior.AllowGet }; } public JsonResult GetNewNews_Mains(long maxNewsCode, int typeID, int pageSize) { var items = NewsBusiness.BaseBusiness.GetNewNews_Mains(typeID, pageSize, maxNewsCode, currentPassport.UserID); jsonResult.Add("items", items); return new JsonResult() { Data = jsonResult, JsonRequestBehavior = JsonRequestBehavior.AllowGet }; } public ActionResult GetNewsDetail(long id) { var item = NewsBusiness.BaseBusiness.GetNewsDetail(id, currentPassport.UserID); jsonResult.Add("item",item); jsonResult.Add("passport",currentPassport); return new JsonResult() { Data = jsonResult, JsonRequestBehavior = JsonRequestBehavior.AllowGet }; } public JsonResult GetNewsComments(long id,long lastCommentID,int pageSize) { var items = NewsBusiness.BaseBusiness.GetNewsComments(id, pageSize, currentPassport.UserID, ref lastCommentID); jsonResult.Add("items", items); jsonResult.Add("lastCommentID", lastCommentID); jsonResult.Add("result", 1); return new JsonResult() { Data = jsonResult, JsonRequestBehavior = JsonRequestBehavior.AllowGet }; } public JsonResult AddNewsComment(string comment) { if (Session["WinWarUser"] == null) { jsonResult.Add("result", -1); } else { JavaScriptSerializer serializer = new JavaScriptSerializer(); NewsCommentEntity model = serializer.Deserialize<NewsCommentEntity>(comment); bool flag = NewsBusiness.BaseBusiness.AddNewsComment(model.Content, model.News_Uni_Code, currentPassport.UserID, currentPassport.Name, model.Reply_ID, model.Reply_User_ID, model.Reply_User_Name); jsonResult.Add("result", flag ? 1 : 0); if (flag) { List<NewsCommentEntity> items = new List<NewsCommentEntity>(); model.Create_Date = DateTime.Now; model.Reply_Count = 1; model.User_Name = currentPassport.Name; model.CreateUser = currentPassport; items.Add(model); jsonResult.Add("items", items); } } return new JsonResult() { Data = jsonResult, JsonRequestBehavior = JsonRequestBehavior.AllowGet }; } public JsonResult AddNewsCollectCount(long id, int isCollect) { if (Session["WinWarUser"] == null) { jsonResult.Add("result", -1); } else { bool flag = NewsBusiness.BaseBusiness.AddNewsCollectCount(id, isCollect == 1 ? true : false, currentPassport.UserID); jsonResult.Add("result", flag ? 1 : 0); } return new JsonResult() { Data = jsonResult, JsonRequestBehavior = JsonRequestBehavior.AllowGet }; } public JsonResult AddNewsPraiseCount(long id, int isPraise) { if (Session["WinWarUser"] == null) { jsonResult.Add("result", -1); } else { bool flag = NewsBusiness.BaseBusiness.AddNewsPraiseCount(id, isPraise == 1 ? true : false, currentPassport.UserID); jsonResult.Add("result", flag ? 1 : 0); } return new JsonResult() { Data = jsonResult, JsonRequestBehavior = JsonRequestBehavior.AllowGet }; } public JsonResult AddNewsCommentPraiseCount(long id, int isAdd) { if (Session["WinWarUser"] == null) { jsonResult.Add("result", -1); } else { bool flag = NewsBusiness.BaseBusiness.AddNewsCommentPraiseCount(id, isAdd == 1 ? true : false, currentPassport.UserID); jsonResult.Add("result", flag ? 1 : 0); } return new JsonResult() { Data = jsonResult, JsonRequestBehavior = JsonRequestBehavior.AllowGet }; } #endregion } } <file_sep>@{ ViewBag.Title = "首页"; Layout = "/Areas/Manage/Views/Shared/_LayoutHome.cshtml"; } <style type="text/css"> .main-content { margin:0; } .home { margin:200px auto; width:300px; text-align:center; font-size:42px; color:#888; } </style> <div class="home">欢迎进入后台!</div> <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Http; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; namespace WinWarWeb { // 注意: 有关启用 IIS6 或 IIS7 经典模式的说明, // 请访问 http://go.microsoft.com/?LinkId=9394801 public class MvcApplication : System.Web.HttpApplication { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( "Default", // 路由名称 "{controller}/{action}/{id}", // 带有参数的 URL new { controller = "Home", action = "Index", id = UrlParameter.Optional }, // 参数默认值 new string[] { "WinWarWeb.Controllers" } ); } protected void Application_Start() { AreaRegistration.RegisterAllAreas(); WebApiConfig.Register(GlobalConfiguration.Configuration); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); } } }<file_sep>@{ var Item = (WinWarEntity.NewsEntity)ViewBag.Item; var NewsMain=Item.Html_Txt; var Passport = (WinWarEntity.Passport)ViewBag.Passport; ViewBag.Title = "未坞互动"; } @section css{ <link href="/modules/css/home/index.css" rel="stylesheet" /> <link href="/modules/css/home/detail.css" rel="stylesheet" /> } @section scripts{ <script type="text/javascript"> $(function () { seajs.use(["scripts/home/detail"], function (obj) { obj.init('@Item.News_Uni_Code', '@NewsMain', '@Item.Is_Collect', '@Item.Is_Praise', '@Passport.UserID'); }); }); </script> } <div class="detail-header"> @* <div class="header-newsimg"> @{ if (!string.IsNullOrEmpty(Item.Pic_URL)){ <img src="@Item.Pic_URL" /> } } </div>*@ <div class="header-back"> <span class="iconfont icon">&#xe60a;</span> </div> <div class="header-content"> <div class="source">@(string.IsNullOrEmpty( Item.Real_Source_Name)?"来源未知":Item.Real_Source_Name)</div> <div class="title">@Item.Title_Main</div> </div> </div> <div class="detail-content"> <div class="news-author"> <div class="author-detail left"> <div class="author-name">@(string.IsNullOrEmpty(Item.News_Author)?"--":Item.News_Author)</div> <div class="author-time">@Item.Pub_Time.ToString("yyyy-MM-dd hh:mm:ss")</div> </div> <div class="author-read right"> <span class="iconfont" title="阅读数"><img class="icon" src="/modules/images/browse.png" /></span> <span class="read">@Item.View_Count</span> </div> <div class="clear"></div> </div> <div class="detail-box" id="newsMain"></div> </div> <div class="detail-replys"> <div class="reply-header"> <div class="reply-title">评论</div> </div> <div class="reply-list"> <ul><li class="no-data">暂无评论</li></ul> <div class="clear"></div> <div class="data-loading hide"></div> <div class="load-more hide">加载更多评论</div> </div> </div> <div class="menu"> <ul class="menu-list"> <li id="li-addComment"> <div class="iconfont"> <img class="icon" data-icon="comment" src="/modules/images/comment.png" /> </div> 写评论 </li> <li id="addNewsCollectCount"> @{ if(Item.Is_Collect==0){ <div class="iconfont"> <img class="icon" data-icon="collect" src="/modules/images/collect.png" /> </div> <span>收藏</span> } else { <div class="iconfont"> <img class="icon" data-icon="collect" src="/modules/images/collect_color.png" /> </div> <span>取消收藏</span> } } </li> <li id="addNewsPraiseCount"> @{ if(Item.Is_Praise==0){ <div class="iconfont"> <img class="icon" data-icon="like" src="/modules/images/like.png" /> </div> } else { <div class="iconfont"> <img class="icon" data-icon="like" src="/modules/images/like_color.png" /> </div> } <span class="Praise_Count">@Item.Praise_Count</span><span class="mLeft5 praise-title">赞</span> } </li> <li> <div class="iconfont"> <img class="icon" style="max-width:22px; max-height:22px;" data-icon="reply" src="/modules/images/reply.png" /> </div> <span id="Comment_Count">@Item.Comment_Count</span>评论 </li> </ul> <div class="clear"></div> </div> <div class="overlay overlay-add-reply"> <div class="detail-reply-box"> <div class="detail-reply-msg"> <textarea class="reply-msg" placeholder="发表评论 (500字)" id="comment-msg" onpropertychange="this.style.height=this.value.split('\n').length*20 + 'px';this.style.height=this.scrollHeight + 'px';" oninput="this.style.height=this.value.split('\n').length*20 + 'px';this.style.height=this.scrollHeight + 'px';"></textarea> </div> <div class="detail-reply-btn" id="btn-addComment"> 发送 </div> </div> </div> <file_sep>Use [WinWar] GO IF EXISTS (SELECT * FROM sysobjects WHERE type = 'P' AND name = 'M_PublishNews') BEGIN DROP Procedure M_PublishNews END GO /*********************************************************** 过程名称: M_PublishNews 功能描述: 收藏新闻 参数说明: 编写日期: 2016/6/6 程序作者: Allen 调试记录: exec M_PublishNews 100000002,1,6128258090 ************************************************************/ CREATE PROCEDURE [dbo].[M_PublishNews] @IsPublish int=1, @NewsCode bigint AS if(@IsPublish=1) begin Update NEWS_MAIN set IS_ISSUE=@IsPublish,PUB_TIME=GETDATE() where NEWS_UNI_CODE=@NewsCode end else begin Update NEWS_MAIN set IS_ISSUE=@IsPublish where NEWS_UNI_CODE=@NewsCode end <file_sep><!DOCTYPE html> @{ string controller = Url.RequestContext.RouteData.Values["controller"].ToString().ToUpper(); string action = Url.RequestContext.RouteData.Values["action"].ToString().ToUpper(); WinWarEntity.Menu controllerMenu = ExpandClass.GetController(HttpContext.Current, controller); WinWarEntity.Users CurrentUser = (WinWarEntity.Users)Session["ClientManager"]; } <html> <head> <title>@ViewBag.Title</title> <meta name="robots" content="noindex,nofollow"> <link href="/modules/css/base.css" rel="stylesheet" /> <link href="/modules/css/layout.css" rel="stylesheet" /> <link href="/modules/css/iconfont/iconfont.css" rel="stylesheet" /> @RenderSection("css", false) <style type="text/css"> body { background-color: #f2f4f8; } </style> </head> <body> <header> <div class="logo left"><a href="/Manage/Home/Index"><img id="companyLogo" src="/modules/images/logo.png"/></a></div> <div class="left companyname long" id="companyName" title="未坞互动">未坞互动</div> <ul id="modulesMenu" class="menu left"> <li class="left"> <a href="/Manage/Home/Index" class="@(controller=="HOME"?"select":"")"> <img class="ico" data-ico="/Content/menuico/home.png" data-hover="/Content/menuico/homehover.png" src="/Content/menuico/home.png" /> <span class="name">首页</span> <span class="cursor"></span> </a> </li> @foreach (WinWarEntity.Menu model in ExpandClass.GetChildMenuByCode(HttpContext.Current, ExpandClass.CLIENT_TOP_CODE)) { <li class="left" data-code="@(model.MenuCode)"> <a class="@( (controller!="HOME" && model.MenuCode.ToUpper()==controllerMenu.PCode.ToUpper()) ? "select" : "")" href="/Manage/@(model.Controller)/@(model.View)"> <img class="ico" data-ico="@(model.IcoPath)" data-hover="@(model.IcoHover)" src="@(model.IcoPath)" /> <span class="name">@(model.Name)</span> <span class="cursor"></span> </a> </li> } </ul> <div id="currentUser" class="currentuser right"> <span> <img src="/modules/images/manage/defaultavatar.png" class="avatar" /> </span> <span class="username"> @(CurrentUser.Name) </span> <span class="dropdown"> <span class="dropdown-top"></span> <span class="dropdown-bottom"></span> </span> </div> </header> <div class="main-body"> <div class="main-content"> @RenderBody() </div> </div> @*点击头像展开下拉列表*@ <div class="dropdown-userinfo hide"> <div class="top-lump"></div> <ul class="items-list"> <li class="item"><a href="/Manage/Home/Logout">安全退出</a></li> </ul> </div> <div class="back-top" title="返回顶部"> <span class="iconfont">&#xe643;</span> </div> <script src="/Scripts/jquery-1.11.1.js"></script> <script type="text/javascript" src="/Scripts/sea.js"></script> <script type="text/javascript" src="/Scripts/sea-config.js?v=20160525"></script> <script type="text/javascript"> seajs.use(["Manage/scripts/layout"], function (layout) { layout.init(); }); </script> @RenderSection("scripts", false) </body> </html> <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Script.Serialization; using WinWarBusiness; using WinWarEntity; using WinWarWeb.Models; namespace WinWarWeb.Areas.Manage.Controllers { public class OrganizationController :BaseController { // // GET: /Manage/System/ public ActionResult Index() { return View(); } public ActionResult Department() { return View(); } public ActionResult Roles() { return View(); } public ActionResult RolePermission(string id) { ViewBag.Model = OrganizationBusiness.GetRoleByID(id); ViewBag.Menus = CommonBusiness.ClientMenus.Where(m => m.PCode == ExpandClass.CLIENT_TOP_CODE).ToList(); return View(); } public ActionResult Users() { ViewBag.Roles = OrganizationBusiness.GetRoles(); ViewBag.IsSysAdmin = CurrentUser.Role.IsDefault == 1 ? true : false; return View(); } public ActionResult CreateUser() { ViewBag.Roles = OrganizationBusiness.GetRoles(); return View(); } public ActionResult Structure() { var list = OrganizationBusiness.GetStructureByParentID("6666666666", CurrentUser.AgentID); if (list.Count > 0) { ViewBag.Model = list[0]; } else { ViewBag.Model = new Users(); } return View(); } public ActionResult UpdatePwd() { return View(); } #region Ajax public JsonResult GetRoles() { var list = OrganizationBusiness.GetRoles(); foreach (var item in list) { if (item.CreateUser == null && !string.IsNullOrEmpty(item.CreateUserID)) { var user = OrganizationBusiness.GetUserByUserID(item.CreateUserID); item.CreateUser = new Users() { Name = user.Name }; } } JsonDictionary.Add("items", list); return new JsonResult() { Data = JsonDictionary, JsonRequestBehavior = JsonRequestBehavior.AllowGet }; } public JsonResult GetRoleByID(string id) { var model = OrganizationBusiness.GetRoleByID(id); JsonDictionary.Add("model", model); return new JsonResult() { Data = JsonDictionary, JsonRequestBehavior = JsonRequestBehavior.AllowGet }; } public JsonResult SaveRole(string entity) { JavaScriptSerializer serializer = new JavaScriptSerializer(); Role model = serializer.Deserialize<Role>(entity); if (string.IsNullOrEmpty(model.RoleID)) { model.RoleID = new OrganizationBusiness().CreateRole(model.Name, model.ParentID, model.Description, CurrentUser.UserID, CurrentUser.AgentID, CurrentUser.ClientID); } else { bool bl = new OrganizationBusiness().UpdateRole(model.RoleID, model.Name, model.Description, CurrentUser.UserID, OperateIP); if (!bl) { model.RoleID = ""; } } JsonDictionary.Add("model", model); return new JsonResult { Data = JsonDictionary, JsonRequestBehavior = JsonRequestBehavior.AllowGet }; } public JsonResult DeleteRole(string roleid) { int result = 0; bool bl = new OrganizationBusiness().DeleteRole(roleid, CurrentUser.UserID, OperateIP, out result); JsonDictionary.Add("status", result); return new JsonResult { Data = JsonDictionary, JsonRequestBehavior = JsonRequestBehavior.AllowGet }; } public JsonResult UpdateUserPwd(string userID, string loginPwd) { bool bl = OrganizationBusiness.UpdateUserPass(userID, loginPwd, CurrentUser.AgentID); JsonDictionary.Add("status", bl); return new JsonResult() { Data = JsonDictionary, JsonRequestBehavior = JsonRequestBehavior.AllowGet }; } public JsonResult UpdateMobilePhone(string userID) { bool flag = false; int result = 0; if (!string.IsNullOrEmpty(CurrentUser.LoginName)) { Users item = WinWarBusiness.OrganizationBusiness.GetUserByUserID(userID); if (!string.IsNullOrEmpty(item.BindMobilePhone)) { flag = OrganizationBusiness.ClearAccountBindMobile(userID, CurrentUser.AgentID); if (flag) { result = 1; if (!string.IsNullOrEmpty(item.MobilePhone)) { result = 2; } } } else { result = 3; } } JsonDictionary.Add("result", result); return new JsonResult() { Data = JsonDictionary, JsonRequestBehavior = JsonRequestBehavior.AllowGet }; } public JsonResult UpdateUserBaseInfo(string entity, string userID) { int result = 0; if (!string.IsNullOrEmpty(userID)) { bool flag = false; JavaScriptSerializer serializer = new JavaScriptSerializer(); WinWarEntity.Users newItem = serializer.Deserialize<WinWarEntity.Users>(entity); WinWarEntity.Users item = OrganizationBusiness.GetUserByUserID(userID); flag = OrganizationBusiness.UpdateUserInfo(userID, newItem.Name, item.Jobs, item.Birthday, item.Age.Value, newItem.DepartID, newItem.Email, newItem.MobilePhone, item.OfficePhone, CurrentUser.AgentID); result = flag ? 1 : 0; } JsonDictionary.Add("result", result); return new JsonResult { Data = JsonDictionary, JsonRequestBehavior = JsonRequestBehavior.AllowGet }; } public JsonResult SaveRolePermission(string roleid, string permissions) { if (permissions.Length > 0) { permissions = permissions.Substring(0, permissions.Length - 1); } bool bl = new OrganizationBusiness().UpdateRolePermission(roleid, permissions, CurrentUser.UserID, OperateIP); JsonDictionary.Add("status", bl); return new JsonResult { Data = JsonDictionary, JsonRequestBehavior = JsonRequestBehavior.AllowGet }; } public JsonResult SaveUser(string entity) { JavaScriptSerializer serializer = new JavaScriptSerializer(); Users model = serializer.Deserialize<Users>(entity); int result = 0; var user = OrganizationBusiness.CreateUser(model.LoginName, model.LoginName, model.Name, model.MobilePhone, model.Email, model.CityCode, model.Address, model.Jobs, model.RoleID, CurrentUser.UserID, out result); JsonDictionary.Add("model", user); JsonDictionary.Add("result", result); return new JsonResult() { Data = JsonDictionary, JsonRequestBehavior = JsonRequestBehavior.AllowGet }; } public JsonResult IsExistLoginName(string loginname) { var bl = OrganizationBusiness.IsExistLoginName(loginname); JsonDictionary.Add("status", bl); return new JsonResult() { Data = JsonDictionary, JsonRequestBehavior = JsonRequestBehavior.AllowGet }; } public JsonResult GetUsersByParentID(string parentid = "") { //var list = OrganizationBusiness.GetUsersByParentID(parentid, CurrentUser.AgentID).OrderBy(m => m.FirstName).ToList(); JsonDictionary.Add("items", null); return new JsonResult() { Data = JsonDictionary, JsonRequestBehavior = JsonRequestBehavior.AllowGet }; } public JsonResult GetUsers(string filter) { JavaScriptSerializer serializer = new JavaScriptSerializer(); FilterUser model = serializer.Deserialize<FilterUser>(filter); int totalCount = 0; int pageCount = 0; var list = OrganizationBusiness.GetUsers(model.Keywords, model.DepartID, model.RoleID, PageSize, model.PageIndex, ref totalCount, ref pageCount); JsonDictionary.Add("totalCount", totalCount); JsonDictionary.Add("pageCount", pageCount); JsonDictionary.Add("items", list); return new JsonResult() { Data = JsonDictionary, JsonRequestBehavior = JsonRequestBehavior.AllowGet }; } public JsonResult GetUserAll() { var list = OrganizationBusiness.GetUsers(CurrentUser.AgentID).Where(m => m.Status == 1).ToList(); JsonDictionary.Add("items", list); return new JsonResult() { Data = JsonDictionary, JsonRequestBehavior = JsonRequestBehavior.AllowGet }; } public JsonResult DeleteUserByID(string userid) { int result = 0; bool bl = new OrganizationBusiness().DeleteUserByID(userid, CurrentUser.UserID, OperateIP, out result); JsonDictionary.Add("status", bl); return new JsonResult() { Data = JsonDictionary, JsonRequestBehavior = JsonRequestBehavior.AllowGet }; } //编辑员工角色 public JsonResult UpdateUserRole(string userid, string roleid) { bool bl = new OrganizationBusiness().UpdateUserRole(userid, roleid, CurrentUser.UserID, OperateIP); JsonDictionary.Add("status", bl); return new JsonResult() { Data = JsonDictionary, JsonRequestBehavior = JsonRequestBehavior.AllowGet }; } public JsonResult ConfirmLoginPwd(string loginName, string loginPwd) { if (string.IsNullOrEmpty(loginName)) { loginName = CurrentUser.LoginName; } bool bl = OrganizationBusiness.ConfirmLoginPwd(loginName, loginPwd); JsonDictionary.Add("Result", bl); return new JsonResult() { Data = JsonDictionary, JsonRequestBehavior = JsonRequestBehavior.AllowGet }; } public JsonResult UpdateUserPass(string loginPwd) { bool bl = OrganizationBusiness.UpdateUserPass(CurrentUser.UserID, loginPwd, CurrentUser.AgentID); JsonDictionary.Add("Result", bl); return new JsonResult() { Data = JsonDictionary, JsonRequestBehavior = JsonRequestBehavior.AllowGet }; } #endregion } } <file_sep>define(function (require, exports, module) { var Global = require("global"); var Upload = require("upload"); var Verify = require("verify"), VerifyObject; var News = { News_Uni_Code:0, Title_Main: '', Title_Sub: '', Title_App: '', News_Sum: '', News_Author: '', Real_Source_Name: '', Pic_URL:'', Nega_Post_Par: 3, Impt_Par: 2, News_Type: "", News_Type_Name2:'', News_Type_1: "", News_Type_Name1: "", Html_Txt:'' }; var ObjectJS = {}; var Editor = null; ObjectJS.init = function (News_Uni_Code, newsMain) { News.News_Uni_Code = News_Uni_Code; ObjectJS.bindEvent(); newsMain = newsMain.replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&quot;/g, '"'); newsMain = newsMain.replace(/&amp;/g, ' &'); $("#newsMain").html(newsMain); }; ObjectJS.initCreate = function (um) { ObjectJS.News_Type = 0; Editor = um; ObjectJS.bindEvent(); VerifyObject = Verify.createVerify({ element: ".verify", emptyAttr: "data-empty", verifyType: "data-type", regText: "data-text" }); VerifyObject.isPass(); }; ObjectJS.initEdit = function (um, News_Uni_Code, News_Type_1, News_Type_Name1, News_Type, News_Type_Name2, Nega_Posi_Par, Impt_Par, Html_Txt) { News.News_Uni_Code = News_Uni_Code; News.News_Type_1 = News_Type_1; News.News_Type_Name1 = News_Type_Name1; News.News_Type = News_Type; News.News_Type_Name2 = News_Type_Name2; ObjectJS.News_Type = News_Type; Html_Txt = Html_Txt.replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&quot;/g, '"');; Html_Txt = Html_Txt.replace(/&amp;/g, ' &'); Editor = um; ObjectJS.bindEvent(); VerifyObject = Verify.createVerify({ element: ".verify", emptyAttr: "data-empty", verifyType: "data-type", regText: "data-text" }); $(".Impt_Par .radiobox .ico-radiobox[data-value='" + Impt_Par + "']").addClass("hover"); $(".Nega_Posi_Par .radiobox .ico-radiobox[data-value='" + Nega_Posi_Par + "']").addClass("hover"); Editor.ready(function () { Editor.setContent(Html_Txt);//decodeURI(Html_Txt) }); }; ObjectJS.bindEvent = function () { var _self = this; if ($("#ParentType").length>0) { require.async("dropdown", function () { Global.post("/Home/GetNewsTypeByParentID", { id: -1 }, function (data) { $("#ParentType").dropdown({ prevText: "一级分类-", defaultText: News.News_Type_Name1 || data.items[0].News_Type_Name1, defaultValue: News.News_Type_1 || data.items[0].News_Type_1, data: data.items, dataValue: "News_Type_1", dataText: "News_Type_Name1", width: "140", onChange: function (data) { _self.getChildTypes(data.value, null, null); } }); if (News.News_Type && News.News_Type_Name2) { _self.getChildTypes(News.News_Type_1, News.News_Type, News.News_Type_Name2); } else { _self.getChildTypes(data.items[0].News_Type_1, null, null); } }); }); } if ($("#Pic_URL").length > 0) { ProductIco = Upload.createUpload({ element: "#Pic_URL", buttonText: "选择图片", className: "", data: { folder: '', action: 'add', oldPath: "" }, success: function (data, status) { if (data.Items.length > 0) { var item = data.Items[0]; $("#productImg").attr("src", item); $("#txt_Pic_URL").val(item); } else { alert("只能上传jpg/png/gif类型的图片,且大小不能超过5M!"); } } }); } $(".Nega_Posi_Par .radiobox").click(function () { var _this = $(this); var _radiobox = _this.find(".ico-radiobox"); if (!_radiobox.hasClass("hover")) { _radiobox.addClass("hover"); _this.siblings().find(".ico-radiobox").removeClass("hover"); } }); $(".Impt_Par .radiobox").click(function () { var _this = $(this); var _radiobox = _this.find(".ico-radiobox"); if (!_radiobox.hasClass("hover")) { _radiobox.addClass("hover"); _this.siblings().find(".ico-radiobox").removeClass("hover"); } }); $("#btn-saveNews").click(function () { if (ObjectJS.News_Type == 0) { alert("选择新闻二级分类"); return; } if (!VerifyObject.isPass()) { return false; } News = { News_Uni_Code:News.News_Uni_Code, Title_Main: $("#Title_Main").val(), Title_Sub: $("#Title_Sub").val(), Title_App: $("#Title_App").val(), News_Sum: $("#News_Sum").val(), News_Author: $("#News_Author").val(), Real_Source_Name: $("#Real_Source_Name").val(), Pic_URL: $("#txt_Pic_URL").val(), Is_Issue: 0, Nega_Posi_Par: $(".Nega_Posi_Par .radiobox .hover").data("value"), Impt_Par: $(".Impt_Par .radiobox .hover").data("value"), News_Type: ObjectJS.News_Type, Html_Txt: Editor.getContent()//encodeURI(Editor.getContent()) }; ObjectJS.saveNews(); }); $("#btn-publishNews").click(function () { ObjectJS.publishNews(News.News_Uni_Code, 1); }); $("#btn-cancelPublishNews").click(function () { ObjectJS.publishNews(News.News_Uni_Code, 0); }); }; //获取下级分类 ObjectJS.getChildTypes = function (parentid, typeid, typename) { Global.post("/Home/GetNewsTypeByParentID", { id: parentid }, function (data) { require.async("dropdown", function () { $("#NewsType").dropdown({ prevText: "二级分类-", defaultText: typename || data.items[0].News_Type_Name2, defaultValue: typeid || data.items[0].News_Type_2, data: data.items, dataValue: "News_Type_2", dataText: "News_Type_Name2", width: "140", onChange: function (data) { ObjectJS.News_Type = data.value; } }); }); ObjectJS.News_Type = typeid || data.items[0].News_Type_2; }); } ObjectJS.saveNews = function () { Global.post("/manage/news/saveNews", { news: JSON.stringify(News) }, function (data) { if (data.result == 1) { if (News.News_Uni_Code == 0) { confirm("是否继续新建新闻?", function () { location.href = location.href; }, function () { location.href = "/Manage/News/Index"; }); } else { alert("保存成功"); setTimeout(function () { location.href = "/Manage/News/Index"; }, 500); } } else { alert("抱歉,保存失败"); } }); } ObjectJS.publishNews = function (id, isPublish) { Global.post("/manage/news/PublishNews", { id: id, isPublish: isPublish }, function (data) { if (data.result == 1) { alert("保存成功"); location.href = "/Manage/News/Index"; } else { alert("保存失败"); } }); } module.exports = ObjectJS; });<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace WinWarWeb.Models { public class FilterNewsComment { public long ID { get; set; } public long News_Uni_Code { get; set; } public int Type { get; set; } public string Content { get; set; } public long Reply_Count { get; set; } public long Reply_ID { get; set; } public long Reply_User_ID { get; set; } public string Reply_User_Name { get; set; } public DateTime Create_Date { get; set; } } }<file_sep>body { background-color:#f2f4f8; } .login-box { margin:35px 25px; } .login-form { border:1px solid #eee; border-radius:3px; background-color:#fff; } .login-username { border-bottom:1px solid #eee; } .login-form input { border:none; width:90%; height:40px; line-height:40px; } .login-btn { margin-top:30px; height:40px; line-height:40px; text-align:center; background-color:#3D9EE1; border-radius:3px; color:#fff; font-size:16px; cursor:pointer; } .register-btn { margin-top:10px; height:40px; line-height:40px; text-align:center; background-color:#fff; border-radius:3px; color:#3D9EE1; font-size:16px; cursor:pointer; } .login-other { margin-top:50px; border-top:1px solid #ddd; } .other-title { width:150px; height:20px; text-align:center; background-color:#f2f4f8; margin:0 auto; margin-top:-10px; font-size:14px; color:#999; } .login-accounts { height: 40px; margin-top: 20px; text-align: center; } .account-weixin { cursor:pointer; } .account-weixin img{ height: 36px; width: 36px; border-radius: 18px; } .registerErr { width: 100%; height: 40px; margin: 10px 0px; background-color: #ffd0d0; line-height: 40px; text-align: center; color: red; border-radius: 3px; }<file_sep> --新闻表 alter table NEWS_MAIN add IS_ISSUE char(1) default '0' Go update NEWS_MAIN set IS_ISSUE='1' alter table NEWS_MAIN add NEWS_TYPE int update NEWS_MAIN set NEWS_TYPE=16 <file_sep>@{ var News = (WinWarEntity.NewsEntity)ViewBag.News; ViewBag.Title = "新闻详情"+News.Title_Main; } @section css{ @* <link href="/modules/plug/umeditor/themes/default/css/umeditor.min.css" rel="stylesheet" />*@ <style type="text/css"> #newsMain table td,#newsMain table th { padding: 5px 10px; border: 1px solid #DDD; } </style> } @section scripts{ <script type="text/javascript"> seajs.use(["manage/scripts/news/detail"], function (obj) { obj.init('@News.News_Uni_Code', '@News.Html_Txt'); }); </script> } <div class="header-box"> <span class="header-title left" >新闻详情</span> <a class="back right" href="javascript:if(history.length>1){ history.go(-1);} else{}"> <i class="iconfont">&#xe62d;</i> 返回 </a> </div> <div class="content-body mTop20"> <ul class="table-add"> <li> <span class="column-title">分类:</span> <span>@(News.NewsType.News_Type_Name1+"-")@News.NewsType.News_Type_Name2</span> </li> <li> <span class="column-title">正标题:</span> <span>@News.Title_Main</span> </li> <li> <span class="column-title">副标题:</span> <span>@News.Title_Sub</span> </li> <li> <span class="column-title">引标题 :</span> <span>@News.Title_App</span> </li> <li> <span class="column-title">作者:</span> <span>@News.News_Author</span> </li> <li> <span class="column-title">来源:</span> <span>@News.Real_Source_Name</span> </li> <li class="Impt_Par"> <span class="column-title left">重要性:</span> <span>@(News.Impt_Par==4?"非常重要":News.Impt_Par==3?"重要":News.Impt_Par==2?"一般":"不重要")</span> </li> <li class="Nega_Posi_Par"> <span class="column-title left">正负面性:</span> <span>@(News.Nega_Posi_Par==2?"正面":News.Nega_Posi_Par==3?"中性":"负面")</span> </li> <li> <span class="column-title">摘要:</span> <span>@News.News_Sum</span> </li> <li> <span class="column-title">详情:</span> <div id="newsMain"></div> </li> </ul> <img class="product-img" id="productImg" alt="" src="@(string.IsNullOrEmpty(News.Pic_URL)?"/modules/images/default.png":News.Pic_URL)" /> <div class="mTop20"> @{ if(News.Is_Issue=="0"){ <div class="btn" id="btn-publishNews">发布</div> } else{ <div class="btn" id="btn-cancelPublishNews">取消发布</div> } } </div> </div> <file_sep>using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WinWarDAL { public class NewsDAL : BaseDAL { public static NewsDAL BaseDAL = new NewsDAL(); #region 查询 public DataTable GetNewsTypes() { return GetDataTable("Select * from NEWS_TYPE order by Cls_Code"); } public DataTable GetNewsTypeByID(int code) { SqlParameter[] paras = { new SqlParameter("@Cls_Code",code), }; return GetDataTable("Select * from NEWS_TYPE where Cls_Code=@Cls_Code", paras, CommandType.Text); } public DataTable GetNews(string keyWords, int typeid, int pageSize, long userid, ref long newsCode) { SqlParameter[] paras = { new SqlParameter("@NewsCode",SqlDbType.BigInt), new SqlParameter("@KeyWords",keyWords), new SqlParameter("@PageSize",pageSize), new SqlParameter("@TypeID",typeid), new SqlParameter("@UserID",userid) }; paras[0].Value = newsCode; paras[0].Direction = ParameterDirection.InputOutput; DataTable dt = GetDataTable("P_GetNews_Mains", paras, CommandType.StoredProcedure); if (paras[0].Value != DBNull.Value) { newsCode = Convert.ToInt64(paras[0].Value); } return dt; } public DataTable GetNewNews_Mains(int typeid, int pageSize, long maxNewsCode, long userid) { SqlParameter[] paras = { new SqlParameter("@MaxNewsCode",maxNewsCode), new SqlParameter("@PageSize",pageSize), new SqlParameter("@TypeID",typeid), new SqlParameter("@UserID",userid) }; DataTable dt = GetDataTable("P_GetNewNews_Mains", paras, CommandType.StoredProcedure); return dt; } public DataTable GetNewsFavorites(long userid, int pageSize, ref long favoriteid) { SqlParameter[] paras = { new SqlParameter("@FavoriteID",SqlDbType.BigInt), new SqlParameter("@PageSize",pageSize), new SqlParameter("@UserID",userid) }; paras[0].Value = favoriteid; paras[0].Direction = ParameterDirection.InputOutput; DataTable dt = GetDataTable("P_GetNEWS_Favorites", paras, CommandType.StoredProcedure); if (paras[0].Value != DBNull.Value) { favoriteid = Convert.ToInt64(paras[0].Value); } return dt; } public DataTable GetNewsDetail(long newsCode, long userid) { SqlParameter[] paras = { new SqlParameter("@NewsCode",newsCode), new SqlParameter("@UserID",userid) }; DataTable dt = GetDataTable("P_GetNewsDetail", paras, CommandType.StoredProcedure); return dt; } public DataTable GetNewsComments(long newsCode, int pageSize, long userid, ref long id) { SqlParameter[] paras = { new SqlParameter("@ID",SqlDbType.BigInt), new SqlParameter("@NewsCode",newsCode), new SqlParameter("@PageSize",pageSize), new SqlParameter("@UserID",userid) }; paras[0].Value = id; paras[0].Direction = ParameterDirection.InputOutput; DataTable dt = GetDataTable("P_GetNewsComments", paras, CommandType.StoredProcedure); if (paras[0].Value != DBNull.Value) { id = Convert.ToInt64(paras[0].Value); } return dt; } #endregion #region 查询 public bool AddNewsViewCount(int newsCode) { SqlParameter[] paras = { new SqlParameter("@NEWS_UNI_CODE",newsCode), }; return ExecuteNonQuery("update NEWS_MAIN set View_Count=View_Count+1 where NEWS_UNI_CODE=@NEWS_UNI_CODE", paras, CommandType.Text) > 0; } public bool AddNewsPraiseCount(long newsCode, bool isAdd, long userid) { SqlParameter[] paras = { new SqlParameter("@NewsCode",newsCode), new SqlParameter("@IsAdd",isAdd ? 1 : 0), new SqlParameter("@UserID",userid) }; return ExecuteNonQuery("P_AddNewsPraiseCount", paras, CommandType.StoredProcedure) > 0; } public bool AddNewsCommentPraiseCount(long id, bool isAdd, long userid) { SqlParameter[] paras = { new SqlParameter("@ID",id), new SqlParameter("@IsAdd",isAdd ? 1 : 0), new SqlParameter("@UserID",userid) }; return ExecuteNonQuery("P_AddNewsCommentPraiseCount", paras, CommandType.StoredProcedure) > 0; } public bool AddNewsCollectCount(long newsCode, bool isAdd, long userid) { SqlParameter[] paras = { new SqlParameter("@NewsCode",newsCode), new SqlParameter("@IsAdd",isAdd ? 1 : 0), new SqlParameter("@UserID",userid) }; return ExecuteNonQuery("P_AddNewsCollectCount", paras, CommandType.StoredProcedure) > 0; } public bool AddNewsComment(string content, long newsCode, long userid, string userName, long replyid, long replyUserID, string replyUserName) { SqlParameter[] paras = { new SqlParameter("@NewsCode",newsCode), new SqlParameter("@Content",content), new SqlParameter("@UserID",userid), new SqlParameter("@UserName",userName), new SqlParameter("@ReplyID",replyid), new SqlParameter("@ReplyUserID",replyUserID), new SqlParameter("@ReplyUserName",replyUserName) }; return ExecuteNonQuery("P_AddNewsComment", paras, CommandType.StoredProcedure) > 0; } #endregion public DataTable GetNews(string keyWords, int bigTypeID, int typeid, int publishStatus, int pageSize, int pageIndex, ref int totalCount, ref int pageCount) { SqlParameter[] paras = { new SqlParameter("@TotalCount",SqlDbType.Int), new SqlParameter("@PageCount",SqlDbType.Int), new SqlParameter("@KeyWords",keyWords), new SqlParameter("@PageSize",pageSize), new SqlParameter("@PageIndex",pageIndex), new SqlParameter("@PublishStatus",publishStatus), new SqlParameter("@TypeID",typeid), new SqlParameter("@BigTypeID",bigTypeID) }; paras[0].Value = totalCount; paras[1].Value = pageCount; paras[0].Direction = ParameterDirection.InputOutput; paras[1].Direction = ParameterDirection.InputOutput; DataTable dt = GetDataTable("M_GetNews_Mains", paras, CommandType.StoredProcedure); totalCount = Convert.ToInt32(paras[0].Value); pageCount = Convert.ToInt32(paras[1].Value); return dt; } public bool AddNews(long id,string title, string titleSub,string titleApp, string newsSum, string author, string source, string picUrl, int posiPar,int important,string isIssue, int typeid,string content) { SqlParameter[] paras = { new SqlParameter("@ID",id), new SqlParameter("@Title",title), new SqlParameter("@TitleSub",titleSub), new SqlParameter("@TitleApp",titleApp), new SqlParameter("@NewsSum",newsSum), new SqlParameter("@Author",author), new SqlParameter("@Source",source), new SqlParameter("@PicUrl",picUrl), new SqlParameter("@PosiPar",posiPar), new SqlParameter("@Important",important), new SqlParameter("@IsIssue",isIssue), new SqlParameter("@TypeID",typeid), new SqlParameter("@Content",content) }; return ExecuteNonQuery("M_AddNews", paras, CommandType.StoredProcedure) > 0; } public bool EditNews(long id, string title, string titleSub, string titleApp, string newsSum, string author, string source,string picUrl, int posiPar, int important, string isIssue, int typeid, string content) { SqlParameter[] paras = { new SqlParameter("@ID",id), new SqlParameter("@Title",title), new SqlParameter("@TitleSub",titleSub), new SqlParameter("@TitleApp",titleApp), new SqlParameter("@NewsSum",newsSum), new SqlParameter("@Author",author), new SqlParameter("@Source",source), new SqlParameter("@PicUrl",picUrl), new SqlParameter("@PosiPar",posiPar), new SqlParameter("@Important",important), new SqlParameter("@IsIssue",isIssue), new SqlParameter("@TypeID",typeid), new SqlParameter("@Content",content) }; return ExecuteNonQuery("M_EditNews", paras, CommandType.StoredProcedure) > 0; } public bool PublishNews(long newsCode, int isPublish) { SqlParameter[] paras = { new SqlParameter("@NewsCode",newsCode), new SqlParameter("@IsPublish",isPublish) }; return ExecuteNonQuery("M_PublishNews", paras, CommandType.StoredProcedure) > 0; } } } <file_sep>Use [WWXW] GO IF EXISTS (SELECT * FROM sysobjects WHERE type = 'P' AND name = 'P_AddNewsCommentPraiseCount') BEGIN DROP Procedure P_AddNewsCommentPraiseCount END GO /*********************************************************** 过程名称: P_AddNewsCommentPraiseCount 功能描述: 点赞评论 参数说明: 编写日期: 2016/7/23 程序作者: Allen 调试记录: exec P_AddNewsCommentPraiseCount 100000002,1,6128258090 ************************************************************/ CREATE PROCEDURE [dbo].[P_AddNewsCommentPraiseCount] @UserID bigint, @IsAdd int=1, @ID bigint AS if(@UserID>0 and @ID>0) begin if (@IsAdd=0 and exists(select ID from Comment_Favorite where Comment_ID=@ID and [User_ID]=@UserID)) begin delete from Comment_Favorite where Comment_ID=@ID and [User_ID]=@UserID Update NEWS_Comment set Praise_Count=Praise_Count-1 where ID=@ID and Praise_Count>0 end else if(@IsAdd=1 and not exists(select ID from Comment_Favorite where Comment_ID=@ID and [User_ID]=@UserID)) begin insert into Comment_Favorite([User_ID],Comment_ID,Create_Date) values(@UserID,@ID,getdate()) Update NEWS_Comment set Praise_Count=Praise_Count+1 where ID=@ID end end <file_sep>Use [WWXW_DEV] GO IF EXISTS (SELECT * FROM sysobjects WHERE type = 'P' AND name = 'P_GetNews_Mains') BEGIN DROP Procedure P_GetNews_Mains END GO /*********************************************************** 过程名称: P_GetNews_Mains 功能描述: 获取新闻列表 参数说明: 编写日期: 2016/6/6 程序作者: Allen 调试记录: declare @out bigint=0 exec P_GetNews_Mains 100000002,'',0,20,@out output; print @out ************************************************************/ CREATE PROCEDURE [dbo].[P_GetNews_Mains] @UserID bigint=0, @KeyWords nvarchar(4000), @BigTypeID int=-1, @TypeID int=-1, @PageSize int, @NewsCode bigint=0 output AS declare @CommandSQL nvarchar(4000) declare @Temp table(News_Uni_Code bigint,Pub_Time datetime,News_Author nvarchar(200),TITLE_MAIN nvarchar(500),Pic_URL nvarchar(300),View_Count int,Comment_Count int,Praise_Count int, Collect_Count int,REAL_SOURCE_NAME nvarchar(200),NEWS_TYPE nvarchar(500),TITLE_SUB nvarchar(500)) if(@NewsCode=0) begin set @CommandSQL='select top '+str(@PageSize)+' News_Uni_Code,Pub_Time,News_Author,TITLE_MAIN,Pic_URL,View_Count,Comment_Count,Praise_Count,Collect_Count, REAL_SOURCE_NAME,NEWS_TYPE,TITLE_SUB from NEWS_MAIN where IS_ISSUE=''1'' ' end else begin set @CommandSQL='select top '+str(@PageSize)+' News_Uni_Code,Pub_Time,News_Author,TITLE_MAIN,Pic_URL,View_Count,Comment_Count,Praise_Count,Collect_Count, REAL_SOURCE_NAME,NEWS_TYPE,TITLE_SUB from NEWS_MAIN where IS_ISSUE=''1'' and News_Uni_Code<'+str(@NewsCode) end if(@KeyWords<>'') set @CommandSQL+=' and (TITLE_MAIN like ''%'+@KeyWords+'%'')' if(@TypeID>0) begin set @CommandSQL+=' and NEWS_TYPE='+str(@TypeID) end else if(@BigTypeID>0) begin create table #Type(TypeID int) insert into #Type select NEWS_TYPE_2 from NEWS_TYPE where NEWS_TYPE_1=@BigTypeID and NEWS_TYPE_2 is not null and NEWS_TYPE_2<>'' set @CommandSQL+=' and NEWS_TYPE in (select TypeID from #Type)' end set @CommandSQL+=' order by News_Uni_Code desc' insert into @Temp exec (@CommandSQL) select t.*,isnull(f.Is_Praise,0) Is_Praise,isnull(Is_Collect,0) Is_Collect from @Temp t left join NEWS_Favorite f on t.News_Uni_Code=f.News_Uni_Code and f.[User_ID]=@UserID select @NewsCode=min(News_Uni_Code) from @Temp <file_sep>Use [WinWar] GO IF EXISTS (SELECT * FROM sysobjects WHERE type = 'P' AND name = 'M_GetNews_Mains') BEGIN DROP Procedure M_GetNews_Mains END GO /*********************************************************** 过程名称: M_GetNews_Mains 功能描述: 获取新闻列表 参数说明: 编写日期: 2016/6/13 程序作者: MU 调试记录: declare @out bigint=0 exec M_GetNews_Mains 100000002,'',0,20,@out output; print @out ************************************************************/ CREATE PROCEDURE [dbo].[M_GetNews_Mains] @KeyWords nvarchar(400)='', @BigTypeID int=-1, @TypeID bigint=0, @PublishStatus int=-1, @PageSize int=10, @PageIndex int=1, @TotalCount int output, @PageCount int output AS declare @CommandSQL nvarchar(4000) declare @tableName nvarchar(4000), @columns nvarchar(4000), @condition nvarchar(4000), @orderColumn nvarchar(100), @key nvarchar(100) set @tableName='NEWS_MAIN' set @columns='*' set @key='News_Uni_Code' set @orderColumn='PUB_TIME desc' set @condition=' 1=1 ' if(@KeyWords<>'') begin set @condition+=' and ( TITLE_MAIN like ''%'+@KeyWords+'%'' or TITLE_SUB like ''%'+@KeyWords+'%'' or TITLE_APP like ''%'+@KeyWords+'%'' or NEWS_AUTHOR like ''%'+@KeyWords+'%'') ' end if(@TypeID>0) begin set @condition+=' and NEWS_TYPE='+str(@TypeID) end else if(@BigTypeID>0) begin create table #Type(TypeID int) insert into #Type select NEWS_TYPE_2 from NEWS_TYPE where NEWS_TYPE_1=@BigTypeID and NEWS_TYPE_2 is not null and NEWS_TYPE_2<>'' set @condition+=' and NEWS_TYPE in (select TypeID from #Type)' end if(@PublishStatus<>-1) begin set @condition+=' and Is_Issue='+str(@PublishStatus) end declare @total int,@page int exec P_GetPagerData @tableName,@columns,@condition,@key,@OrderColumn,@pageSize,@pageIndex,@total out,@page out,0 select @totalCount=@total,@pageCount =@page <file_sep>Use [WWXW_DEV] GO IF EXISTS (SELECT * FROM sysobjects WHERE type = 'P' AND name = 'P_GetNewNews_Mains') BEGIN DROP Procedure P_GetNewNews_Mains END GO /*********************************************************** 过程名称: P_GetNewNews_Mains 功能描述: 获取最新新闻列表 参数说明: 编写日期: 2016/7/31 程序作者: MU 调试记录: declare @out bigint=0 exec P_GetNewNews_Mains 100000002,'',0,20,@out output; print @out ************************************************************/ CREATE PROCEDURE [dbo].[P_GetNewNews_Mains] @UserID bigint=0, @TypeID int=-1, @PageSize int, @MaxNewsCode bigint AS declare @CommandSQL nvarchar(4000) declare @Temp table(News_Uni_Code bigint,Pub_Time datetime,News_Author nvarchar(200),TITLE_MAIN nvarchar(500),Pic_URL nvarchar(300),View_Count int,Comment_Count int,Praise_Count int, Collect_Count int,REAL_SOURCE_NAME nvarchar(200),NEWS_TYPE nvarchar(500),TITLE_SUB nvarchar(500)) begin set @CommandSQL='select top '+str(@PageSize)+' News_Uni_Code,Pub_Time,News_Author,TITLE_MAIN,Pic_URL,View_Count,Comment_Count,Praise_Count,Collect_Count, REAL_SOURCE_NAME,NEWS_TYPE,TITLE_SUB from NEWS_MAIN where IS_ISSUE=''1'' and News_Uni_Code>'+str(@MaxNewsCode) end if(@TypeID>0) begin set @CommandSQL+=' and NEWS_TYPE='+str(@TypeID) end set @CommandSQL+=' order by News_Uni_Code desc' insert into @Temp exec (@CommandSQL) select t.*,isnull(f.Is_Praise,0) Is_Praise,isnull(Is_Collect,0) Is_Collect from @Temp t left join NEWS_Favorite f on t.News_Uni_Code=f.News_Uni_Code and f.[User_ID]=@UserID <file_sep>using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Text; namespace WeiXin.Sdk { public class AppConfig { public static string WeiXinApiUrl = ConfigurationManager.AppSettings["WeiXinApiUrl"] ?? "https://api.weixin.qq.com"; public static string AppKey = ConfigurationManager.AppSettings["AppKey"] ?? "<KEY>"; public static string AppSecret = ConfigurationManager.AppSettings["AppSecret"] ?? "<KEY>"; public static string CallBackUrl = ConfigurationManager.AppSettings["CallBackUrl"] ?? "localhost:9999/User/WeiXinCallBack"; } } <file_sep>define(function (require, exports, module) { var NewsDetail = require("scripts/home/newsdetail"); var ObjectJS = {}; ObjectJS.init = function (id, newsMain, isCollect, isPraise, userID) { NewsDetail.initData(id, isCollect, isPraise, userID, 0); newsMain = newsMain.replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&quot;/g, '"'); newsMain = newsMain.replace(/&amp;/g, ' &'); $("#newsMain").html(newsMain); //var $newsimg = $(".header-newsimg img"); //if ($newsimg.length == 1) { // if ($newsimg.width() > $newsimg.height()) { // $newsimg.css("height", $(window).width()); // } // else { // $newsimg.css("width", $(window).width()); // } //} NewsDetail.bindEvent(2); NewsDetail.getNewsComments(); NewsDetail.setNewsMainHtml(); }; module.exports = ObjectJS; });<file_sep>define(function (require, exports, module) { var ObjectJS = {}; ObjectJS.init = function () { ObjectJS.bindEvent(); } ObjectJS.bindEvent = function () { //窗体滚动 置顶头部 $(window).scroll(function () { if ($(window).scrollTop() > 70) { $(".back-top").fadeIn(500); } else { $(".back-top").fadeOut(1000); } }); //返回顶部 $(".back-top").click(function () { $('body,html').animate({ scrollTop: 0 }, 300); return false; }); //登录信息展开 $("#currentUser").click(function () { $(".dropdown-userinfo").fadeIn("1000"); }); $(document).click(function (e) { if (!$(e.target).parents().hasClass("currentuser") && !$(e.target).hasClass("currentuser")) { $(".dropdown-userinfo").fadeOut("1000"); } }); $(".controller-box").click(function () { var _this = $(this).parent(); var _self = ObjectJS; if (!_this.hasClass("select")) { _self.setRotateR(_this.find(".open"), 0, 90); _this.addClass("select"); _this.find(".action-box").slideDown(200); } else { _self.setRotateL(_this.find(".open"), 90, 0); _this.removeClass("select"); _this.find(".action-box").slideUp(200); } }); //一级菜单图标事件处理 $("#modulesMenu a").mouseenter(function () { var _this = $(this).find("img"); _this.attr("src", _this.data("hover")); }); $("#modulesMenu a").mouseleave(function () { if (!$(this).hasClass("select")) { var _this = $(this).find("img"); _this.attr("src", _this.data("ico")); } }); $("#modulesMenu .select img").attr("src", $("#modulesMenu .select img").data("hover")); } //旋转按钮(顺时针) ObjectJS.setRotateR = function (obj, i, v) { var _self = this; if (i < v) { i += 3; setTimeout(function () { obj.css("transform", "rotate(" + i + "deg)"); _self.setRotateR(obj, i, v); }, 5) } } //旋转按钮(逆时针) ObjectJS.setRotateL = function (obj, i, v) { var _self = this; if (i > v) { i -= 3; setTimeout(function () { obj.css("transform", "rotate(" + i + "deg)"); _self.setRotateL(obj, i, v); }, 5) } } module.exports = ObjectJS; });<file_sep>using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WinWarDAL { public class PassportDAL:BaseDAL { public static PassportDAL BaseDAL = new PassportDAL(); public bool BindWeiXinID(string name, string avatar, string weiXinID) { SqlParameter[] paras = { new SqlParameter("@Name",name), new SqlParameter("@Avatar",avatar), new SqlParameter("@BindWeiXinID",weiXinID) }; return ExecuteNonQuery(" if(not exists(Select * from passport where BindWeiXinID=@BindWeiXinID and status<>9)) insert into passport(Name,Avatar,BindWeiXinID) values(@Name,@Avatar,@BindWeiXinID) ", paras, CommandType.Text) > 0; } public DataTable GetPassportByWeiXinID(string weiXinID) { SqlParameter[] paras = { new SqlParameter("@WeiXinID",weiXinID), }; return GetDataTable("Select * from passport where BindWeiXinID=@WeiXinID and status<>9 ", paras, CommandType.Text); } public DataTable GetPassportByID(long userID) { SqlParameter[] paras = { new SqlParameter("@UserID",userID), }; return GetDataTable("Select * from passport where UserID=@UserID and status<>9 ", paras, CommandType.Text); } } } <file_sep>define(function (require, exports, module) { var Global = require("global"); var DoT = require("dot"); var NewsDetail = require("scripts/home/newsdetail"); var Paras = { keywords:'', parentTypeID: 6, typeID: 0, maxNewsCode:0, lastNewsCode: 0, pageIndex: 1, pageSize: 15 }; var NavsCache = [];//新闻导航缓存 var NewsCache = [];//新闻列表缓存 var ReadNewsCache = [];//已读新闻列表缓存 var NoNewsData = false;//没有新闻数据 var ObjectJS = {}; ObjectJS.init = function (parentTypeID, userID) { ReadNewsCache = window.localStorage.getItem("ReadNewsCache"); if (ReadNewsCache != null && ReadNewsCache != '') { ReadNewsCache = ReadNewsCache.split('|'); }else { ReadNewsCache = []; } ObjectJS.userID = userID; Paras.parentTypeID = parentTypeID; ObjectJS.bindEvent(); if (Paras.parentTypeID == 6) { ObjectJS.getNewsTypeByParentID(); } NewsDetail.bindEvent(); }; ObjectJS.bindEvent = function () { //滚动加载新闻列表 $(window).bind("scroll", function () { if (!NoNewsData) { var bottom = $(document).height() - document.documentElement.scrollTop - document.body.scrollTop - $(window).height(); if (bottom <= 20) { setTimeout(function () { Paras.pageIndex++; ObjectJS.getNews(); }, 500); } } }); //弹出个人遮罩层 $(".passport-icon").click(function () { if (ObjectJS.userID != 0) { $("#passport-box").fadeIn(); $(".passport-box").animate({width:"250px"},200); } else { location.href = "/user/login?returnUrl=" + location.href; } }); //个人遮罩层点击 $(".overlay-passport-content").click(function (e) { if (!$(e.target).parents().hasClass("passport-box") && !$(e.target).hasClass("passport-box")) { $(".passport-box").animate({ width: "0px" }, 200, function () { $(".overlay-passport-content").hide(); }); } }); //弹出关键字遮罩层 $(".search").click(function () { $('.overlay-search-keywords').show(); $("#keywords").focus(); }); //关键字遮罩层点击 $(".overlay-search-keywords").click(function (e) { if (!$(e.target).parents().hasClass("overlay-search") && !$(e.target).hasClass("overlay-search")) { $(".overlay-search-keywords").hide(); } }); //关键字查询 $("#btn-search").click(function () { $('.overlay-search-keywords').hide(); Paras.keywords = $("#keywords").val(); if (Paras.keywords != '') { $("#keywords").val(''); $(".overlay-keywords").show(); $("#keywords-show").val(Paras.keywords); $(".content .no-more").hide(); NoNewsData = false; Paras.pageIndex = 1; Paras.lastNewsCode = 0; ObjectJS.getNews(); } }); //取消关键字查询 $("#btn-cancel").click(function () { $('.overlay-keywords').hide(); $("#keywords-show").val(''); $(".content .no-more").hide(); NoNewsData = false; Paras.keywords = ''; Paras.pageIndex = 1; Paras.lastNewsCode = 0; ObjectJS.getNews(); }); //一级菜单切换 $(".menu-list .item").click(function () { var _this=$(this); if (!_this.hasClass("active")) { var $imgs = $(".menu-list .item").removeClass("active").find("img"); $imgs.each(function () { $(this).attr("src", "/modules/images/" + $(this).data("icon") + ".png"); }); var $img = _this.addClass("active").find("img"); $img.each(function () { $(this).attr("src", "/modules/images/" + $(this).data("icon") + "_color.png"); }); Paras.parentTypeID = _this.data("id"); ObjectJS.getNewsTypeByParentID(); } }); //一级菜单初始化 if (Paras.parentTypeID != 6) { $(".menu-list .item[data-id='" + Paras.parentTypeID + "']").click(); } var pullRefresh = $('.news-list').pPullRefresh({ $el: $('.news-list'), $loadingEl: $('.loading-warp'), sendData: null, url: '', callbacks: { pullStart: function () { $(".data-load-new").show(); ObjectJS.getNewNews_Mains(); }, start: function () { //$statu.text('数据刷新中···'); $(".data-load-new").show(); }, success: function (response) { //$statu.text('数据刷新成功!'); //$(".data-load-new").hide(); }, end: function () { //$statu.text('下拉刷新结束'); $(".data-load-new").hide(); }, error: function () { //$statu.text('找不到请求地址,数据刷新失败'); } } }); }; //获取二级菜单列表 ObjectJS.getNewsTypeByParentID = function () { var data = NavsCache[Paras.parentTypeID]; if (data == null) { Global.post("/Home/GetNewsTypeByParentID", { id: Paras.parentTypeID }, function (data) { NavsCache[Paras.parentTypeID] = data; ObjectJS.bindNewsTypeByParentID(data); }); }else { ObjectJS.bindNewsTypeByParentID(data); } }; //绑定二级菜单 ObjectJS.bindNewsTypeByParentID = function (data) { $(".nav .swiper-wrapper").html(''); for (var i = 0, len = data.items.length; i < len; i++) { var item = data.items[i]; var html = ''; if (i == 0) { html += '<div class="swiper-slide select" data-id="' + item.News_Type_2 + '"><div class="name">' + item.News_Type_Name2 + '</div><div class="circle"></div></div>'; Paras.typeID = item.News_Type_2; }else { html += '<div class="swiper-slide" data-id="' + item.News_Type_2 + '"><div class="name">' + item.News_Type_Name2 + '</div><div class="circle"></div></div>'; } $(".nav .swiper-wrapper").css({ "-webkit-transform": "translate3d(0px, 0px, 0px)", "transform": "translate3d(0px, 0px, 0px)" }).append(html); } $(".content .no-more").hide(); NoNewsData = false; Paras.pageIndex = 1; Paras.lastNewsCode = 0; ObjectJS.bindNewsNavClick(); ObjectJS.bindNewsNavSlide(); ObjectJS.getNews(); } //二级菜单点击 ObjectJS.bindNewsNavClick = function () { $(".nav .swiper-wrapper .swiper-slide").unbind().click(function () { var _this = $(this); if (!_this.hasClass("select")) { _this.addClass("select").siblings().removeClass("select"); NoNewsData = false; $(".content .no-more").hide(); Paras.typeID = _this.data("id"); Paras.pageIndex =1; Paras.lastNewsCode = 0; ObjectJS.getNews(); } }); } //二级菜单左右滑动 ObjectJS.bindNewsNavSlide = function () { var swiper = new Swiper('.nav .swiper-container', { slidesPerView: 3, spaceBetween: 30 }); var $items = $(".nav .swiper-wrapper .swiper-slide"); var width = $items.eq(0).width(); $items.css({ "margin-right":"0","width":(width+20)+"px" }); $items.eq(0).css("width", (width + 50) + "px"); $items.eq(1).css("width", (width - 40) + "px"); $items.eq(2).css("width", (width + 50) + "px"); } //获取新闻列表 ObjectJS.getNews = function () { $(".content .data-loading").show(); var data = null; if (Paras.pageIndex == 1) { data = NewsCache[Paras.parentTypeID +"_"+ Paras.typeID+"_" + Paras.keywords]; $(".news-list .content ul").html(''); } if (data == null) { Global.post("/Home/GetNews", Paras, function (data) { if (Paras.pageIndex == 1) { NewsCache[Paras.parentTypeID + "_" + Paras.typeID + "_" + Paras.keywords] = data; } if (Paras.pageSize > data.items.length) { NoNewsData = true; } ObjectJS.bindNews(data); }); }else{ ObjectJS.bindNews(data); } } //绑定新闻列表 ObjectJS.bindNews = function (data) { var items = data.items; if (Paras.pageIndex == 1) { $(".news-list .content ul").html(''); Paras.maxNewsCode = 0; if (items.length > 0) { Paras.maxNewsCode = items[0].News_Uni_Code; } } Paras.lastNewsCode = data.lastNewsCode; $(".content .data-loading").hide(); if (items.length > 0) { DoT.exec("template/home/news-list.html", function (template) { var innerhtml = template(items); innerhtml = $(innerhtml); $(".news-list .content ul").append(innerhtml); innerhtml.fadeIn(400); if (NoNewsData) { $(".content .no-more").show(); } for (var i = 0; i < items.length; i++) { var item = items[i]; if (ReadNewsCache.indexOf(""+item.News_Uni_Code) > -1) { $("#news_" + item.News_Uni_Code + " .news-title").addClass("news-read"); } } $(".news-list .content ul").find(".news").unbind().click(function () { var id = $(this).data("id"); var scrollTop=$(document).scrollTop(); $("#news-list-box").hide(); NewsDetail.getNewsDetail(id, scrollTop); $("#news-detail-box").fadeIn(); $("#news_" + id + " .news-title").addClass("news-read"); var statetitle = "未坞互动"; var stateurl = "/home/detail/" + id; var state = { title: statetitle, url: stateurl }; history.pushState(state, statetitle, stateurl); }); //if (Paras.pageIndex == 1) { // var swiper = new Swiper('.news-list .swiper-container', { // direction: 'vertical', // onTouchMove: function () { // var y = swiper.getWrapperTranslate("y"); // if (y > 30) { // $(".data-load-new").show(); // } // }, // onTouchEnd: function () { // $(".data-load-new").hide(); // ObjectJS.getNewNews_Mains(); // } // }); //} //$(".news-list .swiper-container .swiper-slide").css("height", "auto"); }); } else { if (Paras.pageIndex == 1) { $(".content ul").html('<li class="no-data">暂无新闻</li>'); NoNewsData = true; }else { if (NoNewsData) { $(".content .no-more").show(); } } } } ObjectJS.getNewNews_Mains = function () { $(".content .data-loading").show(); Global.post("/Home/GetNewNews_Mains", Paras, function (data) { $(".content .data-loading").hide(); var items = data.items; if (items.length > 0) { $(".content ul .no-data").remove(); Paras.maxNewsCode = items[0].News_Uni_Code; var dataCache = NewsCache[Paras.parentTypeID + "_" + Paras.typeID + "_" + Paras.keywords]; if (dataCache == null) { data.lastNewsCode = items[items.length - 1].News_Uni_Code; NewsCache[Paras.parentTypeID + "_" + Paras.typeID + "_" + Paras.keywords] = data; } else { dataCache.items = data.items; NewsCache[Paras.parentTypeID + "_" + Paras.typeID + "_" + Paras.keywords] = dataCache; } DoT.exec("template/home/news-list.html", function (template) { var innerhtml = template(items); innerhtml = $(innerhtml); $(".news-list .content ul").prepend(innerhtml); innerhtml.fadeIn(400); $(".news-list .content ul").find(".news").unbind().click(function () { var id = $(this).data("id"); var scrollTop = $(document).scrollTop(); $("#news-list-box").hide(); NewsDetail.getNewsDetail(id, scrollTop); $("#news-detail-box").fadeIn(); $("#news_" + id + " .news-title").addClass("news-read"); var statetitle = "未坞互动"; var stateurl = "/home/detail/" + id; var state = { title: statetitle, url: stateurl }; history.pushState(state, statetitle, stateurl); }); $(".news-list .swiper-container .swiper-slide").css("height", "auto"); }); } }); } module.exports = ObjectJS; });<file_sep>using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Web; using System.Web.Mvc; namespace WinWarWeb.Controllers { public class PlugController : BaseController { public JsonResult UploadFile() { string folder = "/Content/UploadFiles/"; if (Request.Form.AllKeys.Contains("folder") && !string.IsNullOrEmpty(Request.Form["folder"])) { folder = Request.Form["folder"]; } string uploadPath = HttpContext.Server.MapPath(folder); if (!Directory.Exists(uploadPath)) { Directory.CreateDirectory(uploadPath); } List<string> list = new List<string>(); for (int i = 0; i < Request.Files.Count; i++) { if (i == 10) { break; } HttpPostedFileBase file = Request.Files[i]; //判断图片类型 string ContentType = file.ContentType; Dictionary<string, string> types = new Dictionary<string, string>(); types.Add("image/x-png", "1"); types.Add("image/png", "1"); types.Add("image/gif", "1"); types.Add("image/jpeg", "1"); types.Add("image/tiff", "1"); types.Add("application/x-MS-bmp", "1"); types.Add("image/pjpeg", "1"); if (!types.ContainsKey(ContentType)) { continue; } if (file.ContentLength > 1024 * 1024 * 5) { continue; } string fileName = DateTime.Now.ToString("yyyyMMddHHmmssms") + new Random().Next(1000, 9999).ToString() + "." + Path.GetExtension(file.FileName); string filePath = uploadPath + fileName; file.SaveAs(filePath); list.Add(folder + fileName); } jsonResult.Add("Items", list); return new JsonResult() { Data = jsonResult, JsonRequestBehavior = JsonRequestBehavior.AllowGet }; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Script.Serialization; using WinWarBusiness; using WinWarEntity; namespace WinWarWeb.Areas.Manage.Controllers { public class NewsController : BaseController { // // GET: /Manage/News/ public ActionResult Index() { ViewBag.Types = NewsBusiness.BaseBusiness.GetNewsTypeByParentID(-1); return View(); } public ActionResult Create() { return View(); } public ActionResult Edit(long id) { var news = NewsBusiness.BaseBusiness.GetNewsDetail(id, 0); ViewBag.News = news; return View(); } public ActionResult Detail(long id) { var news = NewsBusiness.BaseBusiness.GetNewsDetail(id, 0); ViewBag.News = news; return View(); } #region ajax public JsonResult GetNews(string keywords, int bigTypeID, int typeID, int publishStatus, int pageSize, int pageIndex) { int totalCount = 0; int pageCount = 0; var items = NewsBusiness.BaseBusiness.GetNews(keywords, bigTypeID, typeID, publishStatus, pageSize, pageIndex, ref totalCount, ref pageCount); jsonResult.Add("items", items); jsonResult.Add("totalCount", totalCount); jsonResult.Add("pageCount", pageCount); return new JsonResult() { Data = jsonResult, JsonRequestBehavior = JsonRequestBehavior.AllowGet }; } [ValidateInput(false)] public JsonResult SaveNews(string news) { JavaScriptSerializer serializer = new JavaScriptSerializer(); NewsEntity model = serializer.Deserialize<NewsEntity>(news); bool flag = false; if (model.News_Uni_Code == 0) { flag = NewsBusiness.BaseBusiness.AddNews(model); } else { flag = NewsBusiness.BaseBusiness.EditNews(model); } jsonResult.Add("result", flag?1:0); return new JsonResult() { Data = jsonResult, JsonRequestBehavior = JsonRequestBehavior.AllowGet }; } public JsonResult PublishNews(long id, int isPublish) { bool flag= NewsBusiness.BaseBusiness.PublishNews(id, isPublish); jsonResult.Add("result",flag?1:0); return new JsonResult() { Data = jsonResult, JsonRequestBehavior = JsonRequestBehavior.AllowGet }; } #endregion } } <file_sep>using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; using WinWarDAL; using WinWarEntity; namespace WinWarBusiness { public class PassportBusiness { public static bool BindWeiXinID(string name, string avatar, string weiXinID) { return PassportDAL.BaseDAL.BindWeiXinID(name, avatar,weiXinID); } public static Passport GetPassportByWeiXinID(string weiXinID) { Passport item = new Passport(); DataTable dt = PassportDAL.BaseDAL.GetPassportByWeiXinID(weiXinID); if (dt.Rows.Count > 0) { item.FillData(dt.Rows[0]); } return item; } public static Passport GetPassportByID(long userID) { Passport item = new Passport(); DataTable dt = PassportDAL.BaseDAL.GetPassportByID(userID); if (dt.Rows.Count > 0) { item.FillData(dt.Rows[0]); } return item; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WinWarEntity { public class NewsTypeEntity { public int Cls_Code { get; set; } public int News_Type_1 { get; set; } public string News_Type_Name1 { get; set; } public int News_Type_2 { get; set; } public string News_Type_Name2 { get; set; } public int News_Type_3 { get; set; } public string News_Type_Name3 { get; set; } /// <summary> /// 填充数据 /// </summary> /// <param name="dr"></param> public void FillData(System.Data.DataRow dr) { dr.FillData(this); } } } <file_sep>Use [WinWar] GO IF EXISTS (SELECT * FROM sysobjects WHERE type = 'P' AND name = 'P_GetNEWS_Favorites') BEGIN DROP Procedure P_GetNEWS_Favorites END GO /*********************************************************** 过程名称: P_GetNEWS_Favorites 功能描述: 获取我收藏的新闻列表 参数说明: 编写日期: 2016/6/6 程序作者: Allen 调试记录: declare @out bigint=0 exec P_GetNEWS_Favorites 111111,1,@out output; print @out ************************************************************/ CREATE PROCEDURE [dbo].[P_GetNEWS_Favorites] @UserID bigint=0, @PageSize int, @FavoriteID bigint=0 output AS declare @CommandSQL nvarchar(4000) declare @Temp table(News_Uni_Code bigint,Pub_Time datetime,News_Author nvarchar(200),TITLE_MAIN nvarchar(500),Pic_URL nvarchar(300),View_Count int,Comment_Count int,Praise_Count int, Collect_Count int,REAL_SOURCE_NAME nvarchar(200),NEWS_TYPE nvarchar(500),TITLE_SUB nvarchar(500),FavoriteID bigint) set @CommandSQL='select top '+str(@PageSize)+' n.News_Uni_Code,Pub_Time,News_Author,TITLE_MAIN,Pic_URL,View_Count,Comment_Count,Praise_Count,Collect_Count, REAL_SOURCE_NAME,NEWS_TYPE,TITLE_SUB,f.ID FavoriteID from NEWS_Favorite as f join NEWS_MAIN as n on f.NEWS_UNI_CODE=n.NEWS_UNI_CODE where n.IS_ISSUE=''1'' and f.Is_Collect=1 and f.USER_ID='+str(@UserID) if(@FavoriteID>0) set @CommandSQL+=' and f.ID>'+str(@FavoriteID) set @CommandSQL+=' order by f.ID desc' insert into @Temp exec (@CommandSQL) select * from @Temp select @FavoriteID=min(FavoriteID) from @Temp <file_sep>Use [WWXW] GO IF EXISTS (SELECT * FROM sysobjects WHERE type = 'P' AND name = 'P_GetNewsComments') BEGIN DROP Procedure P_GetNewsComments END GO /*********************************************************** 过程名称: P_GetNewsComments 功能描述: 获取新闻评论 参数说明: 编写日期: 2016/6/6 程序作者: Allen 调试记录: declare @out bigint=0 exec P_GetNewsComments 6128258538,0,20,@out output; print @out ************************************************************/ CREATE PROCEDURE [dbo].[P_GetNewsComments] @UserID bigint=0, @NewsCode bigint, @PageSize int, @ID bigint=0 output AS declare @CommandSQL nvarchar(4000) declare @Temp table(ID bigint,[User_ID] bigint,[User_Name] nvarchar(200),Content nvarchar(4000),Reply_Count int,Praise_Count int,Create_Date datetime) if(@ID=0) begin set @CommandSQL='select top '+str(@PageSize)+' ID,[User_ID],[User_Name],Content,Reply_Count,Praise_Count,Create_Date from NEWS_Comment where [Type]=1 and News_Uni_Code='+str(@NewsCode)+' order by ID desc ' end else begin set @CommandSQL='select top '+str(@PageSize)+' ID,[User_ID],[User_Name],Content,Reply_Count,Praise_Count,Create_Date from NEWS_Comment where [Type]=1 and News_Uni_Code='+str(@NewsCode)+' and ID<'+str(@ID)+' order by ID desc ' end insert into @Temp exec (@CommandSQL) select t.*,isnull(f.ID,0) Is_Praise from @Temp t left join Comment_Favorite f on t.ID=f.Comment_ID and f.[User_ID]=@UserID select * from @Temp select @ID=min(ID) from @Temp
75c8cf8618b3e4e71813601f214bb7524e95d37d
[ "HTML+Razor", "C#", "ASP.NET", "TSQL", "JavaScript", "CSS" ]
51
HTML+Razor
mugeluo/WinWar
c4d125cdfcae9942aefde8db933e4ea6c5a25429
8f21b1789a88b6fadcdeed165a4dff67412b01a7
refs/heads/main
<repo_name>jeffrichley/primal<file_sep>/pixel_class.py import numpy as np from pygame.sprite import Sprite from pygame import Surface # Define a class for our pixels/grid spaces class Pixel(Sprite): def __init__(self, x, y, screen, color, scale): super(Pixel, self).__init__() self.x = x * scale self.y = y * scale self.color = color self.screen = screen self.surf = Surface((scale, scale)) self.surf.fill(self.color) self.rect = self.surf.get_rect() self.show() # def _change_color(self): # self.color = state_dict[self.state] def show(self): self.screen.blit(self.surf, (self.x, self.y)) def change_state(self, color): if np.array_equal(self.color, color): return # if self.state == state: # return # # self.state = state self.color = color # self._change_color() self.surf.fill(self.color) self.rect = self.surf.get_rect() self.show() <file_sep>/Simulator.py import numpy as np class BasicSimulator(): def __init__(self, state, width, height, **kwargs): self.state = state # screen information # self.width = width # self.height = height # sim information # self.barrier_locations = state.barrier_locations # self.asset_locations = state.asset_locations # self.ally_locations = state.ally_locations # self.enemy_locations = state.enemy_locations # self.goal_locations = state.goal_locations # get the field ready to play self.state.reset_state() def move_asset(self, asset_number, new_location): # we need to make sure it is an empty location before we accept the move moved = True if self.valid_action(asset_number, new_location): self.state.move_asset(asset_number, new_location) else: moved = False return moved def valid_action(self, asset_number, new_location): y = new_location[0] x = new_location[1] asset_y, asset_x = self.state.get_asset_location(asset_number) return (y == asset_y and x == asset_x) or self.state.is_empty_location(y, x) <file_sep>/Trainer.py import datetime import random import numpy as np import tensorflow as tf import scipy.signal as signal from RL_Stuff import ActorCriticModel # from supervised import create_supervised_nn class Trainer: def __init__(self, config, memory, simulator, state, model): self.memory = memory self.simulator = simulator self.state = state # training configuration self.ppo_epochs = config['ppo-epochs'] self.max_grad_norm = config['max-grad-norm'] self.training_size = config['training-size'] self.gae_gamma = config['gae-gamma'] self.gae_lambda = config['gae-lambda'] self.epsilon = config['epsilon'] self.epsilon_decay = config['epsilon-decay'] self.test_frequency = config['test-frequency'] self.asset_visible_window = config['asset-visible-window'] rewards_config = config['rewards'] self.basic_step = rewards_config['basic-step'] self.ally_influence_step = rewards_config['ally-influence-step'] self.enemy_influence_step = rewards_config['enemy-influence-step'] self.mixed_influence_step = rewards_config['mixed-influence-step'] self.goal_step = rewards_config['goal'] network_config = config['network'] self.state_shape = tuple(network_config['state-shape']) self.network_shape = tuple(network_config['network-shape']) self.goal_shape = tuple(network_config['goal-shape']) self.num_actions = network_config['number-of-actions'] # self.supervised_model = create_supervised_nn(self.state_shape, self.goal_shape, self.num_actions) self.model = model # adding Tensorboard metrics self.train_loss = tf.keras.metrics.Mean('train_loss', dtype=tf.float32) self.train_accuracy = tf.keras.metrics.SparseCategoricalAccuracy('train_accuracy') self.train_value_accuracy = tf.keras.metrics.MeanRelativeError(normalizer=[[1]], name='value_accuracy') current_time = datetime.datetime.now().strftime("%Y%m%d-%H%M%S") train_log_dir = f"./logs/{current_time}/train" self.train_summary_writier = tf.summary.create_file_writer(train_log_dir) self.training_step = 0 def get_reward(self, asset_number, state): new_y, new_x = state.assets[asset_number] # we must check for mixed before enemy and ally influence because they would all be 1 if mixed reward = self.basic_step if state.goal_locations[new_y][new_x] == asset_number: reward = self.goal_step elif state.mixed_influence[new_y][new_x] == 1: reward = self.mixed_influence_step elif state.enemy_influence[new_y][new_x] == 1: reward = self.enemy_influence_step elif state.ally_influence[new_y][new_x] == 1: reward = self.ally_influence_step return reward def state_to_training(self, state, asset_number): # start out with everything zeros data = np.zeros(self.state_shape) # add influences data[0, :, :][(state.ally_influence == 1) & (state.mixed_influence != 1)] = 1 data[1, :, :][(state.enemy_influence == 1) & (state.mixed_influence != 1)] = 1 data[2, :, :][state.mixed_influence == 1] = 1 # add walls data[3, :, :][state.barrier_locations == 1] = 1 # add other assets current_asset = state.assets[asset_number] data[4, :, :][state.asset_locations == 1] = 1 data[4, current_asset[0], current_asset[1]] = 0 # add other's goals data[5, :, :][state.goal_locations >= 0] = 1 data[5, :, :][state.goal_locations == asset_number] = 0 # add our goals data[6, :, :][state.goal_locations == asset_number] = 1 # add enemies and allies # TODO: Do we need to split the enemies and allies into separate frames? # If not, the state space would be smaller. data[7, :, :][state.ally_locations == 1] = 1 data[8, :, :][state.enemy_locations == 1] = 1 # add where this asset is currently asset_location = state.get_asset_location(asset_number) data[9, asset_location[0], asset_location[1]] = 1 # now we need to clip to only the viewing region # TODO: could probably make this faster by only making it the viewing region to begin with radius = self.asset_visible_window // 2 # we pad everything with 0's except we need the barrier layer to be padded with 1's padded = np.pad(data, ((0, 0), (radius, radius), (radius, radius)), 'constant', constant_values=(0, 0)) padded[3, :, :] = np.pad(data[3, :, :], ((radius, radius), (radius, radius)), 'constant', constant_values=(1, 1)) # figure out where to slice offset_asset_location = (asset_location[0] + radius + 1, asset_location[1] + radius + 1) top_left_y = offset_asset_location[0] - radius - 1 top_left_x = offset_asset_location[1] - radius - 1 bottom_right_y = top_left_y + self.asset_visible_window bottom_right_x = top_left_x + self.asset_visible_window window_data = padded[:, top_left_y:bottom_right_y, top_left_x:bottom_right_x] # import sys # np.set_printoptions(threshold=sys.maxsize) # np.set_printoptions(linewidth=300) # print(data[3, :, :]) # print(padded[3, :, :]) # goal = np.array(state.goal_locations[1]) # goal_location = np.where(state.goal_locations == asset_number) # goal_location = state.get_asset_goal_location(asset_number) goal = state.get_asset_goal_location(asset_number) # need to get a unit vector towards the goal dy = goal[0] - asset_location[0] dx = goal[1] - asset_location[1] magnitude = (dy ** 2 + dx ** 2) ** 0.5 if magnitude != 0: goal_vector = (dy / magnitude, dx / magnitude) else: goal_vector = (dy, dx) return window_data, goal_vector def train(self): self.training_step += 1 # TODO: for now we will just train with all data, perhaps we should just sample a certain number data = self.memory.sample_memory(self.training_size) # state, goal, action, reward cur_states = np.array([o[0] for o in data]) cur_goals = np.array([o[1] for o in data]) cur_actions = np.array([o[2] for o in data]) rewards = np.array([o[3] for o in data]) self.model.train_imitation(cur_states, cur_goals, cur_actions, rewards, train_loss_logger=self.train_loss, train_accuracy_logger=self.train_accuracy, train_value_accuracy_logger=self.train_value_accuracy) with self.train_summary_writier.as_default(): tf.summary.scalar('loss', self.train_loss.result(), step=self.training_step) tf.summary.scalar('action accuracy', self.train_accuracy.result(), step=self.training_step) tf.summary.scalar('value error', self.train_value_accuracy.result(), step=self.training_step) tf.summary.scalar('epsilon', data=self.epsilon, step=self.training_step) self.train_loss.reset_states() self.train_accuracy.reset_states() self.train_value_accuracy.reset_states() self.epsilon *= self.epsilon_decay def train_rl(self, states, returns, advantages, is_valid, cur_goals): self.training_step += 1 self.model.train_rl(states, returns, advantages, is_valid, cur_goals) self.epsilon *= self.epsilon_decay def save_model(self, file_name): self.model.save_weights(file_name, overwrite=True) def load_model(self, file_name): self.model.load_weights(file_name) def predict_action(self, state, asset_number): state_data, goal_data = self.state_to_training(state, asset_number) # goal_data = state.goal_locations[asset_number] state_data = tf.convert_to_tensor([state_data]) goal_data = tf.convert_to_tensor([goal_data]) policy, value = self.model.call((state_data, goal_data)) action = np.argmax(policy.numpy()) # print(answers) return action, value def normalize_returns(self, x): x -= np.mean(x) x /= (np.std(x) + 1e-8) return x def discount(self, x, gamma): return signal.lfilter([1], [1, -gamma], x[::-1], axis=0)[::-1] def good_discount(self, x, gamma): return self.discount(x, gamma) def compute_gae(self, next_value, rewards, masks, values): values = values + [next_value] # gae = 0 # returns = [] # for step in reversed(range(len(rewards))): # # delta = rewards[step] + (gamma * values[step + 1] * masks[step] - values[step]) # delta = rewards[step] + (self.gae_gamma * values[step + 1] - values[step]) # # gae = delta + gamma * lam * masks[step] * gae # gae = delta + self.gae_gamma * self.gae_lambda * gae # # prepend to get correct order back # returns.insert(0, gae + values[step]) # return returns # TODO: bootrap_value # self.rewards_plus = np.asarray(rewards.tolist() + [bootstrap_value]) rewards_plus = rewards # discounted_rewards = discount(self.rewards_plus, gamma)[:-1] gamma = .95 discounted_rewards = self.discount(rewards_plus, gamma)[:-1] # self.value_plus = np.asarray(values.tolist() + [bootstrap_value]) value_plus = np.asarray(values) # value_plus = values # advantages = rewards + gamma * self.value_plus[1:] - self.value_plus[:-1] advantages = rewards + gamma * value_plus[1:] - value_plus[:-1] # advantages = good_discount(advantages, gamma) advantages = self.good_discount(advantages, gamma)[0, 0, :].astype(np.float32) # advantages = np.reshape(advantages, [200, 1, 1]).tolist() advantages = np.reshape(advantages, [len(advantages), 1, 1]) return advantages def epsilon_greedy_action(self, predicted_action, num_actions=5): r = random.random() if r < self.epsilon: action = random.randint(0, num_actions - 1) else: action = predicted_action return action <file_sep>/RL_Stuff.py import tensorflow as tf # import tensorflow_probability as tfp from tensorflow import keras from tensorflow.keras import layers from numpy.random import choice import numpy as np # from constants import * class ActorCriticModel(keras.Model): def __init__(self, config, min_std=1e-5): super(ActorCriticModel, self).__init__() self.learning_rate = config['learning-rate'] self.ppo_epochs = config['ppo-epochs'] self.mini_batch_size = config['mini-batch-size'] self.max_grad_norm = config['max-grad-norm'] self.critic_discount = config['critic-discount'] self.valid_discount = config['valid-discount'] self.entropy_beta = config['entropy-beta'] network_config = config['network'] self.state_shape = tuple(network_config['state-shape']) self.network_shape = tuple(network_config['network-shape']) self.goal_shape = tuple(network_config['goal-shape']) self.num_actions = network_config['number-of-actions'] self.network_depth = self.network_shape[0] self.network_height = self.network_shape[1] self.network_width = self.network_shape[2] self.global_step = tf.Variable(0, trainable=False) # boundaries = [SUPERVISED_CUTOFF] # values = [LEARNING_RATE, LEARNING_RATE/2] # learning_rate = tf.compat.v1.train.piecewise_constant(self.global_step, boundaries, # values) self.optimizer = tf.keras.optimizers.Adam(learning_rate=self.learning_rate) # learning_rate) # fancy input stuff self.convlayer1 = layers.Conv2D(filters=128, kernel_size=(3,3), strides=(1,1), padding='same', input_shape=(None, *self.network_shape), activation='swish') self.convlayer2 = layers.Conv2D(filters=128, kernel_size=(3,3), strides=(1,1), padding='same', activation='swish') self.pool1 = layers.MaxPooling2D(pool_size=(2,2)) self.convlayer3 = layers.Conv2D(filters=128, kernel_size=(3,3), strides=(1,1), padding='same', activation='swish') self.convlayer4 = layers.Conv2D(filters=64, kernel_size=(3,3), strides=(1,1), padding='same', activation='swish') self.pool2 = layers.MaxPooling2D(pool_size=(2,2)) self.convlayer5 = layers.Conv2D(filters=64, kernel_size=(3,3), strides=(1,1), padding='same', activation='swish') self.flattenlayer = layers.Flatten() self.dropout = layers.Dropout(0.1) # get rid of info to speed up our lives! and overfitting blah blah blah # goal input self.goal_layer1 = layers.Dense(12, input_shape=(None, *self.goal_shape), activation='swish') self.goal_layer2 = layers.Dense(12, activation='swish') # post concatenation self.dense1 = layers.Dense(128, activation='swish') self.dense2 = layers.Dense(128, activation='swish') # self.LSTM = layers.LSTM(128, activation='swish', recurrent_activation='swish', return_sequences=False) self.dense3 = layers.Dense(128, activation='swish') # policy output self.policy_dense1 = layers.Dense(128, activation='swish') self.policy_dense2 = layers.Dense(64, activation='swish') self.policy_output = layers.Dense(self.num_actions, activation='softmax') # value output self.value_dense1 = layers.Dense(128, activation='swish') self.value_dense2 = layers.Dense(64, activation='swish') self.value_output = layers.Dense(1, activation='linear') # on_goal output # self.goal_output = layers.Dense(1, activation='sigmoid') def call(self, inputs): conv_inputs = tf.convert_to_tensor(inputs[0]) conv = self.convlayer1(conv_inputs) conv = self.convlayer2(conv) conv = self.pool1(conv) conv = self.convlayer3(conv) conv = self.convlayer4(conv) conv = self.pool2(conv) conv = self.convlayer5(conv) conv = self.flattenlayer(conv) conv = self.dropout(conv) goal_inputs = tf.convert_to_tensor(inputs[1]) goal = self.goal_layer1(goal_inputs) goal = self.goal_layer2(goal) # print(conv.shape) # print(goal.shape) concatenated = layers.Concatenate(axis=1)([conv, goal]) dense = self.dense1(concatenated) dense = self.dense2(dense) # dense = self.LSTM(dense) dense = self.dense3(dense) policy = self.policy_dense1(dense) policy = self.policy_dense2(policy) policy = self.policy_output(policy) value = self.value_dense1(dense) value = self.value_dense2(value) value = self.value_output(value) # goal = self.goal_output(dense) return policy, value#, goal # @tf.function def train_rl(self, states, returns, advantages, is_valid, cur_goals): self.global_step = self.global_step + 1 count_steps = 0 # PPO EPOCHS is the number of times we will go through ALL the training data to make updates for _ in range(self.ppo_epochs): # grabs random mini-batches several times until we have covered all data # for state, action, return_, advantage, is_valid_, value, goal, goal_guess in self._ppo_iterator(states, actions, returns, advantages, is_valid, values, goals, goal_guesses): for state, return_, advantage, is_valid_, cur_goal in self._ppo_iterator(states, returns, advantages, is_valid, cur_goals): with tf.GradientTape() as tape: tape.watch(self.trainable_variables) # keep track of the trainable variables (don't always need all of them) loss = self._get_loss(state, return_, advantage, is_valid_, cur_goal) # goal, goal_guess) grads = tape.gradient(loss, self.trainable_variables) # get_gradients (backprop) from losses # https://github.com/openai/baselines/blob/ea25b9e8b234e6ee1bca43083f8f3cf974143998/baselines/ppo2/model.py#L102-L108 grads, _ = tf.clip_by_global_norm(grads, self.max_grad_norm) self.optimizer.apply_gradients(zip(grads, self.trainable_variables)) # change weights based on gradients def sample(self, policy): # print(policy) n_policy = policy.numpy() n_policy = n_policy.squeeze() if np.isnan(n_policy).any(): n_policy = np.nan_to_num(n_policy) n_policy = n_policy / n_policy.sum() return choice(self.num_actions, 1, p=n_policy) # return choice(num_actions, 1, p=policy.numpy().squeeze()) def _ppo_iterator(self, states, returns, advantage, is_valid, cur_goals):#, goals, goal_guesses): batch_size = len(states) # generates random mini-batches until we have covered the full batch for _ in range(batch_size // self.mini_batch_size): rand_ids = tf.convert_to_tensor(np.random.randint(0, batch_size, self.mini_batch_size)) yield tf.gather(tf.convert_to_tensor(states), rand_ids), \ tf.gather(tf.convert_to_tensor(returns), rand_ids), tf.gather(tf.convert_to_tensor(advantage), rand_ids), tf.gather(tf.convert_to_tensor(is_valid), rand_ids), \ tf.gather(tf.convert_to_tensor(cur_goals), rand_ids) #\ # tf.gather(tf.convert_to_tensor(goals), rand_ids), tf.gather(tf.convert_to_tensor(goal_guesses), rand_ids) def _get_loss(self, state, return_, advantage, is_valid, cur_goal): # breakpoint() # state = tf.reshape(state, [32,30,30,7]) # cur_goal = tf.reshape(cur_goal, [32,2]) state = tf.reshape(state, [self.mini_batch_size, self.network_depth, self.network_height, self.network_width]) cur_goal = tf.reshape(cur_goal, [self.mini_batch_size, 2]) policy, value = self.call([state, cur_goal]) # l_value = tf.reduce_mean(tf.pow(return_ - value, 2)) l_value = tf.reduce_mean(tf.pow(tf.cast(return_, dtype=tf.float32) - value, 2)) # l_entropy = -tf.reduce_mean(policy*tf.math.log(tf.clip_by_value(policy, 1e-10, 1))) l_entropy = -tf.reduce_mean(policy * tf.math.log(tf.clip_by_value(policy, 1e-7, 1))) # l_policy = -tf.reduce_mean(tf.math.log(tf.clip_by_value(tf.convert_to_tensor(np.array([[np.max(i)] for i in policy])), 1e-10, 1.0)) * advantage) # l_policy = -tf.reduce_mean(tf.math.log(tf.clip_by_value(tf.convert_to_tensor(np.array([[np.max(i)] for i in policy])), 1e-7, 1.0)) * advantage) l_policy = -tf.reduce_mean(tf.math.log(tf.clip_by_value(tf.convert_to_tensor(np.array([[np.max(i)] for i in policy])), 1e-7, 1.0)) * tf.cast(advantage, tf.float32)) legal_policy = tf.cast(tf.convert_to_tensor(is_valid), tf.float32) # valid_policys = tf.clip_by_value(policy, 1e-10, 1.0-1e-10) valid_policys = tf.clip_by_value(policy, 1e-7, 1.0 - 1e-7) l_valid = -tf.reduce_mean(tf.math.log(valid_policys)*legal_policy + tf.math.log(1-valid_policys) * (1-legal_policy)) # cross entropy for illegal moves # l_goal = -tf.reduce_mean(on_goal*tf.math.log(tf.clip_by_value(goal_guess,1e-10,1.0))\ # +(1-on_goal)*tf.math.log(tf.clip_by_value(1-goal_guess,1e-10,1.0))) loss = (self.critic_discount * l_value + l_policy + self.valid_discount * l_valid - self.entropy_beta * l_entropy) / 10 # + ON_GOAL_DISCOUNT*l_goal # + BLOCKING_DISCOUNT*l_blocking return loss def train_imitation(self, cur_states, cur_goals, cur_actions, returns, train_loss_logger=None, train_accuracy_logger=None, train_value_accuracy_logger=None): self.global_step = self.global_step + 1 count_steps = 0 # saving losses for tensorboard tb_losses = [] # PPO EPOCHS is the number of times we will go through ALL the training data to make updates for _ in range(self.ppo_epochs): # grabs random mini-batches several times until we have covered all data for state, cur_goal, correct_action, return_ in self._ppo_imitation_iterator(cur_states, cur_goals, cur_actions, returns): with tf.GradientTape() as tape: tape.watch(self.trainable_variables) # keep track of the trainable variables (don't always need all of them) loss = self._get_imitation_loss(state, cur_goal, correct_action, return_, train_accuracy_logger, train_value_accuracy_logger) grads = tape.gradient(loss, self.trainable_variables) # get_gradients (backprop) from losses tb_losses.append(loss) # https://github.com/openai/baselines/blob/ea25b9e8b234e6ee1bca43083f8f3cf974143998/baselines/ppo2/model.py#L102-L108 grads, _ = tf.clip_by_global_norm(grads, self.max_grad_norm) self.optimizer.apply_gradients(zip(grads, self.trainable_variables)) # change weights based on gradients if train_loss_logger is not None: # tb_loss_average = sum(tb_losses) / len(tb_losses) train_loss_logger(tb_losses) # step = self.global_step.numpy() # with self.train_summary_writier.as_default(): # tf.summary.scalar('loss', self.train_loss.result(), step=step) # tf.summary.scalar('accuracy', self.train_accuracy.result(), step=step) # return tb_loss_average def _get_imitation_loss(self, state, cur_goal, correct_action, return_, train_accuracy_logger=None, train_value_accuracy_logger=None): state = tf.reshape(state, [self.mini_batch_size, self.network_depth, self.network_height, self.network_width]) cur_goal = tf.reshape(cur_goal, [self.mini_batch_size, 2]) return_ = tf.reshape(return_, [self.mini_batch_size, 1]) policy, value = self.call([state, cur_goal]) # useable_actions = np.array([[0 if j != correct_action[i] else 1 for j in range(5)] for i in range(correct_action.shape[0])]) useable_actions = tf.one_hot(correct_action, self.num_actions) l_imitation = tf.reduce_mean(keras.losses.categorical_crossentropy(useable_actions, policy)) # logging for tensorboard if train_accuracy_logger is not None: train_accuracy_logger(correct_action, policy) if train_value_accuracy_logger is not None: train_value_accuracy_logger(return_.numpy(), value.numpy()) # l_value = tf.reduce_mean(tf.pow(return_ - value, 2)) l_value = tf.reduce_mean(tf.pow(tf.subtract(tf.cast(return_, tf.double), tf.cast(value, tf.double)), 2)) return tf.add(tf.multiply(self.critic_discount, l_value), tf.cast(l_imitation, tf.double)) # return self.critic_discount * l_value + l_imitation def _ppo_imitation_iterator(self, cur_states, cur_goals, cur_actions, returns): batch_size = len(cur_states) # generates random mini-batches until we have covered the full batch for _ in range(batch_size // self.mini_batch_size): rand_ids = tf.convert_to_tensor(np.random.randint(0, batch_size, self.mini_batch_size)) yield tf.gather(cur_states, rand_ids), tf.gather(cur_goals, rand_ids), \ tf.gather(cur_actions, rand_ids), tf.gather(returns, rand_ids) <file_sep>/Driver.py import random from tqdm import tqdm import TrainingFactory from DriverUtils import train_imitation, train_rl imitation_probability = 0.50 # imitation_probability = 1.0 trainer, simulator, state, visualizer, memory, tester = TrainingFactory.create(config_file='./configs/training.yml') # visualizer.visualize_combined_state(state) # visualizer.visualize(state=state, show=True) for sim_num in tqdm(range(1, 100001)): if sim_num < 100 or random.random() < imitation_probability: train_imitation(state, simulator, visualizer, trainer, memory) else: train_rl(state, simulator, visualizer, trainer, memory) state.reset_state() visualizer.reset() # the paper says they only train with the current round's data memory.reset() if sim_num % 100 == 0: trainer.save_model(f'./data/primal_weights_{sim_num}') print('finished') <file_sep>/Player.py import TrainingFactory import time from tqdm import tqdm from PathingExpert import a_star trainer, simulator, state, visualizer, memory, tester = TrainingFactory.create(config_file='./configs/training.yml') trainer.load_model('./data/primal_weights_6200') visualizer.visualize(state=state, show=True) # TODO: ew, this is the second place this showed up, need to fix FOUR_CONNECTED_MOVES = [(0, 0), (0, -1), (0, 1), (-1, 0), (1, 0)] print('starting...') time.sleep(5) going = True round = 0 while going: num_on_goal = 0 round += 1 # lets make sure we don't go on forever if we get stuck if round > 400: break; going = False for dude_num in range(len(state.assets)): asset = state.assets[dude_num] goal = state.goals[dude_num] if asset == goal: # print(f'bang-a-rang asset {dude_num} made it!') num_on_goal += 1 else: going = True action_number, value = trainer.predict_action(state, dude_num) move = FOUR_CONNECTED_MOVES[action_number] new_location = (asset[0] + move[0], asset[1] + move[1]) moved = simulator.move_asset(dude_num, new_location) if moved: visualizer.move_asset(asset, new_location) time.sleep(0.1) # if dude_num == 0: # print(f'{dude_num} going to {goal} moved {asset} -> {new_location}') print(num_on_goal) # cost = state.get_cost_matrix() # if agent_paths[dude_num] is None and agent_actions[dude_num] is None: # path, actions = a_star(asset, goal, cost) # agent_paths[dude_num] = path # agent_actions[dude_num] = actions # # get rid of current location # path.pop(0) # else: # path = agent_paths[dude_num] # actions = agent_actions[dude_num] # if len(path) > 0: # going = True # # # new_location = path.pop(0) # moved = simulator.move_asset(dude_num, new_location) # # # if moved: # visualizer.move_asset(asset, new_location) # # else: # path, actions = a_star(asset, goal, cost) # agent_paths[dude_num] = path # agent_actions[dude_num] = actions # get rid of current location # path.pop(0) # try going again to the next best place # new_location = path.pop(0) # moved = simulator.move_asset(dude_num, new_location) # state_data, goal_data = trainer.state_to_training(state, dude_num) # # action = actions[0] # if len(actions) == 0: # action = 0 # else: # action = actions.pop(0) # reward = trainer.get_reward(dude_num, state) # memory.remember(state_data, goal_data, action, reward) end = time.time() # print(f'\nsim {sim_num} took {end - start}') # start = time.time() trainer.train() # end = time.time() # print(f'\ntraining {sim_num} took {end - start} with memory size of {len(memory.memory)}') state.reset_state() visualizer.reset() print('finished') <file_sep>/Tester.py import pickle import copy class PrimalTester: def __init__(self, trainer, simulator, state, model): # trainer, simulator, state, visualizer, memory, tester = TrainingFactory.create(config_file=config_file) self.trainer = copy.copy(trainer) self.simulator = copy.copy(simulator) # self.model = model # self.original_state = state # inject the real model # self.trainer.model = model def score(self, num_sims=5): # TODO: ew, this is the third place this showed up, need to fix FOUR_CONNECTED_MOVES = [(0, 0), (0, -1), (0, 1), (-1, 0), (1, 0)] score = 0 for sim_num in range(1, num_sims + 1): with open(f'./test_data/test_sim_{sim_num}.pkl', 'rb') as inp: sim_state = pickle.load(inp) # inject our test scenario into the mix self.trainer.state = sim_state self.simulator.state = sim_state going = True sim_round = 0 while going and sim_round < 200: sim_round += 1 going = False for dude_num in range(len(sim_state.assets)): asset = sim_state.assets[dude_num] goal = sim_state.goals[dude_num] if asset == goal: pass else: going = True action_number = self.trainer.predict_action(sim_state, dude_num) move = FOUR_CONNECTED_MOVES[action_number] new_location = (asset[0] + move[0], asset[1] + move[1]) self.simulator.move_asset(dude_num, new_location) reward = self.trainer.get_reward(dude_num, sim_state) score += reward # put things back to normal, just like we found it # self.trainer.state = self.original_state # self.simulator.state = self.original_state return score if __name__ == '__main__': import TrainingFactory trainer, simulator, state, visualizer, memory, tester = TrainingFactory.create(config_file='./configs/training.yml') trainer.load_model('./models/exp1') print('model score:', tester.score())<file_sep>/PrimalState.py import numpy as np from random import randrange from math import sqrt from PathingExpert import a_star class PrimalState: def __init__(self, config): # size information self.width = config['simulator']['width'] self.height = config['simulator']['height'] # sim information self.num_enemies = config['simulator']['num-enemies'] self.num_allies = config['simulator']['num-allies'] self.num_assets = config['simulator']['num-assets'] self.num_barriers = config['simulator']['num-barriers'] # location information self.enemy_locations = np.zeros((self.height, self.width)) self.ally_locations = np.zeros((self.height, self.width)) self.asset_locations = np.zeros((self.height, self.width)) self.barrier_locations = np.zeros((self.height, self.width)) # influence information self.enemy_influence_distance = config['simulator']['enemy-influence-distance'] self.ally_influence_distance = config['simulator']['ally-influence-distance'] self.enemy_influence = np.zeros((self.height, self.width)) self.ally_influence = np.zeros((self.height, self.width)) self.mixed_influence = np.zeros((self.height, self.width)) # cost information costs = config['simulator']['costs'] self.cost_normal_movement = costs['normal_movement'] self.cost_ally_influence = costs['ally_influence'] self.cost_enemy_influence = costs['enemy_influence'] self.cost_mixed_influence = costs['mixed_influence'] self.cost_barrier = costs['barrier'] self.cost_asset = costs['asset'] self.cost_ally = costs['ally'] self.cost_enemy = costs['enemy'] self.goal_locations = np.zeros((self.height, self.width)) self.goals = [] self.assets = [] self.cost_matrix = np.zeros((self.height, self.width)) # set the mappings of state names and state values self.state_mapping = {} state_mapping_config = config['state']['mappings'] for key in state_mapping_config: value = state_mapping_config[key] self.state_mapping[key] = value self.state_mapping[value] = key self.reset_state() def get_combined_state(self): answer = np.zeros((self.height, self.width)) answer[self.enemy_influence == 1] = self.state_mapping['enemy_influence'] answer[self.ally_influence == 1] = self.state_mapping['ally_influence'] answer[self.mixed_influence == 1] = self.state_mapping['mixed_influence'] answer[self.enemy_locations == 1] = self.state_mapping['enemy'] answer[self.ally_locations == 1] = self.state_mapping['ally'] answer[self.barrier_locations == 1] = self.state_mapping['barrier'] answer[self.asset_locations == 1] = self.state_mapping['asset'] # remember, goals are numbered by the asset they belong to. # we also start at 0 for assets, all others are -1 if not goal locations answer[self.goal_locations >= 0] = self.state_mapping['goal'] return answer def reset_state(self): self.__reset_info(self.barrier_locations, self.num_barriers) self.__reset_info(self.ally_locations, self.num_allies, self.ally_influence, self.ally_influence_distance) self.__reset_info(self.enemy_locations, self.num_enemies, self.enemy_influence, self.enemy_influence_distance) # don't forget to get the mixed influence self.mixed_influence.fill(0) self.mixed_influence[(self.enemy_influence == 1) & (self.ally_influence == 1)] = 1 # need to calculate cost matrix before assets because assets uses it self.cost_matrix = self.__reset_cost_matrix() self.__reset_asset_info() def __reset_info(self, field, count, influence=None, influence_distance=0): # zero out the field field.fill(0) if influence is not None: influence.fill(0) # keep trying to add until we have the correct amount while field.sum() < count: y, x = randrange(self.height - 1), randrange(self.width - 1) if self.is_empty_location(y, x): field[y][x] = 1 # also set the influence if needed if influence is not None: # TODO: ew, need to vectorize this for i in range(self.height): for j in range(self.width): if sqrt((i - y)**2 + (j - x)**2) < influence_distance: influence[i][j] = 1 def __reset_asset_info(self): self.asset_locations.fill(0) # we are filling goal locations with -1 because the asset numbers start at 0 self.goal_locations.fill(-1) self.goals = [] self.assets = [] asset_num = 0 # create all of the allies and their corresponding goals while np.count_nonzero(self.asset_locations) < self.num_assets: y, x = randrange(self.height - 1), randrange(self.width - 1) if self.is_empty_location(y, x): self.asset_locations[y][x] = 1 self.assets.append((y, x)) # self.assets.append(BaseAgent(y, x)) goal_placed = False while not goal_placed: goal_y, goal_x = randrange(self.height - 1), randrange(self.width - 1) path = a_star((y, x), (goal_y, goal_x), self.cost_matrix) # we need to check if it is physically empty as well as if anyone else's goal is here if self.is_empty_location(goal_y, goal_x) and self.goal_locations[goal_y][goal_x] == -1: # TODO: need to check to see if there is actually a path from the agent to their goal # set the goal location to the number of the ally and save the tuple self.goal_locations[goal_y][goal_x] = asset_num self.goals.append((goal_y, goal_x)) # update record keeping asset_num += 1 goal_placed = True def move_asset(self, asset_number, location): prev_y, prev_x = self.assets[asset_number] new_y, new_x = location self.asset_locations[prev_y][prev_x] = 0 self.asset_locations[new_y][new_x] = 1 self.assets[asset_number] = (new_y, new_x) def get_cost_matrix(self): # copy the static bits matrix = self.cost_matrix.copy() # we need to insert this information in every time because the assets are always moving matrix[self.asset_locations == 1] = self.cost_asset return matrix def is_empty_location(self, y, x): # lets pretend there is a wall around the field if x < 0 or y < 0 or y >= len(self.enemy_locations) or x >= len(self.enemy_locations[0]): return False # we don't look at goals here because they don't take up space return self.enemy_locations[y][x] == 0 and \ self.ally_locations[y][x] == 0 and \ self.asset_locations[y][x] == 0 and \ self.barrier_locations[y][x] == 0 def __reset_cost_matrix(self): cost = np.full(self.barrier_locations.shape, self.cost_normal_movement) cost[(self.ally_influence == 1) & (self.enemy_influence == 1)] = self.cost_mixed_influence cost[self.ally_influence == 1] = self.cost_ally_influence cost[self.enemy_influence == 1] = self.cost_enemy_influence cost[self.barrier_locations == 1] = self.cost_barrier cost[self.enemy_locations == 1] = self.cost_enemy cost[self.ally_locations == 1] = self.cost_ally return cost def get_asset_goal_location(self, asset_number): # goal_location = np.where(self.goal_locations == asset_number) # goal = (goal_location[0][0], goal_location[1][0]) goal = self.goals[asset_number] return goal def get_asset_location(self, asset_number): asset_location = self.assets[asset_number] return asset_location<file_sep>/PathingExpert.py from queue import PriorityQueue from math import sqrt import numpy as np # always have the stay put in position 0 FOUR_CONNECTED_MOVES = [(0, 0), (0, -1), (0, 1), (-1, 0), (1, 0)] def a_star(start, end, cost): if start == end: return [end] # get the x and y locations # adding 1 because we are padding the cost area start_y, start_x = start[0] + 1, start[1] + 1 end_y, end_x = end[0] + 1, end[1] + 1 # pad the cost matrix so we don't have ugly indexing issues cost = np.pad(cost, 1, 'constant', constant_values=999999999) open_set = PriorityQueue() parents = {} visited = [] # add the start location and a 0 cost open_set.put((0, start_y, start_x)) visited.append((start_y, start_x)) parents[(start_y, start_x)] = None solved = False while not solved and not open_set.empty(): previous_cost, y, x = open_set.get() if y == end_y and x == end_x: solved = True break for dir_y, dir_x in FOUR_CONNECTED_MOVES: next_y = y + dir_y next_x = x + dir_x if (next_y, next_x) not in visited: g_cost = cost[next_y][next_x] h_cost = sqrt((end_y - next_y)**2 + (end_x - next_x)**2) open_set.put(((previous_cost + g_cost + h_cost), next_y, next_x)) parents[(next_y, next_x)] = (y, x) visited.append((next_y, next_x)) path = [] actions = [] next = (end_y, end_x) while next is not None: # don't forget to subtract one because we padded everything y = next[0] - 1 x = next[1] - 1 path.append((y, x)) next = parents[next] path.reverse() here = None for next in path: if here is None: here = next else: action = (next[0] - here[0], next[1] - here[1]) action_number = FOUR_CONNECTED_MOVES.index(action) actions.append(action_number) here = next return path, actions <file_sep>/WorkingMemory.py from random import random, sample # Uses a basic array for holding previous training information. # This will hold a certain max amount of training episodes and then start forgetting the oldest class WorkingMemory: def __init__(self, memory_size=100000): # how many training samples should we keep? self.memory_size = memory_size # our actual memory to hold the training samples self.memory = [] # add a training sample to our memory def remember(self, state, goal, action, reward): # add the training sample # training_example = (s, a, r, s_prime, done) training_example = (state, goal, action, reward) self.memory.append(training_example) # if we are over the limit, start forgetting if len(self.memory) > self.memory_size: # pop from the beginning because that is the oldest self.memory.pop(0) # get a bunch of samples to train on def sample_memory(self, count): # return the number they asked for or the entire memory, which ever is smaller return sample(self.memory, min(count, len(self.memory))) def num_samples(self): return len(self.memory) def reset(self): self.memory = [] <file_sep>/TrainingFactory.py from importlib import import_module import yaml from WorkingMemory import WorkingMemory from PrimalState import PrimalState from Trainer import Trainer from Visualizer import Visualizer from RL_Stuff import ActorCriticModel from Tester import PrimalTester def create(config_file, create_state=True): # Read the yml config file with open(config_file, 'r') as stream: config = yaml.safe_load(stream) # create and configure the working memory memory_config = config['working-memory'] memory_size = memory_config['size'] memory = WorkingMemory(memory_size) # create and configure the state if create_state: state = PrimalState(config) else: state = None # create and configure the simulator simulator_config = config['simulator'] simulator_type = simulator_config['type'] module_path, class_name = simulator_type.rsplit('.', 1) module = import_module(module_path) simulator = getattr(module, class_name)(state, **simulator_config) # create a model trainer_config = config['trainer'] model = ActorCriticModel(trainer_config) # create and configure the trainer trainer = Trainer(trainer_config, memory, simulator, state, model) # create and configure the visualizer visualizer = Visualizer(config['visualization']) tester = PrimalTester(trainer, simulator, state, model) return trainer, simulator, state, visualizer, memory, tester <file_sep>/TestDataGenerator.py import TrainingFactory import pickle trainer, simulator, state, visualizer, memory, _ = TrainingFactory.create(config_file='./configs/training.yml') for sim_num in range(1, 11): visualizer.visualize_combined_state(state, file_name=f'./test_data/test_sim_img_{sim_num}.jpg') with open(f'./test_data/test_sim_{sim_num}.pkl', 'wb') as outp: pickle.dump(state, outp, pickle.HIGHEST_PROTOCOL) state.reset_state() <file_sep>/DriverUtils.py import numpy as np from PathingExpert import a_star def train_rl(state, simulator, visualizer, trainer, memory): # TODO: ew, this is the fourth place this showed up, need to fix FOUR_CONNECTED_MOVES = [(0, 0), (0, -1), (0, 1), (-1, 0), (1, 0)] num_assets = len(state.assets) num_actions = len(FOUR_CONNECTED_MOVES) next_values = [0 for _ in range(num_assets)] cur_rewards = [[] for _ in range(num_assets)] cur_values = [[] for _ in range(num_assets)] cur_states = [[] for _ in range(num_assets)] cur_valids = [[] for _ in range(num_assets)] cur_goals = [[] for _ in range(num_assets)] going = True sim_round = 0 while going: sim_round += 1 # lets make sure we don't go on forever if we get stuck if sim_round > 200: break going = False for dude_num in range(len(state.assets)): asset = state.assets[dude_num] goal = state.goals[dude_num] if asset != goal: going = True valid_moves = [1 for i in range(num_actions)] for i in range(num_actions): test_move = FOUR_CONNECTED_MOVES[i] test_location = (asset[0] + test_move[0], asset[1] + test_move[1]) valid_moves[i] = int(simulator.valid_action(dude_num, test_location)) predicted_action, value = trainer.predict_action(state, dude_num) action = trainer.epsilon_greedy_action(predicted_action) move = FOUR_CONNECTED_MOVES[action] new_location = (asset[0] + move[0], asset[1] + move[1]) moved = simulator.move_asset(dude_num, new_location) if moved: visualizer.move_asset(asset, new_location) state_data, goal_data = trainer.state_to_training(state, dude_num) reward = trainer.get_reward(dude_num, state) cur_values[dude_num].append(value) cur_rewards[dude_num].append(reward) cur_states[dude_num].append(state_data) cur_valids[dude_num].append(valid_moves) cur_goals[dude_num].append(goal_data) for dude_num in range(len(state.assets)): asset = state.assets[dude_num] goal = state.goals[dude_num] action, next_value = trainer.predict_action(state, dude_num) move = FOUR_CONNECTED_MOVES[action] new_location = (asset[0] + move[0], asset[1] + move[1]) moved = simulator.move_asset(dude_num, new_location) next_values[dude_num] = next_value # returns = np.array([compute_gae(next_values[asset], cur_rewards[asset], masks, cur_values[asset]) for asset in range(NUM_ASSETS)]) returns = np.array([trainer.compute_gae(next_values[asset], cur_rewards[asset], 1, cur_values[asset]) for asset in range(num_assets)]) advantages = trainer.normalize_returns(returns - cur_values) # state, goal, action, reward # memory.remember(state_data, goal_data, action, reward) flatten = lambda t: [item for sublist in t for item in sublist] cur_states = flatten(cur_states) returns = flatten(returns) advantages = flatten(advantages) cur_valids = flatten(cur_valids) cur_goals = flatten(cur_goals) # TODO: we may be training too many times on the same information, # we might need to look into training every so many sessions trainer.train_rl(cur_states, returns, advantages, cur_valids, cur_goals) def train_imitation(state, simulator, visualizer, trainer, memory): agent_actions = [None for i in range(len(state.assets))] agent_paths = [None for i in range(len(state.assets))] going = True sim_round = 0 while going: sim_round += 1 # lets make sure we don't go on forever if we get stuck if sim_round > 200: # visualizer.visualize_combined_state(state) break going = False for dude_num in range(len(state.assets)): asset = state.assets[dude_num] goal = state.goals[dude_num] # TODO: may need to also add for when they are on the goal for stick actions if asset != goal: cost = state.get_cost_matrix() if agent_paths[dude_num] is None and agent_actions[dude_num] is None: path, actions = a_star(asset, goal, cost) agent_paths[dude_num] = path agent_actions[dude_num] = actions # get rid of current location path.pop(0) else: path = agent_paths[dude_num] actions = agent_actions[dude_num] if len(path) > 0: going = True new_location = path.pop(0) moved = simulator.move_asset(dude_num, new_location) if moved: visualizer.move_asset(asset, new_location) else: path, actions = a_star(asset, goal, cost) agent_paths[dude_num] = path agent_actions[dude_num] = actions # get rid of current location path.pop(0) # try going again to the next best place new_location = path.pop(0) moved = simulator.move_asset(dude_num, new_location) state_data, goal_data = trainer.state_to_training(state, dude_num) if len(actions) == 0: action = 0 else: action = actions.pop(0) reward = trainer.get_reward(dude_num, state) # state, goal, action, reward memory.remember(state_data, goal_data, action, reward) # TODO: we may be training too many times on the same information, # we might need to look into training every so many sessions trainer.train() <file_sep>/Visualizer.py import numpy as np class Visualizer: def __init__(self, config): self.scale = config['scale'] self.colors = {} color_config = config['colors'] # loop through all of the colors and create a numpy array for them for key in color_config: self.colors[key] = np.fromstring(color_config[key], dtype=int, sep=',') # we start out without actually visualizing anything so things are initialized to None self.state = None self.pixels = None self.screen = None self.visualization_initialized = False def visualize(self, state=None, show=True): if show and state is not None: # now we can start importing pixel and pygame classes from pixel_class import Pixel from pygame.display import set_mode, flip from pygame import init as pygame_init pygame_init() self.flip = flip self.state = state self.screen = set_mode((state.width * self.scale, state.height * self.scale)) self.screen.fill((0, 0, 0)) combined_state = state.get_combined_state() self.pixels = [[Pixel(x, y, self.screen, self.colors[state.state_mapping[combined_state[y][x]]], self.scale) for x in range(state.width)] for y in range(state.height)] self.visualization_initialized = True def move_asset(self, previous, next): # we haven't been told we need to visualize anything yet if not self.visualization_initialized: return combined_state = self.state.get_combined_state() old_color = self.colors[self.state.state_mapping[combined_state[previous[0]][previous[1]]]] self.pixels[previous[0]][previous[1]].change_state(old_color) self.pixels[next[0]][next[1]].change_state(self.colors['asset']) self.flip() def visualize_combined_state(self, state, file_name=None): # make sure it has been initialized, be we don't want to unless this is called from matplotlib import pyplot as plt combined_state = state.get_combined_state() data = np.full((state.height, state.width, 3), 255) for key in self.colors: locations = np.where(combined_state == state.state_mapping[key]) data[locations[0], locations[1], :] = self.colors[key] plt.imshow(data, interpolation='nearest') if file_name is not None: plt.savefig(file_name) else: plt.show() def reset(self): # we haven't been told we need to visualize anything yet if not self.visualization_initialized: return from pixel_class import Pixel # from pygame.display import set_mode, flip # from pygame import init as pygame_init # pygame_init() self.screen.fill((0, 0, 0)) combined_state = self.state.get_combined_state() self.pixels = [[Pixel(x, y, self.screen, self.colors[self.state.state_mapping[combined_state[y][x]]], self.scale) for x in range(self.state.width)] for y in range(self.state.height)]
4bb7f6b5a1becd0bbe809114ffa79936205febc6
[ "Python" ]
14
Python
jeffrichley/primal
6b06de7051dda63cc1c215389ac7112c72b04dc0
4ef070c3d5ac001873250a47a662ac8877eb6c9e
refs/heads/master
<repo_name>Karrar98/TranslateApi<file_sep>/app/src/main/java/com/example/translateapi/repositry/TranslateRepository.kt package com.example.translateapi.repositry import com.example.translateapi.model.ResultTranslated import com.example.translateapi.network.Client import com.example.translateapi.utils.Constant import com.example.translateapi.utils.Status import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.flowOn object TranslateRepository { fun getTranslateData(queryMap: Map<String, String>) = flow <Status<ResultTranslated>>{ emit(Status.Loading) emit(Client.initRequest(queryMap = queryMap, typeRequest = Constant.TRANSLATE)) }.flowOn(Dispatchers.IO) }<file_sep>/app/src/main/java/com/example/translateapi/repositry/LanguageRepository.kt package com.example.translateapi.repositry import com.example.translateapi.model.Languages import com.example.translateapi.network.Client import com.example.translateapi.utils.Constant import com.example.translateapi.utils.Status import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.flowOn object LanguageRepository { fun getLanguage() = flow <Status<Languages>>{ emit(Status.Loading) emit(Client.initRequest(queryMap = null, typeRequest = Constant.LANGUAGE)) }.flowOn(Dispatchers.IO) }<file_sep>/app/src/main/java/com/example/translateapi/model/Languages.kt package com.example.translateapi.model class Languages : ArrayList<LanguagesItem>()<file_sep>/app/src/main/java/com/example/translateapi/utils/Constant.kt package com.example.translateapi.utils object Constant { object Url { val SCHEME = "https" val HOST = "translate.argosopentech.com" } val LANGUAGE = "languages" val TRANSLATE = "translate" object Translate { val QUERY = "q" val SOURCE = "source" val TARGET = "target" } }<file_sep>/app/src/main/java/com/example/translateapi/ui/MainActivity.kt package com.example.translateapi.ui import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.View import android.widget.AdapterView import android.widget.ArrayAdapter import androidx.core.widget.doOnTextChanged import androidx.lifecycle.lifecycleScope import com.example.translateapi.R import com.example.translateapi.databinding.ActivityMainBinding import com.example.translateapi.model.Languages import com.example.translateapi.model.ResultTranslated import com.example.translateapi.repositry.LanguageRepository import com.example.translateapi.repositry.TranslateRepository import com.example.translateapi.utils.Constant import com.example.translateapi.utils.Status import kotlinx.coroutines.flow.catch import kotlinx.coroutines.flow.collect import kotlinx.coroutines.flow.onCompletion import kotlinx.coroutines.launch class MainActivity : AppCompatActivity() { private lateinit var binding: ActivityMainBinding private var queryMap = mutableMapOf<String, String>() private val arrayLangName: ArrayList<String> = arrayListOf() private val arrayLangCode: ArrayList<String> = arrayListOf() private var selectLangSource: String? = null private var selectLangTarget: String? = null private var positionSourceLang: Int? = null private var positionTargetLang: Int? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) setup() } private fun setup() { initInput() initSpinner() initSwapLang() } private fun initSwapLang() { binding.swapLang.setOnClickListener { switchLang() } } private fun switchLang() { selectLangSource = selectLangTarget.also { selectLangTarget = selectLangSource } binding.apply { targetText.text = sourceText.text.toString().also { sourceText.setText(targetText.text) } positionTargetLang?.let { dropdownLangSource.setSelection(it) } positionSourceLang?.let { dropdownLangTarget.setSelection(it) } } } private fun initInput() { binding.sourceText.doOnTextChanged { text, start, before, count -> queryMap = initMutableMap(text.toString(), selectLangSource, selectLangTarget) makeTranslateRequest(queryMap = queryMap) } } private fun initMutableMap(query: String, selectLangSource: String?, selectLangTarget: String?): MutableMap<String, String> { queryMap[Constant.Translate.QUERY] = query queryMap[Constant.Translate.SOURCE] = selectLangSource.toString() queryMap[Constant.Translate.TARGET] = selectLangTarget.toString() return queryMap } private fun initSpinner() { makeLanguageRequest() } private fun makeLanguageRequest() { lifecycleScope.launch { LanguageRepository.getLanguage() .onCompletion { }.catch { }.collect(::getResultLanguage) } } private fun getResultLanguage(response: Status<Languages>){ return when(response){ is Status.Error -> { // Toast.makeText( // this@MainActivity, // "error can't access sorry", // Toast.LENGTH_SHORT // ).show() } is Status.Loading -> { // Toast.makeText( // this@MainActivity, // "Loading access", // Toast.LENGTH_SHORT // ).show() } is Status.Success -> { setSpinner(response.data) } } } private fun setSpinner(data: Languages) { data.forEach { arrayLangName.add(it.name.toString()) arrayLangCode.add(it.code.toString()) } val arrayAdapter = ArrayAdapter(this, R.layout.item_dropdown, arrayLangName) binding.dropdownLangSource.apply { setAdapter(arrayAdapter) onItemSelectedListener = object: AdapterView.OnItemSelectedListener{ override fun onItemSelected(p0: AdapterView<*>?, p1: View?, position: Int, p3: Long) { selectLangSource = arrayLangCode[position] positionSourceLang = position queryMap = initMutableMap(binding.sourceText.text.toString(), selectLangSource, selectLangTarget) makeTranslateRequest(queryMap = queryMap) } override fun onNothingSelected(p0: AdapterView<*>?) { } } } binding.dropdownLangTarget.apply { setAdapter(arrayAdapter) onItemSelectedListener = object: AdapterView.OnItemSelectedListener{ override fun onItemSelected(p0: AdapterView<*>?, p1: View?, position: Int, p3: Long) { selectLangTarget = arrayLangCode[position] positionTargetLang = position queryMap = initMutableMap(binding.sourceText.text.toString(), selectLangSource, selectLangTarget) makeTranslateRequest(queryMap = queryMap) } override fun onNothingSelected(p0: AdapterView<*>?) { } } } } private fun makeTranslateRequest(queryMap: Map<String, String>) { lifecycleScope.launch { TranslateRepository.getTranslateData( queryMap = queryMap).collect(::getResultTranslate) } } private fun getResultTranslate(response: Status<ResultTranslated>) { return when (response) { is Status.Error -> { // Toast.makeText( // this@MainActivity, // "error can't access sorry", // Toast.LENGTH_SHORT // ).show() } is Status.Loading -> { // Toast.makeText( // this@MainActivity, // "Loading access", // Toast.LENGTH_SHORT // ).show() } is Status.Success -> { setData(response.data) } } } private fun setData(data: ResultTranslated) { binding.targetText.text = data.translatedText } }<file_sep>/app/src/main/java/com/example/translateapi/network/Client.kt package com.example.translateapi.network import com.example.translateapi.model.Languages import com.example.translateapi.model.ResultTranslated import com.example.translateapi.utils.Constant import com.example.translateapi.utils.Status import com.google.gson.Gson import okhttp3.FormBody import okhttp3.HttpUrl import okhttp3.OkHttpClient import okhttp3.Request object Client { val client = OkHttpClient() val gson = Gson() fun BaseUrl(pathSegment: String, queryMap: Map<String, String>?) = HttpUrl.Builder().scheme(Constant.Url.SCHEME). host(Constant.Url.HOST).addPathSegment(pathSegment).apply { if (pathSegment == Constant.TRANSLATE) { addQueryParameter(Constant.Translate.QUERY, queryMap?.get(Constant.Translate.QUERY)) addQueryParameter(Constant.Translate.SOURCE, queryMap?.get(Constant.Translate.SOURCE)) addQueryParameter(Constant.Translate.TARGET, queryMap?.get(Constant.Translate.TARGET)) } }.toString() inline fun <reified T> initRequest(typeRequest: String, queryMap: Map<String, String>?): Status<T>{ val postBody = FormBody.Builder().build() val request = Request.Builder().url(BaseUrl(typeRequest, queryMap)).apply { if (typeRequest == Constant.TRANSLATE) { post(postBody) } }.build() val response = client.newCall(request).execute() return if (response.isSuccessful) { val parserResponse = gson.fromJson( response.body?.string(), T::class.java ) Status.Success(parserResponse) } else { Status.Error(response.message) } } }<file_sep>/app/src/main/java/com/example/translateapi/model/LanguagesItem.kt package com.example.translateapi.model import com.google.gson.annotations.SerializedName data class LanguagesItem( @SerializedName("code") val code: String?, @SerializedName("name") val name: String? )<file_sep>/app/src/main/java/com/example/translateapi/model/ResultTranslated.kt package com.example.translateapi.model import com.google.gson.annotations.SerializedName data class ResultTranslated( @SerializedName("translatedText") val translatedText: String? )
6d1b6efdebeab35d80823e443726cd88097a728d
[ "Kotlin" ]
8
Kotlin
Karrar98/TranslateApi
875d260e4c68a667dcca57849ca7b2a70c60827f
0a2e5ae97e869d4645cde6e7be320e0d849b2ce1
refs/heads/master
<file_sep>// // BaseViewController.swift // Coordinators // // Created by <NAME> on 11/07/2020. // Copyright © 2020 <NAME>. All rights reserved. // import UIKit class BaseViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false view.addSubview(label) label.font = UIFont.systemFont(ofSize: 60, weight: .bold) label.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true label.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true label.text = title let colors = [ UIColor.lightGray, UIColor.blue, UIColor.orange, UIColor.gray, UIColor.cyan ] view.backgroundColor = colors.randomElement() } } <file_sep>// // SettingsViewController.swift // Coordinators // // Created by <NAME> on 11/07/2020. // Copyright © 2020 <NAME>. All rights reserved. // import UIKit protocol SettingsViewControllerHandling: AnyObject { func handle(event: SettingsViewController.Event) } class SettingsViewController: BaseViewController, Coordinated { enum Event { case dismiss } weak var coordinator: SettingsViewControllerHandling? override func viewDidLoad() { title = "SETTINGS" super.viewDidLoad() } } <file_sep>// // OrderCoordinator.swift // Coordinators // // Created by <NAME> on 11/07/2020. // Copyright © 2020 <NAME>. All rights reserved. // import UIKit protocol OrderCoordinatorHandling: AnyObject { func handle(event: OrderCoordinator.Event) } class OrderCoordinator: NavigationControllerCoordinator, ParentCoordinated { enum Event { } weak var parent: OrderCoordinatorHandling? var navigationController: UINavigationController var childCoordinators: [Coordinator] = [] init(navigationController: UINavigationController) { self.navigationController = navigationController start() } func start() { let orderViewController = OrderViewController() orderViewController.coordinator = self navigationController.setViewControllers([ orderViewController ], animated: false) } } extension OrderCoordinator: OrderViewControllerHandling { func handle(event: OrderViewController.Event) { switch event { case .detail: let orderDetailCoordinator = OrderDetailCoordinator(navigationController: navigationController) orderDetailCoordinator.parent = self childCoordinators.append(orderDetailCoordinator) } } } extension OrderCoordinator: OrderDetailCoordinatorHandling { func handle(event: OrderDetailCoordinator.Event) { switch event { case .dismiss: childCoordinators.removeAll { $0 is OrderDetailCoordinator } } } } <file_sep>// // ChatViewController.swift // Coordinators // // Created by <NAME> on 11/07/2020. // Copyright © 2020 <NAME>. All rights reserved. // import UIKit protocol ChatViewControllerHandling: AnyObject { func handle(event: ChatViewController.Event) } class ChatViewController: BaseViewController, Coordinated { enum Event { case showSettings } weak var coordinator: ChatViewControllerHandling? override func viewDidLoad() { title = "CHAT" super.viewDidLoad() let button = UIButton() view.addSubview(button) button.backgroundColor = .systemRed button.layer.cornerRadius = 5 button.setTitle("Show settings", for: .normal) button.setTitleColor(UIColor.black, for: .normal) button.addTarget(self, action: #selector(didTapSettings), for: .touchUpInside) button.translatesAutoresizingMaskIntoConstraints = false button.widthAnchor.constraint(equalToConstant: 200).isActive = true button.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -80).isActive = true button.centerXAnchor.constraint(equalTo: view.safeAreaLayoutGuide.centerXAnchor).isActive = true } @objc func didTapSettings() { coordinator?.handle(event: .showSettings) } } <file_sep>// // OrderDetailViewController.swift // Coordinators // // Created by <NAME> on 11/07/2020. // Copyright © 2020 <NAME>. All rights reserved. // import UIKit protocol OrderDetailViewControllerHandling: AnyObject { func handle(event: OrderDetailEvent) } enum OrderDetailEvent { case dismiss } class OrderDetailAViewController: BaseViewController, Coordinated { weak var coordinator: OrderDetailViewControllerHandling? override func viewDidLoad() { title = "DETAIL A" super.viewDidLoad() } } class OrderDetailBViewController: BaseViewController, Coordinated { weak var coordinator: OrderDetailViewControllerHandling? override func viewDidLoad() { title = "DETAIL B" super.viewDidLoad() } } <file_sep>// // MainTabBarCoordinator.swift // Coordinators // // Created by <NAME> on 11/07/2020. // Copyright © 2020 <NAME>. All rights reserved. // import UIKit protocol MainTabBarCoordinatorHandling: AnyObject { func handle(event: MainTabBarCoordinator.Event) } class MainTabBarCoordinator: TabBarControllerCoordinator, ParentCoordinated { enum Event { } weak var parent: MainTabBarCoordinatorHandling? var tabBarController: UITabBarController var childCoordinators: [Coordinator] = [] init(tabBarController: UITabBarController) { self.tabBarController = tabBarController start() } func start() { let chatNavigationController = ChatNavigationController() let chatCoordinator = ChatCoordinator(navigationController: chatNavigationController) chatCoordinator.parent = self childCoordinators.append(chatCoordinator) let orderNavigationController = OrderNavigationController() let orderCoordinator = OrderCoordinator(navigationController: orderNavigationController) orderCoordinator.parent = self childCoordinators.append(orderCoordinator) tabBarController.setViewControllers([ chatNavigationController, orderNavigationController ], animated: true) } } extension MainTabBarCoordinator: ChatCoordinatorHandling { func handle(event: ChatCoordinator.Event) { } } extension MainTabBarCoordinator: OrderCoordinatorHandling { func handle(event: OrderCoordinator.Event) { } } <file_sep>// // LoginViewController.swift // Coordinators // // Created by <NAME> on 11/07/2020. // Copyright © 2020 <NAME>. All rights reserved. // import UIKit protocol LoginViewControllerHandling: AnyObject { func handle(event: LoginViewController.Event) } class LoginViewController: BaseViewController, Coordinated { enum Event { case login } weak var coordinator: LoginViewControllerHandling? override func viewDidLoad() { title = "LOGIN" super.viewDidLoad() let button = UIButton() view.addSubview(button) button.backgroundColor = .systemRed button.layer.cornerRadius = 5 button.setTitle("Login", for: .normal) button.setTitleColor(UIColor.black, for: .normal) button.addTarget(self, action: #selector(didTapLogin), for: .touchUpInside) button.translatesAutoresizingMaskIntoConstraints = false button.widthAnchor.constraint(equalToConstant: 200).isActive = true button.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -80).isActive = true button.centerXAnchor.constraint(equalTo: view.safeAreaLayoutGuide.centerXAnchor).isActive = true } @objc func didTapLogin() { coordinator?.handle(event: .login) } } <file_sep>// // SettingsNavigationController.swift // Coordinators // // Created by <NAME> on 11/07/2020. // Copyright © 2020 <NAME>. All rights reserved. // import UIKit class SettingsNavigationController: UINavigationController { override func viewDidLoad() { super.viewDidLoad() presentationController?.delegate = self } } extension SettingsNavigationController: UIAdaptivePresentationControllerDelegate { func presentationControllerDidDismiss(_ presentationController: UIPresentationController) { viewControllers.compactMap { $0 as? SettingsViewController } .first? .coordinator? .handle(event: .dismiss) } } <file_sep>// // ChatNavigationController.swift // Coordinators // // Created by <NAME> on 11/07/2020. // Copyright © 2020 <NAME>. All rights reserved. // import UIKit class ChatNavigationController: UINavigationController { override func viewDidLoad() { super.viewDidLoad() tabBarItem = UITabBarItem( title: "Chat", image: UIImage(systemName: "message"), selectedImage: UIImage(systemName: "message") ) } } <file_sep>// // ChatCoordinator.swift // Coordinators // // Created by <NAME> on 11/07/2020. // Copyright © 2020 <NAME>. All rights reserved. // import UIKit protocol ChatCoordinatorHandling: AnyObject { func handle(event: ChatCoordinator.Event) } class ChatCoordinator: NavigationControllerCoordinator, ParentCoordinated { enum Event { } weak var parent: ChatCoordinatorHandling? var navigationController: UINavigationController var childCoordinators: [Coordinator] = [] init(navigationController: UINavigationController) { self.navigationController = navigationController start() } func start() { let chatViewController = ChatViewController() chatViewController.coordinator = self navigationController.setViewControllers([ chatViewController ], animated: false) } } extension ChatCoordinator: ChatViewControllerHandling { func handle(event: ChatViewController.Event) { switch event { case .showSettings: let settingsCoordinator = SettingsCoordinator( navigationController: SettingsNavigationController() ) settingsCoordinator.parent = self childCoordinators.append(settingsCoordinator) navigationController.present( settingsCoordinator.navigationController, animated: true ) } } } extension ChatCoordinator: SettingsCoordinatorHandling { func handle(event: SettingsCoordinator.Event) { childCoordinators.removeAll { $0 is SettingsCoordinator } } } <file_sep>// // Coordinator.swift // Coordinators // // Created by <NAME> on 11/07/2020. // Copyright © 2020 <NAME>. All rights reserved. // import UIKit protocol Coordinator: AnyObject { var childCoordinators: [Coordinator] { get set } func start() } protocol ParentCoordinated: AnyObject { associatedtype Parent var parent: Parent? { get set } } protocol Coordinated: AnyObject { associatedtype Coordinator var coordinator: Coordinator? { get set } } protocol TabBarControllerCoordinator: Coordinator { var tabBarController: UITabBarController { get } } protocol NavigationControllerCoordinator: Coordinator { var navigationController: UINavigationController { get } } <file_sep># Coordinators 🚀 The repo contains an example app showcasing coordinator navigation pattern. More info can be found in this [article](https://www.strv.com/blog/how-to-supercharge-coordinators-engineering). ![](https://strv.ghost.io/content/images/2020/06/Coordinator-tree2.png) <file_sep>// // AppCoordinator.swift // Coordinators // // Created by <NAME> on 11/07/2020. // Copyright © 2020 <NAME>. All rights reserved. // import UIKit class AppCoordinator { let window: UIWindow var rootCoordinator: Coordinator? init(window: UIWindow) { self.window = window start() } func start() { let userIsLoggedIn = Bool.random() if userIsLoggedIn { showMainTabBar() } else { showLogin() } window.makeKeyAndVisible() } func showMainTabBar() { let tabBarController = UITabBarController() let mainTabBarCoordinator = MainTabBarCoordinator(tabBarController: tabBarController) mainTabBarCoordinator.parent = self rootCoordinator = mainTabBarCoordinator window.rootViewController = tabBarController } func showLogin() { let navigationController = UINavigationController() let loginCoordinator = LoginCoordinator(navigationController: navigationController) loginCoordinator.parent = self rootCoordinator = loginCoordinator window.rootViewController = navigationController } } extension AppCoordinator: MainTabBarCoordinatorHandling { func handle(event: MainTabBarCoordinator.Event) { } } extension AppCoordinator: LoginCoordinatorHandling { func handle(event: LoginCoordinator.Event) { switch event { case .login: showMainTabBar() } } } <file_sep>// // SettingsCoordinator.swift // Coordinators // // Created by <NAME> on 11/07/2020. // Copyright © 2020 <NAME>. All rights reserved. // import UIKit protocol SettingsCoordinatorHandling: AnyObject { func handle(event: SettingsCoordinator.Event) } class SettingsCoordinator: NavigationControllerCoordinator, ParentCoordinated { enum Event { case dismiss } weak var parent: SettingsCoordinatorHandling? var navigationController: UINavigationController var childCoordinators: [Coordinator] = [] init(navigationController: UINavigationController) { self.navigationController = navigationController start() } func start() { let settingsViewController = SettingsViewController() settingsViewController.coordinator = self navigationController.setViewControllers([ settingsViewController ], animated: false ) } } extension SettingsCoordinator: SettingsViewControllerHandling { func handle(event: SettingsViewController.Event) { parent?.handle(event: .dismiss) } } <file_sep>// // OrderViewController.swift // Coordinators // // Created by <NAME> on 11/07/2020. // Copyright © 2020 <NAME>. All rights reserved. // import UIKit protocol OrderViewControllerHandling: AnyObject { func handle(event: OrderViewController.Event) } class OrderViewController: BaseViewController, Coordinated { enum Event { case detail } weak var coordinator: OrderViewControllerHandling? override func viewDidLoad() { title = "ORDERS" super.viewDidLoad() let button = UIButton() view.addSubview(button) button.backgroundColor = .systemRed button.layer.cornerRadius = 5 button.setTitle("Show detail", for: .normal) button.setTitleColor(UIColor.black, for: .normal) button.addTarget(self, action: #selector(didTapDetail), for: .touchUpInside) button.translatesAutoresizingMaskIntoConstraints = false button.widthAnchor.constraint(equalToConstant: 200).isActive = true button.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -80).isActive = true button.centerXAnchor.constraint(equalTo: view.safeAreaLayoutGuide.centerXAnchor).isActive = true } @objc func didTapDetail() { coordinator?.handle(event: .detail) } } <file_sep>// // LoginCoordinator.swift // Coordinators // // Created by <NAME> on 11/07/2020. // Copyright © 2020 <NAME>. All rights reserved. // import UIKit protocol LoginCoordinatorHandling: AnyObject { func handle(event: LoginCoordinator.Event) } class LoginCoordinator: NavigationControllerCoordinator, ParentCoordinated { enum Event { case login } weak var parent: LoginCoordinatorHandling? var navigationController: UINavigationController var childCoordinators: [Coordinator] = [] init(navigationController: UINavigationController) { self.navigationController = navigationController start() } func start() { let loginViewController = LoginViewController() loginViewController.coordinator = self navigationController.setViewControllers([ loginViewController ], animated: false ) } } extension LoginCoordinator: LoginViewControllerHandling { func handle(event: LoginViewController.Event) { parent?.handle(event: .login) } } <file_sep>// // OrderDetailCoordinator.swift // Coordinators // // Created by <NAME> on 11/07/2020. // Copyright © 2020 <NAME>. All rights reserved. // import UIKit protocol OrderDetailCoordinatorHandling: AnyObject { func handle(event: OrderDetailCoordinator.Event) } class OrderDetailCoordinator: NavigationControllerCoordinator, ParentCoordinated { enum Event { case dismiss } weak var parent: OrderDetailCoordinatorHandling? var navigationController: UINavigationController var childCoordinators: [Coordinator] = [] init(navigationController: UINavigationController) { self.navigationController = navigationController start() } func start() { let isOrderSpecial = Bool.random() if isOrderSpecial { let orderDetailViewController = OrderDetailAViewController() orderDetailViewController.coordinator = self navigationController.pushViewController(orderDetailViewController, animated: true) } else { let orderDetailViewController = OrderDetailBViewController() orderDetailViewController.coordinator = self navigationController.pushViewController(orderDetailViewController, animated: true) } } } extension OrderDetailCoordinator: OrderDetailViewControllerHandling { func handle(event: OrderDetailEvent) { switch event { case .dismiss: parent?.handle(event: .dismiss) } } } <file_sep>// // OrderNavigationController.swift // Coordinators // // Created by <NAME> on 11/07/2020. // Copyright © 2020 <NAME>. All rights reserved. // import UIKit class OrderNavigationController: UINavigationController { override func viewDidLoad() { super.viewDidLoad() tabBarItem = UITabBarItem( title: "Orders", image: UIImage(systemName: "list.bullet"), selectedImage: UIImage(systemName: "list.bullet") ) delegate = self } } extension OrderNavigationController: UINavigationControllerDelegate { func navigationController(_ navigationController: UINavigationController, didShow viewController: UIViewController, animated: Bool) { guard let fromViewController = navigationController.transitionCoordinator?.viewController(forKey: .from), !navigationController.viewControllers.contains(fromViewController) else { return } if let orderDetailViewController = fromViewController as? OrderDetailAViewController { orderDetailViewController.coordinator?.handle(event: .dismiss) } if let orderDetailViewController = fromViewController as? OrderDetailBViewController { orderDetailViewController.coordinator?.handle(event: .dismiss) } } }
76b762d776c54bf1262b9f0fe5f3a21d3c271aec
[ "Swift", "Markdown" ]
18
Swift
arkhigleb/coordinators
65f957109b26e5e9c584df70f9406bcdb5ce8904
794ec2957fd52eb398564b76effff9c3a1129d35
refs/heads/master
<file_sep>namespace Divisas2.ViewModels { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Reflection; using System.Windows.Input; using Divisas2.Models; using Divisas2.Services; using GalaSoft.MvvmLight.Command; using System.Linq; using System.Threading.Tasks; public class MainViewModel : INotifyPropertyChanged { #region Events public event PropertyChangedEventHandler PropertyChanged; #endregion #region Attributes ApiService apiService; DialogService dialogService; DataService dataService; bool isRunning; bool isEnabled; string message; string sourceRate; string targetRate; string status; ExchangeRates exchangeRates; ExchangeNames exchangeNames; List<Rate> rates; #endregion #region Properties public ObservableCollection<Rate> Rates { get; set; } public bool IsRunning { set { if (isRunning != value) { isRunning = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("IsRunning")); } } get { return isRunning; } } public bool IsEnabled { set { if (isEnabled != value) { isEnabled = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("IsEnabled")); } } get { return isEnabled; } } public string Message { set { if (message != value) { message = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Message")); } } get { return message; } } public string Status { set { if (status != value) { status = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Status")); } } get { return status; } } public decimal Amount { get; set; } public string SourceRate { set { if (sourceRate != value) { sourceRate = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("SourceRate")); } } get { return sourceRate; } } public string TargetRate { set { if (targetRate != value) { targetRate = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("TargetRate")); } } get { return targetRate; } } #endregion #region Constructors public MainViewModel() { Status = "Cargando tasas..."; apiService = new ApiService(); dialogService = new DialogService(); dataService = new DataService(); Rates = new ObservableCollection<Rate>(); GetRates(); } #endregion #region Methods async void GetRates() { IsRunning = true; IsEnabled = false; var checkConnetion = await apiService.CheckConnection(); if (checkConnetion.IsSuccess) { await GetRatesFromAPI(); SaveRates(); } else { GetRatesFromData(); Status = "Tasas cargadas localmente."; } var lastQuery = dataService.First<LastQuery>(false); if (lastQuery != null) { SourceRate = lastQuery.CodeRateSource; TargetRate = lastQuery.CodeRateTarget; } IsRunning = false; IsEnabled = true; } void SaveRates() { dataService.DeleteAll<Rate>(); dataService.Save(rates); } void GetRatesFromData() { rates = dataService.Get<Rate>(false); Rates.Clear(); foreach (var rate in rates) { Rates.Add(new Rate { Code = rate.Code, Name = rate.Name, TaxRate = rate.TaxRate, }); } } async Task GetRatesFromAPI() { var response1 = await apiService.Get<ExchangeRates>( "https://openexchangerates.org", "/api/latest.json?app_id=f490efbcd52d48ee98fd62cf33c47b9e"); var response2 = await apiService.Get<ExchangeNames>( "https://gist.githubusercontent.com", "/picodotdev/88512f73b61bc11a2da4/raw/9407514be22a2f1d569e75d6b5a58bd5f0ebbad8"); if (response1.IsSuccess && response2.IsSuccess) { exchangeRates = (ExchangeRates)response1.Result; exchangeNames = (ExchangeNames)response2.Result; LoadRates(); Status = "Tasas cargadas de internet."; } else { Status = "Ocurrio un problema cargando las tasas, por favor intente más tarde."; } } void LoadRates() { // Get values var rateValues = new List<RateValue>(); var type = typeof(Rates); var properties = type.GetRuntimeFields(); foreach (var property in properties) { var code = property.Name.Substring(1, 3); rateValues.Add(new RateValue { Code = code, TaxRate = (double)property.GetValue(exchangeRates.Rates), }); } // Get names var rateNames = new List<RateName>(); type = typeof(ExchangeNames); properties = type.GetRuntimeFields(); foreach (var property in properties) { var code = property.Name.Substring(1, 3); rateNames.Add(new RateName { Code = code, Name = (string)property.GetValue(exchangeNames), }); } // Join the complete list var qry = (from v in rateValues join n in rateNames on v.Code equals n.Code select new { v, n }).ToList(); Rates.Clear(); rates = new List<Rate>(); foreach (var item in qry) { Rates.Add(new Rate { Code = item.v.Code, Name = item.n.Name, TaxRate = item.v.TaxRate, }); rates.Add(new Rate { Code = item.v.Code, Name = item.n.Name, TaxRate = item.v.TaxRate, }); } } #endregion #region Commands public ICommand ChangeCommand { get { return new RelayCommand(Change); } } private void Change() { var aux = SourceRate; SourceRate = TargetRate; TargetRate = aux; ConvertMoney(); } public ICommand ConvertMoneyCommand { get { return new RelayCommand(ConvertMoney); } } private async void ConvertMoney() { if (Amount <= 0) { await App.Current.MainPage.DisplayAlert( "Error", "Debes ingresar un valor a convertir", "Aceptar"); return; } if (string.IsNullOrEmpty(SourceRate)) { await App.Current.MainPage.DisplayAlert( "Error", "Debes seleccionar la moneda origen", "Aceptar"); return; } if (string.IsNullOrEmpty(TargetRate)) { await App.Current.MainPage.DisplayAlert( "Error", "Debes seleccionar la moneda destino", "Aceptar"); return; } decimal amountConverted = Amount / Convert.ToDecimal(SourceRate.Substring(3)) * Convert.ToDecimal(TargetRate.Substring(3)); Message = string.Format("{0} {1:N2} = {2} {3:N2}", SourceRate.Substring(0, 3), Amount, TargetRate.Substring(0, 3), amountConverted); var lastQuery = new LastQuery { CodeRateSource = SourceRate, CodeRateTarget = TargetRate, }; dataService.DeleteAll<LastQuery>(); dataService.Insert(lastQuery); } #endregion } } <file_sep>namespace Divisas2.Models { using SQLite.Net.Attributes; public class Rate { [PrimaryKey, AutoIncrement] public int RateId { get; set; } public string Code { get; set; } public double TaxRate { get; set; } public string Name { get; set; } public string FullName { get { return string.Format("({0}) {1}", Code, Name); } } public string CodeRate { get { return string.Format("{0}{1}", Code, TaxRate); } } public override int GetHashCode() { return RateId; } } }<file_sep>using Android.App; using Divisas2.Interfaces; using Xamarin.Forms; [assembly: Dependency(typeof(Divisas2.Droid.CloseApplication))] namespace Divisas2.Droid { public class CloseApplication : ICloseApplication { public void Close() { var activity = (Activity)Forms.Context; activity.FinishAffinity(); } } }<file_sep>namespace Divisas2.Models { using SQLite.Net.Attributes; public class LastQuery { [PrimaryKey] public int LastQueryId { get; set; } public string CodeRateSource { get; set; } public string CodeRateTarget { get; set; } public override int GetHashCode() { return LastQueryId; } } } <file_sep>namespace Divisas2.Interfaces { public interface ICloseApplication { void Close(); } } <file_sep>namespace Divisas2.Services { using System; using System.Net.Http; using System.Threading.Tasks; using Divisas2.Models; using Newtonsoft.Json; using Plugin.Connectivity; public class ApiService { public async Task<Response> CheckConnection() { if (!CrossConnectivity.Current.IsConnected) { return new Response { IsSuccess = false, Message = "Please turn on your internet settings.", }; } var isReachable = await CrossConnectivity.Current.IsRemoteReachable("google.com"); if (!isReachable) { return new Response { IsSuccess = false, Message = "Check you internet connection.", }; } return new Response { IsSuccess = true, Message = "Ok", }; } public async Task<Response> Get<T>(string urlBase, string url) { try { var client = new HttpClient(); client.BaseAddress = new Uri(urlBase); var response = await client.GetAsync(url); if (!response.IsSuccessStatusCode) { return new Response { IsSuccess = false, Message = response.StatusCode.ToString(), }; } var result = await response.Content.ReadAsStringAsync(); var serialized = JsonConvert.DeserializeObject<T>(result); return new Response { IsSuccess = true, Message = "Ok", Result = serialized, }; } catch (Exception ex) { return new Response { IsSuccess = false, Message = ex.Message, }; } } } } <file_sep>using System.Threading; using Divisas2.Interfaces; using Xamarin.Forms; [assembly: Dependency(typeof(Divisas2.iOS.CloseApplication))] namespace Divisas2.iOS { public class CloseApplication : ICloseApplication { public void Close() { Thread.CurrentThread.Abort(); } } }
da938c95e7d82898f67bf4fc253143aac9d991d4
[ "C#" ]
7
C#
Zulu55/Divisas2
957a43ac0ca2f54362fbfe21c46fef773269a5b9
4f1dcbb8ff8b606a46fb8491d4660cbd9db9316e
refs/heads/master
<repo_name>hplegend/algorithmSolve<file_sep>/src/main/java/hplegend/sort/MainTest.java package hplegend.sort; /** * Created with IntelliJ IDEA. * * @author hp.he * @date 2019/6/14 16:03 */ public class MainTest { }
fd685646562781de4f443582fae2a40b74934df7
[ "Java" ]
1
Java
hplegend/algorithmSolve
03ac30ffbccc4e360faf3d2099d5eeffb22bd5a8
d12b692ffd657e7ce6d7a95b3fddc5bdfe193c85
refs/heads/master
<repo_name>yamaguchi-yumiko/mococon<file_sep>/other.php <?php require_once('header.php'); ?> <?php require_once('nav.php'); ?> <main class="Other-content"> <section class="item-category category"> <h1>Other</h1> <div class="items"> <div class="item-category"> <div class="item-content-moer"> <article class="item-box"> <figure><img src="common/img/IMG_8127.JPG" alt=""></figure> <h3></h3> <p></p> <p>準備中</p> </article> <article class="item-box"> <figure><img src="common/img/IMG_8122.JPG" alt=""></figure> <h3></h3> <p></p> <p>準備中</p> </article> <article class="item-box"> <figure><img src="common/img/IMG_8114.JPG" alt=""></figure> <h3></h3> <p></p> <p>準備中</p> </article> <article class="item-box"> <figure><a href="https://www.instagram.com/p/B6A9efajAbn/" target="_blank"><img src="common/img/IMG_8126.JPG" alt=""></a></figure> <h3>アシメトリーピアス<br>No.10</h3> <p>¥2,500</p> </article> </div> <div class="item-category-items"> <article class="item-box"> <figure><a href="https://www.instagram.com/p/B6A9efajAbn/" target="_blank"><img src="common/img/IMG_8132.JPG" alt=""></a></figure> <h3>アシメトリーピアス<br>No.9</h3> <p>¥2,500</p> </article> <article class="item-box"> <figure><a href="https://www.instagram.com/p/B6A9efajAbn/" target="_blank"><img src="common/img/IMG_8131.JPG" alt=""></a></figure> <h3>アシメトリーピアス<br>No.8</h3> <p>¥2,500</p> </article> <article class="item-box"> <figure><a href="https://www.instagram.com/p/B6A9efajAbn/" target="_blank"><img src="common/img/IMG_8124.JPG" alt=""></a></figure> <h3>アシメトリーピアス<br>No.7</h3> <p>¥2,500</p> </article> <article class="item-box"> <figure><a href="https://www.instagram.com/p/B6A9efajAbn/" target="_blank"><img src="common/img/IMG_8125.JPG" alt=""></a></figure> <h3>アシメトリーピアス<br>No.6</h3> <p>¥2,500</p> </article> </div> <div class="item-category-items"> <article class="item-box"> <figure><a href="https://www.instagram.com/p/B6A9efajAbn/" target="_blank"><img src="common/img/IMG_74362.JPG" alt="アシメトリーピアスNo.1"></a></figure> <h2>アシメトリーピアス<br>No.5</h2> <p>¥2,400</p> </article> <article class="item-box"> <figure><a href="https://www.instagram.com/p/B6A9efajAbn/" target="_blank"><img src="common/img/IMG_74352.JPG" alt="アシメトリーピアスNo.2"></a></figure> <h2>アシメトリーピアス<br>No.4</h2> <p>¥2,400</p> </article> <article class="item-box"> <figure><a href="https://www.instagram.com/p/B6A9efajAbn/" target="_blank"><img src="common/img/IMG_74392.JPG" alt="アシメトリーピアスNo.3"></a></figure> <h2>アシメトリーピアス<br>No.3</h2> <p>¥2,400</p> </article> <article class="item-box"> <figure><a href="https://www.instagram.com/p/B6A9efajAbn/" target="_blank"><img src="common/img/IMG_74402.JPG" alt="アシメトリーピアスNo.4"></a></figure> <h2>アシメトリーピアス<br>No.2</h2> <p>¥2,400</p> </article> </div> <div class="item-category-items"> <article class="item-box"> <figure><a href="https://www.instagram.com/p/B6A9efajAbn/" target="_blank"><img src="common/img/IMG_74412.JPG" alt="アシメトリーピアスNo.5"></a></figure> <h2>アシメトリーピアス<br>No.1</h2> <p>¥2,400</p> </article> <article class="item-box"> <figure><img src="common/img/IMG_7446.JPG" alt="フラミンゴオブジェBig"></figure> <h2>フラミンゴオブジェBig</h2> <p>¥27,000</p> <p>準備中</p> </article> <article class="item-box"> <figure><img src="common/img/IMG_7448.JPG" alt="フラミンゴオブジェ小さい"></figure> <h2>フラミンゴオブジェ</h2> <p>¥2,500</p> <p>準備中</p> </article> <article class="item-box"> <figure><img src="common/img/IMG_7434.JPG" alt="ペンカバー"></figure> <h2>フラミンゴペンカバー</h2> <p>¥2,500</p> <p>準備中</p> </article> </div> </div> </div> </section> </main> <?php require_once('footer.php'); ?> <script src="common/js/jquery.js"></script> <script src="common/slick/slick/slick.min.js"></script> <script> $(window).on('load', function() { $('#loader-bg').hide(); }); $('#accordion').on('click', function() { $('#accordion-content').slideToggle(); }); window.onload = function() { scroll_effect(); $(window).scroll(function() { scroll_effect(); }); function scroll_effect() { $('.fadein').each(function() { var elemPos = $(this).offset().top; var scroll = $(window).scrollTop(); var windowHeight = $(window).height(); if (scroll > elemPos - windowHeight) { $(this).addClass('scrollin'); } }); } }; </script> </body> </html><file_sep>/news.php <?php require_once('header.php'); ?> <?php require_once('nav.php'); ?> <main class="tie-content news-top"> <section class="item-category"> <h1>News</h1> <div class="news-archives"> <div class="tim-container"> <p>2020/1/23/~1/29</p> <p>東急たまプラーザ4F 「TeyneyFelt POP UP SHOP!」</p> <p>2019/12/3~12/8</p> <p>Exhibition 「Needle felting 羊毛フェルト作品展Vol.16」at Gallery Le Déco in Shibuya</p> <p>2019/11/17</p> <p> Design Festa vol.50</p> <p>2019/8/1~8/31</p> <p> [Copkun,]Artist-in-Residence「Cokun,Artist Village2019」</p> <p>2019/5/19</p> <p> Design Festa vol.49</p> <p>2019/2/10</p> <p> 【ワークショップ】羊毛フェルトで作るネコのストラップ</p> <p>2019/1/02~1/3</p> <p> 【ワークショップ】羊毛フェルトで作るウリボー</p> <p>2018/11/11 </p> <p>【イベント】デザインフェスタvol.48 出展</p> <p>2018/10/21 </p> <p>【ワークショップ】羊毛フェルトのかわいいキーホルダー作り@横浜市中スポーツセンター</p> <p>2018/7/21~8/17</p> <p> 【イベント】[Cokun,]Artist-in-Residence「Cokun,Artist Village2018</p> <p>2018/4/7</p> <p> 高円寺「ストロベリースーパーソニック」さん販売開始</p> <p>2017/11/13 </p> <p>【ワークショップ】羊毛フェルトのクリスマスツリー</p> <p>2017/11/12 </p> <p>【マーケット】Handmade MAKERS'2017</p> <p>2017/11/11</p> <p> 【ワークショップ】羊毛フェルトのリース</p> <p>2017/7/21~8/31</p> <p> 【イベント】[Cokun,]Artist-in-Residence「Cokun,Artist Village」企画・開催</p> <p>2017/6/24~30 </p> <p>【Exhibision】[Cokun,]「。展」@artmania</p> <p>2017/6/3~6/4</p> <p> 【イベント】[Cokun,]チャサンポーvol.9出店VIVACE前</p> <p>2017/5/27~5/28</p> <p> 【イベント】[Cokun,]DESIGN FESTA vol.45 出展</p> <p>2017/3/18~3/20</p> <p> 【イベント】ワークショップ 「世界の動物作り」@羽田フェア2017</p> <p>2016/12/10 </p> <p>【マーケット】[Cokun,]アート手作りFESTA@東京国際フォーラム</p> <p>2016/11/20 </p> <p>【マーケット】[Cokun,]青空個展@NeWoMan新宿</p> <p>2016/9/3 </p> <p>【マーケット】[Cokun,]青空個展出店@池袋</p> <p>2016/8/21 </p> <p>【マーケット】[Cokun,]朝市出店@西荻(NABEKAORUさんのみのお店番。)</p> <p>2016/6/4~6/5</p> <p> 【イベント】[Cokun,]茶サンポー参加、西荻窪「VIVACE」内出店</p> <p>2016/3/27</p> <p> [Cokun,]スタート、ぺインターNABEKAORUとの新しいブランド</p> <p>2015/11/5~11/18</p> <p> 【Exhibition】NABEKAORU and mococon Group Exhibision at FINDARS</p> <p>2015/6/6 </p> <p>【イベント】茶サンポー参加、西荻窪「VIVACE」内出店</p> <p>2014/11/16</p> <p>【マーケット】手創り市 雑司ヶ谷出店</p> <p>2014/9/28 </p> <p>【イベント】「Kawagoe Knit Park」staff</p> <p>2014/6/7 </p> <p>【マーケット】イベント1日限定販売@VIVACE</p> <p>2014/5/6</p> <p>【イベント】手作りマーケット@八王子</p> <p>2014/5/3</p> <p> 【イベント】出張講師@北上尾</p> <p>2014/4/27 </p> <p>【イベント】asマテリアル企画。手作りマーケット@横浜</p> <p>2014/3/23 </p> <p>【マーケット】手創り市 雑司ヶ谷出店</p> <p>2014/1/13</p> <p> 【イベント】once-in企画。出張講師@北赤羽</p> <p>2013/12/1 </p> <p>【イベント】once-in企画。出張講師@北上尾</p> <p>2013/8/1</p> <p> 「Usagiparis」販売START</p> <p>2012/11/9</p> <p> デザイン修行のため1年間渡仏。</p> <p>2012/11/7</p> <p> イタリア料理[LIBRARY]販売START</p> <p>2012/10/27 </p> <p>【イベント】三鷹上々堂「にじまくら」出店</p> <p>2012/10/15 </p> <p>【イベント】asマテリアル コラボレーションワークショップ</p> <p>2012/9/30</p> <p> 【イベント】西荻窪VIVACE「もちよりおつきさま」ワークショップ</p> <p>2012/9/9</p> <p> 【イベント】once-in企画。出張講師@駒沢</p> <p>2012/8/29</p> <p> mococon Online shop START</p> <p>2012/8/4 </p> <p>【イベント】西荻窪VIVACE「いえよみ」出店</p> <p>2012/7/28</p> <p> 【イベント】once-in企画。「Cafecul」ワークショップ@恵比寿</p> <p>2012/6/2 </p> <p>【イベント】茶サンポー参加、西荻窪「VIVACE」内出店</p> <p>2012/5/20 </p> <p>【イベント】once-in企画。出張講師@豊洲</p> <p>2012/5/6</p> <p> 【イベント】once-in企画。出張講師@熊谷</p> <p>2012/4/21</p> <p> 西荻窪カイロプラクティック「VIVACE」販売START</p> <p>2012/3/25 </p> <p>【イベント】Ranahaコラボレーションワークショップ</p> <p>2012/3/10 </p> <p>【マーケット】モノツクルクル市vol.4出店</p> <p>2012/2/26 </p> <p>【イベント】Ranahaコラボレーションワークショップ</p> <p>2012/1/8 </p> <p>【イベント】Ranahaコラボレーションワークショップ</p> <p>2011/11/11</p> <p> 渋谷「月箱」販売START</p> <p>2010/12/2 </p> <p>「Head spa and Relaxation private salon Ranaha」販売START</p> </div> </div> </section> </main> <?php require_once('footer.php'); ?> <script src="common/js/jquery.js"></script> <script src="common/slick/slick/slick.min.js"></script> <script> $(window).on('load', function() { $('#loader-bg').hide(); }); $('#accordion').on('click', function() { $('#accordion-content').slideToggle(); }); window.onload = function() { scroll_effect(); $(window).scroll(function() { scroll_effect(); }); function scroll_effect() { $('.fadein').each(function() { var elemPos = $(this).offset().top; var scroll = $(window).scrollTop(); var windowHeight = $(window).height(); if (scroll > elemPos - windowHeight) { $(this).addClass('scrollin'); } }); } }; </script> </body> </html><file_sep>/index.php <?php require_once('header.php'); ?> <?php require_once('nav.php'); ?> <main class="home home-top"> <section class="top"> <h1>Wool&nbsp;Natural&nbsp;Cool&Cute</h1> <p>かわいいだけじゃないシックな雑貨をハンドメイドする<br>羊毛フィルトハンドメイド専門店[mococon]</p> </section> <section class="item-category fadein"> <h2>Category</h2> <div class="item-category-top"> <article class="item-box "> <figure><a href="original-mascot.php" target="_blank"><img src="common/img/DrflGoRV4AIeoRz.jpeg" alt="オリジナルマスコット"></a></figure> <h3>Original mascot</h3> </article> <article class="item-box " target="_blank"> <figure><a href="tie.php" target="_blank"><img src="common/img/Tie1.jpg" alt="ネクタイ"></a></figure> <h3t>tie</h3t> </article> <article class="item-box " target="_blank"> <figure><a href="bag.php" target="_blank"><img src="common/img/IMG_74442-1.JPG" alt="バック"></a></figure> <h3>Bag</h3> </article> <article class="item-box "> <figure><a href="other.php" target="_blank"><img src="common/img/403904_o.jpg" alt="その他"></a></figure> <h3>Other</h3> </article> </div> </section> <section class="pickup fadein"> <h2>Pickup</h2> <div> <ul class="slider"> <li><img src="common/img/IMG_8133.JPG" alt="ピックアップ商品"></li> <li><img src="common/img/IMG_8120.JPG" alt="ピックアップ商品"></li> <li><img src="common/img/IMG_8129.JPG" alt="ピックアップ商品"></li> <li><img src="common/img/IMG_8114.JPG" alt="ピックアップ商品"></li> <li><img src="common/img/IMG_8134.JPG" alt="ピックアップ商品"></li> <li><img src="common/img/IMG_8115.JPG" alt="ピックアップ商品"></li> </ul> </div> </section> <section class="about-wrapper fadein"> <h2>About</h2> <div class="about-brand"> <div class="about-top"> <img src="common/img/top_tree.gif" alt="モコのツリー画像"> <div class="about-history"> <div> <p>what is mococon?</p> <p> mococon(モココン)とは<br> 指の形から生まれた不思議生物<br>オリジナルマスコット!</p> <p>羊毛フィルトの特徴を活かしてほわほわ感のある可愛いらしいモココン♡</p> <p>他にも、羊毛フィルトを使ったアクセサリー<br>雑貨などの作品もございます!</p> <a href="about.php" class="button" target="_blank"><span>VIEW MORE</span></a> </div> </div> </div> </div> </section> <section class="items fadein"> <h2>Items</h2> <div class="item-category"> <!-- 1つ目 --> <div class="item-content-moer"> <article class="item-box"> <figure><img src="common/img/IMG_8127.JPG" alt=""></figure> <h3></h3> <p></p> <p>準備中</p> </article> <article class="item-box"> <figure><img src="common/img/IMG_8122.JPG" alt=""></figure> <h3></h3> <p></p> <p>準備中</p> </article> <article class="item-box"> <figure><img src="common/img/IMG_8114.JPG" alt=""></figure> <h3></h3> <p></p> <p>準備中</p> </article> <article class="item-box"> <figure><a href="https://www.instagram.com/p/B6A9efajAbn/" target="_blank"><img src="common/img/IMG_8126.JPG" alt=""></a></figure> <h3>アシメトリーピアス<br>No.10</h3> <p>¥2,500</p> </article> </div> <!-- 2つ目 --> <div class="item-category-items"> <article class="item-box"> <figure><a href="https://www.instagram.com/p/B6A9efajAbn/" target="_blank"><img src="common/img/IMG_8132.JPG" alt=""></a></figure> <h3>アシメトリーピアス<br>No.9</h3> <p>¥2,500</p> </article> <article class="item-box"> <figure><a href="https://www.instagram.com/p/B6A9efajAbn/" target="_blank"><img src="common/img/IMG_8131.JPG" alt=""></a></figure> <h3>アシメトリーピアス<br>No.8</h3> <p>¥2,500</p> </article> <article class="item-box"> <figure><a href="https://www.instagram.com/p/B6A9efajAbn/" target="_blank"><img src="common/img/IMG_8124.JPG" alt=""></a></figure> <h3>アシメトリーピアス<br>No.7</h3> <p>¥2,500</p> </article> <article class="item-box"> <figure><a href="https://www.instagram.com/p/B6A9efajAbn/" target="_blank"><img src="common/img/IMG_8125.JPG" alt=""></a></figure> <h3>アシメトリーピアス<br>No.6</h3> <p>¥2,500</p> </article> </div> <!-- 3つ目 --> <div class="item-content-moer"> <article class="item-box"> <figure><a href="https://www.instagram.com/p/B6A9efajAbn/" target="_blank"><img src="common/img/IMG_74362.JPG" alt="アシメトリーピアスNo.1"></a></figure> <h3>アシメトリーピアス<br>No.5</h3> <p>¥2,500</p> </article> <article class="item-box"> <figure><a href="https://www.instagram.com/p/B6A9efajAbn/" target="_blank"><img src="common/img/IMG_74352.JPG" alt="アシメトリーピアスNo.2"></a></figure> <h3>アシメトリーピアス<br>No.4</h3> <p>¥2,500</p> </article> <article class="item-box"> <figure><a href="https://www.instagram.com/p/B6A9efajAbn/" target="_blank"><img src="common/img/IMG_74392.JPG" alt="アシメトリーピアスNo.3"></a></figure> <h3>アシメトリーピアス<br>No.3</h3> <p>¥2,500</p> </article> <article class="item-box"> <figure><a href="https://www.instagram.com/p/B6A9efajAbn/" target="_blank"><img src="common/img/IMG_74402.JPG" alt="アシメトリーピアスNo.4"></a></figure> <h3>アシメトリーピアス<br>No.2</h3> <p>¥2,500</p> </article> </div> <!-- 4つ目 --> <div class="item-content-moer"> <article class="item-box"> <figure><a href="https://www.instagram.com/p/B6A9efajAbn/" target="_blank"><img src="common/img/IMG_74412.JPG" alt="アシメトリーピアスNo.5"></a></figure> <h3>アシメトリーピアス<br>No.1</h3> <p>¥2,500</p> </article> <article class="item-box"> <figure><a href="https://www.creema.jp/item/7455365/detail" target="_blank"><img src="common/img/2_n.jpg" alt="ピンバチ"></a></figure> <h3>mocoのピンバッチ</h3> <p>¥900</p> </article> <article class="item-box"> <figure><a href="https://www.creema.jp/item/7470867/detail" target="_blank"><img src="common/img/1_n.jpg" alt="ピンバッチ"></a></figure> <h3>gooのピンバッチ</h3> <p>¥900</p> </article> <article class="item-box"> <figure><img src="common/img/IMG_7448.JPG" alt="フラミンゴオブジェ小さい"></figure> <h3>フラミンゴオブジェ</h3> <p>¥2,500</p> <p>準備中</p> </article> </div> <div class="item-content-moer"> <article class="item-box"> <figure><img src="common/img/IMG_7434.JPG" alt="ペンカバー"></figure> <h3>フラミンゴペンカバー</h3> <p>¥2,500</p> <p>準備中</p> </article> <article class="item-box"> <figure><img src="common/img/IMG_7446.JPG" alt="フラミンゴオブジェBig"></figure> <h3>フラミンゴオブジェBig</h3> <p>¥27,000</p> <p>準備中</p> </article> <article class="item-box"> <figure><img src="common/img/IMG_74442.JPG" alt="バックNo.1"></figure> <h3>バックNo.1</h3> <p>¥4,900</p> <p>準備中</p> </article> <article class="item-box"> <figure><img src="common/img/IMG_74452.JPG" alt="バック"></figure> <h3>バックNo.2</h3> <p>¥4,900</p> <p>準備中</p> </article> </div> <!-- <div class="grad-wrap "> <span id="grad-trigger">VIEW MORE</span> <div class="grad-item"> <div class="item-category box"> <div class="item-content-moer"> </div> </div> </div> </div> --> </div> </section> <section class="news fadein"> <h2>News</h2> <div class="news-wrap"> <p>★2020/10/19〜11/1★</p> <p>eyneyfeltプチ作品展at学芸大学に参加します!</p> <p>11/8<br>Design festa vol.52 ブースno.I-208 </p> <P>11/5〜11/11<br>「TeyneyFelt POP-UP SHOP!」at HINKA RINKA in Tokyu plaza Ginza</P> <a href="news.php" target="_blank"><img src="common/img/ELkWlCpUcAAwGnB.jpeg" alt="ポップアップショップ画像"></a> <div class="arrow-content"><a href="news.php" class="arrow" target="_blank">more</a></div> </div> </section> <section class="contact fadein"> <h2>Contact</h2> <div class="contact-content"> <div class="contact-img"> <img src="common/img/contact.jpg" alt="モコの画像"> <div class="contact-button"> <p>オーダーメイドも承ります♡</p> <span class="button1"><a href="http://ws.formzu.net/fgen/S82910306" target="_blank">お問い合わせ</a></span> </div> </div> </div> </section> </main> <?php require_once('footer.php'); ?> <script src="common/js/jquery.js"></script> <script src="common/slick/slick/slick.min.js"></script> <script> //ピックアップのスライダー $('.slider').slick({ centerMode: true, centerPadding: '60px', slidesToShow: 1, autoplay: true, autoplaySpeed: 2000, responsive: [{ breakpoint: 768, settings: { centerMode: true, centerPadding: '40px', slidesToShow: 1 } }, { breakpoint: 480, settings: { centerMode: true, centerPadding: '30px', slidesToShow: 1 } } ] }); //ふわっと出るアニメーション $(window).on('load', function() { $('#loader-bg').hide(); }); $('#accordion').on('click', function() { $('#accordion-content').slideToggle(); }); window.onload = function() { scroll_effect(); $(window).scroll(function() { scroll_effect(); }); function scroll_effect() { $('.fadein').each(function() { var elemPos = $(this).offset().top; var scroll = $(window).scrollTop(); var windowHeight = $(window).height(); if (scroll > elemPos - windowHeight) { $(this).addClass('scrollin'); } }); } }; //アイテムビュー // var itemHeights = []; // $(function() { // $(".grad-item").each(function() { //ターゲット(縮めるアイテム) // var thisHeight = $(this).height(); //ターゲットの高さを取得 // itemHeights.push(thisHeight); //それぞれの高さを配列に入れる // $(this).addClass("is-hide"); //CSSで指定した高さにする // }); // }); // $("#grad-trigger").click(function() { // var index = $(this).index("#grad-trigger"); //トリガーが何個目か // var addHeight = itemHeights[index]; //個数に対応する高さを取得 // $(this).fadeOut().addClass("is-show").next().animate({ // height: addHeight // }, 200).removeClass("is-hide"); //高さを元に戻す // }); </script> </body> </html><file_sep>/footer.php <footer class="footer"> <div class="nsn-icon"> <ul> <li><a href="https://www.facebook.com/mayu.anzai" target="_blank"><img src="common/img/facebook2.svg" alt="anzaimayuのfacebook"></a></li> <li><a href="https://www.instagram.com/mococon_/?hl=ja" target="_blank"><img src="common/img/insta2.svg" alt="anzaimayuのInstagram"></a></li> <li><a href="https://twitter.com/mococon_" target="_blank"><img src="common/img/Twitter2.svg" alt="anzaimayuのTwitter"></a></li> </ul> </div> <p>&copy;2020&nbsp;mococon&nbsp;All&nbsp;Rights&nbsp;Reserved. </p> </footer> <div id="loader-bg"> <img src="common/img/loadinfo.net.gif" alt="ロード中"> </div><file_sep>/original-mascot.php <?php require_once('header.php'); ?> <?php require_once('nav.php'); ?> <main class="Original-Mascot-content category"> <section class="item-category"> <h1>Original Mascot</h1> <div class="items"> <div class="item-category"> <div class="item-category-items"> <article class="item-box "> <figure><a href="https://www.creema.jp/item/7455365/detail" target="_blank"><img src="common/img/2_n.jpg" alt="mocoのピンバッチ"></a></figure> <h2>mocoのピンバッチ</h2> <p>¥900</p> </article> <article class="item-box "> <figure><a href="https://www.creema.jp/item/7455365/detail" target="_blank"><img src="common/img/1_n.jpg" alt="ピンバッチ"></a></figure> <h2>gooのピンバッチ</h2> <p>¥900</p> </article> </div> </div> </div> </section> </main> <?php require_once('footer.php'); ?> <script src="common/js/jquery.js"></script> <script src="common/slick/slick/slick.min.js"></script> <script> $(window).on('load', function() { $('#loader-bg').hide(); }); $('#accordion').on('click', function() { $('#accordion-content').slideToggle(); }); window.onload = function() { scroll_effect(); $(window).scroll(function() { scroll_effect(); }); function scroll_effect() { $('.fadein').each(function() { var elemPos = $(this).offset().top; var scroll = $(window).scrollTop(); var windowHeight = $(window).height(); if (scroll > elemPos - windowHeight) { $(this).addClass('scrollin'); } }); } }; </script> </body> </html><file_sep>/common/scss/base/_variable.scss //変数 出力 $color-foundation 文字列#{} // color 明るいlighten($color-foundation,30%) 暗いdarken $color-text: #fff; $color-gray:#BDBDBD; $color-bule:rgb(18,53,98); $color-red:#E81919; $color: #333333; $color-lightgray:#EFEFEF; $color-light:#5f5f5f; $color-light2:#707070; <file_sep>/common/scss/content/_category.scss /* ============================================================== * categoryレイアウト * ============================================================ */ .tie-content,.Original-Mascot-content,.Other-content,.Bag-content,.news-content{ margin-top:60px; margin-bottom: 60px; text-align: center; .items{ margin-top: 100px; } } <file_sep>/gallery.php <?php require_once('header.php'); ?> <?php require_once('nav.php'); ?> <main class="gallery-content gallery"> <section class="gallery-section"> <div class="gallery-container"> <h1>Gallery</h1> <div class="slider-wrapper"> <h2><span></span>Work</h2> <ul class="slider frist"> <li><a href="#"> <img src="common/img2/20120716_11.08.25.jpg" alt="過去作品"></a></li> <li><a href="#"> <img src="common/img2/20120716_10.52.00.jpg" alt="過去作品"></a></li> <li><a href="#"> <img src="common/img2/20120716_10.59.13.jpg" alt="過去作品"></a></li> <li><a href="#"> <img src="common/img2/20120716_15.32.57.jpg" alt="過去作品"></a></li> <li><a href="#"> <img src="common/img2/20120716_15.29.24.jpg" alt="過去作品"></a></li> <li><a href="#"> <img src="common/img2/20120716_15.22.06.jpg" alt="過去作品"></a></li> <li><a href="#"> <img src="common/img2/20120716_15.36.15.jpg" alt="過去作品"></a></li> <li><a href="#"> <img src="common/img2/20120716_15.01.42.jpg" alt="過去作品"></a></li> <li><a href="#"> <img src="common/img2/20120716_15.03.22.jpg" alt="過去作品"></a></li> <li><a href="#"> <img src="common/img2/20120414_12.55.30.jpg" alt="過去作品"></a></li> <li><a href="#"> <img src="common/img2/20120921_16.43.04.jpg" alt="過去作品"></a></li> <li><a href="#"> <img src="common/img2/20120921_16.49.51.jpg" alt="過去作品"></a></li> <li><a href="#"> <img src="common/img2/20120804_11.44.41.jpg" alt="過去作品"></a></li> <li><a href="#"> <img src="common/img2/20120804_11.54.35.jpg" alt="過去作品"></a></li> <li><a href="#"> <img src="common/img2/20120804_11.58.14.jpg" alt="過去作品"></a></li> <li><a href="#"> <img src="common/img2/20120804_11.59.06.jpg" alt="過去作品"></a></li> <li><a href="#"> <img src="common/img2/20120804_11.57.44.jpg" alt="過去作品"></a></li> <li><a href="#"> <img src="common/img2/20120804_11.59.25.jpg" alt="過去作品"></a></li> <li><a href="#"> <img src="common/img2/20120614_14.26.51.jpg" alt="過去作品"></a></li> <li><a href="#"> <img src="common/img2/20121027_14.52.23.jpg" alt="過去作品"></a></li> <li><a href="#"> <img src="common/img2/20120519_10.22.14.jpg" alt="過去作品"></a></li> <li><a href="#"> <img src="common/img2/20121025_21.25.15.jpg" alt="過去作品"></a></li> <li><a href="#"> <img src="common/img2/20121101_10.20.00.jpg" alt="過去作品"></a></li> <li><a href="#"> <img src="common/img2/20120921_10.51.30.jpg" alt="過去作品"></a></li> <li><a href="#"> <img src="common/img2/20120921_10.55.25.jpg" alt="過去作品"></a></li> <li><a href="#"> <img src="common/img2/20120526_16.50.26.jpg" alt="過去作品"></a></li> <li><a href="#"> <img src="common/img2/20120320_10.32.31.jpg" alt="過去作品"></a></li> <li><a href="#"> <img src="common/img2/20120318_13.17.06.jpg" alt="過去作品"></a></li> <li><a href="#"> <img src="common/img2/20120519_17.01.56.jpg" alt="過去作品"></a></li> <li><a href="#"> <img src="common/img2/20120519_17.03.05.jpg" alt="過去作品"></a></li> <li><a href="#"> <img src="common/img2/20120716_11.11.06.jpg" alt="過去作品"></a></li> </ul> <p>旧作品のギャラリー<br>オンラインショップも行なっていますが<br>オーダーメイドも承っておりますので<br>是非お問い合わせください!</p> <ul class="slider tow"> <li><a href="#"> <img src="common/img1/20111027_15.19.24.jpg" alt="過去作品"></a></li> <li><a href="#"> <img src="common/img1/20110608_15.34.45.jpg" alt="過去作品"></a></li> <li><a href="#"> <img src="common/img1/20111006_14.00.41.jpg" alt="過去作品"></a></li> <li><a href="#"> <img src="common/img1/20111111_12.33.28.jpg" alt="過去作品"></a></li> <li><a href="#"> <img src="common/img1/20111027_15.27.23.jpg" alt="過去作品"></a></li> <li><a href="#"> <img src="common/img1/20111027_15.27.09.jpg" alt="過去作品"></a></li> <li><a href="#"> <img src="common/img1/20110625_15.45.29.jpg" alt="過去作品"></a></li> <li><a href="#"> <img src="common/img1/20110618_12.36.23.jpg" alt="過去作品"></a></li> <li><a href="#"> <img src="common/img1/20111027_15.12.12.jpg" alt="過去作品"></a></li> <li><a href="#"> <img src="common/img1/20111006_14.46.45.jpg" alt="過去作品"></a></li> <li><a href="#"> <img src="common/img1/20111006_13.57.19.jpg" alt="過去作品"></a></li> <li><a href="#"> <img src="common/img1/20111006_13.58.09.jpg" alt="過去作品"></a></li> <li><a href="#"> <img src="common/img1/20111026_13.27.21.jpg" alt="過去作品"></a></li> <li><a href="#"> <img src="common/img1/20110606_17.50.33.jpg" alt="過去作品"></a></li> <li><a href="#"> <img src="common/img1/20110715_12.24.55.jpg" alt="過去作品"></a></li> <li><a href="#"> <img src="common/img1/20110606_17.24.23.jpg" alt="過去作品"></a></li> <li><a href="#"> <img src="common/img1/20111111_12.28.01.jpg" alt="過去作品"></a></li> <li><a href="#"> <img src="common/img1/20111006_14.05.03.jpg" alt="過去作品"></a></li> <li><a href="#"> <img src="common/img1/20110713_13.16.42.jpg" alt="過去作品"></a></li> <li><a href="#"> <img src="common/img1/20110530_19.24.50.jpg" alt="過去作品"></a></li> <li><a href="#"> <img src="common/img1/20111006_14.02.30.jpg" alt="過去作品"></a></li> <li><a href="#"> <img src="common/img1/20111006_14.05.38.jpg" alt="過去作品"></a></li> <li><a href="#"> <img src="common/img1/20111220_12.48.39.jpg" alt="過去作品"></a></li> <li><a href="#"> <img src="common/img1/20111220_12.47.49.jpg" alt="過去作品"></a></li> <li><a href="#"> <img src="common/img1/20111027_15.22.33.jpg" alt="過去作品"></a></li> <li><a href="#"> <img src="common/img1/20111027_15.24.44.jpg" alt="過去作品"></a></li> <li><a href="#"> <img src="common/img1/20110822_12.05.52.jpg" alt="過去作品"></a></li> <li><a href="#"> <img src="common/img1/20111225_14.06.23.jpg" alt="過去作品"></a></li> <li><a href="#"> <img src="common/img1/20111219_12.35.18.jpg" alt="過去作品"></a></li> <li><a href="#"> <img src="common/img1/20111225_14.05.04.jpg" alt="過去作品"></a></li> <li><a href="#"> <img src="common/img1/20111209_10.11.00.jpg" alt="過去作品"></a></li> <li><a href="#"> <img src="common/img1/o0480064011254529683.jpg" alt="過去作品"></a></li> <li><a href="#"> <img src="common/img1/20111130_22.28.38.jpg" alt="過去作品"></a></li> <li><a href="#"> <img src="common/img1/20110614_13.53.55.jpg" alt="過去作品"></a></li> </ul> <div class="line-stamp fadein"> <h2><span></span>mococon <br>LINE&nbsp;Stmp!</h2> <p>ついに登場!指の形から生まれた不思議生物モココン。<br> その仲間は9種類とも言われている!<br>まずまず使えるスタンダードなものを揃えましたのでどうぞよろしくお願いします!</p> <div class="line-stamp-container"> <div class="line-stamp-top"> <div class="line-stamp-content"> <div> <img src="common/img/sticker.png" alt="ピースのかたちの2本足、モコです"> </div> <div class="line-stamp-comtet"> <p>ピースのかたちの2本足のモコ</p> <p class="button"><a href="https://line.me/S/sticker/5132942?lang=ja&ref=lsh_stickerDetail" target="_blank">LINEスタンプはコチラ</a></p> </div> </div> </div> <div class="line-stamp-top"> <div class="line-stamp-content"> <div> <img src="common/img/sticker(1).png" alt="大きくひろがる、5本指のボコ"> </div> <div class="line-stamp-comtet"> <p>大きくひろがる5本指のボコ</p> <p class="button"><a href="https://line.me/S/sticker/9888911?lang=ja&ref=lsh_stickerDetail" target="_blank">LINEスタンプはコチラ</a></p> </div> </div> </div> </div> </div> </div> </div> </section> </main> <?php require_once('footer.php'); ?> <script src="common/js/jquery.js"></script> <script src="common/js/index.js"></script> <script src="common/slick/slick/slick.min.js"></script> <script> $('.frist,.tow').slick({ centerMode: true, centerPadding: '60px', slidesToShow: 1, autoplay: true, autoplaySpeed: 4000, responsive: [{ breakpoint: 768, settings: { centerMode: true, centerPadding: '40px', slidesToShow: 1 } }, { breakpoint: 480, settings: { centerMode: true, centerPadding: '30px', slidesToShow: 1 } } ] }); $(window).on('load', function() { $('#loader-bg').hide(); }); $('#accordion').on('click', function() { $('#accordion-content').slideToggle(); }); window.onload = function() { scroll_effect(); $(window).scroll(function() { scroll_effect(); }); function scroll_effect() { $('.fadein').each(function() { var elemPos = $(this).offset().top; var scroll = $(window).scrollTop(); var windowHeight = $(window).height(); if (scroll > elemPos - windowHeight) { $(this).addClass('scrollin'); } }); } }; </script> </body> </html><file_sep>/common/css/layout/_tablet.css @media (min-width: 600px) { body { background: pink; } } @media (min-width: 380px) { body { background: red; } } /* .body img{ @include tab { width:550%; height:auto; } @include pc{ width:350px; height:auto; } } */ <file_sep>/common/scss/layout/_footer.scss /* ============================================================== * ヘッター レイアウト * ============================================================ */ .footer { margin-top: 100px; padding: 50px 0; text-align: center; p { margin-top: 40px; } } .nsn-icon { ul { display: flex; justify-content: center; } li { list-style-type: none; transition: 0.3s ease 0s; width: 100%; &:hover { opacity: 0.7; } } img { width: 25%; height: auto; } } #loader-bg { background: #fff; height: 100%; width: 100%; position: fixed; top: 0; left: 0; z-index: 10; } #loader-bg img { background: #fff; position: fixed; top: 50%; left: 50%; -webkit-transform: translate(-50%, -50%); -ms-transform: translate(-50%, -50%); transform: translate(-50%, -50%); z-index: 10; } <file_sep>/bag.php <?php require_once('header.php'); ?> <?php require_once('nav.php'); ?> <main class="Bag-content category"> <section class="item-category"> <h1>Bag</h1> <div class="items"> <div class="item-category"> <div class="item-category-items"> <article class="item-box "> <figure><img src="common/img/IMG_74452.JPG" alt="バックNo.1"></figure> <h2>バックNo.1</h2> <p>¥4,900</p> <p>準備中</p> </article> <article class="item-box "> <figure><img src="common/img/IMG_74442.JPG" alt="バックNo.2"></figure> <h2>バックNo.2</h2> <p>¥4,900</p> <p>準備中</p> </article> </div> </div> </div> </section> </main> <?php require_once('footer.php'); ?> <script src="common/js/jquery.js"></script> <script src="common/slick/slick/slick.min.js"></script> <script> window.onload = function() { scroll_effect(); $(window).scroll(function() { scroll_effect(); }); function scroll_effect() { $('.fadein').each(function() { var elemPos = $(this).offset().top; var scroll = $(window).scrollTop(); var windowHeight = $(window).height(); if (scroll > elemPos - windowHeight) { $(this).addClass('scrollin'); } }); } }; $(window).on('load', function() { $('#loader-bg').hide(); }); $('#accordion').on('click', function() { $('#accordion-content').slideToggle(); }); </script> </body> </html><file_sep>/header.php <!DOCTYPE html> <html lang="ja"> <head> <meta charset="UTF-8"> <title>羊毛フェルトハンドメイド雑貨[mococon]</title> <meta name="viewport" content="width=device-width,initial-scale=1"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="format-detection" content="telephone=no"> <meta name="google-site-verification" content="qJLTzCAQfE75imtPHwSA6XkP9qoCnXwE_gPrFGo7ERw" /> <meta name="description" content="羊毛フェルト、ハンドメイド雑貨[mococon]。羊毛フェルトを中心にナチュラル素材のアイテム作りをめざしています。作品紹介ページ、オンラインショップ。オリジナルキャラクター[moco]の紹介など。"> <meta name="keywords" content="羊毛フェルト,ハンドメイドアクセサリー,オリジナルキャラクター,ナチュラル,自然,編み物,ニット,ニードルフェルト,anzaimayu,mococon"> <link rel="icon" href="common/img/whattree.gif" sizes="16x16" type="image/png"> <link rel="stylesheet" href="common/css/style.css"> <link rel="stylesheet" type="text/css" href="common/slick/slick/slick.css" /> <link rel="stylesheet" type="text/css" href="common/slick/slick/slick-theme.css" /> <link href="https://fonts.googleapis.com/css?family=Noto+Sans+JP&display=swap" rel="stylesheet"> <!-- Global site tag (gtag.js) - Google Analytics --> <script async src="https://www.googletagmanager.com/gtag/js?id=UA-156667023-1"></script> </head> <body class="fadein home"> <header class="header"> <div class="header-coment"> <p>羊毛フィルトハンドメイド専門店[mococon]</p> </div> <p><a href="index.php"><img src="common/img/mococon_rogo.gif" alt="mococon"></a></p> </header><file_sep>/common/css/content/_category.css @charset "UTF-8"; /* ============================================================== * categoryレイアウト * ============================================================ */ .tie-content, .Original-Mascot-content, .Other-content, .Bag-content, .news-content { margin-top: 160px; text-align: center; } <file_sep>/about.php <?php require_once('header.php'); ?> <?php require_once('nav.php'); ?> <main class="about-content about"> <div class="about-section"> <h1>About</h1> <article class="about-concept"> <h2><span></span>Wool,Natural<br>Cool&Cute</h2> <div class="about-top-img"></div> <p>かわいいだけじゃない シックな羊毛フェルト雑貨をコンセプトに。<br></p> <p>シックな空間ではワンポイントで温かさを飾れるように、男性でも身に着けられるユニセックスな羊毛雑貨を制作。</p> <p>羊毛をはじめなるべく自然の素材にこだわり、草木染を施した羊毛も取り入れております。</p> </article> <article class="about-profile-img fadein"> <h2><span></span>profile</h2> <div> <img src="common/img/IMG_5272.JPG" alt="プロフィール画像"> <div class="profile-content"> <p>mococon(モココン) = 安齋 繭(Mayu ANZAI) さいたま市出身、さそり座のABがた。</p> <p>ずっと心の中にあったオリジナルキャラクター[moco]。何か形にしたいと模索中、羊毛フェルトと出会いその魅力にひかれ、作家として活動しはじめる</p> <p>2012年、渡仏。アクセサリー製作アシスタントとして働きながら、パリのアートシーンに触れ、制作活動する。市内のギャラリーへ展示販売を行うなど1年間滞在。</p> <p>2015年11月クアラルンプールFINDERSにてぺインターNABEKAORUとともにグループ展を行う。</p> <p>翌年春に同氏とアートユニット[Cokun,]を結成、2017夏に「Cokun,Artist Village(アーティストインレジデンススペース)」を佐賀県唐津市にて企画・開催、活動の幅を広げた。</p> <p>現在は、都内やさいたまを中心に作品制作、販売などイベントやワークショップ、羊毛フェルトの出張講師など活動中。</p> <div class="blog"><a href="http://mococon-blog.blogspot.com/" target="_blank">以前のブログはコチラから</a></div>     </div> </div> </article> </div> </main> <?php require_once('footer.php'); ?> <script src="common/js/jquery.js"></script> <script src="common/slick/slick/slick.min.js"></script> <script> $(window).on('load', function() { $('#loader-bg').hide(); }); $('#accordion').on('click', function() { $('#accordion-content').slideToggle(); }); window.onload = function() { scroll_effect(); $(window).scroll(function() { scroll_effect(); }); function scroll_effect() { $('.fadein').each(function() { var elemPos = $(this).offset().top; var scroll = $(window).scrollTop(); var windowHeight = $(window).height(); if (scroll > elemPos - windowHeight) { $(this).addClass('scrollin'); } }); } }; </script> </body> </html><file_sep>/nav.php <nav class="navigation"> <div class="navigation-pc"> <ul> <li class="navigation-nav"> <p><a href="index.php">Home</a></p> </li> <li class="category-list"> <p>Category</p> <ul> <li class="category-list-items"> <a href="original-mascot.php" target="_blank"> <p>Original mascot</p> </a> </li> <li class="category-list-items"> <a href="tie.php" target="_blank"> <p>tie</p> </a> </li> <li class="category-list-items"> <a href="bag.php" target="_blank"> <p> Bag</p> </a> </li> <li class="category-list-items"> <a href="other.php" target="_blank"> <p>Other</p> </a> </li> </ul> </li> <li class="navigation-nav"> <p><a href="about.php" target="_blank">About</a></p> </li> <li class="navigation-nav"> <p><a href="gallery.php" target="_blank">Gallery</a></p> </li> <li class="navigation-nav"> <p><a href=" http://ws.formzu.net/fgen/S82910306" target="_blank">Contact</a> </p> </li> </ul> </div> <div class="nav"> <input id="drawer-checkbox" type="checkbox"> <label id="drawer-icon" for="drawer-checkbox"><span></span></label> <label id="drawer-close" for="drawer-checkbox"></label> <div id="drawer-content"> <div class="drawer-content-nav"> <ul> <li> <a href="index.php"> <p>Home</p> </a> </li> <li id="accordion"> <a href="#"> <p>Category</p> </a> </li> </ul> <ul id="accordion-content"> <li> <a href="original-mascot.php" target="_blank"> <p>Original mascot</p> </a> </li> <li> <a href="tie.php" target="_blank"> <p>tie</p> </a> </li> <li><a href="bag.php" target="_blank"> <p>Bag</p> </a> </li> <li> <a href="other.php" target="_blank"> <p>Other</p> </a> </li> </ul> <ul> <li> <a href="gallery.php" target="_blank"> <p>Gallery</p> </a> </li> <li> <a href="about.php" target="_blank"> <p>About</p> </a> </li> <li> <a href=" http://ws.formzu.net/fgen/S82910306" target="_blank"> <p>Contact</p> </a> </li> </ul> </div> <div class="nsn-icon-top"> <ul> <li><a href="https://www.facebook.com/mayu.anzai" target="_blank"><img src="common/img/facebook2.svg" alt="anzaimayuのfacebook"></a></li> <li><a href="https://www.instagram.com/mococon_/?hl=ja" target="_blank"><img src="common/img/insta2.svg" alt="anzaimayuのInstagram"></a></li> <li><a href="https://twitter.com/mococon_" target="_blank"><img src="common/img/Twitter2.svg" alt="anzaimayuのTwitter"></a></li> </ul> </div> </div> </div> </nav>
bf915ccadf35b0eb878c63bcf037cec2dd88a1cb
[ "Hack", "SCSS", "CSS", "PHP" ]
15
Hack
yamaguchi-yumiko/mococon
946ac80555cce85ffe8fc2a231e957f32a806a88
8ae29702c157b1384ddd21d509a139043874c76e
refs/heads/master
<repo_name>sophomore99/JavaScript-D3<file_sep>/README.md # JavaScripts-D3-SVG 1. We can use JavaScript's D3 library to represent data. 2. I have drawn some chart and tried to make some beautiful design using this library.
89c0316dd7b0bb8c56ae2e81ad95e3284594a698
[ "Markdown" ]
1
Markdown
sophomore99/JavaScript-D3
775f89ac52d99b8abc3fcce7b7258c239b588ed9
c1842797556024703765fe8408d1fe02a11425e1
refs/heads/master
<repo_name>cjjhust/StarterLearningPython<file_sep>/index.md **This is for everyone.** >In the begning when God created the heavens and the earth. the earth was a formless void and darkness covered the face of the deep, while a wind from God swept over the face of the waters. Then God said,"Let there be light"; and there was light. And God saw that the light was good; and God separated the light from the darkness. (GENESIS 1:1-4) #《零基础学python》(第二版) ##预备动作 1. [关于python的故事](./01.md) 2. [从小工到专家](./02.md) 3. [安装python的开发环境](./03.md) ##第一部分:基础知识 1. [集成开发环境](./101.md)==>集成开发环境;python的IDE 2. [数和四则运算](./102.md)==>整数和浮点数;变量;整数溢出问题; 3. [除法](./103.md)==>整数、浮点数相除;`from __future__ import division`;余数;四舍五入; 4. [常用数学函数和运算优先级](./104.md)==>math模块,求绝对值,运算优先级 5. [写一个简单程序](./105.md)==>程序和语句,注释 6. [字符串(1)](./106.md)==>字符串定义,转义符,字符串拼接,str()与repr()区别 7. [字符串(2)](./107.md)==>raw_input,print,内建函数,原始字符串,再做一个小程序 8. [字符串(3)](./108.md)==>字符串和序列,索引,切片,基本操作 9. [字符串(4)](./109.md)==>字符串格式化,常用的字符串方法 10. [字符编码](./110.md)==>编码的基础知识,python中避免汉字乱码 11. [列表(1)](./111.md)==>列表定义,索引和切片,列表反转,元素追加,基本操作 12. [列表(2)](./112.md)==>列表append/extend/index/count方法,可迭代的和判断方法,列表原地修改 13. [列表(3)](./113.md)==>列表pop/remove/reverse/sort方法 14. [回顾列表和字符串](./114.md)==>比较列表和字符串的相同点和不同点 15. [元组](./115.md)==>元组定义和基本操作,使用意义 16. [字典(1)](./116.md)==>字典创建方法、基本操作(长度、读取值、删除值、判断键是否存在) 17. [字典(2)](./117.md)==>字典方法:copy/deepcopy/clear/get/setdefault/items/iteritems/keys/iterkeys/values/itervalues/pop/popitem/update/has_key 18. [集合(1)](./118.md)==>创建集合,集合方法:add/update,pop/remove/discard/clear,可哈希与不可哈希 19. [集合(2)](./119.md)==>不可变集合,集合关系 20. [运算符](./120.md)==>算数运算符,比较运算符,逻辑运算符/布尔类型 21. [语句(1)](./121.md)==>print, import, 赋值语句、增量赋值 22. [语句(2)](./122.md)==>if...elif...else语句,三元操作 23. [语句(3)](./123.md)==>for循环,range(),循环字典 24. [语句(4)](./124.md)==>并行迭代:zip(),enumerate(),list解析 25. [语句(5)](./125.md)==>while循环,while...else,for...else 26. [文件(1)](./126.md)==>文件打开,读取,写入 27. [文件(2)](./127.md)==>文件状态,read/readline/readlines,大文件读取,seek 28. [迭代](./128.md)==>迭代含义,iter() 29. [练习](./129.md)==>通过四个练习,综合运用以前所学 30. [自省](./130.md)==>自省概念,联机帮助,dir(),文档字符串,检查对象,文档 ##第二部分:函数和类 1. [函数(1)](./201.md)==>定义函数方法,调用函数方法,命名方法,使用函数注意事项 2. [函数(2)](./202.md)==>函数返回值,函数文档,形参和实参,命名空间,全局变量和局部变量 3. [函数(3)](./203.md)==>收集参数:`*`和`**`,及其逆过程,复习参数知识 4. [函数(4)](./204.md)==>递归和filter、map、reduce、lambda、yield 5. [函数练习](./205.md)==>解一元二次方程,统计考试成绩,找素数 6. [类(1)](./206.md)==>类的初步认识和基本概念理解:问题空间、对象、面向对象、类和实例化类 7. [类(2)](./207.md)==>新式类和旧式类,类的命名,构造函数,实例化及方法和属性,self的作用 8. [类(3)](./208.md)==>类属性和实例属性,类内外数据流转,命名空间、作用域 9. [类(4)](./209.md)==>继承,多重继承,super函数 ##第三部分:模块 ##第四部分:用Tornado做网站 ##第五部分:科学计算 ##附:网络文摘 1. [如何成为python高手](./n001.md)
d906a28cbecd90270afdf723b0ea073fd03176ba
[ "Markdown" ]
1
Markdown
cjjhust/StarterLearningPython
e35da9c490d63084f1e4c555c199835fe6d1e9c0
9a4fd5e7d506cba61efc71af76942fefa63f14c6
refs/heads/master
<file_sep># Connect-Four-jQuery-JS<file_sep>// $('h1').click(function(){ // console.log("There was a click!"); // }) var boardButton = $('button'); var table = $('table tr'); var playerOneName = prompt('Player 1: \nEnter your name.') var playerOneColor = 'red' var playerTwoName = prompt('Player 2: \nYou must also enter your name.') var playerTwoColor = 'black' if (playerOneName == '' || playerOneName == null) { playerOneName = 'Player 1' } if (playerTwoName == '' || playerTwoName == null) { playerTwoName = 'Player 2' } var currentPlayerName = playerOneName; var currentPlayerColor = playerOneColor; var headingH1 = $('h1') var headingH2 = $('h2') var headingH3 = $('h3') var testI = 1 headingH3.text(currentPlayerName + ": It is your turn. Please drop a " + currentPlayerColor + " chip.") boardButton.on('click',function() { //Fill in the corresponding column var columnIndex = $(this).closest('td').index() fillColumnBottom(columnIndex, currentPlayerColor) //Check for Win and Swap Turns IF the chosen column was not FULL if (successfulTurn) { //Check for Win if (checkforWin()) { gameEnd() } //Swap Turns if (currentPlayerName === playerOneName) { currentPlayerName = playerTwoName currentPlayerColor = playerTwoColor } else { currentPlayerName = playerOneName currentPlayerColor = playerOneColor } headingH3.text(currentPlayerName + ": It is your turn. Please drop a " + currentPlayerColor + " chip.") } }) function fillColumnBottom(columnIndex, color) { var rowIndex = 100; for (var i = 0; i < 6; i++) { if (getColor(i,columnIndex)=='rgb(128, 128, 128)') { rowIndex = i } } if (rowIndex===100) { //COLUMN IS FULL successfulTurn = false; } else { setColor(rowIndex, columnIndex, color) successfulTurn = true; } } function getColor(rowIndex, columnIndex) { return table.eq(rowIndex).find('td').eq(columnIndex).find('button').css('background-color') } function setColor(rowIndex, columnIndex, color) { table.eq(rowIndex).find('td').eq(columnIndex).find('button').css('background-color',color) } function checkforWin() { if (horizontalWin() || verticalWin() || diagonalWin()) { return true; } else { return false; } } function horizontalWin() { for (var row = 0; row < 6 ; row++) //ROWS { for (var col = 0; col < 4; col++) //COLUMNS { if (isMatching(getColor(row,col),getColor(row,col+1),getColor(row,col+2),getColor(row,col+3))) { return true; } } } } function verticalWin() { for (var col= 0; col < 7 ; col++) //ROWS { for (var row = 0; row < 3; row++) //COLUMNS { if (isMatching(getColor(row,col),getColor(row+1,col),getColor(row+2,col),getColor(row+3,col))) { return true; } } } } function diagonalWin() { for (var row = 0; row < 6 ; row++) //ROWS { for (var col = 0; col < 7; col++) //COLUMNS { if (isMatching(getColor(row,col),getColor(row+1,col+1),getColor(row+2,col+2),getColor(row+3,col+3))) { return true; } else if (isMatching(getColor(row,col),getColor(row-1,col+1),getColor(row-2,col+2),getColor(row-3,col+3))) { return true; } } } } function isMatching(one, two, three, four) { if (one===two && one===three && one===four && one!=='rgb(128, 128, 128)' && one!==undefined) { return true; } else { return false; } } function gameEnd() { var newH1CSS = { 'fontSize':'50px', 'font-weight': 'bold' } headingH1.text(currentPlayerName + " is the champion of the universe!!!").css(newH1CSS) headingH2.text("Click Refresh to Play Again.").css('fontSize','40px') headingH3.fadeOut('fast') } //LOCATE A SPECIFIC ITEM ON THE TABLE AND CHANGE ITS COLOR //OR MORE SPECIFICALLY, FIND A TABLE ROW, THEN WITHIN THAT ROW A COLUMN, THEN WITHIN THAT SPECIFIC CELL THE BUTTON PROPERTY, THEN WITHIN THAT BUTTON THE BACKGROUD COLOR PROPERTY //FIRST ASSIGN A VARIABLE TO TABLE TR, WHICH RETURNS AN "ARRAY" OF EACH TABLE ROW WITHIN THE TABLE //THEN INDEX TO A CERTAIN TABLE ROW //EACH ROW HAS SOME NUMBER OF COLUMNS. FIND THE COLUMN PROPERTY AND INDEX TO A CERTAIN VALUE //ONCE THERE, FIND THE BUTTON PROPERTY AND ACCESS ITS CSS PROPERTIES //CHANGE OR RETURN THE BACKGROUND COLOR TO A COLOR
4453f3d0f61cf913a85f233b78cf5bbc02140265
[ "Markdown", "JavaScript" ]
2
Markdown
bfolks2/Connect-Four-jQuery-JS
f4db9994f456b8e31dae29c1f8fc842272f1a9ca
7d508717e50420474412dbf57b014fcaebe97202
refs/heads/master
<file_sep>package main import ( "fmt" "src/calculator" "src/stringutil" ) func main () { fmt.Println("Calculator Programme") fmt.Println("Add : ", calculator.Add(12,10)) fmt.Println("Sub : ", calculator.Sub(12,10)) fmt.Println("Mul : ", calculator.Mul(12,10)) fmt.Println("divide : ", calculator.Divide(12,10)) fmt.Println(stringutil.Reverse("Hi I am Bhushan")) fmt.Println(stringutil.Swapstring("Bhushan", "Kavita")) fmt.Println(stringutil.ConcatString("Bhushan", "Kavita")) } <file_sep> package userApp const ( NUMBEROFUSER = 10 NUMBEROFRETRY = 3 // Number of retries for password ) type precednce struct { primery int seconder int } type userEmailID struct { emailID map[precednce]string isvalidated bool } type userMobileNumber struct { mnumber map[precednce]rune isvalidated bool } type userGender struct { male bool female bool other bool } type user_info struct { userFristName string userMiddlName string userLastName string userEmailID userMobileNumber userGender userName string passWord string } <file_sep>package main import ( "fmt" ) type person struct{ frist_name string last_name string age int8 } //method attached with porsion func (p person) speek() { fmt.Println("Hello every one I am ", p.frist_name," ",p.last_name," and my age is ",p.age) } func main() { p1 := person{ frist_name: "Bhushan", last_name: "Patil", age: 26, } p2 := person{ frist_name: "unknown", last_name: "someting", age: 00, } p1.speek() p2.speek() }<file_sep>package main import ( "fmt" ) func main () { // rune is alise for int32 var num rune fmt.Printf("Enter the number here : ") fmt.Scanf("%d", &num) fmt.Printf("%d\t\t%b\t\t%#X\n", num,num,num) // num left shift over 1 new_var := num << 1 fmt.Printf("%d\t\t%b\t\t%#x\n", new_var,new_var,new_var) }<file_sep>package main import ( "fmt" ) var x int = 43 var y string = "<NAME>" var z bool = false func main() { s := fmt.Sprintf("%d\t%s\t%t\n", x,y,z) fmt.Println(s) } <file_sep>package calculator //Add two given number func Add(a,b int) int { return a + b } //Sub two number's func Sub(a,b float64) float64 { return a - b } // Multiple two given number func Mul(a,b rune) rune{ return a * b } //Divide two given number func Divide(a, b float64) float64 { if b == 0 { return -1 } return a / b } <file_sep>package main import ( "fmt" "src/userApp" ) func main() { user := userApp.NewUser() fmt.println(user) user.Create_account() }<file_sep>//write programme to print enter number in dec, bin, and hex formate package main import ( "fmt" ) func main() { var num int = 0 fmt.Printf("Enter Number :" ) fmt.Scanf("%d", &num) fmt.Printf("Number IN Decimal :%d\n", num) fmt.Printf("Number IN Binary :%b\n", num) fmt.Printf("Number IN Hexadecimal :%#X\n", num) }<file_sep>package main import ( "fmt" _ "os" // black import ) func main() { // this is for only we are using os package //os.Getgid() /*//exercise 1 ch := make(chan int) go func (){ fmt.Println("ch is push ") ch <- 42 close(ch) fmt.Println("ch is close ") }() fmt.Println("ch is ", <- ch)*/ /* //exercise 2 //sending channel ch := make(chan int) go func(){ ch <- 42 }() fmt.Println(<-ch) // err fmt.Println("............\n") fmt.Printf("ch\t %T \n",ch)*/ /* //exercise 4 ch1 := make(chan int) ch2 := make(chan int) quit := make(chan int) go func(){ for i := 0 ; i < 100; i++ { if i % 2 == 0{ ch1 <- i } else { ch2 <- i } } quit <- 1 close(ch1) close(ch2) close(quit) }() for { select { case c1 := <- ch1 : fmt.Println("channel one value : ", c1) case c2 := <-ch2 : fmt.Println("channel two value : ", c2) case c3 := <- quit : fmt.Println("channel is closed : ", c3) os.Exit(0) //default : //fmt.Println("meight be channel is close ", <-ch1, <-ch2) } }*/ /* // comma ok idiom ch := make(chan int ) go func (){ ch <- 42 close(ch) }() v, ok := <- ch fmt.Println(v, ok) v,ok = <- ch fmt.Println(v , ok)*/ /*// put 100 number to achannel // read that number form that channel value */ ch := sender() for v := range ch { fmt.Println(v) } } // sender function returing receiver channnel func sender() <- chan int { ch := make(chan int) go func (){ for i := 0; i< 100; i++ { ch <- i } close(ch) }() return ch }<file_sep>package main import ( "fmt" ) func main () { bd := 1954 i := 0 for bd <= 2021 { fmt.Println(i, " :- ",bd) bd++; i++ } }<file_sep>package main import ( "fmt" "encoding/json" "os" ) //Note : for converting struct into json , // structure member name should start with upper case leter type user_info struct { Frist string Last string Email string Age int Mobilenumber rune } func main () { u1 := user_info{ "Bhushan", "Patil", "<EMAIL>", 27, 123456789, } fmt.Println(u1) bs, err := json.Marshal(u1) if err != nil { fmt.Println(err) } fmt.Println(string(bs)) fmt.Println() os.Stdout.Write(bs) }<file_sep>package main import ("fmt") func main() { cfunc := func (num []int) int { for i, v := range num { for j, val := range num { //fmt.Println(i, " ",v, " and ", val) if v > val { num[i] = val num[j] = v v = val //fmt.Println(i, " ", j, " ",num) } } } //fmt.Println(num) return num[0] } fmt.Println(get_max_number(cfunc,[]int{-1,-13,-14,0,-6,-7,-8,-9})) } func get_max_number(f func(x []int)int, ii []int) int { return f(ii) }<file_sep>package main import ( "fmt" ) //variadic parameter func foo(x ...int) int { if len(x) <= 0 { return -1 } var total int for _, v := range x { total += v } return total } func bar(x []int) int { if len(x) <= 0 { return -1 } var total int for _, v := range x { total += v } return total } func main() { slice_var := []int{1,2,3,4,5,6,7,8,9,} //var slice_var []int fmt.Println("Sum return from foo func : ", foo(slice_var...)) //slice_var.. called unfirling fmt.Println("sum return from bar func : ", bar(slice_var)) }<file_sep>//for loop // Note : In go lang only for loop is available // for [ conditinal | for [like c] | rangeClause ] // while like loop // i := 0 // for i < some_num { // some code block // i++ or i = i + 1 // } //for i := 0; i < num; i++ { } //for key, value := range data { } //write programe to print number 1 to 10,000 package main import ( "fmt" ) func main() { for i := 1; i <= 10000; i++ { fmt.Println(i) } }<file_sep>package main import ( "fmt" "src/stack" ) var sym = map[byte]int{ 40 : -1, 41 : 1, 91 : -2, 93 : 2, 123 : -3, 125 : 3, } func Is_balence(str string) bool { st := stack.New(256) //fmt.Println(st, "str" ,str, str[0])) for i := 0; i < len(str); i++ { if v, isset := sym[str[i]]; isset && v < 0 { st.Push(str[i]) //fmt.Println(isset, v, str[i]) } else { if st.Is_empty() { return false }else if sym[st.Peek().(byte)] + sym[str[i]] == 0 { st.Pop() } } } if (st.Is_empty()) { return true } return false } func main() { fmt.Println("Enter Parenthesis string :" ) var str string; fmt.Scanf("%s", &str) fmt.Println(str) fmt.Println(Is_balence(str)) }<file_sep>package main import ( "fmt" ) func call_last() { fmt.Println("Hi i am call_last func and i should called at end of main ") } func name() { fmt.Println("name of the code is : defer keyword ") } func version() { fmt.Println("version of code is : 1.0") } func main() { defer call_last() name() version() }<file_sep>package main import ( "os" "bufio" "fmt" "strings" ) //32 to 127 make map map[byte]rune func Make_map(cap rune) map[byte]rune { m := make(map[byte]rune, cap) for i := 23; i < 127; i++ { m[byte(i)] = 0; } return m } func Print_char_freq(m map[byte]rune) { for i := range m{ if v, isset := m[byte(i)]; isset && v != 0{ fmt.Printf("%#U == %d \n",i, m[byte(i)]) } } } func Count_char_freq(str string) map[byte]rune { m := Make_map(128) fmt.Println() for i := 0; i < len(str); i++ { m[str[i]] = m[str[i]]+1 } return m } func main() { fmt.Println("Enter String : ") reader := bufio.NewReader(os.Stdin) str, _ := reader.ReadString('\n') m := Count_char_freq(strings.Trim(str, "\r\n")) Print_char_freq(m) } <file_sep>package main import ( "fmt" "sort" ) type porson struct { Name string Age int } type Byname []porson type Byage []porson func (bn Byname) Len() int { return len(bn) } func (bn Byname) Less(i, j int) bool { return bn[i].Name < bn[j].Name } func (bn Byname) Swap(i, j int) { bn[i], bn[j] = bn[j], bn[i] } func (a Byage) Len() int { return len(a)} func (a Byage) Less(i, j int) bool {return a[i].Age < a[j].Age} func (a Byage) Swap(i, j int) {a[i], a[j] = a[j], a[i]} func main() { var peopls []porson p1 := porson{"Bhushan", 27} p2 := porson{"Dinesh", 30} p3 := porson{"Datta", 28} p4 := porson{"suraj", 32} p5 := porson{"bhupi", 25} p6 := porson{"shubham", 33} p7 := porson{"vikrant", 34} p8 := porson{"vishal", 37} peopls = []porson{p1,p2,p3,p4,p5,p6,p7,p8,} fmt.Println(peopls) sort.Sort(Byname(peopls)) fmt.Println(peopls) sort.Sort(Byage(peopls)) fmt.Println(peopls) }<file_sep>package main import ( "fmt" "src/userApp" ) func main() { fmt.Println(userApp.NewUser()) }<file_sep> package main import ( "fmt" ) type vehicle struct { door int8 color string } type truck struct { vehicle fourwheeler bool } type bmw struct { vehicle luxury bool } func main () { t := truck { vehicle: vehicle{ door: 2, color: "red", }, fourwheeler: true, } fmt.Println(t) }<file_sep> //create map[string] []string package main import ( "fmt" ) func main () { //map_arr := make(map[string][]string, 100) map_arr := map[string][]string{ "1" : []string{"Makan", "Girdhar", "Patil"}, "2" : []string{"Bhushan", "Makan", "Patil"}, "3" : []string{"Jotsanabai", "Makan", "Patil"}, } fmt.Println(map_arr) for k, _ := range map_arr { if v, isset := map_arr[k]; isset { fmt.Println(k,v) } } //aad recoed in map map_arr["4"] = []string{"Kavita", "Bhushan", "Patil"} for k, _ := range map_arr { if v, isset := map_arr[k]; isset { fmt.Println(k,v) } } //delete "4" recoed from map_arr //func delete(map, key) key := "4" if _ , isset := map_arr[key]; isset { delete(map_arr, key) } fmt.Println(map_arr) }<file_sep>//Create slice to hold all state in india, and print it. // {"Andhra Pradesh" , "Arunachal Pradesh" , "Assam" , "Bihar" , "Chhattisgarh" , "Goa" , "Gujarat" , // "Haryana" , "Himachal Pradesh" , "Jammu and Kashmir" , "Jharkhand" , "Karnataka" , "Kerala" , // "Madhya Pradesh" , "Maharashtra" , "Manipur" , "Meghalaya" , "Mizoram" , "Nagaland" , "Odisha" , // "Punjab" , "Rajasthan" , "Sikkim" , "Tamil Nadu" , "Telangana" , "Tripura" , "Uttarakhand" , "Uttar Pradesh" , // "West Bengal" , "Andaman and Nicobar Islands" , "Chandigarh" , "Dadra and Nagar Haveli" , "Daman and Diu" , // "Delhi" , "Lakshadweep" , "Puducherry" } package main import ( "fmt" ) func main () { //create slice using "make" func // func make(s []T, len, capacity) []T var slice_var []string slice_var = make([]string, 36, 50) slice_var = []string{"Andhra Pradesh" , "Arunachal Pradesh" , "Assam" , "Bihar" , "Chhattisgarh" , "Goa" , "Gujarat" , "Haryana" , "Himachal Pradesh" , "Jammu and Kashmir" , "Jharkhand" , "Karnataka" , "Kerala" , "Madhya Pradesh" , "Maharashtra" , "Manipur" , "Meghalaya" , "Mizoram" , "Nagaland" , "Odisha" , "Punjab" , "Rajasthan" , "Sikkim" , "Tamil Nadu" , "Telangana" , "Tripura" , "Uttarakhand" , "Uttar Pradesh" , "West Bengal" , "Andaman and Nicobar Islands" , "Chandigarh" , "Dadra and Nagar Haveli" , "Daman and Diu" , "Delhi" , "Lakshadweep" , "Puducherry" } fmt.Println("Index\t\tState") for i := 0; i < len(slice_var); i++ { fmt.Println(i , slice_var[i]) } }<file_sep>// slice // Note in go use slice instead of array package main import ( "fmt" ) func main() { // short hand oprator , declearation with initilisation slice_var := []int{1,2,3,4,5,6,7,8,9,10} fmt.Println(slice_var) for i, v := range slice_var { fmt.Println(i,v) } fmt.Printf("%T\n", slice_var) //use ':' oprator for slicing data //output should be bellow given //1-> [1,2,3,4] //2-> [5,6,7,8] //3-> [3,4,5,6] //4-> [ 7,8,9,10] fmt.Println("array slicing ") fmt.Println(slice_var[:4]) fmt.Println(slice_var[4:8]) fmt.Println(slice_var[2:6]) fmt.Println(slice_var[6:]) //use "append" func for append value into the slice //func append (s []T, x ...T) []T --> func defination // append value 11, int slice_var variable using append func slice_var = append(slice_var, 11) fmt.Println(slice_var) //append 3 more value into some slice slice_var = append(slice_var, 12,13,14) fmt.Println(slice_var) //create new slice x := []int{15,16,17,18,19,20} fmt.Println(x) //append x slice into the slice_var using "dst = append(dst, src...)" slice_var = append(slice_var, x...) fmt.Println(slice_var) fmt.Println("Delete element from slice 12, 13, 14") //for delete element from slice we use were simple method // we use append func and : oprator // Delete 12, 13, 14 from given slice slice_var = append(slice_var[:11], slice_var[14:]...) fmt.Println(slice_var) }<file_sep>//Array package main import ( "fmt" ) func main () { arr := []int{1,2,3,4,5} fmt.Println(arr) fmt.Println("using for loop ") for i := 0; i < len(arr); i++ { fmt.Println(i, arr[i]) } fmt.Println("using for loop with range") for i , v := range arr { fmt.Println(i, v) } fmt.Println("Type of the Array : ") fmt.Printf("%T\n",arr); }<file_sep>// go "if else statement" package main import ( "fmt" ) func main() { var num int fmt.Printf("Enter Number : ") fmt.Scanf("%d", &num) if num == 3 { fmt.Println("Enter Number is Match And Your The Winner.......!") } else { fmt.Println("Please Try Again Enter Number Did not Match") } } <file_sep>//write programe "switch statement without' expression package main import ( "fmt" ) func main() { var num int fmt.Printf("1 -> Hi\t 2 -> Hello\t3 -> Hey\n : ") fmt.Scanf("%d", &num) switch { case (num == 1): fmt.Println("Hi :)") case (num == 2): fmt.Println("Hello .<)") case (num == 3): fmt.Println("Hey :^") default : fmt.Println(":( Try Again ") } }<file_sep>package main import ( "fmt" "sync" ) //fanin is a tequenic that use in conccerency // fanin means pull data from two or more channles and push into one channele // it's called fanIN // ch1 -------- // \ // |-->fanIN--> // / // ch2 -------- func main() { ch1 := make(chan int) ch2 := make(chan int) fanin := make(chan int) go sender(ch1, ch2) go receiverAndFanIn(ch1, ch2, fanin) for v := range fanin { fmt.Println(v) } } func sender(ch1, ch2 chan<- int) { for i := 0; i < 10; i++ { if i % 2 == 0 { ch1 <- i } else { ch2 <- i } } close(ch1) close(ch2) //if we are not close ch1 and ch2 go comiler throws error deadlock } func receiverAndFanIn(ch1, ch2 <- chan int, fanin chan <- int) { var wg sync.WaitGroup wg.Add(2) go func(){ for v := range ch1{ fanin <- v } wg.Done() }() go func(){ for v := range ch2 { fanin <- v } wg.Done() }() wg.Wait() close(fanin) }<file_sep>// "if statement" with variable initilastion package main import ( "fmt" ) func main () { map_var := map[int] string { 1 : "Bhushan", 2 : "Makan", 3 : "Patil", } fmt.Println(map_var) fmt.Println(map_var[1]) for i := 0; i < 5; i++ { if v, ok := map_var[i]; ok { fmt.Println(i, v) } else { fmt.Printf("for key %d value not fund \n",i) } } //add value into map map_var[0] = "Kavita" map_var[4] = "Bhushan" map_var[5] = "Patil" // map with range for v, k := range map_var { fmt.Println(k, v) } // delete value from map // use delete func to delete value from map // delete(map, key) if v, ok := map_var[0]; ok { fmt.Println(v) delete(map_var, 0) } fmt.Println(map_var) //use make for map mm_map := make(map[int]string, 10) fmt.Println(len(mm_map)) // fmt.Println(cap(mm_map)) }<file_sep>package main import ( "fmt" ) func main() { x := 43 y := "<NAME>" z := true fmt.Println(x) fmt.Println(y) fmt.Println(z) } <file_sep>package main import ( "fmt" ) func main() { ch := make(chan int) //sender routine fmt.Println("anonymaous go routine is launched ... ") go func(){ for i := 0; i < 10; i++{ ch <- i //fmt.Println("anonymaous routine : ",<-ch) :err : dead-lock } close(ch) }() //Thise loop is alive until channle close by sender routine for v := range ch { fmt.Println(v) } }<file_sep>package main import ( "fmt" ) func sum(num ...int) int { if len(num) <= 0 { return -1 } var total int for _, v := range num { total += v } return total } func even(Cfunc func(num ...int) int, num ...int) int { if len(num) <= 0 { return -1 } var s_var []int for _ , v := range num { if v % 2 == 0 { s_var = append(s_var, v) } } return Cfunc(s_var...) } func main() { i := []int{1,2,3,4,5,6,7,8,9,10,11,12,13,14,15} fmt.Println(even(sum,i...)) }<file_sep>package main import ( "fmt" ) func main () { foo() fmt.Println("return normally from foo") } func foo() { //check how this work defer func(){ //comma ok idiom sytle if r := recover(); r != nil { fmt.Println("recovering in foo : ", r) } }() fmt.Println("calling func get ") get(0) fmt.Println("return normally from get") } func get(i int ) { if i > 3 { fmt.Println("Panicing here !") panic(fmt.Sprintf("%v",i)) } defer fmt.Println("Defer in get : ",i) fmt.Println("print in get :",i) get(i+1) }<file_sep>//write programe to print uppercase ascii three time package main import ( "fmt" ) func main () { for i := 65; i <= 90; i++ { for j :=0; j < 3; j++ { fmt.Printf("%#U\n", i) } fmt.Println() } }<file_sep> package main import ( "fmt" ) type porson struct { fristName string lastName string favorate []string } func main () { p1 := porson{ fristName: "Bhushan", lastName: "Patil", favorate: []string{"I","like","write code", "c", "c++", "go","so on"}, } p2 := porson{ fristName: "Bhushan", lastName: "Patil", favorate: []string{"I","like","write code", "c", "c++", "go","so on"}, } fmt.Println(p1, p2) //creare map using porson //note : map not contain dublicate key entries map_var := map[string]porson{ p1.lastName : p1, p2.lastName : p2 } fmt.Println(map_var) //range over it for k, v := range map_var { fmt.Println(k) fmt.Println(v.fristName,v.lastName) for i , v := range v.favorate { fmt.Println(i, v) } } }<file_sep>package stringutil //Hi Hello //i -> H // j -> o //i -> o , j -> H // func Reverse(s string) string { r := []rune(s) for i, j := 0, (len(r) -1); i < len(r)/2; i, j = i + 1, j - 1 { r[i], r[j] = r[j], r[i] } return string(r) } //a = 2 // b = 3 // b = a ^ b // a = a ^ b // b = a ^ b // func Swapstring(dst, src string) (string, string){ size := 0 var d, s []rune if len(src) == len(dst) { size = len(src) - 1 d = []rune(dst)//a s = []rune(src)//b } else if len(src) > len(dst) { size = len(src) d = make([]rune, size) s = make([]rune, size) //fmt.Println(len(d), len(s)) copy(d, []rune(dst)) copy(s, []rune(src)) //fmt.Println(len(d), len(s)) } else if len(src) < len(dst) { size = len(dst) d = make([]rune, size) s = make([]rune, size) //fmt.Println(len(d), len(s)) copy(d, []rune(dst)) copy(s, []rune(src)) //fmt.Println(len(d), len(s)) } for i := 0; i < size; i++ { s[i] = xro_op(d[i], s[i]) } for i := 0; i < size; i++ { d[i] = xro_op(d[i], s[i]) } for i := 0; i < size; i++ { s[i] = xro_op(d[i], s[i]) } //fmt.Println("s :" , string(s) , "d : ", string(d)) return string(d), string(s) } func xro_op(a, b rune) rune { return a ^ b } func ConcatString(str1, str2 string) string { return str1 + str2 } <file_sep>package main import ( "fmt" //"sync" ) /*In Go language, a channel is a medium through which a goroutine communicates with another goroutine and this communication is lock-free. Or in other words, a channel is a technique which allows to let one goroutine to send data to another goroutine. By default channel is bidirectional, means the goroutines can send or receive data through the same channel*/ // var idenfier-name chan Type [int, string, map, floate64 and so on] //var channel_var chan int //var wg sync.WaitGroup func main() { channel_var := make(chan int, 1) //wg.Add(2) fmt.Println("master_chan go routine is lonched ") go master_chan(channel_var) slave_chan(channel_var) //wg.Wait() fmt.Println("main routine exit ") close(channel_var) } //sender only func master_chan(ch chan <- int) { i := 1 for { ch <- i i++ //fmt.Println("master_chan %d ", <- ch) //if val, isset := <- ch; isset { // if val == 5 { // break //} //} } fmt.Println("master_chan close..") //wg.Done() //close(ch) } //receiver only func slave_chan(ch <- chan int) { for { if val, isset := <- ch; isset { if val == 5 { break } fmt.Println("slave_chan value is : " ,<-ch) } } //wg.Done() //close(ch) : err : invalid operation: close(ch) (cannot close receive-only channel) fmt.Println("slave_chan exit...") }<file_sep>package main import ( "fmt" "sync" ) var wg sync.WaitGroup func main() { wg.Add(2) go foo() go bar() for i := 0; i < 100; i++{ fmt.Println("printing in main routine : ", i) } wg.Wait() fmt.Println("Code Exit...") } func foo() { for i := 0; i < 10; i++ { fmt.Println("printing in foo routine : ", i) } wg.Done() } func bar() { for i := 0; i < 10; i++ { fmt.Println("printing in bar routine : ", i) } wg.Done() }<file_sep>package main import ( "fmt" ) var allUserInfo map[string]user_info type user_info struct { fristName string lastNmae string phoneNumbr rune email string userName string password string } func addNewUser(user *user_info) bool { if user == nil || allUserInfo == nil{ fmt.Println("nill fund ", user, " | ", allUserInfo) return false } allUserInfo[user.userName] = *user fmt.Println("Your username is : ", allUserInfo[user.userName].userName) return true } func editUserInfo(userName string) bool{ var user_intput string = "user Name" if v, isset := allUserInfo[userName]; isset { fmt.Println(v) fmt.Println("What you want to edit : ") //fmt.Scanf("%s", &user_intput) switch user_intput { case "user Name": un := "" cun := "" fmt.Print("Enter yout New user name : ") fmt.Scanf("%s", &un) fmt.Print("Re-Enter your user name : ") fmt.Scanf("%s", &cun) fmt.Print("Processing......") if un == cun { return true } else { fmt.Print("somthing wrong happen") } case "password" : case "email id" : case "phone no" : default : } } return false } func main () { userName := "" allUserInfo = make (map[string]user_info, 10) newUser := user_info{"Bhushan", "Patil", 12345 , "<EMAIL>", "<PASSWORD>", "<PASSWORD>",} addNewUser(&newUser) fmt.Print("Enter your user name for edit info : ") fmt.Scanf("%s", &userName) editUserInfo(userName) }<file_sep>//write program using "iota" for the last 4 years and print it package main import ( "fmt" ) const ( y_1 = (2018 + iota) y_2 = (2018 + iota) y_3 = (2018 + iota) y_4 = (2018 + iota) ) func main () { fmt.Println(y_1) fmt.Println(y_2) fmt.Println(y_3) fmt.Println(y_4) }<file_sep>//create slice of slice of string ([][]string) package main import ( "fmt" ) func main () { var s_of_s_of_str [][]string s_of_s_of_str = make([][]string, 5, 10) x := []string{"Bhushan", "Makan", "Patil"} y := []string{"Jotsanabai", "Makan", "Patil"} s_of_s_of_str = [][]string{x,y} fmt.Println(s_of_s_of_str) }<file_sep>package main import ( "fmt" ) var x int var y string var z bool //q :-> The compiler assigned value to the variables , what these called? // ans :-> Zero value func main() { fmt.Println(x,"\n",y,"\n",z) fmt.Printf("%T\t%T\t%T\n", x,y,z) } <file_sep>//map exercise package main import ( "fmt" ) func main () { //map[kayType]valueType map_var := map[string]string {"1" : "Bhushan", "2" : "Makan", "3" : "Patil"} fmt.Println(map_var) for k, _ := range map_var { fmt.Println(k) if v, isset := map_var[k]; isset { fmt.Println(v) } } }<file_sep>package main import ( "fmt" ) func input(x []int, err error) []int { if err != nil { return x } var d int n, err := fmt.Scanf("%d", &d) if n == 1 { x = append(x, d) } return input(x, err) } func main() { fmt.Println("Enter Element :") x := input([]int{}, nil) fmt.Println(x,len(x)) PrintNGE(x) fmt.Println("PrintNGE_using_stack : ") PrintNGE_using_stack(x) } func PrintNGE(a []int) { for i := 0; i < len(a); i++ { next := -1; for j := i + 1; j < len(a); j++{ if a[j] > a[i] { next = a[j] break } } fmt.Println(a[i], "-.- ", next) } } type ( Stack struct { top *node length int } node struct { value interface{} prev *node } ) // Create a new stack func New() *Stack { return &Stack{nil,0} } // Return the number of items in the stack func (this *Stack) Len() int { return this.length } // View the top item on the stack func (this *Stack) Peek() interface{} { if this.length == 0 { return nil } return this.top.value } // Pop the top item of the stack and return it //func (this *Stack) Pop() interface{} { func (this *Stack) Pop() { if this.length == 0 { return } //n := this.top //this.top = n.prev this.top = this.top.prev this.length-- //return n.value } // Push a value onto the top of the stack func (this *Stack) Push(value interface{}) { n := &node{value,this.top} this.top = n this.length++ } func (this *Stack) Is_empty() bool { return this.length == 0 } func PrintNGE_using_stack(a []int) { s := New() for i := 0; i < len(a); i++ { if s.Is_empty() { s.Push(a[i]) continue } for ;(s.Is_empty() == false) && (s.Peek().(int) < a[i]); { fmt.Println(s.Peek().(int)," -.- ", a[i]) s.Pop() } s.Push(a[i]) } for ;!s.Is_empty(); { fmt.Println(s.Peek().(int), " -.- ", "-1") s.Pop() } }<file_sep>package userApp //var userInfoData user_info import ( "fmt" ) func NewUser() *user_info { user := new(user_info) user.userFristName = "" user.userLastName = "" user.userEmailID.emailID = make(map[precednce]string, 3) user.userEmailID.isvalidated = false user.userMobileNumber.mnumber = make(map[precednce] rune, 3) user.userMobileNumber.isvalidated = false user.userGender.male = false user.userGender.female = false user.userGender.other = false user.passWord = "" user.userName = "" return user } func (user_info u) Create_account() { fmt.print("You Want to Create new account [y/n]: ") var c string fmt.scanf("%s",&c) if c == "y" { fmt.println("Please feel below given info [* is mandetory] ") } } <file_sep>//struct in go package main import ( "fmt" ) type porson struct { first string last string age int city string } //Embedded struct type S_porson struct { porson isset bool } func main () { p1 := porson{ first: "Bhushan", last: "Patil", age: 26 , city: "Vishwanath", } var p2 porson p2.first = "Kavita" p2.last = "Patil" p2.age = 23 p2.city = "Vishwanath" fmt.Println(p1, p2) //embedded struc var p3 S_porson p3.first = "Makan" p3.last = "Patil" p3.age = 67 p3.city = "Vishwanath" p3.isset = true fmt.Println(p3) //anonymous struct : structure with no identifer s := struct { first string friend map[string]rune }{ first : "Bhushan", friend: map[string]rune { "kavita": 12345, "Dinesh" : 45345, "me": 342445, }, } fmt.Println(s.first) for k, v := range s.friend { fmt.Println(k,v) } }<file_sep>package main import ( "fmt" "runtime" ) func main() { fmt.Println("os : ", runtime.GOOS) fmt.Println("No . of CPUs : ", runtime.NumCPU()) }<file_sep>package main import ( "fmt" "encoding/json" "os" ) type user_info struct { Frist string Last string Email string Age int Mobilenumber rune } // convert go struct to json and snd to stdout using // func NewEncoder(w io.Writer) *Encoder // func (enc *Encoder) Encode(v interface{}) error // func (enc *Encoder) SetEscapeHTML(on bool) // func (enc *Encoder) SetIndent(prefix, indent string) func main () { u1 := user_info{ "Bhushan", "Patil", "<EMAIL>", 27, 123456789, } u2 := user_info{ "Dinesh", "Sonwane", "<EMAIL>", 30, 123456789, } var uesrs []user_info uesrs = []user_info{u1, u2} fmt.Println(uesrs) /*bs, err := json.Marshal(uesrs) if err != nil { fmt.Println(err) } fmt.Println(string(bs))*/ err := json.NewEncoder(os.Stdout).Encode(uesrs) if err != nil { fmt.Println(err) } }<file_sep>package main import ( "fmt" ) //create your own type using "type" keyword type own_t int var x own_t func main () { x = 43 fmt.Println(x) fmt.Printf(" Type of the variable is : %T\n", x) }<file_sep>//write a program to show "if statemate" in action package main import ( "fmt" ) func main() { if true { fmt.Println("if in action....!") } }<file_sep>package main import ( "fmt" ) const PI float64 = 3.14159 //square type square struct{ side float64 } type circle struct{ radius float64 } func (c circle) area() float64{ return (PI * (c.radius * c.radius)) } func (s square) area() float64{ return (s.side * s.side) } type shape interface{ area() float64 } func math_func(a shape) { switch a.(type) { case circle: fmt.Println("circle Radius is : ", a.(circle).radius) case square: fmt.Println("square side is : ", a.(square).side) } fmt.Println("Area is : ", a.area()) } func main () { var c circle c.radius = 3 var s square s.side = 4 math_func(c) math_func(s) }<file_sep>//write programe to use all reletinal/conditinal opratore of go package main import ( "fmt" ) func main() { a := (43 == 43) b := (43 <= 45) c := (43 >= 30) d := (43 != 43) e := (43 > 43) f := (43 < 43) fmt.Printf("%t\t%t\t%t\t%t\t%t\t%t\t\n",a,b,c,d,e,f) }<file_sep>package main import ( "fmt" ) func main() { //fmt.Println(foo()()) x := foo() fmt.Printf("%T\n", x) fmt.Println(x()) } //function that returns function func foo() func() int{ fmt.Println("I am in foo\n") return func()int{ return 1995 } }<file_sep>// wirte program define TYPE and UNTYPE const and print it's value and type package main import ( "fmt" ) const PI = 3.14 const ( a int = iota b float64 = 0.0 c string = "" d byte = 0 e rune = 0 ) func main () { fmt.Println(PI) fmt.Printf("%T\n", PI) fmt.Println(a,b,c,d,e) fmt.Printf("%T\n%T\n%T\n%T\n%T\n",a,b,c,d,e) }<file_sep>package main import ( "fmt" ) func main() { bd := 1995 i := 0 for { if bd > 2080 { break } fmt.Println(i, " :- ",bd) bd++; i++ } }
83bbb05a3415fce4c3c1dd396d0c4e3da6bf186d
[ "Go" ]
54
Go
bhushanwankhede/Go_workspace
0a2121849162aef8d7a853a55b8583bab4a86e74
dda25767e9a1604fbbdacc0f5f894fa422f5d375
refs/heads/master
<file_sep>/* * The MIT License (MIT) * * Copyright (c) 2015 baoyongzhang <<EMAIL>> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.baoyz.smirk; import android.content.Context; import com.baoyz.smirk.exception.SmirkManagerNotFoundException; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import dalvik.system.DexFile; /** * Created by baoyz on 15/10/27. */ public class Smirk { public static final String MANAGER_SUFFIX = "$$SmirkManager"; private Map<DexFile, ExtensionClassLoader> mDexFiles; private Context mContext; private Map<String, SmirkManager> mManagerCache; public Smirk(Context context, Map<DexFile, ExtensionClassLoader> dexFiles) { mDexFiles = dexFiles; mContext = context; mManagerCache = new HashMap<>(); } public <T> T create(Class<T> clazz) { SmirkManager manager = findExtensionManager(clazz); if (clazz.isInstance(manager)) { return (T) manager; } return null; } private <T> SmirkManager findExtensionManager(Class<T> clazz) { String className = clazz.getCanonicalName() + MANAGER_SUFFIX; SmirkManager manager = mManagerCache.get(className); if (manager != null) { return manager; } try { manager = (SmirkManager) Class.forName(className).newInstance(); List<T> extensionInstances = findExtensionInstances(clazz); manager.putAll(extensionInstances); return manager; } catch (ClassNotFoundException e) { e.printStackTrace(); throw new SmirkManagerNotFoundException(className); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } return null; } private <T> List<T> findExtensionInstances(Class<T> clazz) { List<Class<T>> classList = findSubClasses(clazz); List<T> list = new ArrayList<>(); for (Class<T> cla : classList) { try { list.add(cla.newInstance()); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } return list; } private <T> List<Class<T>> findSubClasses(Class<T> clazz) { List<Class<T>> list = new ArrayList<>(); Set<Map.Entry<DexFile, ExtensionClassLoader>> entries = mDexFiles.entrySet(); for (Map.Entry<DexFile, ExtensionClassLoader> dexEntry : entries) { list.addAll(findSubClassesFromDexFile(dexEntry, clazz)); } return list; } private <T> List<Class<T>> findSubClassesFromDexFile(Map.Entry<DexFile, ExtensionClassLoader> dexEntry, Class<T> clazz) { List<Class<T>> list = new ArrayList<>(); Enumeration<String> entries = dexEntry.getKey().entries(); while (entries.hasMoreElements()) { String name = entries.nextElement(); Class cla = null; try { cla = dexEntry.getValue().loadClass(name); } catch (ClassNotFoundException e) { e.printStackTrace(); } if (cla == null) continue; if (clazz.isAssignableFrom(cla)) { list.add(cla); } } return list; } public static class Builder { private Context mContext; private Map<DexFile, ExtensionClassLoader> mDexFiles; public Builder(Context context) { mContext = context; mDexFiles = new HashMap<>(); } public Builder addDexPath(String dexPath) { loadDex(new File(dexPath)); return this; } public Builder addDexPath(File dexPath) { Map<DexFile, ExtensionClassLoader> map = loadDex(dexPath); if (map != null) { mDexFiles.putAll(map); } return this; } public Smirk build() { return new Smirk(mContext, mDexFiles); } private Map<DexFile, ExtensionClassLoader> loadDex(File dexPath) { if (dexPath == null || !dexPath.exists()) { return null; } Map<DexFile, ExtensionClassLoader> dexMap = new HashMap<>(); if (dexPath.isDirectory()) { File[] files = dexPath.listFiles(); for (File file : files) { if (file.isDirectory()) { dexMap.putAll(loadDex(file)); continue; } if (file.getName().endsWith(".dex")) { putDex(file.getAbsoluteFile(), dexMap); } } } else { if (dexPath.getName().endsWith(".dex")) { putDex(dexPath, dexMap); } } return dexMap; } private void putDex(File dexPath, Map<DexFile, ExtensionClassLoader> dexMap) { try { File outPath = mContext.getDir("smirk", 0); DexFile dexFile = DexFile.loadDex(dexPath.getAbsolutePath(), new File(outPath, dexPath.getName()).getAbsolutePath(), 0); ExtensionClassLoader classLoader = new ExtensionClassLoader(dexPath.getAbsolutePath(), outPath.getAbsolutePath(), null, mContext.getClassLoader()); dexMap.put(dexFile, classLoader); } catch (IOException e) { e.printStackTrace(); } } } } <file_sep>apply plugin: 'java' dependencies { compile fileTree(include: ['*.jar'], dir: 'libs') compile project(':smirk') compile 'com.squareup:javapoet:1.1.0' } apply from: rootProject.file('gradle/gradle-jcenter-push.gradle')<file_sep>Smirk =================== [ ![Travis CI](https://travis-ci.org/baoyongzhang/Smirk.svg?branch=master) ](https://travis-ci.org/baoyongzhang/Smirk) [ ![Download](https://api.bintray.com/packages/baoyongzhang/maven/Smirk/images/download.svg) ](https://bintray.com/baoyongzhang/maven/Smirk/_latestVersion) `Smirk`是一个Android运行时动态扩展库,其本质就是动态加载dex文件,`Smirk`进行了封装,可以很方便的完成动态dex的加载,以及调用。 ## 使用方法 ##### 1、定义接口 我们需要定义一套接口,因为扩展肯定是由主程序调用执行的,也就是主程序必须提前知道扩展程序有哪些方法,所以需要定义接口规范。例如: ```java @Extension public interface TextExtension { void showText(TextView textView); } ``` 这里定义了一个接口`TextExtension`,暴露了一个方法`showText(TextView textView)`,需要用`@Extension`注解修饰。 ##### 2、在是适当的地方调用扩展 我们必须在主程序需要的地方调用扩展,这里是动态加载的重点。由于我们在编写主程序的时候还不知道以后想要扩展什么功能,当我们想要添加扩展功能的时候,需要将新功能编译为一个dex文件,主程序把dex下载到本地,使用`Smirk`加载即可。 ```java // 加载dex,dexPath可以是一个dex文件,也可以是一个目录 // 如果dexPath是目录,会把目录中以及子目录中所有dex文件加载 Smirk smirk = new Smirk.Builder(context) .addDexPath(dexPath) .build(); // 通过之前定义的TextExtension接口创建一个扩展对象 TextExtension textExt = smirk.create(TextExtension.class); // 适当的地方,调用扩展 textExt.showText(textView); ``` 我们通过`Smirk.create()`方法创建了一个`TextExtension`对象,这个对象相当于是一个代理对象,当调用方法的时候,例如`textExt.showText(textView)`,会依次调用dex中所有实现了`TextExtension`接口类的对象的`showText(textView)`方法。 ##### 3、编写扩展功能 假设我们的App已经上线,现在想动态的增加一个功能,例如: ```java public class TextExtension1 implements TextExtension { @Override public void showText(TextView textView) { textView.setText("TextExtension1 执行"); } } ``` 我们编写了一个扩展类,实现了`TextExtension`,在`showText(TextView textView)`方法中将`textView`显示的文本设置为`TextExtension1 执行`。 当然我们编写多个`TextExtension`,写完之后,需要把扩展类文件编译为dex文件,然后主程序下载dex文件即可。 ## Demo <p> <img src="https://raw.githubusercontent.com/baoboy/image.baoboy.github.io/master/2015-10/smirk_demo.gif" width="320" alt="demo.gif"/> </p> ## Gradle ```groovy compile 'com.baoyz.smirk:smirk:0.1.0' provided 'com.baoyz.smirk:smirk-compiler:0.1.0' ``` ## 编译dex 当编写扩展程序的时候,我们可以在`AndroidStudio`中新建一个`Android Library`,下面是我自己写的脚本,用于编译dex文件,复制到`build.gradle`中。 ```groovy task buildDex(dependsOn: build, type: Exec) { Properties properties = new Properties() properties.load(project.rootProject.file('local.properties').newDataInputStream()) def sdkDir = properties.getProperty('sdk.dir') if (sdkDir == null || sdkDir.isEmpty()) { sdkDir = System.getenv("ANDROID_HOME") } def dx = "${sdkDir}/build-tools/${android.buildToolsVersion}/dx" def output = file("build/outputs/dex") output.mkdirs() commandLine dx args '--dex', "--output=${output}/${project.name}.dex", 'build/intermediates/bundles/release/classes.jar' } ``` 然后运行 ```shell $ ./gradlew buildDex ``` 成功之后,会在`build/outputs/dex`目录中生成一个dex文件。 (Gradle我并不熟悉,如果有更好的写法感谢指正) ## 感谢 [javapoet](https://github.com/square/javapoet) License ======= The MIT License (MIT) Copyright (c) 2015 baoyongzhang <<EMAIL>> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. <file_sep>apply plugin: 'java' apply plugin: 'idea' configurations { provided } sourceSets.main.compileClasspath += [configurations.provided] idea { module{ scopes.PROVIDED.plus += [configurations.provided] } } dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) provided 'com.google.android:android:+' } apply from: rootProject.file('gradle/gradle-jcenter-push.gradle')<file_sep>language: android jdk: oraclejdk7 env: matrix: - ANDROID_TARGET=android-23 android: components: - build-tools-23.0.0 - build-tools-23.0.1 - android-23 - extra-android-m2repository - extra-android-support script: ./gradlew assembleDebug <file_sep>task buildDex(dependsOn: build, type: Exec) { Properties properties = new Properties() try { properties.load(project.rootProject.file('local.properties').newDataInputStream()) } catch (Exception e) { } def sdkDir = properties.getProperty('sdk.dir') if (sdkDir == null || sdkDir.isEmpty()) { sdkDir = System.getenv("ANDROID_HOME") } def dx = "${sdkDir}/build-tools/${android.buildToolsVersion}/dx" def output = file("build/outputs/dex") output.mkdirs() commandLine dx args '--dex', "--output=${output}/${project.name}.dex", 'build/intermediates/bundles/release/classes.jar' }
c2167903b9aadc6db7ee7d45acfced4fb94a5068
[ "Java", "Markdown", "Gradle", "YAML" ]
6
Java
baoyongzhang/Smirk
862033876ff20f2d7a9bc91f9cc2271374aa2a41
ef3f42bc69f425d5fe6bdfd9bdb81c1de829159a
refs/heads/master
<file_sep>Given a number N, both players subtract a factor of N from it turn by turn until one of the players can't do so anymore. That is : After subtracting a factor : N := N-K , where K is a factor of N. You're playing against the computer so it always plays to win!<file_sep>#include<bits/stdc++.h> using namespace std; vector<int>factor[501]; void get_factors() { int i,j; for(i=1;i<=500;i++) { for(j=i;j<=500;j+=i) { factor[j].push_back(i); } } } //Take n between 1-500 int main() { int n,i,x,user,toss; char ans; srand (time(NULL)); cout<<"Let's have a toss for who plays first. Choose Heads(H) or Tails(T): "; cin>>ans; toss = rand() % 2; switch(toss) { case 0: cout<<"It was Tails\n"; break; case 1: cout<<"It was Heads\n"; break; } n = rand() % 500 + 1; cout<<"n = "<<n<<endl; get_factors(); if(toss==1 && ans=='H' || toss==0 && ans=='T') // user starts first { if(n==1) { cout<<"Can't subtract 1 from itself. You lost, Hahaha! :P"<<endl; return 0; } cout<<"Choose a factor of n to subtract from it: \n"; for(x=0;x<factor[n].size()-1;x++) { cout<<factor[n][x]<<" "; } cout<<endl; cin>>user; n-=user; cout<<"Now n becomes "<<n<<endl; } for(i=1;;i++) { if(i%2==1) //comp chance { if(n==1) { cout<<"Can't subtract 1 from itself. I lost, Congratulations :/"<<endl; break; } else if(n%2==0) { for(x=factor[n].size()-1;x>=0;x--) { if(factor[n][x]%2==1) { cout<<"I subtract "<<factor[n][x]<<" from "<<n<<"."; n-=factor[n][x]; cout<<"Now you get "<<n<<endl; break; } } } else { x=factor[n].size()-2; cout<<"I subtract "<<factor[n][x]<<" from "<<n<<"."; n-=factor[n][x]; cout<<"Now you get "<<n<<endl; } } else //user chance { if(n==1) { cout<<"Can't subtract 1 from itself. You lost, Hahaha! :P"<<endl; break; } cout<<"Choose a factor of n to subtract from it: \n"; for(x=0;x<factor[n].size()-1;x++) { cout<<factor[n][x]<<" "; } cout<<endl; cin>>user; n-=user; cout<<"Now n becomes "<<n<<endl; } } return 0; }
454f09c15a6e0078725dd2afec8ec8872ff43eb2
[ "Markdown", "C++" ]
2
Markdown
OrionStar25/Factor_Game
f97faafb2179c45aa305003b2e8da14513738f51
f457d6c75e34e0c083836002473a8c52a7c2e1f8
refs/heads/master
<file_sep># hello-world WADDUP BROSKIES!!! I am Joe, learning how to use github. I love programming and learning in general.
a71cc2a8c91fb6dc0fa99d28fde0c14e0d7894b3
[ "Markdown" ]
1
Markdown
kylekatarn/hello-world
eaa7886434137040b6447577fd739d0406c6732b
cd92b7708b8fd1ec340c8ab37969c3e489ff33c0
refs/heads/master
<repo_name>mchrapek/studia-projekt-zespolowy-backend<file_sep>/gateway-service/src/main/resources/application-dev.properties eureka.client.service-url.defaultZone=http://eureka:8761/eureka/ eureka.instance.prefer-ip-address=true server.ssl.enabled=true server.ssl.key-store=classpath:progzesp.p12 server.ssl.key-store-password=${KEY_STORE_PASSWORD} server.ssl.key-password=${KEY_PASSWORD} server.ssl.key-alias=progzesp<file_sep>/common/src/main/java/com/journeyplanner/common/config/paths/Paths.java package com.journeyplanner.common.config.paths; public class Paths { public final static String[] GET_PERMIT_ALL_PATHS = { "/catalogue", "/catalogue/photos/**", "/catalogue/journeys", "/catalogue/journeys/{\\w+}/photos", "/catalogue/photos/{\\w+}", "/reservations/journey/{\\w+}" }; public final static String[] POST_PERMIT_ALL_PATHS = { "/users/register", "/users/reset", "/users/password" }; public final static String[] PUT_PERMIT_ALL_PATHS = { }; public final static String[] GET_USER_PATHS = { "/users/details", "/users/avatar", "/reservations", "/reservations/**", "/billing/payments/**", "/billing/accounts", "/billing/accounts/charge" }; public final static String[] POST_USER_PATHS = { "/users/details", "/users/avatar", "/billing/payments/**", "/catalogue/journeys/{\\w+}/reservation" }; public final static String[] DELETE_USER_PATHS = { "/reservations/**" }; public final static String[] GET_ADMIN_PATHS = { "/users", "/users/details/**", "/users/guides" }; public final static String[] POST_ADMIN_PATHS = { "/users/block", "/users/reset/request", "/register/guides", "/catalogue/journeys", "/catalogue/journeys/{\\w+}/photos" }; public final static String[] PUT_ADMIN_PATHS = { "/catalogue/journeys/{\\w+}", "/catalogue/journeys/{\\w+}/guides" }; public final static String[] DELETE_ADMIN_PATHS = { "/users/block", "/catalogue/journeys/**" }; public final static String[] GET_GUIDE_PATHS = { "/catalogue/journeys/{\\w+}/guides" }; } <file_sep>/user-service/src/test/groovy/com/journeyplanner/user/domain/user/ResetTokenMotherObject.groovy package com.journeyplanner.user.domain.user import com.journeyplanner.user.domain.password.ResetToken class ResetTokenMotherObject { static aResetToken(String email) { ResetToken.builder() .token(UUID.randomUUID().toString()) .email(email) .active(Boolean.TRUE) .build() } } <file_sep>/user-service/src/test/groovy/com/journeyplanner/user/ApplicationTestConfig.groovy package com.journeyplanner.user import com.journeyplanner.user.app.UserServiceApplication import com.journeyplanner.user.infrastructure.output.queue.MailSender import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.boot.test.autoconfigure.data.mongo.AutoConfigureDataMongo import org.springframework.boot.test.mock.mockito.MockBean import org.springframework.context.annotation.ComponentScan import org.springframework.context.annotation.FilterType import org.springframework.data.mongodb.repository.config.EnableMongoRepositories import org.springframework.test.context.TestPropertySource @SpringBootApplication @ComponentScan( basePackages = [ "com.journeyplanner.user", "com.journeyplanner.common.config.security" ], excludeFilters = [ @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = MailSender.class), @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = UserServiceApplication.class) ] ) @TestPropertySource(locations = "classpath:test.properties") @AutoConfigureDataMongo @EnableMongoRepositories(basePackages = "com.journeyplanner.user.domain") class ApplicationTestConfig { @MockBean MailSender mailSender } <file_sep>/catalogue-service/src/test/groovy/com/journeyplanner/catalogue/domain/journey/CancelJourneySpec.groovy package com.journeyplanner.catalogue.domain.journey import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc import org.springframework.boot.test.context.SpringBootTest import org.springframework.test.annotation.DirtiesContext import org.springframework.test.web.servlet.MockMvc import spock.lang.Specification import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status @SpringBootTest @DirtiesContext @AutoConfigureMockMvc class CancelJourneySpec extends Specification { @Autowired private MockMvc mvc @Autowired private JourneyRepository journeyRepository def setup() { journeyRepository.deleteAll() } def "should cancel journey"() { given: def journey = JourneyMotherObject.aJourney() journeyRepository.save(journey) when: mvc.perform(delete("/catalogue/journeys/" + journey.getId())) .andExpect(status().isNoContent()) .andReturn() then: journeyRepository.findById(journey.getId()).get().status == JourneyStatus.INACTIVE } } <file_sep>/payment-service/src/main/java/com/journeyplanner/payment/domain/account/AccountHistoryCreator.java package com.journeyplanner.payment.domain.account; import java.math.BigDecimal; import java.time.Instant; import java.util.UUID; class AccountHistoryCreator { AccountHistory chargeEvent(final String accountId, final BigDecimal value) { return AccountHistory.builder() .id(UUID.randomUUID().toString()) .accountId(accountId) .createdTime(Instant.now()) .type(AccountEventType.CHARGE) .value(value) .build(); } AccountHistory loadEvent(final String accountId, final Transfer transfer) { return AccountHistory.builder() .id(UUID.randomUUID().toString()) .accountId(accountId) .createdTime(transfer.getEventTime()) .type(AccountEventType.LOAD) .value(transfer.getValue()) .build(); } AccountHistory returnEvent(final String accountId, final Transfer transfer) { return AccountHistory.builder() .id(UUID.randomUUID().toString()) .accountId(accountId) .createdTime(transfer.getEventTime()) .type(AccountEventType.RETURN) .value(transfer.getValue()) .build(); } } <file_sep>/reservation-service/src/main/java/com/journeyplanner/reservation/domain/reservation/CancelJourneyRuleCustomRepositoryImpl.java package com.journeyplanner.reservation.domain.reservation; import lombok.AllArgsConstructor; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.data.mongodb.core.query.Query; import org.springframework.data.mongodb.core.query.Update; @AllArgsConstructor public class CancelJourneyRuleCustomRepositoryImpl implements CancelJourneyRuleCustomRepository { private MongoTemplate mongoTemplate; @Override public void updateCancelJourneyRuleStatusTo(final String id, final CancelJourneyRuleStatus status) { Query query = new Query(); query.addCriteria(Criteria.where("id").is(id)); Update update = new Update(); update.set("status", status); mongoTemplate.updateFirst(query, update, CancelJourneyRule.class); } } <file_sep>/catalogue-service/src/test/groovy/com/journeyplanner/catalogue/domain/photo/AddPhotoSpec.groovy package com.journeyplanner.catalogue.domain.photo import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc import org.springframework.boot.test.context.SpringBootTest import org.springframework.mock.web.MockMultipartFile import org.springframework.test.annotation.DirtiesContext import org.springframework.test.web.servlet.MockMvc import spock.lang.Specification import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.multipart import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status @SpringBootTest @DirtiesContext @AutoConfigureMockMvc class AddPhotoSpec extends Specification { @Autowired private MockMvc mvc @Autowired private PhotoRepository photoRepository def setup() { photoRepository.deleteAll() } def "should add photo"() { given: def journeyId = UUID.randomUUID().toString() def request = new MockMultipartFile("image", "AVATAR".getBytes()) when: mvc.perform(multipart("/catalogue/journeys/" + journeyId + "/photos") .file(request)) .andExpect(status().isOk()) .andReturn() then: photoRepository.findAllByJourneyId(journeyId).size() == 1 } def "should add photos"() { given: def journeyId = UUID.randomUUID().toString() def request = new MockMultipartFile("image", "AVATAR".getBytes()) when: mvc.perform(multipart("/catalogue/journeys/" + journeyId + "/photos") .file(request)) .andExpect(status().isOk()) .andReturn() and: mvc.perform(multipart("/catalogue/journeys/" + journeyId + "/photos") .file(request)) .andExpect(status().isOk()) .andReturn() then: photoRepository.findAllByJourneyId(journeyId).size() == 2 } } <file_sep>/.github/workflows/maven.yml # This workflow will build a Java project with Maven # For more information see: https://help.github.com/actions/language-and-framework-guides/building-and-testing-java-with-maven name: Java CI with Maven on: push: branches: [ master ] pull_request: branches: [ master ] jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - name: Set up JDK 1.8 uses: actions/setup-java@v1 with: java-version: 1.8 - name: Build run: ./build.sh - name: Test Auth-Service run: cd auth-service && ./test.sh - name: Test Catalogue-Service run: cd catalogue-service && ./test.sh - name: Test Mail-Service run: cd mail-service && ./test.sh - name: Test Payment-Service run: cd payment-service && ./test.sh - name: Test Reservation-Service run: cd reservation-service && ./test.sh - name: Test User-Service run: cd user-service && ./test.sh<file_sep>/user-service/src/main/java/com/journeyplanner/user/domain/avatar/AvatarFacade.java package com.journeyplanner.user.domain.avatar; import com.journeyplanner.user.domain.exceptions.CannotParseFile; import com.journeyplanner.user.domain.exceptions.ResourceNotFound; import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.web.multipart.MultipartFile; import static java.text.MessageFormat.format; @Slf4j @AllArgsConstructor public class AvatarFacade { private final AvatarRepository repository; private final AvatarCreator creator; public AvatarDto getByEmail(final String email) { return repository.findByEmail(email) .map(AvatarDto::from) .orElseThrow(() -> new ResourceNotFound(format("Cannot find avatar for : {0}", email))); } public void add(final String email, final MultipartFile file) { Avatar updatedAvatar = repository.findByEmail(email) .map(a -> creator.from(a.getId(), email, file)) .orElseGet(() -> creator.from(email, file)) .orElseThrow(() -> new CannotParseFile(format("Cannot parse avatar for journey : {0} : ", email))); repository.save(updatedAvatar); log.info(format("Avatar for user {0} updated", email)); } } <file_sep>/user-service/src/main/java/com/journeyplanner/user/domain/user/UserConfiguration.java package com.journeyplanner.user.domain.user; import com.journeyplanner.user.domain.password.PasswordFacade; import com.journeyplanner.user.infrastructure.output.queue.MailSender; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration class UserConfiguration { @Bean UserFacade userFacade(UserRepository userRepository, MailSender mailSender, PasswordFacade passwordFacade) { return new UserFacade(userRepository, new UserCreator(), mailSender, passwordFacade); } } <file_sep>/user-service/src/main/java/com/journeyplanner/user/domain/user/UserDto.java package com.journeyplanner.user.domain.user; import lombok.Builder; import lombok.Value; @Value @Builder public class UserDto { String id; String email; String firstName; String secondName; String role; boolean isBlocked; boolean newPasswordRequired; static UserDto from(User user) { return UserDto.builder() .id(user.getId()) .email(user.getEmail()) .firstName(user.getFirstName()) .secondName(user.getSecondName()) .role(user.getRole()) .isBlocked(user.isBlocked()) .newPasswordRequired(user.isNewPasswordRequired()) .build(); } } <file_sep>/user-service/src/main/java/com/journeyplanner/user/domain/password/PasswordConfiguration.java package com.journeyplanner.user.domain.password; import com.journeyplanner.user.infrastructure.output.queue.MailSender; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.crypto.password.PasswordEncoder; @Configuration class PasswordConfiguration { @Bean PasswordFacade resetTokenFacade(ResetTokenRepository resetTokenRepository, MailSender mailSender, PasswordEncoder passwordEncoder) { return new PasswordFacade(resetTokenRepository, new ResetTokenCreator(), mailSender, passwordEncoder); } } <file_sep>/user-service/src/main/java/com/journeyplanner/user/domain/details/UserDetails.java package com.journeyplanner.user.domain.details; import lombok.Builder; import lombok.NonNull; import lombok.Value; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.index.Indexed; import org.springframework.data.mongodb.core.mapping.Document; @Value @Builder @Document(value = "userDetails") class UserDetails { @Id @NonNull String id; @Indexed(unique = true) @NonNull String email; @NonNull String country; @NonNull String city; @NonNull String street; @NonNull String postCode; @NonNull String phoneNumber; } <file_sep>/mail-service/src/main/java/com/journeyplanner/mail/domain/template/TemplateParser.java package com.journeyplanner.mail.domain.template; import io.vavr.control.Option; import java.util.Map; public interface TemplateParser { Option<String> parse(String templateName, Map<String, String> params); } <file_sep>/reservation-service/src/test/groovy/com/journeyplanner/reservation/ApplicationTest.groovy package com.journeyplanner.reservation import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.context.SpringBootTest import org.springframework.test.annotation.DirtiesContext import org.springframework.web.context.WebApplicationContext import spock.lang.Specification @SpringBootTest @DirtiesContext class ApplicationTest extends Specification { @Autowired private WebApplicationContext context def "should boot up without errors"() { expect: "web application context exists" context != null } } <file_sep>/reservation-service/src/main/java/com/journeyplanner/reservation/domain/reservation/CancelJourneyRuleCreator.java package com.journeyplanner.reservation.domain.reservation; import com.journeyplanner.common.config.events.CancelJourneyEvent; import java.time.Instant; import java.util.UUID; public class CancelJourneyRuleCreator { CancelJourneyRule from(final CancelJourneyEvent event) { return CancelJourneyRule.builder() .id(UUID.randomUUID().toString()) .journeyId(event.getJourneyId()) .createdTime(Instant.now()) .status(CancelJourneyRuleStatus.ACTIVE) .build(); } } <file_sep>/payment-service/src/test/groovy/com/journeyplanner/payment/domain/account/GetTransactionSpec.groovy package com.journeyplanner.payment.domain.account import com.journeyplanner.common.config.events.TransferType import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc import org.springframework.boot.test.context.SpringBootTest import org.springframework.test.annotation.DirtiesContext import org.springframework.test.web.servlet.MockMvc import spock.lang.Specification import java.time.Instant import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status @SpringBootTest @DirtiesContext @AutoConfigureMockMvc class GetTransactionSpec extends Specification { @Autowired private MockMvc mvc @Autowired private AccountRepository accountRepository @Autowired private AccountHistoryRepository accountHistoryRepository @Autowired private TransferRepository transferRepository @Autowired private TransferScheduler transferScheduler def setup() { accountRepository.deleteAll() accountHistoryRepository.deleteAll() transferRepository.deleteAll() } def "should get transaction details"() { given: def email = "<EMAIL>" def account = AccountMotherObject.aAccount(email, BigDecimal.TEN) accountRepository.save(account) and: def transfer = TransferMotherObject.aTransfer(email, TransferType.LOAD, BigDecimal.TEN) transferRepository.save(transfer) and: transferScheduler.fetch() when: def result = mvc.perform(get("/billing/payments/" + transfer.getPaymentId()) .header("x-username", email)) .andExpect(status().isOk()) .andReturn() then: result.response.getContentAsString().contains(transfer.getPaymentId()) } def "should get newest details"() { given: def email = "<EMAIL>" def account = AccountMotherObject.aAccount(email, BigDecimal.TEN) accountRepository.save(account) and: def transfer1 = Transfer.builder() .id(UUID.randomUUID().toString()) .email(email) .paymentId(UUID.randomUUID().toString()) .value(BigDecimal.ONE) .type(TransferType.RETURN) .status(TransferStatus.ERROR) .eventTime(Instant.now()) .build() transferRepository.save(transfer1) and: def transfer2 = Transfer.builder() .id(UUID.randomUUID().toString()) .email(email) .paymentId(transfer1.getPaymentId()) .value(BigDecimal.ONE) .type(TransferType.RETURN) .status(TransferStatus.DONE) .eventTime(Instant.now()) .build() transferRepository.save(transfer2) when: def result = mvc.perform(get("/billing/payments/" + transfer2.getPaymentId()) .header("x-username", email)) .andExpect(status().isOk()) .andReturn() then: result.response.getContentAsString().contains(transfer2.getPaymentId()) } } <file_sep>/payment-service/src/main/java/com/journeyplanner/payment/domain/account/AccountCreator.java package com.journeyplanner.payment.domain.account; import java.math.BigDecimal; import java.util.UUID; class AccountCreator { Account emptyAccount(String email) { return Account.builder() .id(UUID.randomUUID().toString()) .email(email) .balance(BigDecimal.ZERO) .build(); } } <file_sep>/payment-service/src/main/java/com/journeyplanner/payment/domain/account/AccountRepository.java package com.journeyplanner.payment.domain.account; import org.springframework.data.repository.Repository; import java.util.Optional; interface AccountRepository extends Repository<Account, String>, AccountCustomRepository { Optional<Account> findByEmail(String email); Account save(Account account); void deleteAll(); } <file_sep>/user-service/src/test/groovy/com/journeyplanner/user/domain/user/UserMotherObject.groovy package com.journeyplanner.user.domain.user import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder class UserMotherObject { static aUser(String email, String role = "USER", Boolean isBlocked = Boolean.FALSE) { User.builder() .id(UUID.randomUUID().toString()) .email(email) .firstName("FirstName") .secondName("SecondName") .password(new BCryptPasswordEncoder().encode("<PASSWORD>")) .role(role) .isBlocked(isBlocked) .build() } } <file_sep>/user-service/src/main/java/com/journeyplanner/user/domain/password/ResetTokenCustomRepositoryImpl.java package com.journeyplanner.user.domain.password; import lombok.AllArgsConstructor; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.data.mongodb.core.query.Query; import org.springframework.data.mongodb.core.query.Update; import java.util.Optional; @AllArgsConstructor public class ResetTokenCustomRepositoryImpl implements ResetTokenCustomRepository { private final MongoTemplate mongoTemplate; @Override public Optional<ResetToken> deprecateToken(final String token) { Query query = new Query(); query.addCriteria(Criteria.where("token").is(token)); Update update = new Update(); update.set("active", Boolean.FALSE); return Optional.ofNullable(mongoTemplate.findAndModify(query, update, ResetToken.class)); } } <file_sep>/user-service/src/test/groovy/com/journeyplanner/user/domain/user/GenerateResetPasswordTokenSpec.groovy package com.journeyplanner.user.domain.user import com.fasterxml.jackson.databind.ObjectMapper import com.journeyplanner.user.domain.password.ResetTokenRepository import com.journeyplanner.user.domain.user.UserRepository import com.journeyplanner.user.infrastructure.input.request.GenerateResetPasswordLinkRequest import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc import org.springframework.boot.test.context.SpringBootTest import org.springframework.test.annotation.DirtiesContext import org.springframework.test.web.servlet.MockMvc import spock.lang.Specification import javax.ws.rs.core.MediaType import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status @SpringBootTest @DirtiesContext @AutoConfigureMockMvc class GenerateResetPasswordTokenSpec extends Specification { @Autowired private MockMvc mvc @Autowired private ResetTokenRepository resetTokenRepository @Autowired private UserRepository userRepository def setup() { userRepository.deleteAll() resetTokenRepository.deleteAll() } def "should generate reset token password"() { given: def email = "<EMAIL>" def user = UserMotherObject.aUser(email) userRepository.save(user) and: def request = new GenerateResetPasswordLinkRequest(email) def json = new ObjectMapper().writeValueAsString(request) when: mvc.perform(post("/users/reset") .contentType(MediaType.APPLICATION_JSON) .content(json)) .andExpect(status().isNoContent()) .andReturn() then: resetTokenRepository.findByEmail(email).size() == 1 } def "should fail when generating token for non exists user"() { given: def email = "<EMAIL>" def request = new GenerateResetPasswordLinkRequest(email) def json = new ObjectMapper().writeValueAsString(request) when: mvc.perform(post("/reset") .contentType(MediaType.APPLICATION_JSON) .content(json)) .andExpect(status().is4xxClientError()) .andReturn() then: resetTokenRepository.findByEmail(email).size() == 0 } } <file_sep>/catalogue-service/src/test/groovy/com/journeyplanner/catalogue/domain/photo/PhotoMotherObject.groovy package com.journeyplanner.catalogue.domain.photo import org.bson.BsonBinarySubType import org.bson.types.Binary class PhotoMotherObject { static aPhoto(String journeyId, String content = "PHOTO") { Photo.builder() .id(UUID.randomUUID().toString()) .journeyId(journeyId) .image(new Binary(BsonBinarySubType.BINARY, content.getBytes())) .build() } } <file_sep>/user-service/src/test/groovy/com/journeyplanner/user/domain/user/BlockUserSpec.groovy package com.journeyplanner.user.domain.user import com.fasterxml.jackson.databind.ObjectMapper import com.journeyplanner.user.infrastructure.input.request.AddUserToBlacklistRequest import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc import org.springframework.boot.test.context.SpringBootTest import org.springframework.test.annotation.DirtiesContext import org.springframework.test.web.servlet.MockMvc import spock.lang.Specification import javax.ws.rs.core.MediaType import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status @SpringBootTest @DirtiesContext @AutoConfigureMockMvc class BlockUserSpec extends Specification { @Autowired private MockMvc mvc @Autowired private UserRepository userRepository def setup() { userRepository.deleteAll() } def "should block exists user"() { given: def email = "<EMAIL>" def user = UserMotherObject.aUser(email) userRepository.save(user) and: def request = new AddUserToBlacklistRequest(email) def json = new ObjectMapper().writeValueAsString(request) when: mvc.perform(post("/users/block") .contentType(MediaType.APPLICATION_JSON) .content(json)) .andExpect(status().isNoContent()) .andReturn() then: userRepository.findByEmail(email).get().blocked } def "should fail when blocking non exists user"() { given: def email = "<EMAIL>" and: def request = new AddUserToBlacklistRequest(email) def json = new ObjectMapper().writeValueAsString(request) when: mvc.perform(post("/users/block") .contentType(MediaType.APPLICATION_JSON) .content(json)) .andExpect(status().is4xxClientError()) .andReturn() then: !userRepository.existsByEmail(email) } } <file_sep>/README.md # Studia - Projekt Zespolowy - Backend ## Projekt - System do rezerwacji wycieczek # Table of contents 1. [Wymagania](#wymagania) 2. [Uruchomienie](#uruchomienie) 3. [Zasoby](#zasoby) 4. [Event Storming - Big Picture](#event-storming---big-picture-event-storming) 5. [Architektura](#architektura) 6. [Agile Personas](#agile-personas) --- ### Wymagania Do uruchomienia projektu niezbędny jest: `maven` oraz `docker-compose` --- ### Uruchomienie * Wykonanie skryptu `build.sh`. * W głównym katalogu projektu wykonanie komendy `docker-compose build`, a następnie `docker-compose up`. --- ### Zasoby * **MongoDB:** host: `locahost` port: `27017` * **Panel administracyjny RabbitMq:** `http://localhost:15672/` user: `guest` password: `<PASSWORD>` * **MailHog:** `http://localhost:8025/` * **Eureka Server:** `http://localhost:8761/` * **Grafan Dashboard:** `http://localhost:3000/` user: `admin` password: `<PASSWORD>` plik z dashboard'em: `monitoring/jvm-micrometer_rev8.json` * **Default Gateway:** ``http://localhost:8762/`` * **Swagger:** ``http://localhost:9115/swagger-ui.html`` ``http://localhost:9105/swagger-ui.html`` ``http://localhost:9120/swagger-ui.html`` ``http://localhost:9125/swagger-ui.html`` --- ### Event Storming - Big Picture ![Image event-storming-big-picture](docs/event-storming-big-picture.png) ---- ### Architektura #### Diagram: poziom C2 ![C2 diagram](docs/C4/C2.png) #### Diagram: poziom C3 ![C3 diagram](docs/C4/C3.png) ---- ### Agile Personas Admin: ![Admin](docs/agile_personas/admin.png) Username: `<EMAIL>` Password: `<PASSWORD>` Guide: ![Guide](docs/agile_personas/guide.png) Username: `<EMAIL>` Password: `<PASSWORD>` User: ![User](docs/agile_personas/user.png) Username: `<EMAIL>` Password: `<PASSWORD>` <file_sep>/catalogue-service/src/main/java/com/journeyplanner/catalogue/infrastructure/input/response/JourneyWithPhotoResponse.java package com.journeyplanner.catalogue.infrastructure.input.response; import com.journeyplanner.catalogue.domain.journey.Journey; import com.journeyplanner.catalogue.domain.journey.JourneyDto; import com.journeyplanner.catalogue.domain.journey.JourneyStatus; import lombok.Builder; import lombok.Value; import java.math.BigDecimal; import java.time.Instant; import java.util.List; @Value @Builder public class JourneyWithPhotoResponse { String id; String name; String country; JourneyStatus status; String city; String description; String transportType; BigDecimal price; Instant start; Instant end; String guideEmail; String guideName; List<String> photoIds; public static JourneyWithPhotoResponse from(final JourneyDto journey, final List<String> photoIds) { return JourneyWithPhotoResponse.builder() .id(journey.getId()) .status(journey.getStatus()) .name(journey.getName()) .country(journey.getCountry()) .city(journey.getCity()) .description(journey.getDescription()) .transportType(journey.getTransportType()) .price(journey.getPrice()) .start(journey.getStart()) .end(journey.getEnd()) .guideEmail(journey.getGuideEmail()) .guideName(journey.getGuideName()) .photoIds(photoIds) .build(); } } <file_sep>/reservation-service/src/main/java/com/journeyplanner/reservation/domain/reservation/CancelJourneyRuleCustomRepository.java package com.journeyplanner.reservation.domain.reservation; interface CancelJourneyRuleCustomRepository { void updateCancelJourneyRuleStatusTo(String id, CancelJourneyRuleStatus status); } <file_sep>/user-service/src/main/java/com/journeyplanner/user/domain/user/UserCustomRepository.java package com.journeyplanner.user.domain.user; interface UserCustomRepository { void updatePassword(String email, String password); void changeIsBlacklisted(final String email, final boolean isBlocked); void changeNewPasswordRequired(final String email, final boolean newPasswordRequired); } <file_sep>/gateway-service/src/main/java/com/journeyplanner/gateway/security/AuthenticationZuulFilter.java package com.journeyplanner.gateway.security; import com.netflix.zuul.ZuulFilter; import com.netflix.zuul.context.RequestContext; import com.netflix.zuul.exception.ZuulException; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; public class AuthenticationZuulFilter extends ZuulFilter { @Override public String filterType() { return "pre"; } @Override public int filterOrder() { return 1; } @Override public boolean shouldFilter() { return true; } @Override public Object run() throws ZuulException { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (authentication != null) { if (!authentication.getPrincipal().toString().equals("anonymousUser")) { RequestContext ctx = RequestContext.getCurrentContext(); ctx.addZuulRequestHeader("x-username", authentication.getPrincipal().toString()); } } return null; } } <file_sep>/mail-service/src/main/resources/application-email.properties mail.auth.enable=false mail.username= mail.password= mail.port=1025 mail.protocol=smtp mail.host=mailhog mail.starttls.enable=false mail.debug.enable=true<file_sep>/user-service/src/main/java/com/journeyplanner/user/domain/password/ResetTokenCreator.java package com.journeyplanner.user.domain.password; import java.util.UUID; class ResetTokenCreator { ResetToken from(final String email) { return ResetToken.builder() .token(UUID.randomUUID().toString()) .email(email) .active(Boolean.TRUE) .build(); } } <file_sep>/mail-service/src/main/java/com/journeyplanner/mail/config/QueueConfig.java package com.journeyplanner.mail.config; import org.springframework.amqp.core.Queue; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class QueueConfig { @Bean public Queue mailQueue(@Value("${queue.mail.name}") String mailQueue) { return new Queue(mailQueue, true); } } <file_sep>/reservation-service/src/main/java/com/journeyplanner/reservation/infrastructure/input/ReservationController.java package com.journeyplanner.reservation.infrastructure.input; import com.journeyplanner.reservation.domain.reservation.ReservationDto; import com.journeyplanner.reservation.domain.reservation.ReservationFacade; import com.journeyplanner.reservation.domain.users.BasicInfoUser; import com.journeyplanner.reservation.domain.users.UserFetcher; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.util.List; import java.util.stream.Collectors; @RestController @RequestMapping("reservations") @Slf4j @AllArgsConstructor @Api(tags = "ReservationAPI") public class ReservationController { public ReservationFacade reservationFacade; public UserFetcher userFetcher; @GetMapping @ApiOperation(value = "Get User Reservations", notes = "User") public ResponseEntity<List<ReservationDto>> getUserReservation(@RequestHeader("x-username") String username) { return ResponseEntity.ok(reservationFacade.getUserReservation(username)); } @DeleteMapping("{id}") @ResponseStatus(HttpStatus.NO_CONTENT) @ApiOperation(value = "Cancel Reservation", notes = "User") public void cancelReservation(@RequestHeader("x-username") String username, @PathVariable("id") String reservationId) { reservationFacade.cancelByUser(username, reservationId); } @GetMapping("journey/{journeyId}") @ApiOperation(value = "Get Users for Journey", notes = "Guide") public ResponseEntity<List<BasicInfoUser>> getUsersForJourney(@PathVariable("journeyId") String journeyId) { List<BasicInfoUser> users = reservationFacade.getAllUserEmailsForJourney(journeyId) .stream() .map(e -> userFetcher.fetch(e)) .collect(Collectors.toList()); return ResponseEntity.ok(users); } } <file_sep>/catalogue-service/src/main/java/com/journeyplanner/catalogue/domain/journey/JourneyStatus.java package com.journeyplanner.catalogue.domain.journey; public enum JourneyStatus { ACTIVE,INACTIVE; } <file_sep>/user-service/src/test/groovy/com/journeyplanner/user/domain/user/GetUserSpec.groovy package com.journeyplanner.user.domain.user import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc import org.springframework.boot.test.context.SpringBootTest import org.springframework.test.annotation.DirtiesContext import org.springframework.test.web.servlet.MockMvc import spock.lang.Specification import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status @SpringBootTest @DirtiesContext @AutoConfigureMockMvc class GetUserSpec extends Specification { @Autowired private MockMvc mvc @Autowired private UserRepository userRepository def setup() { userRepository.deleteAll() } def "should return first page with users"() { given: def user1 = UserMotherObject.aUser("<EMAIL>") def user2 = UserMotherObject.aUser("<EMAIL>") def user3 = UserMotherObject.aUser("<EMAIL>") userRepository.save(user1) userRepository.save(user2) userRepository.save(user3) when: def result = mvc.perform(get("/users")) .andExpect(status().isOk()) .andReturn() then: result.response.getContentAsString().contains("\"pageNumber\":0") result.response.getContentAsString().contains("\"totalPages\":1") result.response.getContentAsString().contains("\"pageSize\":10") result.response.getContentAsString().contains("\"offset\":0") result.response.getContentAsString().concat("\"numberOfElements\":3") } def "should return first page with two users"() { given: def user1 = UserMotherObject.aUser("<EMAIL>") def user2 = UserMotherObject.aUser("<EMAIL>") def user3 = UserMotherObject.aUser("<EMAIL>") userRepository.save(user1) userRepository.save(user2) userRepository.save(user3) when: def result = mvc.perform(get("/users/?page=0&size=2")) .andExpect(status().isOk()) .andReturn() then: result.response.getContentAsString().contains("\"pageNumber\":0") result.response.getContentAsString().contains("\"totalPages\":2") result.response.getContentAsString().contains("\"pageSize\":2") result.response.getContentAsString().contains("\"offset\":0") result.response.getContentAsString().concat("\"numberOfElements\":2") } def "should get first page with email"() { given: def user1 = UserMotherObject.aUser("<EMAIL>") def user2 = UserMotherObject.aUser("<EMAIL>") def user3 = UserMotherObject.aUser("<EMAIL>") userRepository.save(user1) userRepository.save(user2) userRepository.save(user3) when: def result = mvc.perform(get("/users/?email=aragorn")) .andExpect(status().isOk()) .andReturn() then: result.response.getContentAsString().contains(user1.email) !result.response.getContentAsString().contains(user2.email) !result.response.getContentAsString().contains(user3.email) } def "should get first page with status"() { given: def user1 = UserMotherObject.aUser("<EMAIL>", "USER", Boolean.TRUE) def user2 = UserMotherObject.aUser("<EMAIL>") def user3 = UserMotherObject.aUser("<EMAIL>") userRepository.save(user1) userRepository.save(user2) userRepository.save(user3) when: def result = mvc.perform(get("/users/?isBlocked=false")) .andExpect(status().isOk()) .andReturn() then: !result.response.getContentAsString().contains(user1.email) result.response.getContentAsString().contains(user2.email) result.response.getContentAsString().contains(user3.email) } } <file_sep>/mail-service/src/test/groovy/com/journeyplanner/mail/ApplicationTestConfig.groovy package com.journeyplanner.mail import com.journeyplanner.mail.app.MailServiceApplication import com.journeyplanner.mail.config.QueueConfig import com.journeyplanner.mail.infrastructure.input.SendMailEventReceiver import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.boot.test.autoconfigure.data.mongo.AutoConfigureDataMongo import org.springframework.context.annotation.ComponentScan import org.springframework.context.annotation.FilterType import org.springframework.data.mongodb.repository.config.EnableMongoRepositories import org.springframework.test.context.TestPropertySource @SpringBootApplication @ComponentScan(basePackages = [ "com.journeyplanner.mail" ], excludeFilters = [ @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = MailServiceApplication.class), @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = QueueConfig.class), @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = SendMailEventReceiver.class) ]) @TestPropertySource(locations = "classpath:test.properties") @AutoConfigureDataMongo @EnableMongoRepositories(basePackages = "com.journeyplanner.mail.domain") class ApplicationTestConfig { } <file_sep>/catalogue-service/src/test/groovy/com/journeyplanner/catalogue/domain/journey/JourneyMotherObject.groovy package com.journeyplanner.catalogue.domain.journey import java.time.Instant import java.time.temporal.ChronoUnit class JourneyMotherObject { static aJourney(String id = UUID.randomUUID().toString(), String name = "NameJourney") { Journey.builder() .id(id) .name(name) .country("Country") .status(JourneyStatus.ACTIVE) .city("City") .description("Description") .transportType("PLAIN") .price(new BigDecimal(1000)) .start(Instant.now().plus(10, ChronoUnit.DAYS)) .end(Instant.now().plus(12, ChronoUnit.DAYS)) .guideName("") .guideEmail("") .build() } } <file_sep>/reservation-service/src/test/groovy/com/journeyplanner/reservation/domain/reservation/CancelReservationSpec.groovy package com.journeyplanner.reservation.domain.reservation import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc import org.springframework.boot.test.context.SpringBootTest import org.springframework.test.annotation.DirtiesContext import org.springframework.test.web.servlet.MockMvc import spock.lang.Specification import java.time.Instant import java.time.temporal.ChronoUnit import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status @SpringBootTest @DirtiesContext @AutoConfigureMockMvc class CancelReservationSpec extends Specification { @Autowired private MockMvc mvc @Autowired private ReservationRepository repository def setup() { repository.deleteAll(); } def "should cancel reservation"() { given: def email = "<EMAIL>" def reservation = ReservationMotherObject.aReservation(email) repository.save(reservation) when: mvc.perform(delete("/reservations/" + reservation.getId()) .header("x-username", email)) .andExpect(status().isNoContent()) .andReturn() then: repository.getReservationByEmail(email).get(0).id == reservation.getId() repository.getReservationByEmail(email).get(0).status == ReservationStatus.CANCEL } def "should fail when cancel reservation 14 days before"() { given: def email = "<EMAIL>" def reservation = ReservationMotherObject.aReservation(email, Instant.now().plus(2, ChronoUnit.DAYS)) repository.save(reservation) when: mvc.perform(delete("/reservations/" + reservation.getId()) .header("x-username", email)) .andExpect(status().is4xxClientError()) .andReturn() then: repository.getReservationByEmail(email).get(0).id == reservation.getId() repository.getReservationByEmail(email).get(0).status == ReservationStatus.ACTIVE } } <file_sep>/reservation-service/src/test/groovy/com/journeyplanner/reservation/ApplicationTestConfig.groovy package com.journeyplanner.reservation import com.journeyplanner.reservation.app.ReservationServiceApplication import com.journeyplanner.reservation.config.QueueConfig import com.journeyplanner.reservation.infrastructure.input.ReservationCreateEventReceiver import com.journeyplanner.reservation.infrastructure.output.MailSender import com.journeyplanner.reservation.infrastructure.output.PaymentCreator import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.boot.test.autoconfigure.data.mongo.AutoConfigureDataMongo import org.springframework.boot.test.mock.mockito.MockBean import org.springframework.context.annotation.ComponentScan import org.springframework.context.annotation.FilterType import org.springframework.data.mongodb.repository.config.EnableMongoRepositories import org.springframework.test.context.TestPropertySource @SpringBootApplication @ComponentScan( basePackages = [ "com.journeyplanner.reservation" ], excludeFilters = [ @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = QueueConfig.class), @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = MailSender.class), @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = ReservationCreateEventReceiver.class), @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = ReservationServiceApplication.class) ] ) @TestPropertySource(locations = "classpath:test.properties") @AutoConfigureDataMongo @EnableMongoRepositories(basePackages = "com.journeyplanner.reservation.domain") class ApplicationTestConfig { @MockBean MailSender mailSender @MockBean PaymentCreator paymentCreator } <file_sep>/common/src/main/java/com/journeyplanner/common/config/security/JwtProperties.java package com.journeyplanner.common.config.security; import lombok.Getter; @Getter public class JwtProperties { private final String uri; private final String secret; private final String header; private final String prefix; private final int expirationTime; public JwtProperties() { this.uri = "/auth/**"; this.secret = "SuperSecretToken"; this.header = "Authorization"; this.prefix = "Bearer"; this.expirationTime = 36000; } } <file_sep>/user-service/src/test/groovy/com/journeyplanner/user/domain/user/CreateUserSpec.groovy package com.journeyplanner.user.domain.user import com.fasterxml.jackson.databind.ObjectMapper import com.journeyplanner.user.infrastructure.input.request.CreateUserRequest import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc import org.springframework.boot.test.context.SpringBootTest import org.springframework.test.annotation.DirtiesContext import org.springframework.test.web.servlet.MockMvc import spock.lang.Specification import javax.ws.rs.core.MediaType import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status @SpringBootTest @DirtiesContext @AutoConfigureMockMvc class CreateUserSpec extends Specification { @Autowired private MockMvc mvc @Autowired private UserRepository userRepository def setup() { userRepository.deleteAll() } def "should create user"() { given: def email = "<EMAIL>" def request = new CreateUserRequest(email, "12345a", "Aragorn", "Obiezyswiat") def json = new ObjectMapper().writeValueAsString(request) when: mvc.perform(post("/users/register") .contentType(MediaType.APPLICATION_JSON) .content(json)) .andExpect(status().isNoContent()) .andReturn() then: userRepository.findByEmail("<EMAIL>").isPresent() } def "should fail when adding user with the same mail"() { given: def email = "<EMAIL>" def request = new CreateUserRequest(email, "12345a", "Aragorn", "Obiezyswiat") def json = new ObjectMapper().writeValueAsString(request) when: "first attempt" mvc.perform(post("/users/register") .contentType(MediaType.APPLICATION_JSON) .content(json)) .andExpect(status().isNoContent()) .andReturn() and: "second attempt" mvc.perform(post("/users/register") .contentType(MediaType.APPLICATION_JSON) .content(json)) .andExpect(status().is4xxClientError()) .andReturn() then: userRepository.findByEmail(email).isPresent() } } <file_sep>/reservation-service/src/test/groovy/com/journeyplanner/reservation/domain/reservation/CreateReservationSpec.groovy package com.journeyplanner.reservation.domain.reservation import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc import org.springframework.boot.test.context.SpringBootTest import org.springframework.test.annotation.DirtiesContext import spock.lang.Specification @SpringBootTest @DirtiesContext @AutoConfigureMockMvc class CreateReservationSpec extends Specification { @Autowired private ReservationFacade facade @Autowired private ReservationRepository repository def setup() { repository.deleteAll(); } def "should create new reservation"() { given: def email = "<EMAIL>" def createReservationEvent = CreateReservationMotherObject.aCreateReservation(email) when: facade.createNew(createReservationEvent) then: repository.findAll().size() == 1 } } <file_sep>/mail-service/src/test/groovy/com/journeyplanner/mail/domain/template/VelocityParserTest.groovy package com.journeyplanner.mail.domain.template import org.apache.velocity.app.VelocityEngine import spock.lang.Specification class VelocityParserTest extends Specification { private static final String TEMPLATE_NAME = "test.vm"; private VelocityEngine velocityEngine private VelocityParser velocityParser def setup() { VelocityConfig config = new VelocityConfig() velocityEngine = config.configVelocity() velocityParser = new VelocityParser(velocityEngine) } def "velocity engine should pass params to velocity template"() { given: def params = new HashMap<String, String>() params.put("firstName", "Indiana") when: def text = velocityParser.parse(TEMPLATE_NAME, params) then: text.isDefined() assert text.get().contains(params.get("firstName")) } } <file_sep>/payment-service/src/main/java/com/journeyplanner/payment/domain/account/AccountHistoryRepository.java package com.journeyplanner.payment.domain.account; import org.springframework.data.repository.Repository; import java.util.List; interface AccountHistoryRepository extends Repository<AccountHistory, String> { AccountHistory save(AccountHistory accountHistory); List<AccountHistory> findAllByAccountId(String accountId); void deleteAll(); } <file_sep>/auth-service/src/main/resources/application.properties spring.application.name=auth-service server.port=9100 management.endpoints.web.exposure.include=health,info,metrics,prometheus spring.profiles.active=local <file_sep>/payment-service/src/test/groovy/com/journeyplanner/payment/domain/account/ReturnTransactionSpec.groovy package com.journeyplanner.payment.domain.account import com.journeyplanner.common.config.events.TransferType import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc import org.springframework.boot.test.context.SpringBootTest import org.springframework.test.annotation.DirtiesContext import org.springframework.test.web.servlet.MockMvc import spock.lang.Specification import java.time.Instant import java.time.temporal.ChronoUnit @SpringBootTest @DirtiesContext @AutoConfigureMockMvc class ReturnTransactionSpec extends Specification { @Autowired private MockMvc mvc @Autowired private AccountRepository accountRepository @Autowired private AccountHistoryRepository accountHistoryRepository @Autowired private TransferRepository transferRepository @Autowired private TransferScheduler transferScheduler def setup() { accountRepository.deleteAll() accountHistoryRepository.deleteAll() transferRepository.deleteAll() } def "should create load transaction"() { given: def email = "<EMAIL>" def account = AccountMotherObject.aAccount(email) accountRepository.save(account) and: def transfer = TransferMotherObject.aTransfer(email, TransferType.RETURN) transferRepository.save(transfer) when: transferScheduler.fetch() then: transferRepository.findById(transfer.getId()).get().status == TransferStatus.DONE accountHistoryRepository.findAllByAccountId(account.getId()).size() == 1 accountRepository.findByEmail(email).get().balance == BigDecimal.TEN } def "should load older transaction"() { given: def email = "<EMAIL>" def account = AccountMotherObject.aAccount(email) accountRepository.save(account) and: def transfer1 = TransferMotherObject.aTransfer(email, TransferType.RETURN) transferRepository.save(transfer1) and: def transfer2 = TransferMotherObject.aTransfer(email, TransferType.RETURN, new BigDecimal(20.00), Instant.now().minus(10, ChronoUnit.MINUTES)) transferRepository.save(transfer2) when: transferScheduler.fetch() then: transferRepository.findById(transfer1.getId()).get().status == TransferStatus.PENDING transferRepository.findById(transfer2.getId()).get().status == TransferStatus.DONE accountHistoryRepository.findAllByAccountId(account.getId()).size() == 1 accountRepository.findByEmail(email).get().balance == new BigDecimal(20.00) } } <file_sep>/catalogue-service/src/test/groovy/com/journeyplanner/catalogue/domain/journey/CreateJourneySpec.groovy package com.journeyplanner.catalogue.domain.journey import com.fasterxml.jackson.databind.ObjectMapper import com.journeyplanner.catalogue.domain.journey.JourneyRepository import com.journeyplanner.catalogue.infrastructure.input.request.CreateJourneyRequest import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc import org.springframework.boot.test.context.SpringBootTest import org.springframework.data.mongodb.core.aggregation.ArrayOperators import org.springframework.test.annotation.DirtiesContext import org.springframework.test.web.servlet.MockMvc import spock.lang.Specification import javax.ws.rs.core.MediaType import java.time.Instant import java.time.temporal.ChronoUnit import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status @SpringBootTest @DirtiesContext @AutoConfigureMockMvc class CreateJourneySpec extends Specification { @Autowired private MockMvc mvc @Autowired private JourneyRepository journeyRepository def setup() { journeyRepository.deleteAll() } def "should create journey"() { given: def request = new CreateJourneyRequest("Name Journey", "Country", "CityCity", "Description", "PLAIN", new BigDecimal(1000), new Date(1614556800000), new Date(1614729600000)) def json = new ObjectMapper().writeValueAsString(request) when: def result = mvc.perform(post("/catalogue/journeys") .contentType(MediaType.APPLICATION_JSON) .content(json)) .andExpect(status().isOk()) .andReturn() then: result.response.getContentAsString().contains("2021-03-01") result.response.getContentAsString().contains("2021-03-03") } } <file_sep>/catalogue-service/src/test/groovy/com/journeyplanner/catalogue/domain/journey/UpdateJourneySpec.groovy package com.journeyplanner.catalogue.domain.journey import com.fasterxml.jackson.databind.ObjectMapper import com.journeyplanner.catalogue.infrastructure.input.request.UpdateJourneyRequest import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc import org.springframework.boot.test.context.SpringBootTest import org.springframework.test.annotation.DirtiesContext import org.springframework.test.web.servlet.MockMvc import spock.lang.Specification import javax.ws.rs.core.MediaType import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status @SpringBootTest @DirtiesContext @AutoConfigureMockMvc class UpdateJourneySpec extends Specification { @Autowired private MockMvc mvc @Autowired private JourneyRepository journeyRepository def setup() { journeyRepository.deleteAll() } def "should update journey"() { given: Journey journey = JourneyMotherObject.aJourney() journeyRepository.save(journey) and: def request = new UpdateJourneyRequest("NewName", journey.getCountry(), journey.getCity(), journey.getDescription(), journey.getTransportType(), journey.getPrice()) def json = new ObjectMapper().writeValueAsString(request) when: mvc.perform(put("/catalogue/journeys/" + journey.getId()) .contentType(MediaType.APPLICATION_JSON) .content(json)) .andExpect(status().isOk()) .andReturn() then: journeyRepository.findById(journey.getId()).get().getName() == request.getName() } } <file_sep>/monitoring/prometheus/prometheus.yml global: scrape_interval: 15s scrape_configs: - job_name: 'user' scrape_interval: 10s metrics_path: '/actuator/prometheus' static_configs: - targets: ['user:9105'] labels: application: 'user' - job_name: 'mail' scrape_interval: 10s metrics_path: '/actuator/prometheus' static_configs: - targets: ['mail:9110'] labels: application: 'mail' - job_name: 'gateway' scrape_interval: 10s metrics_path: '/actuator/prometheus' static_configs: - targets: ['gateway:8762'] labels: application: 'gateway' - job_name: 'catalogue' scrape_interval: 10s metrics_path: '/actuator/prometheus' static_configs: - targets: ['catalogue:9115'] labels: application: 'catalogue' - job_name: 'auth' scrape_interval: 10s metrics_path: '/actuator/prometheus' static_configs: - targets: ['auth:9100'] labels: application: 'auth' - job_name: 'reservation' scrape_interval: 10s metrics_path: '/actuator/prometheus' static_configs: - targets: ['reservation:9120'] labels: application: 'reservation' - job_name: 'payment' scrape_interval: 10s metrics_path: '/actuator/prometheus' static_configs: - targets: ['payment:9125'] labels: application: 'payment' <file_sep>/reservation-service/src/main/java/com/journeyplanner/reservation/domain/reservation/CancelJourneyRuleRepository.java package com.journeyplanner.reservation.domain.reservation; import org.springframework.data.repository.Repository; import java.util.List; interface CancelJourneyRuleRepository extends Repository<CancelJourneyRule, String>, CancelJourneyRuleCustomRepository { CancelJourneyRule save(CancelJourneyRule cancelJourney); List<CancelJourneyRule> findAllByStatus(CancelJourneyRuleStatus status); void deleteAll(); } <file_sep>/user-service/src/test/groovy/com/journeyplanner/user/domain/details/CreateDetailsSpec.groovy package com.journeyplanner.user.domain.details import com.fasterxml.jackson.databind.ObjectMapper import com.journeyplanner.user.infrastructure.input.request.UpdateUserDetailsRequest import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc import org.springframework.boot.test.context.SpringBootTest import org.springframework.test.annotation.DirtiesContext import org.springframework.test.web.servlet.MockMvc import spock.lang.Specification import javax.ws.rs.core.MediaType import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status @SpringBootTest @DirtiesContext @AutoConfigureMockMvc class CreateDetailsSpec extends Specification { @Autowired private MockMvc mvc @Autowired private UserDetailsRepository userDetailsRepository def setup() { userDetailsRepository.deleteAll() } def "should create user details"() { given: def email = "<EMAIL>" def request = new UpdateUserDetailsRequest("Country", "City", "Street", "00-000", "0001112222") def json = new ObjectMapper().writeValueAsString(request) when: mvc.perform(post("/users/details") .contentType(MediaType.APPLICATION_JSON) .header("x-username", email) .content(json)) .andExpect(status().isOk()) .andReturn() then: userDetailsRepository.findByEmail(email).get().email == email } def "should fail when creating details for non logged user"() { given: def email = "<EMAIL>" def request = new UpdateUserDetailsRequest("Country", "City", "Street", "00-000", "0001112222") def json = new ObjectMapper().writeValueAsString(request) when: mvc.perform(post("/users/details") .contentType(MediaType.APPLICATION_JSON) .content(json)) .andExpect(status().is4xxClientError()) .andReturn() then: !userDetailsRepository.findByEmail(email).isPresent() } def "should update user details"() { given: def email = "<EMAIL>" def userDetails = UserDetailsMotherObject.aUserDetails(email) userDetailsRepository.save(userDetails) and: def request = new UpdateUserDetailsRequest("Country", "City", "Street", "00-000", "0001112222") def json = new ObjectMapper().writeValueAsString(request) when: mvc.perform(post("/users/details") .contentType(MediaType.APPLICATION_JSON) .header("x-username", email) .content(json)) .andExpect(status().isOk()) .andReturn() then: userDetailsRepository.findByEmail(email).get().email == email userDetailsRepository.findByEmail(email).get().phoneNumber == request.getPhoneNumber() } } <file_sep>/reservation-service/src/test/groovy/com/journeyplanner/reservation/domain/reservation/CancelJourneySpec.groovy package com.journeyplanner.reservation.domain.reservation import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc import org.springframework.boot.test.context.SpringBootTest import org.springframework.test.annotation.DirtiesContext import org.springframework.test.web.servlet.MockMvc import spock.lang.Specification import java.time.Instant import java.time.temporal.ChronoUnit @SpringBootTest @DirtiesContext @AutoConfigureMockMvc class CancelJourneySpec extends Specification { @Autowired private MockMvc mvc @Autowired private ReservationRepository reservationRepository @Autowired private CancelJourneyRuleRepository cancelJourneyRuleRepository @Autowired private CancelJourneyScheduler scheduler def setup() { reservationRepository.deleteAll() cancelJourneyRuleRepository.deleteAll() } def "should cancel all reservations"() { given: def journeyId1 = UUID.randomUUID().toString() def journeyId2 = UUID.randomUUID().toString() def userEmail1 = "<EMAIL>" def userEmail2 = "<EMAIL>" def userEmail3 = "<EMAIL>" def reservation1 = ReservationMotherObject.aReservation(userEmail1, Instant.now().plus(10, ChronoUnit.DAYS), journeyId1) def reservation2 = ReservationMotherObject.aReservation(userEmail2, Instant.now().plus(10, ChronoUnit.DAYS), journeyId1) def reservation3 = ReservationMotherObject.aReservation(userEmail3, Instant.now().plus(10, ChronoUnit.DAYS), journeyId2) reservationRepository.save(reservation1) reservationRepository.save(reservation2) reservationRepository.save(reservation3) and: def rule = CancelJourneyRuleMotherObject.aRule(journeyId1) cancelJourneyRuleRepository.save(rule) when: scheduler.cancel() then: reservationRepository.findById(reservation1.getId()).get().status == ReservationStatus.CANCEL reservationRepository.findById(reservation2.getId()).get().status == ReservationStatus.CANCEL reservationRepository.findById(reservation3.getId()).get().status == ReservationStatus.ACTIVE cancelJourneyRuleRepository.findAllByStatus(CancelJourneyRuleStatus.ACTIVE).size() == 1 cancelJourneyRuleRepository.findAllByStatus(CancelJourneyRuleStatus.INACTIVE).size() == 0 } def "should deactivate rule after expiration time"() { given: def journeyId = UUID.randomUUID().toString() def userEmail = "<EMAIL>" def reservation = ReservationMotherObject.aReservation(userEmail, Instant.now().plus(10, ChronoUnit.DAYS), journeyId) reservationRepository.save(reservation) and: def rule = CancelJourneyRuleMotherObject.aRule(journeyId, Instant.now().plus(60, ChronoUnit.MINUTES)) cancelJourneyRuleRepository.save(rule) when: scheduler.cancel() then: reservationRepository.findById(reservation.getId()).get().status == ReservationStatus.CANCEL cancelJourneyRuleRepository.findAllByStatus(CancelJourneyRuleStatus.ACTIVE).size() == 0 cancelJourneyRuleRepository.findAllByStatus(CancelJourneyRuleStatus.INACTIVE).size() == 1 } } <file_sep>/auth-service/src/main/resources/application-local.properties spring.data.mongodb.host=localhost spring.data.mongodb.port=27017 spring.data.mongodb.auto-index-creation=true eureka.client.service-url.defaultZone=http://localhost:8761/eureka/ eureka.instance.prefer-ip-address=true <file_sep>/user-service/src/test/groovy/com/journeyplanner/user/domain/user/GetBasicUserInfoSpec.groovy package com.journeyplanner.user.domain.user import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc import org.springframework.boot.test.context.SpringBootTest import org.springframework.test.annotation.DirtiesContext import org.springframework.test.web.servlet.MockMvc import spock.lang.Specification import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status @SpringBootTest @DirtiesContext @AutoConfigureMockMvc class GetBasicUserInfoSpec extends Specification { @Autowired private MockMvc mvc @Autowired private UserRepository userRepository def setup() { userRepository.deleteAll() } def "should return user basic info"() { given: def user1 = UserMotherObject.aUser("<EMAIL>") userRepository.save(user1) when: def result = mvc.perform(get("/users/basic?email=" + user1.getEmail())) .andExpect(status().isOk()) .andReturn() then: result.response.getContentAsString().contains(user1.getFirstName()) } } <file_sep>/user-service/src/main/java/com/journeyplanner/user/app/UserServiceApplication.java package com.journeyplanner.user.app; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.eureka.EnableEurekaClient; import org.springframework.context.annotation.ComponentScan; import org.springframework.data.mongodb.repository.config.EnableMongoRepositories; @SpringBootApplication @ComponentScan(basePackages = { "com.journeyplanner.user.config", "com.journeyplanner.user.domain", "com.journeyplanner.user.infrastructure" }) @EnableEurekaClient @EnableMongoRepositories(basePackages = { "com.journeyplanner.user.domain" }) public class UserServiceApplication { public static void main(String[] args) { SpringApplication.run(UserServiceApplication.class, args); } } <file_sep>/auth-service/src/main/resources/application-dev.properties spring.data.mongodb.host=mongodb spring.data.mongodb.port=27017 spring.data.mongodb.auto-index-creation=true eureka.client.service-url.defaultZone=http://eureka:8761/eureka eureka.instance.prefer-ip-address=true<file_sep>/catalogue-service/src/main/java/com/journeyplanner/catalogue/domain/photo/Photo.java package com.journeyplanner.catalogue.domain.photo; import lombok.Builder; import lombok.NonNull; import lombok.Value; import org.bson.types.Binary; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; @Value @Builder @Document(collection = "photos") class Photo { @Id @NonNull String id; @NonNull String journeyId; @NonNull Binary image; } <file_sep>/user-service/src/test/groovy/com/journeyplanner/user/domain/details/GetDetailsSpec.groovy package com.journeyplanner.user.domain.details import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc import org.springframework.boot.test.context.SpringBootTest import org.springframework.test.annotation.DirtiesContext import org.springframework.test.web.servlet.MockMvc import spock.lang.Specification import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status @SpringBootTest @DirtiesContext @AutoConfigureMockMvc class GetDetailsSpec extends Specification { @Autowired private MockMvc mvc @Autowired private UserDetailsRepository userDetailsRepository def setup() { userDetailsRepository.deleteAll() } def "should return empty user details"() { given: def email = "<EMAIL>" when: def result = mvc.perform(get("/users/details") .header("x-username", email)) .andExpect(status().isOk()) .andReturn() then: result.response.getContentAsString().contains("\"country\":\"\"") } def "should return user details by email"() { given: def email = "<EMAIL>" def userDetails = UserDetailsMotherObject.aUserDetails(email) userDetailsRepository.save(userDetails) when: def result = mvc.perform(get("/users/details") .header("x-username", email)) .andExpect(status().isOk()) .andReturn() then: result.response.getContentAsString().contains(userDetails.getCity()) result.response.getContentAsString().contains(userDetails.getPhoneNumber()) } } <file_sep>/payment-service/src/main/java/com/journeyplanner/payment/domain/account/TransferStatus.java package com.journeyplanner.payment.domain.account; public enum TransferStatus { PENDING, PROCESSING, DONE, ERROR; } <file_sep>/payment-service/src/test/groovy/com/journeyplanner/payment/ApplicationTestConfig.groovy package com.journeyplanner.payment import com.journeyplanner.payment.app.PaymentServiceApplication import com.journeyplanner.payment.config.QueueConfig import com.journeyplanner.payment.infrastructure.output.MailSender import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.boot.test.autoconfigure.data.mongo.AutoConfigureDataMongo import org.springframework.boot.test.mock.mockito.MockBean import org.springframework.context.annotation.ComponentScan import org.springframework.context.annotation.FilterType import org.springframework.data.mongodb.repository.config.EnableMongoRepositories import org.springframework.test.context.TestPropertySource @SpringBootApplication @ComponentScan( basePackages = [ "com.journeyplanner.payment" ], excludeFilters = [ @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = QueueConfig.class), @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = MailSender.class), @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = PaymentServiceApplication.class) ] ) @TestPropertySource(locations = "classpath:test.properties") @AutoConfigureDataMongo @EnableMongoRepositories(basePackages = "com.journeyplanner.payment.domain") class ApplicationTestConfig { @MockBean MailSender mailSender } <file_sep>/reservation-service/src/test/groovy/com/journeyplanner/reservation/domain/reservation/CancelJourneyRuleMotherObject.groovy package com.journeyplanner.reservation.domain.reservation import java.time.Instant class CancelJourneyRuleMotherObject { static aRule(String journeyId, Instant createdTime = Instant.now()) { CancelJourneyRule.builder() .id(UUID.randomUUID().toString()) .journeyId(journeyId) .status(CancelJourneyRuleStatus.ACTIVE) .createdTime(createdTime) .build() } } <file_sep>/catalogue-service/src/main/java/com/journeyplanner/catalogue/domain/photo/PhotoFacade.java package com.journeyplanner.catalogue.domain.photo; import com.journeyplanner.catalogue.exceptions.CannotParseFile; import com.journeyplanner.catalogue.exceptions.ResourcesNotFound; import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.web.multipart.MultipartFile; import java.util.List; import java.util.stream.Collectors; import static java.text.MessageFormat.format; @Slf4j @AllArgsConstructor public class PhotoFacade { private final PhotoRepository photoRepository; private final PhotoCreator photoCreator; public String add(final String journeyId, final MultipartFile file) { Photo photo = photoCreator.from(journeyId, file) .orElseThrow(() -> new CannotParseFile(format("Cannot parse photo for journey : {0} : ", journeyId))); photoRepository.save(photo); log.info(format("Photo added to journey : {0}", journeyId)); return photo.getId(); } public PhotoDto getById(final String photoId) { return photoRepository.findById(photoId) .map(PhotoDto::from) .orElseThrow(() -> new ResourcesNotFound(format("Cannot found photo with id : {0} : ", photoId))); } public List<String> getAllForJourney(final String journeyId) { return photoRepository.findAllByJourneyId(journeyId) .stream() .map(Photo::getId) .collect(Collectors.toList()); } } <file_sep>/catalogue-service/src/test/groovy/com/journeyplanner/catalogue/domain/journey/AddGuideSpec.groovy package com.journeyplanner.catalogue.domain.journey import com.fasterxml.jackson.databind.ObjectMapper import com.journeyplanner.catalogue.app.CatalogueServiceApplication import com.journeyplanner.catalogue.infrastructure.input.request.AddGuideToJourneyRequest import com.journeyplanner.catalogue.infrastructure.input.request.UpdateJourneyRequest import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc import org.springframework.boot.test.context.SpringBootTest import org.springframework.test.annotation.DirtiesContext import org.springframework.test.web.servlet.MockMvc import spock.lang.Specification import javax.ws.rs.core.MediaType import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status @SpringBootTest @DirtiesContext @AutoConfigureMockMvc class AddGuideSpec extends Specification { @Autowired private MockMvc mvc @Autowired private JourneyRepository journeyRepository def setup() { journeyRepository.deleteAll() } def "should add guide to journey"() { given: def journey = JourneyMotherObject.aJourney() journeyRepository.save(journey) and: def request = new AddGuideToJourneyRequest("<EMAIL>", "FirstName", "SecondName") def json = new ObjectMapper().writeValueAsString(request) when: mvc.perform(put("/catalogue/journeys/" + journey.getId() + "/guides") .contentType(MediaType.APPLICATION_JSON) .content(json)) .andExpect(status().isOk()) .andReturn() then: journeyRepository.findById(journey.getId()).get().guideEmail == request.getEmail() journeyRepository.findById(journey.getId()).get().guideName == request.getFirstName() + " " + request.getSecondName() } def "should add empty guide to journey"() { given: def journey = JourneyMotherObject.aJourney() journeyRepository.save(journey) and: def request = new AddGuideToJourneyRequest("", "", "") def json = new ObjectMapper().writeValueAsString(request) when: mvc.perform(put("/catalogue/journeys/" + journey.getId() + "/guides") .contentType(MediaType.APPLICATION_JSON) .content(json)) .andExpect(status().isOk()) .andReturn() then: journeyRepository.findById(journey.getId()).get().guideEmail == "" journeyRepository.findById(journey.getId()).get().guideName == "" } } <file_sep>/reservation-service/src/main/java/com/journeyplanner/reservation/domain/reservation/CustomReservationRepository.java package com.journeyplanner.reservation.domain.reservation; interface CustomReservationRepository { void updateReservationStatusTo(String id, ReservationStatus status); } <file_sep>/user-service/src/main/java/com/journeyplanner/user/domain/exceptions/UserWithEmailAlreadyExists.java package com.journeyplanner.user.domain.exceptions; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ResponseStatus; @ResponseStatus(value = HttpStatus.BAD_REQUEST) public class UserWithEmailAlreadyExists extends RuntimeException { public UserWithEmailAlreadyExists(String message) { super(message); } } <file_sep>/catalogue-service/src/main/java/com/journeyplanner/catalogue/domain/journey/JourneyFacade.java package com.journeyplanner.catalogue.domain.journey; import com.journeyplanner.catalogue.exceptions.ResourcesNotFound; import com.journeyplanner.catalogue.infrastructure.input.request.AddGuideToJourneyRequest; import com.journeyplanner.catalogue.infrastructure.input.request.CreateJourneyRequest; import com.journeyplanner.catalogue.infrastructure.input.request.UpdateJourneyRequest; import com.journeyplanner.catalogue.infrastructure.output.queue.CancelJourney; import com.journeyplanner.catalogue.infrastructure.output.queue.ReservationCreator; import com.journeyplanner.common.config.events.CancelJourneyEvent; import com.journeyplanner.common.config.events.CreateReservationEvent; import com.querydsl.core.types.Predicate; import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import java.time.Instant; import java.util.List; import java.util.UUID; import java.util.stream.Collectors; import static java.text.MessageFormat.format; @Slf4j @AllArgsConstructor public class JourneyFacade { private final JourneyRepository repository; private final JourneyCreator journeyCreator; private final JourneyUpdater journeyUpdater; private final ReservationCreator reservationCreator; private final CancelJourney cancelJourney; public Page<JourneyDto> getAll(final Predicate predicate, final Pageable pageable) { return repository .findAll(predicate, pageable) .map(JourneyDto::from); } public JourneyDto create(final CreateJourneyRequest request) { Journey savedJourney = repository.save(journeyCreator.from(request)); log.info(format("Journey created : {0}", savedJourney.getId())); return JourneyDto.from(savedJourney); } public JourneyDto update(final String journeyId, final UpdateJourneyRequest request) { Journey journey = repository.findById(journeyId) .orElseThrow(() -> new ResourcesNotFound(format("Cannot found journey with id : {0}", journeyId))); Journey updatedJourney = repository.save(journeyUpdater.from(journey, request)); log.info(format("Journey updated : {0}", updatedJourney.getId())); return JourneyDto.from(updatedJourney); } public void cancel(final String id) { Journey journey = repository.findById(id) .orElseThrow(() -> new ResourcesNotFound(format("Cannot found journey with id : {0}", id))); if (journey.getStatus() == JourneyStatus.ACTIVE) { repository.updateJourneyStatus(journey.getId(), JourneyStatus.INACTIVE); } cancelJourney.publish(CancelJourneyEvent.builder() .id(UUID.randomUUID().toString()) .journeyId(journey.getId()) .eventTimeStamp(Instant.now()) .build()); } public void createReservation(final String journeyId, final String username) { Journey journey = repository.findById(journeyId) .orElseThrow(() -> new ResourcesNotFound(format("Cannot found journey with id : {0}", journeyId))); if (journey.getStatus() == JourneyStatus.INACTIVE) { throw new ResourcesNotFound(format("Journey : {0} : is inactive", journeyId)); } log.info(format("Request for reservation for journey : {0}", journeyId)); reservationCreator.publish(CreateReservationEvent.builder() .id(UUID.randomUUID().toString()) .start(journey.getStart()) .end(journey.getEnd()) .email(username) .journeyId(journey.getId()) .journeyName(journey.getName()) .price(journey.getPrice()) .eventTimeStamp(Instant.now()) .build()); } public JourneyDto addGuide(final String journeyId, final AddGuideToJourneyRequest request) { Journey journey = repository.findById(journeyId) .orElseThrow(() -> new ResourcesNotFound(format("Cannot found journey with id : {0}", journeyId))); Journey updatedJourney; if (request.getEmail().isEmpty()) { updatedJourney = repository.save(journeyUpdater.fromWithoutGuide(journey)); } else { updatedJourney = repository.save(journeyUpdater.from(journey, request)); } log.info(format("Journey Guide updated : {0}", updatedJourney.getId())); return JourneyDto.from(updatedJourney); } public List<JourneyDto> getGuideJourneys(final String email) { return repository.findByGuideEmail(email) .stream() .map(JourneyDto::from) .collect(Collectors.toList()); } } <file_sep>/build.sh #!/bin/bash mvn clean install -f common/pom.xml -DskipTests mvn clean install -f auth-service/pom.xml -DskipTests mvn clean install -f catalogue-service/pom.xml -DskipTests mvn clean install -f eureka-service/pom.xml -DskipTests mvn clean install -f gateway-service/pom.xml -DskipTests mvn clean install -f mail-service/pom.xml -DskipTests mvn clean install -f user-service/pom.xml -DskipTests mvn clean install -f reservation-service/pom.xml -DskipTests mvn clean install -f payment-service/pom.xml -DskipTests <file_sep>/user-service/src/main/resources/application.properties spring.application.name=user-service server.port=9105 management.endpoints.web.exposure.include=health,info,metrics,prometheus spring.profiles.active=local queue.mail.name=mail-queue queue.reservation.name=reservation-queue swagger.title=JourneyPlanner API swagger.description=User Service swagger.version=1.0-SNAPSHOT <file_sep>/user-service/src/main/java/com/journeyplanner/user/domain/details/UserDetailsFacade.java package com.journeyplanner.user.domain.details; import com.journeyplanner.user.domain.avatar.AvatarDto; import com.journeyplanner.user.domain.avatar.AvatarFacade; import com.journeyplanner.user.infrastructure.input.request.UpdateUserDetailsRequest; import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.web.multipart.MultipartFile; @Slf4j @AllArgsConstructor public class UserDetailsFacade { private final UserDetailsRepository repository; private final UserDetailsCreator creator; private final AvatarFacade avatarFacade; public UserDetailsDto getDetailsByEmail(final String email) { return repository.findByEmail(email) .map(UserDetailsDto::from) .orElseGet(UserDetailsDto::empty); } public UserDetailsDto addOrUpdateDetails(final String email, final UpdateUserDetailsRequest request) { UserDetails updatedUserDetails = repository.findByEmail(email) .map(d -> creator.createFrom(d, request)) .orElseGet(() -> creator.createFrom(email, request)); return UserDetailsDto.from(repository.save(updatedUserDetails)); } public AvatarDto getAvatarByEmail(final String email) { return avatarFacade.getByEmail(email); } public void addAvatar(final String email, final MultipartFile file) { avatarFacade.add(email, file); } } <file_sep>/catalogue-service/src/main/resources/application.properties spring.application.name=catalogue-service server.port=9115 management.endpoints.web.exposure.include=health,info,metrics,prometheus spring.profiles.active=local queue.reservation.name=reservation-queue queue.cancel-journey.name=cancel-journey-queue spring.servlet.multipart.max-file-size=6MB spring.servlet.multipart.max-request-size=6MB spring.servlet.multipart.enabled=true swagger.title=JourneyPlanner API swagger.description=Catalogue Service swagger.version=1.0-SNAPSHOT <file_sep>/catalogue-service/src/test/groovy/com/journeyplanner/catalogue/domain/photo/GetPhotoSpec.groovy package com.journeyplanner.catalogue.domain.photo import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc import org.springframework.boot.test.context.SpringBootTest import org.springframework.test.annotation.DirtiesContext import org.springframework.test.web.servlet.MockMvc import spock.lang.Specification import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status @SpringBootTest @DirtiesContext @AutoConfigureMockMvc class GetPhotoSpec extends Specification { @Autowired private MockMvc mvc @Autowired private PhotoRepository photoRepository def setup() { photoRepository.deleteAll() } def "should get list of ids"() { given: def journeyId = UUID.randomUUID().toString() def photo = PhotoMotherObject.aPhoto(journeyId) photoRepository.save(photo) when: def result = mvc.perform(get("/catalogue/journeys/" + journeyId + "/photos")) .andExpect(status().isOk()) .andReturn() then: result.response.getContentAsString().contains(photo.getId()) } def "should get photo"() { given: def journeyId = UUID.randomUUID().toString() def content = "PHOTO" def photo = PhotoMotherObject.aPhoto(journeyId, content) photoRepository.save(photo) when: def result = mvc.perform(get("/catalogue/photos/" + photo.getId())) .andExpect(status().isOk()) .andReturn() then: result.response.getContentAsString() == content } } <file_sep>/payment-service/src/test/groovy/com/journeyplanner/payment/domain/account/TransferMotherObject.groovy package com.journeyplanner.payment.domain.account import com.journeyplanner.common.config.events.TransferType import java.time.Instant class TransferMotherObject { static aTransfer(String email, TransferType type, BigDecimal value = BigDecimal.TEN, eventTime = Instant.now()) { Transfer.builder() .id(UUID.randomUUID().toString()) .email(email) .paymentId(UUID.randomUUID().toString()) .value(value) .type(type) .status(TransferStatus.PENDING) .eventTime(eventTime) .build() } } <file_sep>/payment-service/src/test/groovy/com/journeyplanner/payment/domain/account/AccountMotherObject.groovy package com.journeyplanner.payment.domain.account import java.time.Instant import java.time.temporal.ChronoUnit class AccountMotherObject { static aAccount(String email, BigDecimal balance = BigDecimal.ZERO) { Account.builder() .id(UUID.randomUUID().toString()) .email(email) .balance(balance) .build() } } <file_sep>/common/src/main/java/com/journeyplanner/common/config/mail/Template.java package com.journeyplanner.common.config.mail; public enum Template { NEW_USER("new_user.vm"), BLOCK_USER("block_user.vm"), UNBLOCK_USER("unblock_user.vm"), RESET_PASSWORD("<PASSWORD>"), RESET_PASSWORD_ADMIN("reset_password_admin.vm"), NEW_RESERVATION_CREATED("new_reservation_created.vm"), RESERVATION_CANCELED("reservation_canceled.vm"), JOURNEY_CANCELED("journey_canceled.vm"), ACCOUNT_CHARGED("account_charged.vm"), PAYMENT_ERROR("payment_error.vm"), PAYMENT_LOAD("payment_load.vm"), PAYMENT_RETURN("payment_return.vm"); private final String path; Template(String path) { this.path = path; } public String getPath() { return this.path; } } <file_sep>/catalogue-service/src/main/java/com/journeyplanner/catalogue/infrastructure/input/response/PhotoIdResponse.java package com.journeyplanner.catalogue.infrastructure.input.response; import lombok.Value; @Value public class PhotoIdResponse { String id; } <file_sep>/payment-service/src/test/groovy/com/journeyplanner/payment/domain/account/ChargeAccountSpec.groovy package com.journeyplanner.payment.domain.account import com.fasterxml.jackson.databind.ObjectMapper import com.journeyplanner.payment.domain.account.AccountRepository import com.journeyplanner.payment.infrastructure.input.request.ChargeAccountRequest import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc import org.springframework.boot.test.context.SpringBootTest import org.springframework.test.annotation.DirtiesContext import org.springframework.test.web.servlet.MockMvc import spock.lang.Specification import javax.ws.rs.core.MediaType import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status @SpringBootTest @DirtiesContext @AutoConfigureMockMvc class ChargeAccountSpec extends Specification { @Autowired private MockMvc mvc @Autowired private AccountRepository accountRepository def setup() { accountRepository.deleteAll() } def "should charge account"() { given: def email = "<EMAIL>" def account = AccountMotherObject.aAccount(email) accountRepository.save(account) and: def request = new ChargeAccountRequest(BigDecimal.TEN) def json = new ObjectMapper().writeValueAsString(request) when: mvc.perform(post("/billing/accounts/charge") .contentType(MediaType.APPLICATION_JSON) .header("x-username", email) .content(json)) .andExpect(status().isOk()) .andReturn() then: accountRepository.findByEmail(email).get().balance == BigDecimal.TEN } } <file_sep>/payment-service/src/main/java/com/journeyplanner/payment/domain/account/TransferRepository.java package com.journeyplanner.payment.domain.account; import org.springframework.data.repository.Repository; import java.util.List; import java.util.Optional; interface TransferRepository extends Repository<Transfer, String>, TransferCustomRepository { Transfer save(Transfer transfer); Optional<Transfer> findFirstByPaymentIdOrderByEventTimeDesc(String paymentId); Optional<Transfer> findById(String id); void deleteAll(); } <file_sep>/mail-service/src/main/java/com/journeyplanner/mail/events/MailSendEvent.java package com.journeyplanner.mail.events; import lombok.Builder; import lombok.Getter; import lombok.ToString; import lombok.Value; import java.util.Map; @Value @Builder @ToString public class MailSendEvent { String to; String templateName; Map<String, String> params; } <file_sep>/catalogue-service/src/main/java/com/journeyplanner/catalogue/domain/photo/PhotoDto.java package com.journeyplanner.catalogue.domain.photo; import lombok.Builder; import lombok.Value; import org.bson.types.Binary; @Value @Builder public class PhotoDto { String id; String journeyId; Binary image; static PhotoDto from(final Photo photo) { return PhotoDto.builder() .id(photo.getId()) .journeyId(photo.getJourneyId()) .image(photo.getImage()) .build(); } } <file_sep>/catalogue-service/src/main/java/com/journeyplanner/catalogue/domain/photo/PhotoCreator.java package com.journeyplanner.catalogue.domain.photo; import org.bson.BsonBinarySubType; import org.bson.types.Binary; import org.springframework.web.multipart.MultipartFile; import java.util.Optional; import java.util.UUID; public class PhotoCreator { Optional<Photo> from(final String journeyId, final MultipartFile file) { try { return Optional.ofNullable(Photo.builder() .id(UUID.randomUUID().toString()) .journeyId(journeyId) .image(new Binary(BsonBinarySubType.BINARY, file.getBytes())) .build()); } catch (Exception e) { return Optional.empty(); } } } <file_sep>/user-service/src/main/java/com/journeyplanner/user/domain/user/GuideDto.java package com.journeyplanner.user.domain.user; import lombok.Builder; import lombok.Value; @Value @Builder public class GuideDto { String email; String firstName; String secondName; static GuideDto from(User user) { return GuideDto.builder() .email(user.getEmail()) .firstName(user.getFirstName()) .secondName(user.getSecondName()) .build(); } } <file_sep>/auth-service/src/main/java/com/journeyplanner/auth/security/JwtAuthenticationFilter.java package com.journeyplanner.auth.security; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.journeyplanner.auth.security.dto.TokenResponse; import com.journeyplanner.auth.security.dto.UserCredentialsRequest; import com.journeyplanner.auth.security.jwt.JwtTokenProvider; import com.journeyplanner.auth.user.AppUserService; import com.journeyplanner.auth.user.model.AppUser; import com.journeyplanner.common.config.security.JwtProperties; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.AuthenticationServiceException; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; import java.util.Collections; public class JwtAuthenticationFilter extends UsernamePasswordAuthenticationFilter { private final AuthenticationManager authenticationManager; private final JwtProperties jwtProperties; private final JwtTokenProvider jwtTokenProvider; private final AppUserService appUserService; public JwtAuthenticationFilter(AuthenticationManager authenticationManager, JwtProperties jwtProperties, JwtTokenProvider jwtTokenProvider, AppUserService appUserService) { this.authenticationManager = authenticationManager; this.jwtProperties = jwtProperties; this.jwtTokenProvider = jwtTokenProvider; this.appUserService = appUserService; this.setRequiresAuthenticationRequestMatcher(new AntPathRequestMatcher(jwtProperties.getUri(), "POST")); } @Override public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException { try { UserCredentialsRequest credentials = new ObjectMapper().findAndRegisterModules() .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) .readValue(request.getInputStream(), UserCredentialsRequest.class); UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(credentials.getUsername(), credentials.getPassword(), Collections.emptyList()); credentials.setPassword(""); return authenticationManager.authenticate(authToken); } catch (IOException e) { throw new RuntimeException(e); } } @Override protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException { AppUser user = appUserService.getUserByEmail(authResult.getName()) .orElseThrow(() -> new AuthenticationServiceException("")); String token = jwtTokenProvider.createToken(user); TokenResponse tokenResponse = new TokenResponse(jwtProperties.getPrefix(), token); PrintWriter out = response.getWriter(); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); out.print(new ObjectMapper().writeValueAsString(tokenResponse)); out.flush(); } } <file_sep>/reservation-service/src/main/java/com/journeyplanner/reservation/config/QueueConfig.java package com.journeyplanner.reservation.config; import org.springframework.amqp.core.Queue; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class QueueConfig { @Bean public Queue reservationQueue(@Value("${queue.reservation.name}") String reservationQueue) { return new Queue(reservationQueue, true); } @Bean public Queue cancelJourneyQueue(@Value("${queue.cancel-journey.name}") String cancelJourneyQueue) { return new Queue(cancelJourneyQueue, true); } } <file_sep>/mail-service/src/main/resources/application.properties spring.application.name=mail-service server.port=9110 management.endpoints.web.exposure.include=health,info,metrics,prometheus mailsender.mail.cron=*/5 * * * * * mail.from=<EMAIL> mail.subject=New notification - Journey Planner queue.mail.name=mail-queue spring.profiles.active=local <file_sep>/user-service/src/test/groovy/com/journeyplanner/user/domain/details/GetAvatarSpec.groovy package com.journeyplanner.user.domain.details import com.journeyplanner.user.domain.avatar.AvatarRepository import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc import org.springframework.boot.test.context.SpringBootTest import org.springframework.test.annotation.DirtiesContext import org.springframework.test.web.servlet.MockMvc import spock.lang.Specification import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status @SpringBootTest @DirtiesContext @AutoConfigureMockMvc class GetAvatarSpec extends Specification { @Autowired private MockMvc mvc @Autowired private AvatarRepository avatarRepository def setup() { avatarRepository.deleteAll() } def "should get avatar"() { given: def email = "<EMAIL>" def avatar = AvatarMotherObject.aAvatar(email) avatarRepository.save(avatar) when: def result = mvc.perform(get("/users/avatar") .header("x-username", email)) .andExpect(status().isOk()) .andReturn() then: result.response.getContentAsString().contains("AVATAR") } def "should fail when avatar doesn't exist"() { given: def email = "<EMAIL>" when: def result = mvc.perform(get("/users/avatar") .header("x-username", email)) .andExpect(status().is4xxClientError()) .andReturn() then: println result.response.getContentAsString() } } <file_sep>/mail-service/src/main/java/com/journeyplanner/mail/domain/sender/SenderMockImpl.java package com.journeyplanner.mail.domain.sender; import com.journeyplanner.mail.domain.Mail; import lombok.extern.slf4j.Slf4j; import org.springframework.context.annotation.Profile; import org.springframework.stereotype.Service; import static java.text.MessageFormat.format; @Service @Slf4j @Profile("!email") class SenderMockImpl implements Sender { @Override public void send(Mail mail, String body) { log.info("Use MOCK sender implementation"); log.info(format("Start sending mail with id : {0}", mail.getId())); log.info(format("Mail : {0}", body)); } } <file_sep>/user-service/src/main/java/com/journeyplanner/user/domain/user/UserFacade.java package com.journeyplanner.user.domain.user; import com.journeyplanner.common.config.events.SendMailEvent; import com.journeyplanner.common.config.mail.Template; import com.journeyplanner.user.domain.exceptions.IllegalOperation; import com.journeyplanner.user.domain.exceptions.ResourceNotFound; import com.journeyplanner.user.domain.exceptions.UserWithEmailAlreadyExists; import com.journeyplanner.user.domain.password.PasswordFacade; import com.journeyplanner.user.infrastructure.input.request.*; import com.journeyplanner.user.infrastructure.input.response.BasicInfoUserResponse; import com.journeyplanner.user.infrastructure.output.queue.MailSender; import com.querydsl.core.types.Predicate; import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import java.util.HashMap; import java.util.List; import java.util.UUID; import java.util.stream.Collectors; import static java.text.MessageFormat.format; @Slf4j @AllArgsConstructor public class UserFacade { private final UserRepository repository; private final UserCreator userCreator; private final MailSender mailSender; private final PasswordFacade passwordFacade; public void create(final CreateUserRequest request) { if (repository.existsByEmail(request.getEmail())) { throw new UserWithEmailAlreadyExists(format("User with email : {0} : already exists", request.getEmail())); } User userToSave = userCreator.from(request, passwordFacade.encodePassword(request.getPassword())); repository.save(userToSave); log.info(format("New user : {0} : created", userToSave.getEmail())); mailSender.publish(SendMailEvent.builder() .id(UUID.randomUUID().toString()) .to(userToSave.getEmail()) .templateName(Template.NEW_USER.getPath()) .params(new HashMap<String, String>() {{ put("firstName", userToSave.getFirstName()); put("secondName", userToSave.getSecondName()); }}) .build()); } public void createGuide(final CreateGuideRequest request) { if (repository.existsByEmail(request.getEmail())) { throw new UserWithEmailAlreadyExists(format("User with email : {0} : already exists", request.getEmail())); } User userToSave = userCreator.from(request, passwordFacade.encodePassword(request.getPassword())); repository.save(userToSave); log.info(format("New guide : {0} : created", userToSave.getEmail())); } public void sendResetPasswordToken(final GenerateResetPasswordLinkRequest request) { User user = repository.findByEmail(request.getEmail()) .orElseThrow(() -> new ResourceNotFound(format("Cannot found user with email : {0}", request.getEmail()))); passwordFacade.generateAndSendResetPasswordLinkWithToken(user.getEmail(), user.getFirstName()); } public void sendResetPasswordTokenByAdminRequest(final GenerateResetPasswordLinkRequest request) { User user = repository.findByEmail(request.getEmail()) .orElseThrow(() -> new ResourceNotFound(format("Cannot found user with email : {0}", request.getEmail()))); repository.changeNewPasswordRequired(request.getEmail(), Boolean.TRUE); passwordFacade.generateAndSendResetPasswordLinkWithTokenByAdmin(user.getEmail(), user.getFirstName()); } public void resetPassword(final ResetPasswordRequest request) { passwordFacade.validateToken(request.getToken(), request.getEmail()); repository.updatePassword(request.getEmail(), passwordFacade.encodePassword(request.getNewPassword())); repository.changeNewPasswordRequired(request.getEmail(), Boolean.FALSE); } public void block(final AddUserToBlacklistRequest request) { User user = repository.findByEmail(request.getEmail()) .orElseThrow(() -> new ResourceNotFound(format("Cannot found user with email : {0}", request.getEmail()))); if (user.getRole().equals("ADMIN")) { log.warn("Cannot add admin to blacklist"); throw new IllegalOperation("You cannot add to blacklist user with admin role"); } repository.changeIsBlacklisted(request.getEmail(), Boolean.TRUE); log.info("User added to blacklist : {0}"); mailSender.publish(SendMailEvent.builder() .id(UUID.randomUUID().toString()) .to(user.getEmail()) .templateName(Template.BLOCK_USER.getPath()) .params(new HashMap<String, String>()) .build()); } public void unblock(final RemoveUserFromBlacklistRequest request) { User user = repository.findByEmail(request.getEmail()) .orElseThrow(() -> new ResourceNotFound(format("Cannot found user with email : {0}", request.getEmail()))); repository.changeIsBlacklisted(request.getEmail(), Boolean.FALSE); log.info(format("User removed from blacklist : {0}", request.getEmail())); mailSender.publish(SendMailEvent.builder() .id(UUID.randomUUID().toString()) .to(user.getEmail()) .templateName(Template.UNBLOCK_USER.getPath()) .params(new HashMap<String, String>()) .build()); } public Page<UserDto> getAll(Predicate predicate, Pageable pageable) { return repository.findAll(predicate, pageable).map(UserDto::from); } public List<GuideDto> getGuides() { return repository.findByRole(UserRole.GUIDE.getRoleName()) .stream() .map(GuideDto::from) .collect(Collectors.toList()); } public UserDto findById(final String id) { return repository.findById(id) .map(UserDto::from) .orElseThrow(() -> new ResourceNotFound(format("Cannot found user with id : {0}", id))); } public BasicInfoUserResponse findByEmail(final String email) { return repository.findByEmail(email) .map(UserDto::from) .map(BasicInfoUserResponse::from) .orElseThrow(() -> new ResourceNotFound(format("Cannot found user with email : {0}", email))); } } <file_sep>/mail-service/src/main/resources/application-local.properties spring.data.mongodb.host=localhost spring.data.mongodb.port=27017 spring.data.mongodb.auto-index-creation=true eureka.client.service-url.defaultZone=http://localhost:8761/eureka/ eureka.instance.prefer-ip-address=true spring.rabbitmq.host=localhost spring.rabbitmq.port=5672 <file_sep>/user-service/src/main/java/com/journeyplanner/user/domain/user/UserCreator.java package com.journeyplanner.user.domain.user; import com.journeyplanner.user.infrastructure.input.request.CreateGuideRequest; import com.journeyplanner.user.infrastructure.input.request.CreateUserRequest; import java.util.UUID; class UserCreator { User from(final CreateUserRequest request, final String encodedPassword) { return User.builder() .id(UUID.randomUUID().toString()) .email(request.getEmail()) .firstName(request.getFirstName()) .secondName(request.getSecondName()) .password(<PASSWORD>) .role(UserRole.USER.getRoleName()) .isBlocked(Boolean.FALSE) .newPasswordRequired(Boolean.FALSE) .build(); } User from(final CreateGuideRequest request, final String encodedPassword) { return User.builder() .id(UUID.randomUUID().toString()) .email(request.getEmail()) .firstName(request.getFirstName()) .secondName(request.getSecondName()) .password(<PASSWORD>) .role(UserRole.GUIDE.getRoleName()) .isBlocked(Boolean.FALSE) .newPasswordRequired(Boolean.FALSE) .build(); } } <file_sep>/common/src/main/java/com/journeyplanner/common/config/events/SendMailEvent.java package com.journeyplanner.common.config.events; import lombok.*; import java.util.Map; @Getter @Builder @ToString @AllArgsConstructor @NoArgsConstructor public class SendMailEvent implements Event { @NonNull String id; @NonNull String to; @NonNull String templateName; @NonNull Map<String, String> params; } <file_sep>/payment-service/src/test/groovy/com/journeyplanner/payment/domain/account/LoadTransactionSpec.groovy package com.journeyplanner.payment.domain.account import com.journeyplanner.common.config.events.TransferType import com.journeyplanner.payment.exceptions.IllegalOperation import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc import org.springframework.boot.test.context.SpringBootTest import org.springframework.test.annotation.DirtiesContext import org.springframework.test.web.servlet.MockMvc import spock.lang.Specification @SpringBootTest @DirtiesContext @AutoConfigureMockMvc class LoadTransactionSpec extends Specification { @Autowired private MockMvc mvc @Autowired private AccountRepository accountRepository @Autowired private AccountHistoryRepository accountHistoryRepository @Autowired private TransferRepository transferRepository @Autowired private TransferScheduler transferScheduler def setup() { accountRepository.deleteAll() accountHistoryRepository.deleteAll() transferRepository.deleteAll() } def "should create return transaction"() { given: def email = "<EMAIL>" def account = AccountMotherObject.aAccount(email, new BigDecimal(10.00)) accountRepository.save(account) and: def transfer = TransferMotherObject.aTransfer(email, TransferType.LOAD, new BigDecimal(8.00)) transferRepository.save(transfer) when: transferScheduler.fetch() then: transferRepository.findById(transfer.getId()).get().status == TransferStatus.DONE accountHistoryRepository.findAllByAccountId(account.getId()).size() == 1 accountRepository.findByEmail(email).get().balance == new BigDecimal(2.00) } def "should fail when user doesn't have enough money"() { given: def email = "<EMAIL>" def account = AccountMotherObject.aAccount(email, new BigDecimal(10.00)) accountRepository.save(account) and: def transfer = TransferMotherObject.aTransfer(email, TransferType.LOAD, new BigDecimal(18.00)) transferRepository.save(transfer) when: transferScheduler.fetch() then: transferRepository.findById(transfer.getId()).get().status == TransferStatus.ERROR } } <file_sep>/user-service/src/test/groovy/com/journeyplanner/user/domain/details/CreateAvatarSpec.groovy package com.journeyplanner.user.domain.details import com.fasterxml.jackson.databind.ObjectMapper import com.journeyplanner.user.domain.avatar.AvatarRepository import com.journeyplanner.user.domain.user.UserRepository import com.journeyplanner.user.infrastructure.input.request.UpdateUserDetailsRequest import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc import org.springframework.boot.test.context.SpringBootTest import org.springframework.mock.web.MockMultipartFile import org.springframework.test.annotation.DirtiesContext import org.springframework.test.web.servlet.MockMvc import spock.lang.Specification import javax.ws.rs.core.MediaType import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.multipart import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status @SpringBootTest @DirtiesContext @AutoConfigureMockMvc class CreateAvatarSpec extends Specification { @Autowired private MockMvc mvc @Autowired private AvatarRepository avatarRepository def setup() { avatarRepository.deleteAll() } def "should create avatar"() { given: def email = "<EMAIL>" def request = new MockMultipartFile("image", "AVATAR".getBytes()) when: mvc.perform(multipart("/users/avatar") .file(request) .header("x-username", email)) .andExpect(status().isNoContent()) .andReturn() then: avatarRepository.findByEmail(email).get().image.data.length != 0 } def "should update avatar"() { given: def email = "<EMAIL>" def avatar = AvatarMotherObject.aAvatar(email) avatarRepository.save(avatar) and: def request = new MockMultipartFile("image", "S".getBytes()) when: mvc.perform(multipart("/users/avatar") .file(request) .header("x-username", email)) .andExpect(status().isNoContent()) .andReturn() then: avatarRepository.findByEmail(email).get().image.data.length != 0 avatarRepository.findByEmail(email).get().image.data == [83] } } <file_sep>/user-service/src/main/java/com/journeyplanner/user/domain/exceptions/IllegalOperation.java package com.journeyplanner.user.domain.exceptions; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ResponseStatus; @ResponseStatus(value = HttpStatus.BAD_REQUEST) public class IllegalOperation extends RuntimeException { public IllegalOperation() { super(); } public IllegalOperation(String message) { super(message); } } <file_sep>/user-service/src/main/java/com/journeyplanner/user/domain/password/PasswordFacade.java package com.journeyplanner.user.domain.password; import com.journeyplanner.common.config.events.SendMailEvent; import com.journeyplanner.common.config.mail.Template; import com.journeyplanner.user.domain.exceptions.ResourceNotFound; import com.journeyplanner.user.infrastructure.output.queue.MailSender; import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.security.crypto.password.PasswordEncoder; import java.util.HashMap; import java.util.UUID; import static java.text.MessageFormat.format; @Slf4j @AllArgsConstructor public class PasswordFacade { private final ResetTokenRepository resetTokenRepository; private final ResetTokenCreator resetTokenCreator; private final MailSender mailSender; private final PasswordEncoder passwordEncoder; public void generateAndSendResetPasswordLinkWithToken(final String email, final String firstName) { ResetToken resetToken = resetTokenCreator.from(email); resetTokenRepository.save(resetToken); log.info(format("New reset token generated : {0} : for email {1}", resetToken.getToken(), email)); mailSender.publish(SendMailEvent.builder() .id(UUID.randomUUID().toString()) .to(email) .templateName(Template.RESET_PASSWORD.getPath()) .params(new HashMap<String, String>() {{ put("firstName", firstName); put("token", resetToken.getToken()); }}) .build()); log.info(format("Mail sent with token : {0} : to user : {1}", resetToken.getToken(), email)); } public void generateAndSendResetPasswordLinkWithTokenByAdmin(final String email, final String firstName) { ResetToken resetToken = resetTokenCreator.from(email); resetTokenRepository.save(resetToken); log.info(format("New reset token generated by admin : {0} : for email {1}", resetToken.getToken(), email)); mailSender.publish(SendMailEvent.builder() .id(UUID.randomUUID().toString()) .to(email) .templateName(Template.RESET_PASSWORD_ADMIN.getPath()) .params(new HashMap<String, String>() {{ put("firstName", firstName); put("token", resetToken.getToken()); }}) .build()); log.info(format("Mail sent with token by admin : {0} : to user : {1}", resetToken.getToken(), email)); } public void validateToken(final String token, final String email) { ResetToken resetToken = resetTokenRepository .deprecateToken(token) .orElseThrow(() -> new ResourceNotFound(format("Token with this id {0} doesn't exists", token))); if (!resetToken.getEmail().equals(email)) { throw new ResourceNotFound(format("Token with this id {0} doesn't exists for this email {1}", token, email)); } log.info(format("Token : {0} : is valid for email : {1}", token, email)); } public String encodePassword(final String password) { return passwordEncoder.encode(password); } } <file_sep>/catalogue-service/src/main/java/com/journeyplanner/catalogue/domain/journey/Journey.java package com.journeyplanner.catalogue.domain.journey; import lombok.Builder; import lombok.NonNull; import lombok.Value; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; import java.math.BigDecimal; import java.time.Instant; @Value @Builder @Document(collection = "journey") public class Journey { @Id @NonNull String id; @NonNull JourneyStatus status; @NonNull String name; @NonNull String country; @NonNull String city; @NonNull String description; @NonNull String transportType; @NonNull BigDecimal price; @NonNull Instant start; @NonNull Instant end; @NonNull String guideEmail; @NonNull String guideName; } <file_sep>/reservation-service/src/test/groovy/com/journeyplanner/reservation/domain/reservation/GetReservationSpec.groovy package com.journeyplanner.reservation.domain.reservation import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc import org.springframework.boot.test.context.SpringBootTest import org.springframework.test.annotation.DirtiesContext import org.springframework.test.web.servlet.MockMvc import spock.lang.Specification import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status @SpringBootTest @DirtiesContext @AutoConfigureMockMvc class GetReservationSpec extends Specification { @Autowired private MockMvc mvc @Autowired private ReservationRepository repository def setup() { repository.deleteAll(); } def "should get user reservation"() { given: def email = "<EMAIL>" def reservation = ReservationMotherObject.aReservation(email) repository.save(reservation) when: def result = mvc.perform(get("/reservations/") .header("x-username", email)) .andExpect(status().isOk()) .andReturn() then: result.response.getContentAsString().contains(reservation.getId()) } } <file_sep>/mail-service/src/test/groovy/com/journeyplanner/mail/domain/MailMotherObject.groovy package com.journeyplanner.mail.domain import com.journeyplanner.mail.events.MailSendEvent class MailMotherObject { static Mail aMail(String id, MailStatus status) { Mail.builder() .id(id) .to("<EMAIL>") .templateName("test.vm") .status(status) .build() } static MailSendEvent aMailSendEvent() { def params = new HashMap() params.put("param", "value") MailSendEvent.builder() .to("<EMAIL>") .templateName("test.vm") .params(params) .build() } } <file_sep>/user-service/src/main/java/com/journeyplanner/user/domain/exceptions/CannotParseFile.java package com.journeyplanner.user.domain.exceptions; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ResponseStatus; @ResponseStatus(value = HttpStatus.BAD_REQUEST) public class CannotParseFile extends RuntimeException { public CannotParseFile(String message) { super(message); } } <file_sep>/reservation-service/src/test/groovy/com/journeyplanner/reservation/domain/reservation/ReservationMotherObject.groovy package com.journeyplanner.reservation.domain.reservation import java.time.Instant import java.time.temporal.ChronoUnit class ReservationMotherObject { static aReservation(String mail, Instant start = Instant.now().plus(100, ChronoUnit.DAYS), String journeyId = UUID.randomUUID().toString()) { Reservation.builder() .id(UUID.randomUUID().toString()) .start(start) .end(Instant.now().plus(102, ChronoUnit.DAYS)) .status(ReservationStatus.ACTIVE) .journeyId(journeyId) .journeyName("JOURNEY_NAME") .email(mail) .price(new BigDecimal(1000)) .createdTime(Instant.now()) .paymentId(UUID.randomUUID().toString()) .build() } } <file_sep>/user-service/src/test/groovy/com/journeyplanner/user/domain/details/AvatarMotherObject.groovy package com.journeyplanner.user.domain.details import com.journeyplanner.user.domain.avatar.Avatar import org.bson.BsonBinarySubType import org.bson.types.Binary class AvatarMotherObject { static aAvatar(String mail, String content = "AVATAR") { Avatar.builder() .id(UUID.randomUUID().toString()) .email(mail) .image(new Binary(BsonBinarySubType.BINARY, content.getBytes())) .build() } } <file_sep>/payment-service/src/main/resources/application.properties spring.application.name=payment-service server.port=9125 management.endpoints.web.exposure.include=health,info,metrics,prometheus spring.profiles.active=local queue.payment.name=payment-queue queue.mail.name=mail-queue transfer.cron=0 * * * * * swagger.title=JourneyPlanner API swagger.description=Payment Service swagger.version=1.0-SNAPSHOT <file_sep>/reservation-service/src/main/java/com/journeyplanner/reservation/domain/users/BasicInfoUser.java package com.journeyplanner.reservation.domain.users; import lombok.Data; @Data public class BasicInfoUser { private String id; private String email; private String firstName; private String secondName; } <file_sep>/user-service/src/main/java/com/journeyplanner/user/domain/details/UserDetailsCreator.java package com.journeyplanner.user.domain.details; import com.journeyplanner.user.infrastructure.input.request.UpdateUserDetailsRequest; import java.util.UUID; class UserDetailsCreator { public UserDetails createFrom(final UserDetails userDetails, final UpdateUserDetailsRequest request) { return UserDetails.builder() .id(userDetails.getId()) .email(userDetails.getEmail()) .country(request.getCountry()) .city(request.getCity()) .street(request.getStreet()) .postCode(request.getPostCode()) .phoneNumber(request.getPhoneNumber()) .build(); } public UserDetails createFrom(final String email, final UpdateUserDetailsRequest request) { return UserDetails.builder() .id(UUID.randomUUID().toString()) .email(email) .country(request.getCountry()) .city(request.getCity()) .street(request.getStreet()) .postCode(request.getPostCode()) .phoneNumber(request.getPhoneNumber()) .build(); } } <file_sep>/reservation-service/src/test/groovy/com/journeyplanner/reservation/domain/reservation/CreateReservationMotherObject.groovy package com.journeyplanner.reservation.domain.reservation import com.journeyplanner.common.config.events.CreateReservationEvent import java.time.Instant import java.time.temporal.ChronoUnit class CreateReservationMotherObject { static aCreateReservation(String email, String journeyId = UUID.randomUUID().toString()) { CreateReservationEvent.builder() .id(UUID.randomUUID().toString()) .email(email) .journeyId(journeyId) .journeyName("JOURNEY_NAME") .price(new BigDecimal(1000)) .eventTimeStamp(Instant.now()) .start(Instant.now().plus(2, ChronoUnit.DAYS)) .end(Instant.now().plus(2, ChronoUnit.DAYS)) .build() } } <file_sep>/eureka-service/src/main/resources/application-dev.properties eureka.client.service-url.defaultZone=http://eureka:8761/eureka eureka.instance.prefer-ip-address=true <file_sep>/payment-service/src/test/groovy/com/journeyplanner/payment/domain/account/RetryTransactionSpec.groovy package com.journeyplanner.payment.domain.account import com.journeyplanner.common.config.events.TransferType import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc import org.springframework.boot.test.context.SpringBootTest import org.springframework.test.annotation.DirtiesContext import org.springframework.test.web.servlet.MockMvc import spock.lang.Specification import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status @SpringBootTest @DirtiesContext @AutoConfigureMockMvc class RetryTransactionSpec extends Specification { @Autowired private MockMvc mvc @Autowired private AccountRepository accountRepository @Autowired private AccountHistoryRepository accountHistoryRepository @Autowired private TransferRepository transferRepository @Autowired private TransferScheduler transferScheduler def setup() { accountRepository.deleteAll() accountHistoryRepository.deleteAll() transferRepository.deleteAll() } def "should retry transaction"() { given: def email = "<EMAIL>" def account = AccountMotherObject.aAccount(email, BigDecimal.TEN) accountRepository.save(account) and: def transfer1 = TransferMotherObject.aTransfer(email, TransferType.LOAD, new BigDecimal(20.00)) transferRepository.save(transfer1) transferScheduler.fetch() and: def transfer2 = TransferMotherObject.aTransfer(email, TransferType.RETURN, new BigDecimal(30.00)) transferRepository.save(transfer2) transferScheduler.fetch() when: mvc.perform(post("/billing/payments/" + transfer1.getPaymentId() + "/retry") .header("x-username", email)) .andExpect(status().isNoContent()) .andReturn() and: transferScheduler.fetch() then: transferRepository.findFirstByPaymentIdOrderByEventTimeDesc(transfer1.getPaymentId()).get().status == TransferStatus.DONE transferRepository.findFirstByPaymentIdOrderByEventTimeDesc(transfer2.getPaymentId()).get().status == TransferStatus.DONE and: transferRepository.findById(transfer1.getId()).get().status == TransferStatus.ERROR transferRepository.findById(transfer2.getId()).get().status == TransferStatus.DONE } } <file_sep>/scripts/tests.sh #!/bin/bash cd ../auth-service && ./test.sh cd ../catalogue-service && ./test.sh cd ../mail-service && ./test.sh cd ../payment-service && ./test.sh cd ../reservation-service && ./test.sh cd ../user-service && ./test.sh <file_sep>/reservation-service/src/main/resources/application.properties spring.application.name=reservation-service server.port=9120 management.endpoints.web.exposure.include=health,info,metrics,prometheus spring.profiles.active=local queue.reservation.name=reservation-queue queue.cancel-journey.name=cancel-journey-queue queue.mail.name=mail-queue queue.payment.name=payment-queue reservation.cancel.cron=0 * * * * * swagger.title=JourneyPlanner API swagger.description=Reservation Service swagger.version=1.0-SNAPSHOT user.uri=http://localhost:9105/users/ <file_sep>/catalogue-service/src/main/java/com/journeyplanner/catalogue/domain/journey/JourneyConfiguration.java package com.journeyplanner.catalogue.domain.journey; import com.journeyplanner.catalogue.infrastructure.output.queue.CancelJourney; import com.journeyplanner.catalogue.infrastructure.output.queue.ReservationCreator; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration class JourneyConfiguration { @Bean JourneyFacade journeyFacade(JourneyRepository journeyRepository, ReservationCreator reservationCreator, CancelJourney cancelJourney) { return new JourneyFacade(journeyRepository, new JourneyCreator(), new JourneyUpdater(), reservationCreator, cancelJourney); } } <file_sep>/payment-service/src/main/java/com/journeyplanner/payment/domain/account/AccountCustomRepository.java package com.journeyplanner.payment.domain.account; import java.math.BigDecimal; interface AccountCustomRepository { void modifyAccountBalance(String id, BigDecimal balance); } <file_sep>/mail-service/src/main/java/com/journeyplanner/mail/domain/Mail.java package com.journeyplanner.mail.domain; import lombok.Builder; import lombok.Getter; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; import java.util.Map; @Getter @Builder @Document(collection = "mail") public class Mail { @Id private String id; private String to; private MailStatus status; private String templateName; private Map<String, String> params; void setPendingStatus() { this.status = MailStatus.PENDING; } void setErrorStatus() { this.status = MailStatus.ERROR; } void setSentStatus() { this.status = MailStatus.SENT; } } <file_sep>/user-service/src/main/java/com/journeyplanner/user/domain/avatar/AvatarCreator.java package com.journeyplanner.user.domain.avatar; import lombok.extern.slf4j.Slf4j; import org.bson.BsonBinarySubType; import org.bson.types.Binary; import org.springframework.web.multipart.MultipartFile; import java.util.Optional; import java.util.UUID; import static java.text.MessageFormat.format; @Slf4j class AvatarCreator { Optional<Avatar> from(final String email, final MultipartFile file) { try { return Optional.ofNullable(Avatar.builder() .id(UUID.randomUUID().toString()) .email(email) .image(new Binary(BsonBinarySubType.BINARY, file.getBytes())) .build()); } catch (Exception e) { log.warn(format("Cannot parse avatar for user {0} : {1}", email, e.getMessage())); return Optional.empty(); } } Optional<Avatar> from(final String id, String email, final MultipartFile file) { try { return Optional.ofNullable(Avatar.builder() .id(id) .email(email) .image(new Binary(BsonBinarySubType.BINARY, file.getBytes())) .build()); } catch (Exception e) { log.warn(format("Cannot parse avatar for user {0} : {1}", email, e.getMessage())); return Optional.empty(); } } } <file_sep>/auth-service/src/main/java/com/journeyplanner/auth/security/jwt/JwtTokenProvider.java package com.journeyplanner.auth.security.jwt; import com.journeyplanner.auth.user.model.AppUser; import com.journeyplanner.common.config.security.JwtProperties; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; import lombok.AllArgsConstructor; import java.util.*; @AllArgsConstructor public class JwtTokenProvider { private final JwtProperties jwtProperties; public String createToken(final AppUser appUser) { long now = System.currentTimeMillis(); Map<String, Object> claims = new HashMap<>(); claims.put("authorities", Collections.singletonList("ROLE_" + appUser.getRole())); claims.put("id", appUser.getId()); return Jwts.builder() .setClaims(claims) .setSubject(appUser.getEmail()) .setIssuedAt(new Date(now)) .setExpiration(new Date(now + jwtProperties.getExpirationTime() * 1000)) .signWith(SignatureAlgorithm.HS512, jwtProperties.getSecret().getBytes()) .compact(); } } <file_sep>/payment-service/src/test/groovy/com/journeyplanner/payment/domain/account/GetAccountSpec.groovy package com.journeyplanner.payment.domain.account import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc import org.springframework.boot.test.context.SpringBootTest import org.springframework.test.annotation.DirtiesContext import org.springframework.test.web.servlet.MockMvc import spock.lang.Specification import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status @SpringBootTest @DirtiesContext @AutoConfigureMockMvc class GetAccountSpec extends Specification { @Autowired private MockMvc mvc @Autowired private AccountRepository accountRepository def setup() { accountRepository.deleteAll() } def "should return account"() { given: def email = "<EMAIL>" def account = AccountMotherObject.aAccount(email) accountRepository.save(account) when: def result = mvc.perform(get("/billing/accounts") .header("x-username", email)) .andExpect(status().isOk()) .andReturn() then: result.response.getContentAsString().contains(account.getId()) } def "should create account if account doesn't exists"() { given: def email = "<EMAIL>" when: def result = mvc.perform(get("/billing/accounts") .header("x-username", email)) .andExpect(status().isOk()) .andReturn() then: accountRepository.findByEmail(email).get().email == email } } <file_sep>/auth-service/src/main/java/com/journeyplanner/auth/security/dto/TokenResponse.java package com.journeyplanner.auth.security.dto; import lombok.AllArgsConstructor; import lombok.Data; @Data @AllArgsConstructor public class TokenResponse { String tokenType; String token; } <file_sep>/mail-service/src/test/groovy/com/journeyplanner/mail/domain/AdditionalRepositoryMethodsTest.groovy package com.journeyplanner.mail.domain import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.context.SpringBootTest import org.springframework.test.annotation.DirtiesContext import spock.lang.Specification @SpringBootTest @DirtiesContext class AdditionalRepositoryMethodsTest extends Specification { @Autowired private MailService service @Autowired private MailRepository repository def setup() { repository.deleteAll() } def "should find pending mail and change status to update"() { given: 2.times { repository.save(MailMotherObject.aMail(UUID.randomUUID().toString(), MailStatus.PENDING)) } 5.times { repository.save(MailMotherObject.aMail(UUID.randomUUID().toString(), MailStatus.ERROR)) } when: def mail = service.getPendingMessageAndUpdateToProcessingStatus() then: def processingMail = repository.findById(mail.get().getId()) processingMail.get().getStatus() == MailStatus.PROCESSING } def "should update mail status"() { given: def mailId = UUID.randomUUID().toString() def mail = MailMotherObject.aMail(mailId, MailStatus.PROCESSING) repository.save(mail) when: service.updateStatus(mailId, MailStatus.SENT) then: def updateMail = repository.findById(mailId) updateMail.get().getStatus() == MailStatus.SENT } } <file_sep>/payment-service/src/main/java/com/journeyplanner/payment/domain/account/TransferCustomRepositoryImpl.java package com.journeyplanner.payment.domain.account; import lombok.AllArgsConstructor; import org.springframework.data.domain.Sort; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.data.mongodb.core.query.Query; import org.springframework.data.mongodb.core.query.Update; import java.util.Optional; @AllArgsConstructor public class TransferCustomRepositoryImpl implements TransferCustomRepository { private MongoTemplate mongoTemplate; @Override public Optional<Transfer> findPendingAndModifyStatus() { Query query = new Query(); query.addCriteria(Criteria.where("status").is(TransferStatus.PENDING)); query.limit(1); query.with(Sort.by(Sort.Direction.ASC, "eventTime")); Update update = new Update(); update.set("status", TransferStatus.PROCESSING); return Optional.ofNullable(mongoTemplate.findAndModify(query, update, Transfer.class)); } @Override public Optional<Transfer> findAndModifyStatus(final String id, final TransferStatus status) { Query query = new Query(); query.addCriteria(Criteria.where("id").is(id)); Update update = new Update(); update.set("status", status); return Optional.ofNullable(mongoTemplate.findAndModify(query, update, Transfer.class)); } } <file_sep>/payment-service/src/main/java/com/journeyplanner/payment/domain/account/TransferDto.java package com.journeyplanner.payment.domain.account; import com.journeyplanner.common.config.events.TransferType; import lombok.Builder; import lombok.Value; import java.math.BigDecimal; import java.time.Instant; @Value @Builder public class TransferDto { String paymentId; String email; BigDecimal value; TransferType type; TransferStatus status; Instant eventTime; static TransferDto from(Transfer transfer) { return TransferDto.builder() .email(transfer.getEmail()) .paymentId(transfer.getPaymentId()) .value(transfer.getValue()) .type(transfer.getType()) .status(transfer.getStatus()) .eventTime(transfer.getEventTime()) .build(); } } <file_sep>/catalogue-service/src/test/groovy/com/journeyplanner/catalogue/ApplicationTestConfig.groovy package com.journeyplanner.catalogue import com.journeyplanner.catalogue.app.CatalogueServiceApplication import com.journeyplanner.catalogue.infrastructure.output.queue.CancelJourney import com.journeyplanner.catalogue.infrastructure.output.queue.ReservationCreator import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.boot.test.autoconfigure.data.mongo.AutoConfigureDataMongo import org.springframework.boot.test.mock.mockito.MockBean import org.springframework.context.annotation.ComponentScan import org.springframework.context.annotation.FilterType import org.springframework.data.mongodb.repository.config.EnableMongoRepositories import org.springframework.test.context.TestPropertySource @SpringBootApplication @ComponentScan( basePackages = [ "com.journeyplanner.catalogue", "com.journeyplanner.common.config.security" ], excludeFilters = [ @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = CatalogueServiceApplication.class), @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = ReservationCreator.class), @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = CancelJourney.class) ] ) @TestPropertySource(locations = "classpath:test.properties") @AutoConfigureDataMongo @EnableMongoRepositories(basePackages = "com.journeyplanner.catalogue.domain") class ApplicationTestConfig { @MockBean ReservationCreator reservationCreator @MockBean CancelJourney cancelJourney } <file_sep>/catalogue-service/src/main/java/com/journeyplanner/catalogue/domain/photo/PhotoConfiguration.java package com.journeyplanner.catalogue.domain.photo; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class PhotoConfiguration { @Bean PhotoFacade photoFacade(PhotoRepository photoRepository) { return new PhotoFacade(photoRepository, new PhotoCreator()); } } <file_sep>/mail-service/src/main/java/com/journeyplanner/mail/domain/sender/Sender.java package com.journeyplanner.mail.domain.sender; import com.journeyplanner.mail.domain.Mail; public interface Sender { void send(Mail mail, String body); } <file_sep>/auth-service/src/test/groovy/com/journeyplanner/auth/security/CreateTokenSpec.groovy package com.journeyplanner.auth.security import com.fasterxml.jackson.databind.ObjectMapper import com.journeyplanner.auth.security.dto.UserCredentialsRequest import com.journeyplanner.auth.user.AppUserRepository import com.journeyplanner.auth.user.model.AppUser import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc import org.springframework.boot.test.context.SpringBootTest import org.springframework.security.crypto.password.PasswordEncoder import org.springframework.test.annotation.DirtiesContext import org.springframework.test.web.servlet.MockMvc import spock.lang.Specification import javax.ws.rs.core.MediaType import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status @SpringBootTest @DirtiesContext @AutoConfigureMockMvc class CreateTokenSpec extends Specification { @Autowired private MockMvc mvc @Autowired private AppUserRepository repository @Autowired private PasswordEncoder encoder def setup() { repository.deleteAll() } def "should return token"() { given: def email = "<EMAIL>" repository.save(new AppUser(UUID.randomUUID().toString(), email, encoder.encode("12345"), "James", "Bond", "USER", Boolean.FALSE, Boolean.FALSE)) and: def userCredentials = new UserCredentialsRequest(email, "12345") def json = new ObjectMapper().writeValueAsString(userCredentials) when: def result = mvc.perform(post("/auth") .contentType(MediaType.APPLICATION_JSON) .content(json)) .andExpect(status().isOk()) .andReturn() then: print(result.response.getContentAsString()) result.response.getContentAsString().contains("Bearer") } def "should return 400 status code without token when credentials are not valid"() { given: repository.save(new AppUser(UUID.randomUUID().toString(), "<EMAIL>", encoder.encode("12345"), "James", "Bond", "USER", Boolean.FALSE, Boolean.FALSE)) and: def userCredentials = new UserCredentialsRequest("<EMAIL>", "<PASSWORD>") def json = new ObjectMapper().writeValueAsString(userCredentials) when: def result = mvc.perform(post("/auth") .contentType(MediaType.APPLICATION_JSON) .content(json)) .andExpect(status().is4xxClientError()) .andReturn() then: !result.response.getContentAsString().contains("Bearer") } def "should return 400 status without token when user is blocked"() { given: repository.save(new AppUser(UUID.randomUUID().toString(), "<EMAIL>", encoder.encode("12345"), "Gandalf", "White", "USER", Boolean.TRUE, Boolean.FALSE)) and: def userCredentials = new UserCredentialsRequest("<EMAIL>", "<PASSWORD>") def json = new ObjectMapper().writeValueAsString(userCredentials) when: def result = mvc.perform(post("/auth") .contentType(MediaType.APPLICATION_JSON) .content(json)) .andExpect(status().is4xxClientError()) .andReturn() then: !result.response.getContentAsString().contains("Bearer") } } <file_sep>/common/src/main/java/com/journeyplanner/common/config/events/Event.java package com.journeyplanner.common.config.events; public interface Event { } <file_sep>/scripts/healthcheck.sh #!/bin/bash curl -XGET http://localhost:8762/actuator/health curl -XGET http://localhost:9100/actuator/health curl -XGET http://localhost:9105/actuator/health curl -XGET http://localhost:9110/actuator/health curl -XGET http://localhost:9115/actuator/health curl -XGET http://localhost:9120/actuator/health curl -XGET http://localhost:9125/actuator/health<file_sep>/user-service/src/test/groovy/com/journeyplanner/user/domain/details/UserDetailsMotherObject.groovy package com.journeyplanner.user.domain.details class UserDetailsMotherObject { static aUserDetails(String email) { UserDetails.builder() .id(UUID.randomUUID().toString()) .email(email) .country("COUNTRY") .city("CITY") .street("STREET") .postCode("POSTCODE") .phoneNumber("PHONENUMBER") .build() } } <file_sep>/catalogue-service/src/test/groovy/com/journeyplanner/catalogue/domain/journey/GetJourneySpec.groovy package com.journeyplanner.catalogue.domain.journey import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc import org.springframework.boot.test.context.SpringBootTest import org.springframework.test.annotation.DirtiesContext import org.springframework.test.web.servlet.MockMvc import spock.lang.Specification import java.time.Instant import java.time.temporal.ChronoUnit import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status @SpringBootTest @DirtiesContext @AutoConfigureMockMvc class GetJourneySpec extends Specification { @Autowired private MockMvc mvc @Autowired private JourneyRepository journeyRepository def setup() { journeyRepository.deleteAll() } def "should get first page"() { given: def journey1 = JourneyMotherObject.aJourney() def journey2 = JourneyMotherObject.aJourney() def journey3 = JourneyMotherObject.aJourney() journeyRepository.save(journey1) journeyRepository.save(journey2) journeyRepository.save(journey3) when: def result = mvc.perform(get("/catalogue/journeys")) .andExpect(status().isOk()) .andReturn() then: result.response.getContentAsString().contains("\"pageNumber\":0") result.response.getContentAsString().contains("\"totalPages\":1") result.response.getContentAsString().contains("\"pageSize\":10") result.response.getContentAsString().contains("\"offset\":0") result.response.getContentAsString().contains("\"numberOfElements\":3") } def "should get first page with active status"() { given: def journeys = prepareJourneys() journeys.each { value -> journeyRepository.save(value) } when: def result = mvc.perform(get("/catalogue/journeys/?status=ACTIVE")) .andExpect(status().isOk()) .andReturn() then: result.response.getContentAsString().contains("Journey1") result.response.getContentAsString().contains("Journey2") !result.response.getContentAsString().contains("Journey3") } def "should get first page with specific price"() { given: def journeys = prepareJourneys() journeys.each { value -> journeyRepository.save(value) } when: def result = mvc.perform(get("/catalogue/journeys/?price=20&price=200")) .andExpect(status().isOk()) .andReturn() then: !result.response.getContentAsString().contains("Journey1") result.response.getContentAsString().contains("Journey2") !result.response.getContentAsString().contains("Journey3") } def "should get first page with specific date and active"() { given: def journeys = prepareJourneys() journeys.each { value -> journeyRepository.save(value) } when: def result = mvc.perform(get("/catalogue/journeys/?start=2020-03-01T00:00:00.000Z&status=ACTIVE")) .andExpect(status().isOk()) .andReturn() then: result.response.getContentAsString().contains("Journey1") result.response.getContentAsString().contains("Journey2") !result.response.getContentAsString().contains("Journey3") } def prepareJourneys() { def journey1 = Journey.builder() .id(UUID.randomUUID().toString()) .name("Journey1") .country("CountryJourney1") .status(JourneyStatus.ACTIVE) .city("CityJourney1") .description("DescriptionJourney1") .transportType("PLAIN") .price(new BigDecimal(10)) .start(Instant.now().plus(10, ChronoUnit.DAYS)) .end(Instant.now().plus(12, ChronoUnit.DAYS)) .guideEmail("") .guideName("") .build() def journey2 = Journey.builder() .id(UUID.randomUUID().toString()) .name("Journey2") .country("CountryJourney2") .status(JourneyStatus.ACTIVE) .city("CityJourney2") .description("DescriptionJourney2") .transportType("TRAIN") .price(new BigDecimal(100)) .start(Instant.now().plus(15, ChronoUnit.DAYS)) .end(Instant.now().plus(16, ChronoUnit.DAYS)) .guideEmail("") .guideName("") .build() def journey3 = Journey.builder() .id(UUID.randomUUID().toString()) .name("Journey3") .country("CountryJourney3") .status(JourneyStatus.INACTIVE) .city("CityJourney3") .description("DescriptionJourney3") .transportType("TRAIN") .price(new BigDecimal(1000)) .start(Instant.now().plus(20, ChronoUnit.DAYS)) .end(Instant.now().plus(22, ChronoUnit.DAYS)) .guideEmail("") .guideName("") .build() [journey1, journey2, journey3] } } <file_sep>/auth-service/src/test/groovy/com/journeyplanner/auth/ApplicationTestConfig.groovy package com.journeyplanner.auth import com.journeyplanner.auth.app.AuthServiceApplication import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.boot.test.autoconfigure.data.mongo.AutoConfigureDataMongo import org.springframework.context.annotation.ComponentScan import org.springframework.context.annotation.FilterType import org.springframework.data.mongodb.repository.config.EnableMongoRepositories import org.springframework.test.context.TestPropertySource @SpringBootApplication @ComponentScan( basePackages = [ "com.journeyplanner.auth", "com.journeyplanner.common.config.security" ], excludeFilters = [ @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = AuthServiceApplication.class) ] ) @TestPropertySource(locations = "classpath:test.properties") @AutoConfigureDataMongo @EnableMongoRepositories(basePackages = "com.journeyplanner.auth") class ApplicationTestConfig { } <file_sep>/catalogue-service/src/main/java/com/journeyplanner/catalogue/domain/journey/JourneyUpdater.java package com.journeyplanner.catalogue.domain.journey; import com.journeyplanner.catalogue.infrastructure.input.request.AddGuideToJourneyRequest; import com.journeyplanner.catalogue.infrastructure.input.request.UpdateJourneyRequest; class JourneyUpdater { Journey from(Journey journey, UpdateJourneyRequest request) { return Journey.builder() .id(journey.getId()) .name(request.getName()) .status(journey.getStatus()) .city(request.getCity()) .country(request.getCountry()) .description(request.getDescription()) .transportType(request.getTransportType()) .price(request.getPrice()) .start(journey.getStart()) .end(journey.getEnd()) .guideName(journey.getGuideName()) .guideEmail(journey.getGuideEmail()) .build(); } Journey from(Journey journey, AddGuideToJourneyRequest request) { return Journey.builder() .id(journey.getId()) .name(journey.getName()) .status(journey.getStatus()) .city(journey.getCity()) .country(journey.getCountry()) .description(journey.getDescription()) .transportType(journey.getTransportType()) .price(journey.getPrice()) .start(journey.getStart()) .end(journey.getEnd()) .guideName(request.getFirstName() + " " + request.getSecondName()) .guideEmail(request.getEmail()) .build(); } Journey fromWithoutGuide(Journey journey) { return Journey.builder() .id(journey.getId()) .name(journey.getName()) .status(journey.getStatus()) .city(journey.getCity()) .country(journey.getCountry()) .description(journey.getDescription()) .transportType(journey.getTransportType()) .price(journey.getPrice()) .start(journey.getStart()) .end(journey.getEnd()) .guideName("") .guideEmail("") .build(); } } <file_sep>/user-service/src/main/java/com/journeyplanner/user/infrastructure/input/rest/UserController.java package com.journeyplanner.user.infrastructure.input.rest; import com.journeyplanner.user.domain.avatar.AvatarDto; import com.journeyplanner.user.domain.details.UserDetailsDto; import com.journeyplanner.user.domain.details.UserDetailsFacade; import com.journeyplanner.user.domain.user.GuideDto; import com.journeyplanner.user.domain.user.User; import com.journeyplanner.user.domain.user.UserDto; import com.journeyplanner.user.domain.user.UserFacade; import com.journeyplanner.user.infrastructure.input.request.*; import com.journeyplanner.user.infrastructure.input.response.BasicInfoUserResponse; import com.querydsl.core.types.Predicate; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import org.springframework.data.querydsl.binding.QuerydslPredicate; import org.springframework.data.web.PageableDefault; import org.springframework.data.web.SortDefault; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import javax.validation.Valid; import java.util.List; @RestController @RequestMapping("users") @Slf4j @AllArgsConstructor @Api(tags = "UserAPI") public class UserController { private final UserFacade userFacade; private final UserDetailsFacade userDetailsFacade; @PostMapping("register") @ResponseStatus(HttpStatus.NO_CONTENT) @ApiOperation(value = "Register New User", notes = "Anonymous") public void createUser(@RequestBody @Valid CreateUserRequest request) { userFacade.create(request); } @PostMapping("reset") @ResponseStatus(HttpStatus.NO_CONTENT) @ApiOperation(value = "Send Email With Reset Password Token", notes = "Anonymous") public void generateResetPasswordLink(@RequestBody @Valid GenerateResetPasswordLinkRequest request) { userFacade.sendResetPasswordToken(request); } @PostMapping("reset/request") @ResponseStatus(HttpStatus.NO_CONTENT) @ApiOperation(value = "Send Email With Request Reset Password", notes = "Admin") public void generateResetPasswordLinkByAdminRequest(@RequestBody @Valid GenerateResetPasswordLinkRequest request) { userFacade.sendResetPasswordTokenByAdminRequest(request); } @PostMapping("password") @ResponseStatus(HttpStatus.NO_CONTENT) @ApiOperation(value = "Reset Password", notes = "Anonymous") public void resetPassword(@RequestBody @Valid ResetPasswordRequest request) { userFacade.resetPassword(request); } @PostMapping("block") @ResponseStatus(HttpStatus.NO_CONTENT) @ApiOperation(value = "Add User to blacklist", notes = "Admin") public void addUserToBlacklist(@RequestBody @Valid AddUserToBlacklistRequest request) { userFacade.block(request); } @DeleteMapping("block") @ResponseStatus(HttpStatus.NO_CONTENT) @ApiOperation(value = "Remove User from blacklist", notes = "Admin") public void removeUserFromBlacklist(@RequestBody @Valid RemoveUserFromBlacklistRequest request) { userFacade.unblock(request); } @GetMapping @ResponseStatus(HttpStatus.OK) @ApiOperation(value = "Get all Users", notes = "Admin") public ResponseEntity<Page<UserDto>> getUsers(@PageableDefault @SortDefault.SortDefaults(@SortDefault(sort = "email", direction = Sort.Direction.DESC)) Pageable pageable, @QuerydslPredicate(root = User.class) Predicate predicate) { return ResponseEntity.ok(userFacade.getAll(predicate, pageable)); } @GetMapping("details") @ApiOperation(value = "Get User Details", notes = "User") public ResponseEntity<UserDetailsDto> getUserDetails(@RequestHeader("x-username") String username) { return ResponseEntity.ok(userDetailsFacade.getDetailsByEmail(username)); } @PostMapping("details") @ApiOperation(value = "Update User Details", notes = "User") public ResponseEntity<UserDetailsDto> updateUserDetails(@RequestHeader("x-username") String username, @RequestBody @Valid UpdateUserDetailsRequest request) { return ResponseEntity.ok(userDetailsFacade.addOrUpdateDetails(username, request)); } @GetMapping("details/{id}") @ApiOperation(value = "Get User Details By Id", notes = "Admin") public ResponseEntity<UserDetailsDto> getUserDetailsById(@PathVariable("id") String userId) { UserDto user = userFacade.findById(userId); return ResponseEntity.ok(userDetailsFacade.getDetailsByEmail(user.getEmail())); } @GetMapping(value = "avatar", produces = MediaType.IMAGE_JPEG_VALUE) @ApiOperation(value = "Get User Avatar", notes = "User") public ResponseEntity<byte[]> getAvatarForUser(@RequestHeader("x-username") String username) { AvatarDto avatarDto = userDetailsFacade.getAvatarByEmail(username); return ResponseEntity.ok(avatarDto.getImage().getData()); } @PostMapping(value = "avatar") @ResponseStatus(HttpStatus.NO_CONTENT) @ApiOperation(value = "Add/Update User Avatar", notes = "User") public void add(@RequestHeader("x-username") String username, @RequestParam("image") MultipartFile file) { userDetailsFacade.addAvatar(username, file); } @GetMapping("guides") @ApiOperation(value = "Get Guides", notes = "Admin") public ResponseEntity<List<GuideDto>> guides() { return ResponseEntity.ok(userFacade.getGuides()); } @PostMapping("register/guides") @ResponseStatus(HttpStatus.NO_CONTENT) @ApiOperation(value = "Add new guide", notes = "Admin") public void createGuide(@RequestBody @Valid CreateGuideRequest request) { userFacade.createGuide(request); } @GetMapping("basic") public ResponseEntity<BasicInfoUserResponse> getUserBasicInfo(@RequestParam("email") String email) { return ResponseEntity.ok(userFacade.findByEmail(email)); } }
a7228879491dc8d0cf2c3cdc24b123d567dafdad
[ "Shell", "INI", "Java", "Groovy", "Markdown", "YAML" ]
130
Shell
mchrapek/studia-projekt-zespolowy-backend
196ea7576834b6811ea648370cd069540be5f4bb
9762be6dab96363b6a03b3a2b3d2a37aafef8b6f
refs/heads/master
<file_sep><!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title><NAME>'s Recipes</title> <link rel="stylesheet" type="text/css" href="styles.css" > </head> <body> <div id="container"> <header> <h1><NAME> Recipes</h1> <nav> <ul> <li><a class="current" href="index.html">Home</a></li> <li><a href="rice.html">Rice</a></li> <li><a href="beans.html">Beans</a></li> <li><a href="sofrito.html">Sofrito</a></li> </ul> </nav> </header> <section> <h2>My Homepage</h2> <p><img class="image" src="images/sadie.png" title="My dog, Sadie" alt="My dog, Sadie" />Welcome to my recipes site! As a recent transplant from Tampa, FL, now living in Birmingham, AL, caribbean-style spanish food can be hard to come by. Almost everything spanish around Birmingham is based around Mexican culture. And while burritos and tacos are always delicious, I need some home-cooked style Puerto Rican food in my life and the only way to get it is to cook it myself. So I'm going to show you how to make a few Puerto Rican staples that are tasty and cheap!</p> <div id="homeList"> <ol> <li><a href="rice.html">White Rice</a></li> <li><a href="beans.html">Garbanzo Beans</a></li> <li><a href="sofrito.html">Sofrito</a></li> </ol> </div> </section> <aside> <h3>About My Recipes</h3> <p> The recipes I'm sharing with you are my version of these Puerto Rican foods. I don't claim them to be entirely authentic to something you'd get on the island or even authentic to Tampa; they're pretty close though. I tinker with recipes until I've made them my own and I suggest you do the same with these. </p> <h3>Contact Me</h3> <p>You can reach me at <a href="mailto:<EMAIL>"><EMAIL></a> or follow me on <a href="https://www.instagram.com/bert0rican" target="_blank">Instagram</a>. But you'd probably rather follow my dog, <a href="https://www.instagram.com/sadie.says.so" target="_blank">Sadie</a>. </aside> </div> </body> </html><file_sep># C376_-_Web_Project WGU project to demonstrate basic understanding of HTML and CSS Test Change 2
cb58b2a5c5317eec8811d92d3548625c7b1790a8
[ "Markdown", "HTML" ]
2
Markdown
RBertoCases/C376-Web-Project
511fce989245d0d2a33315c05c4f0b5b9e525bad
b6df98803a2d499bcf4f6295b437a262fdcea43e
refs/heads/master
<repo_name>qiyulin/php_workspace-Base<file_sep>/Base/.htaccess RewriteEngine on #default RewriteRule ^index/(\w+)$ index/core/$1.php [NC] RewriteRule ^admin/(\w+)$ admin/core/$1.php [NC] #index RewriteRule ^index[/]{0,1}$ index/core/index.php [NC] RewriteRule ^admin[/]{0,1}$ admin/core/index.php [NC] RewriteRule ^(/)?$ index/core/index.php [L]<file_sep>/House/admin/core/index.php <?php include_once('common.php'); #log error_log(getDatetime()." action->".phpSelfname()."\n","3",getPath()."console.log"); #check session $user= !empty($_SESSION['user']) ? $_SESSION['user'] : header("Location:".htaccess('admin/core/login.php?t=timeout')); #main include_once(getTPL()); ?><file_sep>/House/admin/core/login.php <?php include_once('common.php'); #log error_log(getDatetime()." action->".phpSelfname()."?t=".@$_GET["t"]."\n","3",getPath()."console.log"); #get $type = @$_GET["t"]; #logout $error=""; if(!empty($type)&&$type=="logout"){ $error="用户已退出,请重新登录"; } #timeout if(!empty($type)&&$type=='timeout'){ $error="用户认证超时,请重新登录"; } #login $status = 0; if(!empty($type)&&$type=="login"){ $username = @$_POST['username']; $password = @$_POST['<PASSWORD>']; if(!empty($username)&&!empty($password)){ $sql = "select * from ".tablePrefix()."user where username=? and status=1 limit 1"; $res=_select($sql,array($username)); if(!empty($res)&&count($res)>0){ $user = $res[0]; $user_pwd = $user['<PASSWORD>']; if(md5($password)==$user_pwd){ $_SESSION['user']=$user; //session $error="登录成功,正在跳转"; $status=1; }else{ $error="密码错误,请检查密码填写"; $status=0; } }else{ $error="登录失败,未找到该用户"; $status=0; } }else{ $error="登录失败,用户名或密码不能为空"; $status=0; } } #return include_once(getTPL()); ?><file_sep>/House/admin/core/common.php <?php /** *@author com.love *general methods and configuration *@date 2015 12 19 **/ session_start(); #分页大小 define("page_size", 20); #根目录 define("ROOT", getROOT()); //get connection function getConnection(){ $config =include('../../config.php'); $con = new mysqli($config["DB_HOST"],$config["DB_USER"],$config["DB_PWD"],$config["DB_NAME"],$config["DB_PORT"]); if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit(); } mysqli_set_charset($con,"UTF8"); return $con; } //close connection function closeConnection($con){ mysqli_close($con); } //table_prefix function tablePrefix(){ $config =include('../../config.php'); return $config['DB_PREFIX']; } //find types is array, params is array function _select($sql,$values=null){ if($values!=null&&count($values)==0){ $values=null; } #log error_log(getDatetime()." db->sql:".$sql." ->values:".json_encode($values)."\n","3",getPath()."console.log"); #con $con = getConnection(); $stmt = $con->prepare($sql); #bind param if($values){ $args= ""; for($i=0;$i<count($values);$i++){ $value = $values[$i]; if(is_integer($value)){ $args.='i'; }else if(is_double($value)||is_float($value)){ $args.='d'; }else if(is_string($value)){ $args.='s'; }else{ $args.='b'; } } if(!empty($args)){ call_user_func_array(array($stmt,'bind_param'), array_merge((array)$args,$values)); } } $stmt->execute(); #bind result $array = array(); $variables = array(); $data = array(); $meta = $stmt->result_metadata(); while($field = $meta->fetch_field()) $variables[] = &$data[$field->name]; // pass by reference call_user_func_array(array($stmt, 'bind_result'), $variables); #return $i=0; while($stmt->fetch()){ $array[$i] = array(); foreach($data as $k=>$v) $array[$i][$k] = $v; $i++; } # close statement $stmt->close(); closeConnection($con); return $array; } //findCount types is array, params is array function _selectCount($sql,$values=null){ if($values!=null&&count($values)==0){ $values=null; } #jiexi $start = strpos($sql," from "); $end = strpos($sql," order "); $sql="select count(*) as count ".substr($sql,$start,$end-$start); #log error_log(getDatetime()." db->sql:".$sql." ->values:".json_encode($values)."\n","3",getPath()."console.log"); #con $con = getConnection(); $stmt = $con->prepare($sql); #bind param if($values){ $args= ""; for($i=0;$i<count($values);$i++){ $value = $values[$i]; if(is_integer($value)){ $args.='i'; }else if(is_double($value)||is_float($value)){ $args.='d'; }else if(is_string($value)){ $args.='s'; }else{ $args.='b'; } } if(!empty($args)){ call_user_func_array(array($stmt,'bind_param'), array_merge((array)$args,$values)); } } $stmt->execute(); #bind result $all= 0; $stmt->bind_result($count); if ($stmt->fetch()) { $all = $count; } # close statement $stmt->close(); closeConnection($con); return $all; } //execute function _execute($sql,$values=null,$insert_id =false){ if($values!=null&&count($values)==0){ $values=null; } #log error_log(getDatetime()." db->sql:".$sql." ->values:".json_encode($values)."\n","3",getPath()."console.log"); #con $con = getConnection(); $stmt = $con->prepare($sql); #bind param if($values){ $args= ""; for($i=0;$i<count($values);$i++){ $value = $values[$i]; if(is_integer($value)){ $args.='i'; }else if(is_double($value)||is_float($value)){ $args.='d'; }else if(is_string($value)){ $args.='s'; }else{ $args.='b'; } } if(!empty($args)&&!empty($stmt)){ call_user_func_array(array($stmt,'bind_param'), array_merge((array)$args,$values)); } } $stmt->execute(); if($insert_id){ $id = $stmt->insert_id; #close $stmt->close(); closeConnection($con); #return return $id; }else{ #close $stmt->close(); closeConnection($con); } } //get client ip function getClientIp(){ static $ip = NULL; if($_SERVER['HTTP_X_REAL_IP']){//nginx agent $ip=$_SERVER['HTTP_X_REAL_IP']; }elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {//客户端的ip $ip=$_SERVER['HTTP_CLIENT_IP']; }elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {//浏览当前页面的用户计算机的网关 $arr=explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']); $pos=array_search('unknown',$arr); if(false !== $pos) unset($arr[$pos]); $ip=trim($arr[0]); }elseif (isset($_SERVER['REMOTE_ADDR'])) { $ip=$_SERVER['REMOTE_ADDR'];//浏览当前页面的用户计算机的ip地址 }else{ $ip=$_SERVER['REMOTE_ADDR']; } return $ip; } //htaccess function htaccess($url){ $uri = $_SERVER["REQUEST_URI"]; $uri= substr($uri,0,strrpos($uri, "/")); $uri= substr($uri,0,strrpos($uri, "/")+1); $url = str_replace(".php", "", $url); $url = str_replace("core/", "", $url); return $uri.$url; } //get tpl function getTPL($name=null){ if($name==null){ $base=$_SERVER['SCRIPT_NAME']; $arr=explode("/",$base); $default_name = $arr[count($arr)-1]; return "../tpl/".str_replace(".php", "",$default_name).".html"; }else{ return "../tpl/".$name.".html"; } } //get ROOT function getROOT(){ $host = $_SERVER["SERVER_NAME"]; $port = $_SERVER["SERVER_PORT"]; $uri = $_SERVER["REQUEST_URI"]; $uri= substr($uri,0,strrpos($uri, "/")); $uri= substr($uri,0,strrpos($uri, "/")+1); return 'http://'.$host.($port==80?"":$port).$uri; } //get Path function getPath(){ return dirname(dirname(dirname(__FILE__))).DIRECTORY_SEPARATOR; } //get datetime function getDatetime(){ return date("Y-m-d H:i:s"); } //get current access php file name function phpSelfname(){ $php_self=substr($_SERVER['PHP_SELF'],strrpos($_SERVER['PHP_SELF'],'/')+1); return $php_self; } ?><file_sep>/House/admin/core/house_village.php <?php include_once('common.php'); #log error_log(getDatetime()." action->".phpSelfname()."?t=".@$_GET["t"]."\n","3",getPath()."console.log"); #check session $user= !empty($_SESSION['user']) ? $_SESSION['user'] : header("Location:".htaccess('admin/core/login.php?t=timeout')); #op $type= @$_GET['t']; //list if(!empty($type)&&$type=="list"){ #地区 $sql_dq = "select id,name,parent_id from ".tablePrefix()."house_area where status= 0 order by id asc"; $arr_dq = _select($sql_dq); #tpl include_once(getTPL()); exit(); } //json if(!empty($type)&&$type=="json"){ $where=""; $where_values= array(); $q1 = @$_GET["q1"]; if(!empty($q1)){ $where.=" and hv.house_area_id = ?"; $where_values[]=$q1; } $q2 = @$_GET["q2"]; if(!empty($q2)){ $where.=" and hv.name like ?"; $where_values[] = '%'.$q2.'%'; } #page $page = @$_GET["page"]; if(empty($page)){ $page = 1; } #sql $sql = "select hv.*,ha.name as ha_name from ".tablePrefix()."house_village as hv left join ".tablePrefix()."house_area as ha on hv.house_area_id=ha.id where 1 ".$where." order by hv.createtime desc limit ".($page-1)*page_size.",".page_size; #find data $arr=_select($sql,$where_values); for($i=0;$i<count($arr);$i++){ $status=$arr[$i]["status"]; $status_str = "启用"; $status_label = '<span class="badge badge-danger">已禁用</span>'; if($status==0){ $status_str="禁用"; $status_label = '<span class="badge badge-success">已启用</span>'; } $arr[$i]["status_str"] = $status_str; $arr[$i]["status_label"]=$status_label; } #sql count $count = _selectCount($sql,$where_values); #json echo json_encode(array('list'=>$arr,'count'=>$count,'status'=>1)); exit(); } //status if(!empty($type)&&$type=="status"){ #param $status = @$_GET["status"]; $id = @$_GET["id"]; #update if(!empty($id)){ if($status!=null&&$status=="0"){ $status = 1; }else{ $status = 0; } $sql ="update ".tablePrefix()."house_village set status =? where id = ?"; _execute($sql,array($status,$id)); $error ="操作成功"; }else{ $error="操作失败,缺少必要参数"; } #tpl include_once(getTPL("tishi")); exit(); } //edit if(!empty($type)&&$type=='edit'){ #地区 $sql_dq = "select id,name,parent_id from ".tablePrefix()."house_area where status= 0 order by id asc"; $arr_dq = _select($sql_dq); #tpl include_once(getTPL("house_village-edit")); exit(); } ?><file_sep>/House/README.md php基础开发框架 =================================== ### 安装 1.删除install.lock文件 2.访问install执行安装 <file_sep>/Base/install/house.sql -- com.love -- date:2015 12 19 -- db file -- -- 表的结构 `h_access` -- DROP TABLE IF EXISTS `h_access`; CREATE TABLE `h_access` ( `role_id` smallint(6) unsigned NOT NULL DEFAULT '0', `node_id` smallint(6) unsigned NOT NULL DEFAULT '0', `level` tinyint(1) unsigned NOT NULL DEFAULT '0', `pid` smallint(6) unsigned NOT NULL DEFAULT '0', `model` varchar(50) DEFAULT NULL DEFAULT '', KEY `groupId` (`role_id`), KEY `nodeId` (`node_id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8; -- -- 表的结构 `h_article` -- DROP TABLE IF EXISTS `h_article`; CREATE TABLE `h_article` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `catid` smallint(5) unsigned NOT NULL DEFAULT '0' , `userid` int(11) unsigned NOT NULL DEFAULT '0' , `username` varchar(40) NOT NULL DEFAULT '' , `title` varchar(120) NOT NULL DEFAULT '' , `title_style` varchar(40) NOT NULL DEFAULT '' , `keywords` varchar(120) NOT NULL DEFAULT '' , `copyfrom` varchar(40) NOT NULL DEFAULT '' , `fromlink` varchar(80) NOT NULL DEFAULT '0' , `description` mediumtext NOT NULL , `content` text NOT NULL, `template` varchar(30) NOT NULL DEFAULT '', `thumb` varchar(100) NOT NULL DEFAULT '' , `posid` tinyint(2) unsigned NOT NULL DEFAULT '0' , `status` tinyint(1) unsigned NOT NULL DEFAULT '0' , `recommend` tinyint(1) unsigned NOT NULL DEFAULT '1', `readgroup` varchar(255) NOT NULL DEFAULT '', `readpoint` int(10) unsigned NOT NULL DEFAULT '0', `listorder` int(10) unsigned NOT NULL DEFAULT '0' , `url` varchar(50) NOT NULL DEFAULT '', `hits` int(11) unsigned NOT NULL DEFAULT '0' , `createtime` int(11) unsigned NOT NULL DEFAULT '0' , `updatetime` int(11) unsigned NOT NULL DEFAULT '0' , PRIMARY KEY (`id`), KEY `status` (`id`,`status`,`listorder`), KEY `catid` (`id`,`catid`,`status`), KEY `listorder` (`id`,`catid`,`status`,`listorder`) ) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8; -- -- 表的结构 `h_attachment` -- DROP TABLE IF EXISTS `h_attachment`; CREATE TABLE `h_attachment` ( `aid` int(10) unsigned NOT NULL AUTO_INCREMENT, `moduleid` tinyint(2) unsigned NOT NULL DEFAULT '0', `catid` smallint(5) unsigned NOT NULL DEFAULT '0', `id` int(8) unsigned NOT NULL DEFAULT '0', `filename` varchar(50) NOT NULL DEFAULT '', `filepath` varchar(80) NOT NULL DEFAULT '', `filesize` int(10) unsigned NOT NULL DEFAULT '0', `fileext` char(10) NOT NULL DEFAULT '', `isimage` tinyint(1) unsigned NOT NULL DEFAULT '0', `isthumb` tinyint(1) unsigned NOT NULL DEFAULT '0', `userid` mediumint(8) unsigned NOT NULL DEFAULT '0', `createtime` int(10) unsigned NOT NULL DEFAULT '0', `uploadip` char(15) NOT NULL DEFAULT '', `status` tinyint(1) unsigned NOT NULL DEFAULT '0', PRIMARY KEY (`aid`) ) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8; -- -- 表的结构 `h_category` -- DROP TABLE IF EXISTS `h_category`; CREATE TABLE `h_category` ( `id` smallint(5) unsigned NOT NULL AUTO_INCREMENT, `catname` varchar(255) NOT NULL DEFAULT '' , `catdir` varchar(30) NOT NULL DEFAULT '', `parentdir` varchar(50) NOT NULL DEFAULT '', `parentid` smallint(5) unsigned NOT NULL DEFAULT '0' , `moduleid` tinyint(2) unsigned NOT NULL DEFAULT '0', `module` char(24) NOT NULL DEFAULT '', `arrparentid` varchar(100) NOT NULL DEFAULT '', `arrchildid` varchar(100) NOT NULL DEFAULT '', `type` tinyint(1) unsigned NOT NULL DEFAULT '0' , `title` varchar(150) NOT NULL DEFAULT '', `keywords` varchar(200) NOT NULL DEFAULT '' , `description` varchar(255) NOT NULL DEFAULT '' , `listorder` smallint(5) unsigned NOT NULL DEFAULT '0' , `ishtml` tinyint(1) unsigned NOT NULL DEFAULT '0', `ismenu` tinyint(1) unsigned NOT NULL DEFAULT '0' , `hits` int(10) unsigned NOT NULL DEFAULT '0' , `image` varchar(100) NOT NULL DEFAULT '', `child` tinyint(1) unsigned NOT NULL DEFAULT '0' , `url` varchar(100) NOT NULL DEFAULT '', `template_list` varchar(20) NOT NULL DEFAULT '', `template_show` varchar(20) NOT NULL DEFAULT '', `pagesize` tinyint(2) unsigned NOT NULL DEFAULT '0', `readgroup` varchar(100) NOT NULL DEFAULT '', `listtype` tinyint(1) unsigned NOT NULL DEFAULT '0', `lang` tinyint(1) unsigned NOT NULL DEFAULT '0', PRIMARY KEY (`id`), KEY `parentid` (`parentid`), KEY `listorder` (`listorder`) ) ENGINE=MyISAM AUTO_INCREMENT=20 DEFAULT CHARSET=utf8; -- -- 导出`h_category`表中的数据 `h_category` -- INSERT INTO `h_category` VALUES ('1','新闻中心','news','','0','2','Article','0','1,2,3,10,16','0','公司新闻11','公司新闻','公司新闻','0','0','1','0','','1','/index.php?m=Article&a=index&id=1','','','0','','1','0'); INSERT INTO `h_category` VALUES ('2','行业新闻','hangye','news/','1','2','Article','0,1','2','0','行业新闻','行业新闻','行业新闻','0','0','1','0','','0','/index.php?m=Article&a=index&id=2','','','0','','0','0'); INSERT INTO `h_category` VALUES ('3','公司新闻','gongsi','news/','1','2','Article','0,1','3','0','公司新闻','公司新闻','公司新闻','0','0','1','0','','0','/index.php?m=Article&a=index&id=3','','','0','','0','0'); INSERT INTO `h_category` VALUES ('4','产品展示','Product','','0','3','Product','0','4,5,6,7,9,13','0','产品展示标题','产品展示关键词','产品展示栏目简介','0','0','1','0','','1','/index.php?m=Product&a=index&id=4','','','0','','0','0'); INSERT INTO `h_category` VALUES ('5','产品分类1','cp1','Product/','4','3','Product','0,4','5','0','产品分类1','产品分类1产品分类1','产品分类1','0','0','1','0','','0','/index.php?m=Product&a=index&id=5','','','0','2,3,4','0','0'); INSERT INTO `h_category` VALUES ('6','产品分类2','cp2','Product/','4','3','Product','0,4','6','0','产品分类2','产品分类2','产品分类2','0','0','1','0','','0','/index.php?m=Product&a=index&id=6','','','0','','0','0'); INSERT INTO `h_category` VALUES ('7','产品分类3','cp3','Product/','4','3','Product','0,4','7','0','产品分类3','产品分类3','产品分类3','0','0','1','0','','0','/index.php?m=Product&a=index&id=7','','','0','','0','0'); INSERT INTO `h_category` VALUES ('8','关于我们','about','','0','1','Page','0','8,11,12','0','','','','99','0','1','0','','1','/index.php?m=Page&a=index&id=8','','','0','','0','0'); INSERT INTO `h_category` VALUES ('10','行业资讯','zixun','news/','1','2','Article','0,1','10','0','','','','0','0','1','0','','0','/index.php?m=Article&a=index&id=10','','','0','','0','0'); INSERT INTO `h_category` VALUES ('13','产品分类5','cp5','Product/cp4/','9','3','Product','0,4,9','13','0','','','','0','0','1','0','','0','/index.php?m=Product&a=index&id=13','','Product_show','0','','0','0'); INSERT INTO `h_category` VALUES ('9','产品分类4','cp4','Product/','4','3','Product','0,4','9,13','0','','','','0','0','1','0','','1','/index.php?m=Product&a=index&id=9','','','0','2,3','0','0'); INSERT INTO `h_category` VALUES ('11','公司简介','info','about/','8','1','Page','0,8','11','0','','','','0','0','1','0','','0','/index.php?m=Page&a=index&id=11','','','0','','0','0'); INSERT INTO `h_category` VALUES ('12','联系我们','contactus','about/','8','1','Page','0,8','12','0','联系我们','联系我们','联系我们','0','0','1','0','','0','/index.php?m=Page&a=index&id=12','','','0','','0','0'); INSERT INTO `h_category` VALUES ('14','图片展示','pics','','0','4','Picture','0','14','0','','','','0','0','1','0','','0','/index.php?m=Picture&a=index&id=14','','','0','','0','0'); INSERT INTO `h_category` VALUES ('17','文档下载','down','','0','5','Download','0','17','0','','','','0','0','1','0','','0','/index.php?m=Download&a=index&id=17','','','0','','0','0'); INSERT INTO `h_category` VALUES ('16','国内新闻','cnnews','news/','1','2','Article','0,1','16','0','','','','0','0','1','0','','0','/index.php?m=Article&a=index&id=16','','','0','','0','0'); INSERT INTO `h_category` VALUES ('18','信息反馈','Feedback','Guestbook/','19','6','Feedback','0,19','18','0','','','','0','0','1','0','','0','/index.php?m=Feedback&a=index&id=18','','','0','','0','0'); INSERT INTO `h_category` VALUES ('19','在线留言','Guestbook','','0','8','Guestbook','0','19,18','0','','','','0','0','1','0','','1','/index.php?m=Guestbook&a=index&id=19','','','5','','0','0'); -- -- 表的结构 `h_config` -- DROP TABLE IF EXISTS `h_config`; CREATE TABLE `h_config` ( `id` smallint(8) unsigned NOT NULL AUTO_INCREMENT, `varname` varchar(20) NOT NULL DEFAULT '', `info` varchar(100) NOT NULL DEFAULT '', `groupid` tinyint(3) unsigned NOT NULL DEFAULT '1', `value` text NOT NULL, `type` tinyint(1) unsigned NOT NULL DEFAULT '1', PRIMARY KEY (`id`), KEY `varname` (`varname`) ) ENGINE=MyISAM AUTO_INCREMENT=51 DEFAULT CHARSET=utf8; -- -- 导出`h_config`表中的数据 `h_config` -- INSERT INTO `h_config` VALUES ('1','site_name','网站名称','2','House简易房产管理系统','2'); INSERT INTO `h_config` VALUES ('2','site_url','网站网址','2','http://localhost','2'); INSERT INTO `h_config` VALUES ('3','logo','网站LOGO','2','./index/images/logo.png','2'); INSERT INTO `h_config` VALUES ('4','site_company_name','企业名称','2','House简易房产管理系统','2'); INSERT INTO `h_config` VALUES ('5','site_email','站点邮箱','2','<EMAIL>','2'); INSERT INTO `h_config` VALUES ('6','site_contact_name','联系人','2','liuxun','2'); INSERT INTO `h_config` VALUES ('7','site_tel','联系电话','2','0317-5022625','2'); INSERT INTO `h_config` VALUES ('8','site_mobile','手机号码','2','13292793176','2'); INSERT INTO `h_config` VALUES ('9','site_fax','传真号码','2','0317-5022625','2'); INSERT INTO `h_config` VALUES ('10','site_address','公司地址','2','山东省威海市xx','2'); INSERT INTO `h_config` VALUES ('11','qq','客服QQ','2','147613338','2'); INSERT INTO `h_config` VALUES ('12','seo_title','网站标题','3','House简易房产管理系统','2'); INSERT INTO `h_config` VALUES ('13','seo_keywords','关键词','3','房产,房产系统,简易房产系统','2'); INSERT INTO `h_config` VALUES ('14','seo_description','网站简介','3','House简易房产系统,采用原生php不采用任何第三方框架开发,更快,更简单,更高效,同时伴有手机端APP公开发布','2'); INSERT INTO `h_config` VALUES ('15','mail_type','邮件发送模式','4','1','2'); INSERT INTO `h_config` VALUES ('16','mail_server','邮件服务器','4','smtp.yourphp.cn','2'); INSERT INTO `h_config` VALUES ('17','mail_port','邮件发送端口','4','25','2'); INSERT INTO `h_config` VALUES ('18','mail_from','发件人地址','4','<EMAIL>','2'); INSERT INTO `h_config` VALUES ('19','mail_auth','AUTH LOGIN验证','4','1','2'); INSERT INTO `h_config` VALUES ('20','mail_user','验证用户名','4','<EMAIL>','2'); INSERT INTO `h_config` VALUES ('21','mail_password','验证密码','4','','2'); INSERT INTO `h_config` VALUES ('22','attach_maxsize','允许上传附件大小','5','5200000','1'); INSERT INTO `h_config` VALUES ('23','attach_allowext','允许上传附件类型','5','jpg,jpeg,gif,png,doc,docx,rar,zip,swf','2'); INSERT INTO `h_config` VALUES ('24','watermark_enable','是否开启图片水印','5','1','1'); INSERT INTO `h_config` VALUES ('25','watemard_text','水印文字内容','5','YourPHP','2'); INSERT INTO `h_config` VALUES ('26','watemard_text_size','文字大小','5','18','1'); INSERT INTO `h_config` VALUES ('27','watemard_text_color','watemard_text_color','5','#FFFFFF','2'); INSERT INTO `h_config` VALUES ('28','watemard_text_face','字体','5','elephant.ttf','2'); INSERT INTO `h_config` VALUES ('29','watermark_minwidth','图片最小宽度','5','300','1'); INSERT INTO `h_config` VALUES ('30','watermark_minheight','水印最小高度','5','300','1'); INSERT INTO `h_config` VALUES ('31','watermark_img','水印图片名称','5','mark.png','2'); INSERT INTO `h_config` VALUES ('32','watermark_pct','水印透明度','5','80','1'); INSERT INTO `h_config` VALUES ('33','watermark_quality','JPEG 水印质量','5','100','1'); INSERT INTO `h_config` VALUES ('34','watermark_pospadding','水印边距','5','10','1'); INSERT INTO `h_config` VALUES ('35','watermark_pos','水印位置','5','9','1'); INSERT INTO `h_config` VALUES ('36','PAGE_LISTROWS','列表分页数','6','15','1'); INSERT INTO `h_config` VALUES ('37','URL_MODEL','URL访问模式','6','0','1'); INSERT INTO `h_config` VALUES ('38','URL_PATHINFO_DEPR','参数分割符','6','/','2'); INSERT INTO `h_config` VALUES ('39','URL_HTML_SUFFIX','URL伪静态后缀','6','.html','2'); INSERT INTO `h_config` VALUES ('40','TOKEN_ON','令牌验证','6','1','1'); INSERT INTO `h_config` VALUES ('41','TOKEN_NAME','令牌表单字段','6','__hash__','2'); INSERT INTO `h_config` VALUES ('42','TMPL_CACHE_ON','模板编译缓存','6','0','1'); INSERT INTO `h_config` VALUES ('43','TMPL_CACHE_TIME','模板缓存有效期','6','-1','1'); INSERT INTO `h_config` VALUES ('44','HTML_CACHE_ON','静态缓存','6','0','1'); INSERT INTO `h_config` VALUES ('45','HTML_CACHE_TIME','缓存有效期','6','60','1'); INSERT INTO `h_config` VALUES ('46','HTML_READ_TYPE','缓存读取方式','6','0','1'); INSERT INTO `h_config` VALUES ('47','HTML_FILE_SUFFIX','静态文件后缀','6','.html','2'); INSERT INTO `h_config` VALUES ('48','ADMIN_ACCESS','ADMIN_ACCESS','6','2bf6f62c327cbd49dfbd4cea71865a5e','2'); INSERT INTO `h_config` VALUES ('49','DEFAULT_THEME','默认模板','6','Default','2'); INSERT INTO `h_config` VALUES ('50','HOME_ISHTML','首页生成html','6','0','1'); -- -- 表的结构 `h_download` -- DROP TABLE IF EXISTS `h_download`; CREATE TABLE `h_download` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `catid` smallint(5) unsigned NOT NULL DEFAULT '0', `userid` int(8) unsigned NOT NULL DEFAULT '0', `username` varchar(40) NOT NULL DEFAULT '', `title` varchar(120) NOT NULL DEFAULT '', `title_style` varchar(40) NOT NULL DEFAULT '', `thumb` varchar(100) NOT NULL DEFAULT '', `keywords` varchar(120) NOT NULL DEFAULT '', `description` mediumtext NOT NULL, `content` mediumtext NOT NULL, `template` varchar(40) NOT NULL DEFAULT '', `posid` tinyint(2) unsigned NOT NULL DEFAULT '0', `status` tinyint(1) unsigned NOT NULL DEFAULT '0', `recommend` tinyint(1) unsigned NOT NULL DEFAULT '0', `readgroup` varchar(100) NOT NULL DEFAULT '', `readpoint` smallint(5) unsigned NOT NULL, `listorder` int(10) unsigned NOT NULL DEFAULT '0', `hits` int(11) unsigned NOT NULL DEFAULT '0', `createtime` int(11) unsigned NOT NULL DEFAULT '0', `updatetime` int(11) unsigned NOT NULL DEFAULT '0', `url` varchar(60) NOT NULL DEFAULT '', `file` varchar(80) NOT NULL DEFAULT '', `ext` varchar(10) NOT NULL DEFAULT '', `size` varchar(10) NOT NULL DEFAULT '', `downs` int(10) unsigned NOT NULL DEFAULT '0', PRIMARY KEY (`id`), KEY `status` (`id`,`status`,`listorder`), KEY `catid` (`id`,`catid`,`status`), KEY `listorder` (`id`,`catid`,`status`,`listorder`) ) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8; -- -- 表的结构 `h_feedback` -- DROP TABLE IF EXISTS `h_feedback`; CREATE TABLE `h_feedback` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `listorder` int(10) unsigned NOT NULL DEFAULT '0', `username` varchar(20) NOT NULL DEFAULT '', `telephone` varchar(255) NOT NULL DEFAULT '', `email` varchar(50) NOT NULL DEFAULT '', `content` mediumtext NOT NULL, `ip` varchar(255) NOT NULL DEFAULT '', `title` varchar(50) NOT NULL DEFAULT '', `createtime` int(11) unsigned NOT NULL DEFAULT '0', `status` tinyint(1) unsigned NOT NULL DEFAULT '0', `typeid` smallint(5) unsigned NOT NULL DEFAULT '0', PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8; -- -- 表的结构 `h_field` -- DROP TABLE IF EXISTS `h_field`; CREATE TABLE `h_field` ( `id` smallint(5) unsigned NOT NULL AUTO_INCREMENT, `moduleid` tinyint(3) unsigned NOT NULL DEFAULT '0', `field` varchar(20) NOT NULL DEFAULT '', `name` varchar(30) NOT NULL DEFAULT '', `tips` varchar(150) NOT NULL DEFAULT '', `required` tinyint(1) unsigned NOT NULL DEFAULT '0', `minlength` int(10) unsigned NOT NULL DEFAULT '0', `maxlength` int(10) unsigned NOT NULL DEFAULT '0', `pattern` varchar(255) NOT NULL DEFAULT '', `errormsg` varchar(255) NOT NULL DEFAULT '', `class` varchar(20) NOT NULL DEFAULT '', `type` varchar(20) NOT NULL DEFAULT '', `setup` mediumtext NOT NULL, `ispost` tinyint(1) NOT NULL DEFAULT '0', `unpostgroup` varchar(60) NOT NULL DEFAULT '', `listorder` int(10) unsigned NOT NULL DEFAULT '0', `status` tinyint(1) unsigned NOT NULL DEFAULT '0', `issystem` tinyint(1) unsigned NOT NULL DEFAULT '0', PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=103 DEFAULT CHARSET=utf8; -- -- 导出`h_field`表中的数据 `h_field` -- INSERT INTO `h_field` VALUES ('1','1','title','标题','','1','3','80','','标题必填3-80个字','','title','array (\n \'thumb\' => \'1\',\n \'style\' => \'0\',\n \'size\' => \'\',\n)','1','','0','1','1'); INSERT INTO `h_field` VALUES ('2','1','keywords','关键词','','0','0','0','','','','text','array (\n \'size\' => \'55\',\n \'default\' => \'\',\n \'ispassword\' => \'0\',\n)','1','','0','1','1'); INSERT INTO `h_field` VALUES ('3','1','description','SEO简介','','0','0','0','','','','textarea','array (\n \'rows\' => \'4\',\n \'cols\' => \'55\',\n \'default\' => \'\',\n)','1','','0','1','1'); INSERT INTO `h_field` VALUES ('4','1','content','内容','','0','0','0','','','','editor','array (\n \'toolbar\' => \'full\',\n \'default\' => \'\',\n \'height\' => \'\',\n \'showpage\' => \'1\',\n \'enablekeylink\' => \'0\',\n \'replacenum\' => \'\',\n \'enablesaveimage\' => \'0\',\n \'flashupload\' => \'1\',\n \'alowuploadexts\' => \'*.jpg;*.jpeg;*.gif;*.doc;*.rar;*.zip;*.xls\',\n)','1','','0','1','1'); INSERT INTO `h_field` VALUES ('5','2','catid','栏目','','1','1','6','digits','必须选择一个栏目','','catid','','1','','0','1','1'); INSERT INTO `h_field` VALUES ('6','2','title','标题','','1','0','0','','标题必须为1-80个字符','','title','array (\n \'thumb\' => \'1\',\n \'style\' => \'1\',\n \'size\' => \'55\',\n)','1','','0','1','1'); INSERT INTO `h_field` VALUES ('7','2','keywords','关键词','','0','0','0','','','','text','array (\n \'size\' => \'55\',\n \'default\' => \'\',\n \'ispassword\' => \'0\',\n)','1','','0','1','1'); INSERT INTO `h_field` VALUES ('8','2','description','SEO简介','','0','0','0','','','','textarea','array (\n \'rows\' => \'4\',\n \'cols\' => \'55\',\n \'default\' => \'\',\n)','1','','0','1','1'); INSERT INTO `h_field` VALUES ('9','2','content','内容','','0','0','0','','','','editor','array (\n \'toolbar\' => \'full\',\n \'default\' => \'\',\n \'height\' => \'\',\n \'show_add_description\' => \'1\',\n \'show_auto_thumb\' => \'1\',\n \'showpage\' => \'1\',\n \'enablekeylink\' => \'0\',\n \'replacenum\' => \'\',\n \'enablesaveimage\' => \'0\',\n \'flashupload\' => \'1\',\n \'alowuploadexts\' => \'\',\n)','1','','0','1','1'); INSERT INTO `h_field` VALUES ('10','2','createtime','发布时间','','1','0','0','','','','datetime','','1','','0','1','1'); INSERT INTO `h_field` VALUES ('11','2','copyfrom','来源','','0','0','0','','','','text','array (\n \'size\' => \'20\',\n \'default\' => \'\',\n \'ispassword\' => \'0\',\n)','1','','0','1','1'); INSERT INTO `h_field` VALUES ('12','2','fromlink','来源网址','','0','0','0','','','','text','array (\n \'size\' => \'20\',\n \'default\' => \'\',\n \'ispassword\' => \'0\',\n)','1','','0','1','1'); INSERT INTO `h_field` VALUES ('13','2','readgroup','访问权限','','0','0','0','','','','groupid','array (\n \'inputtype\' => \'checkbox\',\n \'fieldtype\' => \'varchar\',\n \'numbertype\' => \'1\',\n \'labelwidth\' => \'85\',\n \'default\' => \'\',\n)','1','','0','1','1'); INSERT INTO `h_field` VALUES ('14','2','posid','推荐位','','0','0','0','','','','posid','','1','','0','1','1'); INSERT INTO `h_field` VALUES ('15','2','template','模板','','0','0','0','','','','template','','1','','0','1','1'); INSERT INTO `h_field` VALUES ('16','2','status','状态','','0','0','0','','','','radio','array (\n \'options\' => \'发布|1\r\n定时发布|0\',\n \'fieldtype\' => \'tinyint\',\n \'labelwidth\' => \'75\',\n \'default\' => \'1\',\n)','1','','0','1','1'); INSERT INTO `h_field` VALUES ('17','3','catid','栏目','','1','1','6','','必须选择一个栏目','','catid','','1','','0','1','1'); INSERT INTO `h_field` VALUES ('18','3','title','标题','','1','1','80','','标题必须为1-80个字符','','title','array (\n \'thumb\' => \'1\',\n \'style\' => \'1\',\n \'size\' => \'55\',\n)','1','','0','1','1'); INSERT INTO `h_field` VALUES ('19','3','keywords','关键词','','0','0','80','','','','text','array (\n \'size\' => \'55\',\n \'default\' => \'\',\n \'ispassword\' => \'0\',\n \'fieldtype\' => \'varchar\',\n)','1','','0','1','1'); INSERT INTO `h_field` VALUES ('20','3','description','SEO简介','','0','0','0','','','','textarea','array (\n \'fieldtype\' => \'mediumtext\',\n \'rows\' => \'4\',\n \'cols\' => \'55\',\n \'default\' => \'\',\n)','1','','0','1','1'); INSERT INTO `h_field` VALUES ('21','3','content','内容','','0','0','0','','','','editor','array (\n \'toolbar\' => \'full\',\n \'default\' => \'\',\n \'height\' => \'\',\n \'showpage\' => \'1\',\n \'enablekeylink\' => \'0\',\n \'replacenum\' => \'\',\n \'enablesaveimage\' => \'0\',\n \'flashupload\' => \'1\',\n \'alowuploadexts\' => \'\',\n)','1','','10','1','1'); INSERT INTO `h_field` VALUES ('22','3','createtime','发布时间','','1','0','0','','','','datetime','','1','','93','1','1'); INSERT INTO `h_field` VALUES ('31','2','recommend','允许评论','','0','0','1','','','','radio','array (\n \'options\' => \'允许评论|1\r\n不允许评论|0\',\n \'fieldtype\' => \'tinyint\',\n \'numbertype\' => \'1\',\n \'labelwidth\' => \'\',\n \'default\' => \'1\',\n)','1','','0','0','0'); INSERT INTO `h_field` VALUES ('30','3','xinghao','型号','','0','0','30','','','','text','array (\n \'size\' => \'20\',\n \'default\' => \'\',\n \'ispassword\' => \'0\',\n \'fieldtype\' => \'varchar\',\n)','1','','0','1','1'); INSERT INTO `h_field` VALUES ('25','3','readgroup','访问权限','','0','0','0','','','','groupid','array (\n \'inputtype\' => \'checkbox\',\n \'fieldtype\' => \'tinyint\',\n \'labelwidth\' => \'85\',\n \'default\' => \'\',\n)','1','','96','0','1'); INSERT INTO `h_field` VALUES ('26','3','posid','推荐位','','0','0','0','','','','posid','','1','','97','1','1'); INSERT INTO `h_field` VALUES ('27','3','template','模板','','0','0','0','','','','template','','1','','98','1','1'); INSERT INTO `h_field` VALUES ('28','3','status','状态','','0','0','0','','','','radio','array (\n \'options\' => \'发布|1\r\n定时发布|0\',\n \'fieldtype\' => \'tinyint\',\n \'numbertype\' => \'1\',\n \'labelwidth\' => \'75\',\n \'default\' => \'1\',\n)','1','','99','1','1'); INSERT INTO `h_field` VALUES ('29','3','price','价格','','0','0','0','','','','number','array (\n \'numbertype\' => \'1\',\n \'decimaldigits\' => \'2\',\n \'default\' => \'0\',\n)','1','','0','1','1'); INSERT INTO `h_field` VALUES ('34','3','recommend','允许评论','','0','0','1','','','','radio','array (\n \'options\' => \'允许评论|1\r\n不允许评论|0\',\n \'fieldtype\' => \'tinyint\',\n \'numbertype\' => \'1\',\n \'labelwidth\' => \'\',\n \'default\' => \'\',\n)','1','','0','0','0'); INSERT INTO `h_field` VALUES ('32','2','readpoint','阅读收费','','0','0','3','','','','number','array (\n \'size\' => \'5\',\n \'numbertype\' => \'1\',\n \'decimaldigits\' => \'0\',\n \'default\' => \'\',\n)','1','','0','0','0'); INSERT INTO `h_field` VALUES ('33','2','hits','点击次数','','0','0','8','','','','number','array (\n \'size\' => \'5\',\n \'numbertype\' => \'1\',\n \'decimaldigits\' => \'0\',\n \'default\' => \'\',\n)','1','','0','0','0'); INSERT INTO `h_field` VALUES ('35','3','readpoint','阅读收费','','0','0','5','','','','number','array (\n \'size\' => \'5\',\n \'numbertype\' => \'1\',\n \'decimaldigits\' => \'0\',\n \'default\' => \'0\',\n)','1','','0','0','0'); INSERT INTO `h_field` VALUES ('36','3','hits','点击次数','','0','0','8','','','','number','array (\n \'size\' => \'10\',\n \'numbertype\' => \'1\',\n \'decimaldigits\' => \'0\',\n \'default\' => \'0\',\n)','1','','0','0','0'); INSERT INTO `h_field` VALUES ('37','4','catid','栏目','','1','1','6','','必须选择一个栏目','','catid','','1','','0','1','1'); INSERT INTO `h_field` VALUES ('38','4','title','标题','','1','1','80','','标题必须为1-80个字符','','title','array (\n \'thumb\' => \'1\',\n \'style\' => \'1\',\n \'size\' => \'55\',\n)','1','','0','1','1'); INSERT INTO `h_field` VALUES ('39','4','keywords','关键词','','0','0','80','','','','text','array (\n \'size\' => \'55\',\n \'default\' => \'\',\n \'ispassword\' => \'0\',\n \'fieldtype\' => \'varchar\',\n)','1','','0','1','1'); INSERT INTO `h_field` VALUES ('40','4','description','SEO简介','','0','0','0','','','','textarea','array (\n \'fieldtype\' => \'mediumtext\',\n \'rows\' => \'4\',\n \'cols\' => \'55\',\n \'default\' => \'\',\n)','1','','0','1','1'); INSERT INTO `h_field` VALUES ('41','4','content','内容','','0','0','0','','','','editor','array (\n \'toolbar\' => \'full\',\n \'default\' => \'\',\n \'height\' => \'\',\n \'showpage\' => \'1\',\n \'enablekeylink\' => \'0\',\n \'replacenum\' => \'\',\n \'enablesaveimage\' => \'0\',\n \'flashupload\' => \'1\',\n \'alowuploadexts\' => \'\',\n)','1','','10','1','1'); INSERT INTO `h_field` VALUES ('42','4','createtime','发布时间','','1','0','0','','','','datetime','','1','','93','1','1'); INSERT INTO `h_field` VALUES ('43','4','recommend','允许评论','','0','0','1','','','','radio','array (\n \'options\' => \'允许评论|1\r\n不允许评论|0\',\n \'fieldtype\' => \'tinyint\',\n \'numbertype\' => \'1\',\n \'labelwidth\' => \'\',\n \'default\' => \'\',\n)','1','','0','0','0'); INSERT INTO `h_field` VALUES ('44','4','readpoint','阅读收费','','0','0','5','','','','number','array (\n \'size\' => \'5\',\n \'numbertype\' => \'1\',\n \'decimaldigits\' => \'0\',\n \'default\' => \'0\',\n)','1','','0','0','0'); INSERT INTO `h_field` VALUES ('45','4','hits','点击次数','','0','0','8','','','','number','array (\n \'size\' => \'10\',\n \'numbertype\' => \'1\',\n \'decimaldigits\' => \'0\',\n \'default\' => \'0\',\n)','1','','0','0','0'); INSERT INTO `h_field` VALUES ('46','4','readgroup','访问权限','','0','0','0','','','','groupid','array (\n \'inputtype\' => \'checkbox\',\n \'fieldtype\' => \'tinyint\',\n \'labelwidth\' => \'85\',\n \'default\' => \'\',\n)','1','','96','0','1'); INSERT INTO `h_field` VALUES ('47','4','posid','推荐位','','0','0','0','','','','posid','','1','','97','1','1'); INSERT INTO `h_field` VALUES ('48','4','template','模板','','0','0','0','','','','template','','1','','98','1','1'); INSERT INTO `h_field` VALUES ('49','4','status','状态','','0','0','0','','','','radio','array (\n \'options\' => \'发布|1\r\n定时发布|0\',\n \'fieldtype\' => \'tinyint\',\n \'numbertype\' => \'1\',\n \'labelwidth\' => \'75\',\n \'default\' => \'1\',\n)','1','','99','1','1'); INSERT INTO `h_field` VALUES ('50','5','catid','栏目','','1','1','6','','必须选择一个栏目','','catid','','1','','0','1','1'); INSERT INTO `h_field` VALUES ('51','5','title','标题','','1','1','80','','标题必须为1-80个字符','','title','array (\n \'thumb\' => \'1\',\n \'style\' => \'1\',\n \'size\' => \'55\',\n)','1','','0','1','1'); INSERT INTO `h_field` VALUES ('52','5','keywords','关键词','','0','0','80','','','','text','array (\n \'size\' => \'55\',\n \'default\' => \'\',\n \'ispassword\' => \'0\',\n \'fieldtype\' => \'varchar\',\n)','1','','0','1','1'); INSERT INTO `h_field` VALUES ('53','5','description','SEO简介','','0','0','0','','','','textarea','array (\n \'fieldtype\' => \'mediumtext\',\n \'rows\' => \'4\',\n \'cols\' => \'55\',\n \'default\' => \'\',\n)','1','','0','1','1'); INSERT INTO `h_field` VALUES ('54','5','content','内容','','0','0','0','','','','editor','array (\n \'toolbar\' => \'full\',\n \'default\' => \'\',\n \'height\' => \'\',\n \'showpage\' => \'1\',\n \'enablekeylink\' => \'0\',\n \'replacenum\' => \'\',\n \'enablesaveimage\' => \'0\',\n \'flashupload\' => \'1\',\n \'alowuploadexts\' => \'\',\n)','1','','10','1','1'); INSERT INTO `h_field` VALUES ('55','5','createtime','发布时间','','1','0','0','','','','datetime','','1','','93','1','1'); INSERT INTO `h_field` VALUES ('56','5','recommend','允许评论','','0','0','1','','','','radio','array (\n \'options\' => \'允许评论|1\r\n不允许评论|0\',\n \'fieldtype\' => \'tinyint\',\n \'numbertype\' => \'1\',\n \'labelwidth\' => \'\',\n \'default\' => \'\',\n)','1','','0','0','0'); INSERT INTO `h_field` VALUES ('57','5','readpoint','阅读收费','','0','0','5','','','','number','array (\n \'size\' => \'5\',\n \'numbertype\' => \'1\',\n \'decimaldigits\' => \'0\',\n \'default\' => \'0\',\n)','1','','0','0','0'); INSERT INTO `h_field` VALUES ('58','5','hits','点击次数','','0','0','8','','','','number','array (\n \'size\' => \'10\',\n \'numbertype\' => \'1\',\n \'decimaldigits\' => \'0\',\n \'default\' => \'0\',\n)','1','','0','0','0'); INSERT INTO `h_field` VALUES ('59','5','readgroup','访问权限','','0','0','0','','','','groupid','array (\n \'inputtype\' => \'checkbox\',\n \'fieldtype\' => \'tinyint\',\n \'labelwidth\' => \'85\',\n \'default\' => \'\',\n)','1','','96','0','1'); INSERT INTO `h_field` VALUES ('60','5','posid','推荐位','','0','0','0','','','','posid','','1','','97','1','1'); INSERT INTO `h_field` VALUES ('61','5','template','模板','','0','0','0','','','','template','','1','','98','1','1'); INSERT INTO `h_field` VALUES ('62','5','status','状态','','0','0','0','','','','radio','array (\n \'options\' => \'发布|1\r\n定时发布|0\',\n \'fieldtype\' => \'tinyint\',\n \'numbertype\' => \'1\',\n \'labelwidth\' => \'75\',\n \'default\' => \'1\',\n)','1','','99','1','1'); INSERT INTO `h_field` VALUES ('63','3','pics','图片','','0','0','0','','','','images','array (\n \'size\' => \'55\',\n \'default\' => \'\',\n \'upload_maxnum\' => \'10\',\n \'upload_maxsize\' => \'2\',\n \'upload_allowext\' => \'*.jpeg;*.jpg;*.gif\',\n \'watermark\' => \'0\',\n \'more\' => \'1\',\n)','1','','0','1','0'); INSERT INTO `h_field` VALUES ('64','4','pics','图组','','0','0','0','','','','images','array (\n \'size\' => \'55\',\n \'default\' => \'\',\n \'upload_maxnum\' => \'20\',\n \'upload_maxsize\' => \'2\',\n \'upload_allowext\' => \'*.jpeg;*.jpg;*.png;*.gif\',\n \'watermark\' => \'0\',\n \'more\' => \'1\',\n)','1','','0','1','0'); INSERT INTO `h_field` VALUES ('65','5','file','上传文件','','0','0','0','','','','file','array (\n \'size\' => \'55\',\n \'default\' => \'\',\n \'upload_maxsize\' => \'2\',\n \'upload_allowext\' => \'*.zip;*.rar;*.doc;*.ppt\',\n \'more\' => \'1\',\n)','1','','0','1','0'); INSERT INTO `h_field` VALUES ('66','5','ext','文档类型','','0','0','10','','','','text','array (\n \'size\' => \'10\',\n \'default\' => \'\',\n \'ispassword\' => \'0\',\n \'fieldtype\' => \'varchar\',\n)','1','','0','1','0'); INSERT INTO `h_field` VALUES ('67','5','size','文档大小','','0','0','10','','','','text','array (\n \'size\' => \'10\',\n \'default\' => \'\',\n \'ispassword\' => \'0\',\n \'fieldtype\' => \'varchar\',\n)','1','','0','1','0'); INSERT INTO `h_field` VALUES ('68','5','downs','下载次数','','0','0','0','','','','number','array (\n \'size\' => \'10\',\n \'numbertype\' => \'1\',\n \'decimaldigits\' => \'0\',\n \'default\' => \'\',\n)','1','','0','0','0'); INSERT INTO `h_field` VALUES ('69','6','username','姓名','','1','2','20','cn_username','','','text','array (\n \'size\' => \'10\',\n \'default\' => \'\',\n \'ispassword\' => \'0\',\n \'fieldtype\' => \'varchar\',\n)','1','','2','1','0'); INSERT INTO `h_field` VALUES ('70','6','telephone','电话','','0','0','0','tel','','','text','array (\n \'size\' => \'20\',\n \'default\' => \'\',\n \'ispassword\' => \'0\',\n \'fieldtype\' => \'varchar\',\n)','1','','4','1','0'); INSERT INTO `h_field` VALUES ('71','6','email','邮箱','','1','0','50','email','','','text','array (\n \'size\' => \'20\',\n \'default\' => \'\',\n \'ispassword\' => \'0\',\n \'fieldtype\' => \'varchar\',\n)','1','','2','1','0'); INSERT INTO `h_field` VALUES ('72','6','content','内容','','1','4','200','','','','textarea','array (\n \'fieldtype\' => \'mediumtext\',\n \'rows\' => \'5\',\n \'cols\' => \'60\',\n \'default\' => \'\',\n)','1','','5','1','0'); INSERT INTO `h_field` VALUES ('81','7','status','状态','','0','0','1','','','','radio','array (\n \'options\' => \'已审核|1\r\n未审核|0\',\n \'fieldtype\' => \'tinyint\',\n \'numbertype\' => \'1\',\n \'labelwidth\' => \'75\',\n \'default\' => \'1\',\n)','1','','99','1','1'); INSERT INTO `h_field` VALUES ('73','6','ip','提交IP','','0','0','0','','','','text','array (\n \'size\' => \'20\',\n \'default\' => \'\',\n \'ispassword\' => \'0\',\n \'fieldtype\' => \'varchar\',\n)','0','','6','1','0'); INSERT INTO `h_field` VALUES ('74','6','title','标题','','1','4','50','','','','text','array (\n \'size\' => \'40\',\n \'default\' => \'\',\n \'ispassword\' => \'0\',\n \'fieldtype\' => \'varchar\',\n)','1','3,4','1','1','0'); INSERT INTO `h_field` VALUES ('80','35','createtime','发布时间','','1','0','0','','','','datetime','','1','','93','1','1'); INSERT INTO `h_field` VALUES ('76','6','createtime','提交时间','','0','0','0','','','','datetime','','0','','98','1','0'); INSERT INTO `h_field` VALUES ('79','6','typeid','反馈类别','','0','0','0','','','','typeid','array (\n \'inputtype\' => \'select\',\n \'fieldtype\' => \'smallint\',\n \'numbertype\' => \'1\',\n \'labelwidth\' => \'\',\n \'default\' => \'4\',\n)','1','','0','1','0'); INSERT INTO `h_field` VALUES ('78','6','status','审核状态','','0','0','1','','','','radio','array (\n \'options\' => \'己审核|1\r\n未审核|0\',\n \'fieldtype\' => \'tinyint\',\n \'numbertype\' => \'1\',\n \'labelwidth\' => \'\',\n \'default\' => \'0\',\n)','0','','99','1','0'); INSERT INTO `h_field` VALUES ('82','7','name','网站名称','','1','2','50','','','','text','array (\n \'size\' => \'40\',\n \'default\' => \'\',\n \'ispassword\' => \'0\',\n \'fieldtype\' => \'varchar\',\n)','1','','1','1','0'); INSERT INTO `h_field` VALUES ('83','7','logo','网站LOGO','','0','0','0','','','','image','array (\n \'size\' => \'50\',\n \'default\' => \'\',\n \'upload_maxsize\' => \'\',\n \'upload_allowext\' => \'jpg,jpeg,gif,png\',\n \'watermark\' => \'0\',\n \'more\' => \'0\',\n)','1','','2','1','0'); INSERT INTO `h_field` VALUES ('84','7','siteurl','网站地址','','1','10','150','url','','','text','array (\n \'size\' => \'50\',\n \'default\' => \'\',\n \'ispassword\' => \'0\',\n \'fieldtype\' => \'varchar\',\n)','1','','3','1','0'); INSERT INTO `h_field` VALUES ('85','7','typeid','友情链接分类','','0','0','0','','','','typeid','array (\n \'inputtype\' => \'select\',\n \'fieldtype\' => \'smallint\',\n \'numbertype\' => \'1\',\n \'labelwidth\' => \'\',\n \'default\' => \'1\',\n)','1','','0','1','0'); INSERT INTO `h_field` VALUES ('86','7','linktype','链接类型','','0','0','1','','','','radio','array (\n \'options\' => \'文字链接|1\r\nLOGO链接|2\',\n \'fieldtype\' => \'tinyint\',\n \'numbertype\' => \'1\',\n \'labelwidth\' => \'\',\n \'default\' => \'1\',\n)','1','','0','1','0'); INSERT INTO `h_field` VALUES ('87','7','siteinfo','站点简介','','0','0','0','','','','textarea','array (\n \'fieldtype\' => \'mediumtext\',\n \'rows\' => \'3\',\n \'cols\' => \'60\',\n \'default\' => \'\',\n)','1','','4','1','0'); INSERT INTO `h_field` VALUES ('88','8','createtime','提交时间','','1','0','0','','','','datetime','','0','','93','1','1'); INSERT INTO `h_field` VALUES ('89','8','status','状态','','0','0','0','','','','radio','array (\n \'options\' => \'已审核|1\r\n未审核|0\',\n \'fieldtype\' => \'tinyint\',\n \'numbertype\' => \'1\',\n \'labelwidth\' => \'75\',\n \'default\' => \'0\',\n)','0','','99','1','1'); INSERT INTO `h_field` VALUES ('90','8','title','标题','','1','2','50','','','','text','array (\n \'size\' => \'40\',\n \'default\' => \'\',\n \'ispassword\' => \'0\',\n \'fieldtype\' => \'varchar\',\n)','1','','0','1','0'); INSERT INTO `h_field` VALUES ('91','8','username','姓名','','1','2','20','','','','text','array (\n \'size\' => \'10\',\n \'default\' => \'\',\n \'ispassword\' => \'0\',\n \'fieldtype\' => \'varchar\',\n)','1','','0','1','0'); INSERT INTO `h_field` VALUES ('92','8','telephone','电话','','0','0','0','tel','','','text','array (\n \'size\' => \'20\',\n \'default\' => \'\',\n \'ispassword\' => \'0\',\n \'fieldtype\' => \'varchar\',\n)','1','','1','1','0'); INSERT INTO `h_field` VALUES ('93','8','email','邮箱','','1','0','40','email','','','text','array (\n \'size\' => \'20\',\n \'default\' => \'\',\n \'ispassword\' => \'0\',\n \'fieldtype\' => \'varchar\',\n)','1','','0','1','0'); INSERT INTO `h_field` VALUES ('94','8','content','内容','','1','2','200','','','','textarea','array (\n \'fieldtype\' => \'mediumtext\',\n \'rows\' => \'4\',\n \'cols\' => \'50\',\n \'default\' => \'\',\n)','1','','10','1','0'); INSERT INTO `h_field` VALUES ('95','8','reply_content','回复','','0','0','0','','','','textarea','array (\n \'fieldtype\' => \'mediumtext\',\n \'rows\' => \'4\',\n \'cols\' => \'50\',\n \'default\' => \'\',\n)','0','','10','1','0'); INSERT INTO `h_field` VALUES ('96','8','ip','IP','','0','0','15','','','','text','array (\n \'size\' => \'15\',\n \'default\' => \'\',\n \'ispassword\' => \'0\',\n \'fieldtype\' => \'varchar\',\n)','0','','90','1','0'); INSERT INTO `h_field` VALUES ('97','9','createtime','发布时间','','1','0','0','','','','datetime','','0','','93','1','1'); INSERT INTO `h_field` VALUES ('98','9','status','状态','','0','0','0','','','','radio','array (\n \'options\' => \'已审核|1\r\n未审核|0\',\n \'fieldtype\' => \'tinyint\',\n \'numbertype\' => \'1\',\n \'labelwidth\' => \'75\',\n \'default\' => \'1\',\n)','0','','99','1','1'); INSERT INTO `h_field` VALUES ('99','9','name','客服名称','','0','2','20','','','','text','array (\n \'size\' => \'20\',\n \'default\' => \'\',\n \'ispassword\' => \'0\',\n \'fieldtype\' => \'varchar\',\n)','0','','0','1','0'); INSERT INTO `h_field` VALUES ('100','9','type','客服类型','','1','1','2','0','','','select','array (\n \'options\' => \'QQ|1\r\nMSN|2\r\n旺旺|3\r\n贸易通|6\r\n电话|4\r\n代码|5\',\n \'multiple\' => \'0\',\n \'fieldtype\' => \'tinyint\',\n \'numbertype\' => \'1\',\n \'size\' => \'\',\n \'default\' => \'\',\n)','0','','0','1','0'); INSERT INTO `h_field` VALUES ('101','9','code','ID或代码','','0','2','0','0','','','textarea','array (\n \'fieldtype\' => \'mediumtext\',\n \'rows\' => \'4\',\n \'cols\' => \'50\',\n \'default\' => \'\',\n)','0','','10','1','0'); INSERT INTO `h_field` VALUES ('102','9','skin','风格样式','','0','0','3','0','','','select','array (\n \'options\' => \'无风格图标|0\r\nQQ风格1|q1\r\nQQ风格2|q2\r\nQQ风格3|q3\r\nQQ风格4|q4\r\nQQ风格5|q5\r\nQQ风格6|q6\r\nQQ风格7|q7\r\nMSN小图|m1\r\nMSN大图1|m2\r\nMSN大图2|m3\r\nMSN大图3|m4\r\n旺旺小图|w2\r\n旺旺大图|w1\r\n贸易通|al1\',\n \'multiple\' => \'0\',\n \'fieldtype\' => \'varchar\',\n \'numbertype\' => \'1\',\n \'size\' => \'\',\n \'default\' => \'\',\n)','0','','0','1','0'); -- -- 表的结构 `h_guestbook` -- DROP TABLE IF EXISTS `h_guestbook`; CREATE TABLE `h_guestbook` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `title` varchar(50) NOT NULL DEFAULT '', `status` tinyint(3) unsigned NOT NULL DEFAULT '1', `listorder` int(10) unsigned NOT NULL DEFAULT '0', `createtime` int(11) unsigned NOT NULL DEFAULT '0', `username` varchar(20) NOT NULL DEFAULT '', `telephone` varchar(255) NOT NULL DEFAULT '', `email` varchar(40) NOT NULL DEFAULT '', `content` mediumtext NOT NULL, `reply_content` mediumtext NOT NULL, `ip` varchar(15) NOT NULL DEFAULT '', PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8; -- -- 表的结构 `h_kefu` -- DROP TABLE IF EXISTS `h_kefu`; CREATE TABLE `h_kefu` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `status` tinyint(1) unsigned NOT NULL DEFAULT '0', `listorder` int(10) unsigned NOT NULL DEFAULT '0', `createtime` int(11) unsigned NOT NULL DEFAULT '0', `name` varchar(20) NOT NULL DEFAULT '', `type` tinyint(2) unsigned NOT NULL DEFAULT '0', `code` mediumtext NOT NULL, `skin` varchar(3) NOT NULL DEFAULT '0', PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=6 DEFAULT CHARSET=utf8; -- -- 导出`h_kefu`表中的数据 `h_kefu` -- INSERT INTO `h_kefu` VALUES ('1','1','4','1306807701','咨询电话','4','0317-5022625','0'); INSERT INTO `h_kefu` VALUES ('2','1','3','1306808546','技术咨询','1','147613338','q3'); INSERT INTO `h_kefu` VALUES ('3','1','3','1306808886','QQ客服','1','147613338','q3'); INSERT INTO `h_kefu` VALUES ('4','1','2','1306811439','MSN客服','2','<EMAIL>','m2'); INSERT INTO `h_kefu` VALUES ('5','1','0','1306830001','旺旺客服','3','snliuxun','w1'); -- -- 表的结构 `h_link` -- DROP TABLE IF EXISTS `h_link`; CREATE TABLE `h_link` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `status` tinyint(1) unsigned NOT NULL DEFAULT '1', `listorder` int(10) unsigned NOT NULL DEFAULT '0', `createtime` int(11) unsigned NOT NULL DEFAULT '0', `name` varchar(50) NOT NULL DEFAULT '', `logo` varchar(80) NOT NULL DEFAULT '', `siteurl` varchar(150) NOT NULL DEFAULT '', `typeid` smallint(5) unsigned NOT NULL, `linktype` tinyint(1) unsigned NOT NULL DEFAULT '1', `siteinfo` mediumtext NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=3 DEFAULT CHARSET=utf8; -- -- 导出`h_link`表中的数据 `h_link` -- INSERT INTO `h_link` VALUES ('1','1','0','1306547518','Yourphp企业网站管理系统','http://demo.yourphp.cn/Public/Images/logo.gif','http://www.yourphp.cn','2','2','php企业网站管理系统'); INSERT INTO `h_link` VALUES ('2','1','0','1306554684','企业网站管理系统','','http://www.yourphp.cn','2','1',''); -- -- 表的结构 `h_menu` -- DROP TABLE IF EXISTS `h_menu`; CREATE TABLE `h_menu` ( `id` smallint(6) unsigned NOT NULL AUTO_INCREMENT, `parentid` smallint(6) unsigned NOT NULL DEFAULT '0', `model` char(20) NOT NULL DEFAULT '', `action` char(20) NOT NULL DEFAULT '', `data` char(50) NOT NULL DEFAULT '', `type` tinyint(1) NOT NULL DEFAULT '0', `status` tinyint(1) unsigned NOT NULL DEFAULT '0', `group_id` tinyint(3) unsigned NOT NULL DEFAULT '0', `name` varchar(50) NOT NULL DEFAULT '', `remark` varchar(255) NOT NULL DEFAULT '', `listorder` smallint(6) unsigned NOT NULL DEFAULT '0', PRIMARY KEY (`id`), KEY `status` (`status`), KEY `parentid` (`parentid`), KEY `model` (`model`) ) ENGINE=MyISAM AUTO_INCREMENT=59 DEFAULT CHARSET=utf8; -- -- 导出`h_menu`表中的数据 `h_menu` -- INSERT INTO `h_menu` VALUES ('1','0','Main','main','menuid=42','1','1','0','后台首页','','0'); INSERT INTO `h_menu` VALUES ('2','0','Config','','menuid=50','1','1','0','系统设置','系统设置','1'); INSERT INTO `h_menu` VALUES ('3','0','Category','','menuid=17','1','1','0','内容管理','模型管理','2'); INSERT INTO `h_menu` VALUES ('4','0','Module','index','type=2&menuid=51','1','1','0','模块管理','','4'); INSERT INTO `h_menu` VALUES ('5','0','User','','menuid=9','1','1','0','会员管理','','90'); INSERT INTO `h_menu` VALUES ('6','0','Createhtml','','menuid=33','1','1','0','网站更新','','99'); INSERT INTO `h_menu` VALUES ('7','0','Template','index','menuid=60','1','1','0','模板管理','','99'); INSERT INTO `h_menu` VALUES ('39','2','Menu','','','1','1','0','后台管理菜单','后台管理菜单','11'); INSERT INTO `h_menu` VALUES ('15','39','Menu','add','','1','1','0','添加菜单','','0'); INSERT INTO `h_menu` VALUES ('50','2','Config','','','1','1','0','站点配置','','0'); INSERT INTO `h_menu` VALUES ('22','3','Product','','','1','1','0','产品模型','','3'); INSERT INTO `h_menu` VALUES ('8','50','Config','sys','','1','1','0','系统参数','','0'); INSERT INTO `h_menu` VALUES ('32','50','Config','seo','','1','1','0','SEO设置','','0'); INSERT INTO `h_menu` VALUES ('59','50','Config','add','','1','1','0','添加系统变量','','99'); INSERT INTO `h_menu` VALUES ('9','5','User','','','1','1','0','会员资料管理','','0'); INSERT INTO `h_menu` VALUES ('10','9','User','add','','1','1','0','添加会员','','0'); INSERT INTO `h_menu` VALUES ('11','5','Role','','','1','1','0','会员组管理','','0'); INSERT INTO `h_menu` VALUES ('12','11','Role','add','','1','1','0','添加会员组','','0'); INSERT INTO `h_menu` VALUES ('13','5','Node','','','1','1','0','权限节点管理','','0'); INSERT INTO `h_menu` VALUES ('14','13','Node','add','','1','1','0','添加权限节点','','0'); INSERT INTO `h_menu` VALUES ('16','3','Module','','','1','1','0','模型管理','','99'); INSERT INTO `h_menu` VALUES ('17','3','Category','','','1','1','0','栏目管理','栏目管理','1'); INSERT INTO `h_menu` VALUES ('18','16','Module','add','','1','1','0','添加模型','','0'); INSERT INTO `h_menu` VALUES ('19','17','Category','add','','1','1','0','添加栏目','','0'); INSERT INTO `h_menu` VALUES ('20','3','Article','','','1','1','0','文章模型','','2'); INSERT INTO `h_menu` VALUES ('21','20','Article','add','','1','1','0','添加文章','','0'); INSERT INTO `h_menu` VALUES ('23','2','Posid','','','1','1','0','推荐位管理','','0'); INSERT INTO `h_menu` VALUES ('24','23','Posid','add','','1','1','0','添加推荐位','','0'); INSERT INTO `h_menu` VALUES ('25','22','Product','add','','1','1','0','添加产品','','0'); INSERT INTO `h_menu` VALUES ('26','3','Picture','','','1','1','0','图片模型','','4'); INSERT INTO `h_menu` VALUES ('27','3','Download','','','1','1','0','下载模型','','5'); INSERT INTO `h_menu` VALUES ('28','2','Type','','','1','1','0','类别管理','','6'); INSERT INTO `h_menu` VALUES ('29','50','Config','mail','','1','1','0','系统邮箱','','0'); INSERT INTO `h_menu` VALUES ('30','50','Config','attach','','1','1','0','附件配置','','0'); INSERT INTO `h_menu` VALUES ('31','17','Category','repair_cache','','1','1','0','恢复栏目数据','','0'); INSERT INTO `h_menu` VALUES ('33','6','Createhtml','index','','1','1','0','更新首页','','0'); INSERT INTO `h_menu` VALUES ('34','6','Createhtml','Createlist','','1','1','0','更新列表页','','0'); INSERT INTO `h_menu` VALUES ('35','6','Createhtml','Createshow','','1','1','0','更新内容页','','0'); INSERT INTO `h_menu` VALUES ('36','6','Createhtml','Updateurl','','1','1','0','更新内容页url','','0'); INSERT INTO `h_menu` VALUES ('37','26','Picture','add','','1','1','0','添加图片','','0'); INSERT INTO `h_menu` VALUES ('38','27','Download','add','','1','1','0','添加文件','','0'); INSERT INTO `h_menu` VALUES ('40','1','Main','password','','1','1','0','修改密码','','2'); INSERT INTO `h_menu` VALUES ('41','1','Main','profile','','1','1','0','个人资料','','3'); INSERT INTO `h_menu` VALUES ('42','1','Main','main','','1','1','0','后台首页','','1'); INSERT INTO `h_menu` VALUES ('43','17','Category','add','&type=1','1','1','0','添加外部链接','','0'); INSERT INTO `h_menu` VALUES ('44','2','Database','','','1','1','0','数据库管理','','0'); INSERT INTO `h_menu` VALUES ('45','44','Database','query','','1','1','0','执行SQL语句','','0'); INSERT INTO `h_menu` VALUES ('46','44','Database','recover','','1','1','0','恢复数据库','','0'); INSERT INTO `h_menu` VALUES ('47','1','Main','cache','menuid=47','1','1','0','更新缓存','','4'); INSERT INTO `h_menu` VALUES ('48','51','Module','add','type=2','1','1','0','创建模块','','0'); INSERT INTO `h_menu` VALUES ('49','3','Feedback','index','','1','1','0','信息反馈','信息反馈','7'); INSERT INTO `h_menu` VALUES ('51','4','Module','index','type=2','1','1','0','模块管理','','0'); INSERT INTO `h_menu` VALUES ('52','28','Type','add','','1','1','0','添加类别','','0'); INSERT INTO `h_menu` VALUES ('53','4','Link','index','','1','1','0','友情链接','','0'); INSERT INTO `h_menu` VALUES ('54','53','Link','add','','1','1','0','添加链接','','0'); INSERT INTO `h_menu` VALUES ('55','3','Guestbook','index','','1','1','0','在线留言','','8'); INSERT INTO `h_menu` VALUES ('56','4','Order','index','','1','1','0','订单管理','','0'); INSERT INTO `h_menu` VALUES ('57','4','Kefu','index','','1','1','0','在线客服','','0'); INSERT INTO `h_menu` VALUES ('58','57','Kefu','add','','1','1','0','添加客服','','0'); INSERT INTO `h_menu` VALUES ('60','7','Template','index','','1','1','0','模板管理','','0'); INSERT INTO `h_menu` VALUES ('61','60','Template','add','','1','1','0','添加模板','','0'); INSERT INTO `h_menu` VALUES ('62','60','Template','index','type=css','1','1','0','CSS管理','','0'); INSERT INTO `h_menu` VALUES ('63','60','Template','index','type=js','1','1','0','JS管理','','0'); INSERT INTO `h_menu` VALUES ('64','60','Template','images','','1','1','0','媒体文件管理','','0'); INSERT INTO `h_menu` VALUES ('65','7','Theme','index','menuid=65','1','1','0','风格管理','','0'); INSERT INTO `h_menu` VALUES ('66','65','Theme','upload','','1','1','0','上传风格','','0'); -- -- 表的结构 `h_module` -- DROP TABLE IF EXISTS `h_module`; CREATE TABLE `h_module` ( `id` tinyint(3) unsigned NOT NULL AUTO_INCREMENT, `title` varchar(100) NOT NULL DEFAULT '', `name` varchar(50) NOT NULL DEFAULT '' , `description` varchar(200) NOT NULL DEFAULT '', `type` tinyint(1) unsigned NOT NULL DEFAULT '0', `issystem` tinyint(1) unsigned NOT NULL DEFAULT '0', `issearch` tinyint(1) unsigned NOT NULL DEFAULT '0', `listfields` varchar(255) NOT NULL DEFAULT '', `setup` text NOT NULL, `listorder` smallint(3) unsigned NOT NULL DEFAULT '0' , `status` tinyint(1) unsigned NOT NULL DEFAULT '0' , PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=10 DEFAULT CHARSET=utf8; -- -- 导出`h_module`表中的数据 `h_module` -- INSERT INTO `h_module` VALUES ('1','单页模型','Page','单页模型','1','1','0','id,catid,url,title,title_style,keywords,description,thumb,createtime','','0','1'); INSERT INTO `h_module` VALUES ('2','文章模型','Article','新闻文章','1','1','1','id,catid,url,title,userid,username,hits,title_style,keywords,description,thumb,createtime','','0','1'); INSERT INTO `h_module` VALUES ('3','产品模型','Product','产品展示','1','1','1','id,catid,url,title,userid,username,hits,title_style,keywords,description,thumb,createtime,xinghao,price','','0','1'); INSERT INTO `h_module` VALUES ('4','图片模型','Picture','图片展示','1','1','1','id,catid,url,title,userid,username,hits,title_style,keywords,description,thumb,createtime','','0','1'); INSERT INTO `h_module` VALUES ('5','下载模型','Download','文件下载','1','1','1','id,catid,url,title,title_style,userid,username,hits,keywords,description,thumb,createtime,ext,size','','0','1'); INSERT INTO `h_module` VALUES ('6','信息反馈','Feedback','信息反馈','1','0','0','*','','0','1'); INSERT INTO `h_module` VALUES ('7','友情链接','Link','友情链接','2','0','0','*','','0','1'); INSERT INTO `h_module` VALUES ('8','在线留言','Guestbook','在线留言','1','0','0','*','','0','1'); INSERT INTO `h_module` VALUES ('9','在线客服','Kefu','在线客服','2','0','0','*','','0','1'); -- -- 表的结构 `h_node` -- DROP TABLE IF EXISTS `h_node`; CREATE TABLE `h_node` ( `id` smallint(5) unsigned NOT NULL AUTO_INCREMENT, `name` varchar(20) NOT NULL DEFAULT '', `title` varchar(50) NOT NULL DEFAULT '', `status` tinyint(3) unsigned NOT NULL DEFAULT '0', `remark` varchar(255) NOT NULL DEFAULT '', `listorder` smallint(5) unsigned NOT NULL DEFAULT '0', `pid` smallint(5) unsigned NOT NULL DEFAULT '0', `level` tinyint(3) unsigned NOT NULL DEFAULT '0', PRIMARY KEY (`id`), KEY `name` (`name`,`status`,`pid`) ) ENGINE=MyISAM AUTO_INCREMENT=30 DEFAULT CHARSET=utf8; -- -- 导出`h_node`表中的数据 `h_node` -- INSERT INTO `h_node` VALUES ('1','Admin','后台管理','1','后台项目','0','0','1'); INSERT INTO `h_node` VALUES ('2','Index','后台默认','1','控制器','0','1','2'); INSERT INTO `h_node` VALUES ('3','Config','系统设置','1','控制器','0','1','2'); INSERT INTO `h_node` VALUES ('4','index','站点配置','1','动作','0','3','3'); INSERT INTO `h_node` VALUES ('5','sys','系统参数','1','动作','0','3','3'); INSERT INTO `h_node` VALUES ('6','seo','SEO设置','1','动作','0','3','3'); INSERT INTO `h_node` VALUES ('7','add','添加变量','1','动作','0','3','3'); INSERT INTO `h_node` VALUES ('8','Menu','菜单管理','1','菜单控制器','0','1','2'); INSERT INTO `h_node` VALUES ('9','index','菜单列表','1','菜单列表-动作','0','8','3'); INSERT INTO `h_node` VALUES ('10','add','添加菜单','1','添加菜单-动作','0','8','3'); INSERT INTO `h_node` VALUES ('11','index','后台默认动作','1','后台默认动作','0','2','3'); INSERT INTO `h_node` VALUES ('12','Main','后台首页','1','控制器','0','1','2'); INSERT INTO `h_node` VALUES ('13','profile','个人资料','1','动作','0','12','3'); INSERT INTO `h_node` VALUES ('14','password','修改密码','1','动作','0','12','3'); INSERT INTO `h_node` VALUES ('15','index','后台首页','1','动作','0','12','3'); INSERT INTO `h_node` VALUES ('16','main','欢迎首页','1','动作','0','12','3'); INSERT INTO `h_node` VALUES ('17','attach','附件设置','1','动作','0','3','3'); INSERT INTO `h_node` VALUES ('18','mail','系统邮箱','1','动作','0','3','3'); INSERT INTO `h_node` VALUES ('19','Posid','推荐位','1','控制器','0','1','2'); INSERT INTO `h_node` VALUES ('20','index','列表','1','动作','0','19','3'); INSERT INTO `h_node` VALUES ('21','Category','模型管理','1','','0','1','2'); INSERT INTO `h_node` VALUES ('22','User','会员管理','1','','0','1','2'); INSERT INTO `h_node` VALUES ('23','Createhtml','网站更新','1','','0','1','2'); INSERT INTO `h_node` VALUES ('24','index','栏目管理','1','','0','21','3'); INSERT INTO `h_node` VALUES ('25','index','会员资料管理','1','','0','22','3'); INSERT INTO `h_node` VALUES ('26','index','更新首页','1','','0','23','3'); INSERT INTO `h_node` VALUES ('27','Createlist','更新列表页','1','','0','23','3'); INSERT INTO `h_node` VALUES ('28','Createshow','更新内容页','1','','0','23','3'); INSERT INTO `h_node` VALUES ('29','Updateurl','更新URL','1','','0','23','3'); -- -- 表的结构 `h_order` -- DROP TABLE IF EXISTS `h_order`; CREATE TABLE `h_order` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `sn` char(22) NOT NULL DEFAULT '', `password` varchar(30) NOT NULL DEFAULT '', `module` varchar(20) NOT NULL DEFAULT '', `userid` int(8) unsigned NOT NULL DEFAULT '0', `username` varchar(40) NOT NULL DEFAULT '', `price` decimal(10,0) unsigned NOT NULL DEFAULT '0', `productlist` mediumtext NOT NULL, `note` mediumtext NOT NULL, `realname` varchar(40) NOT NULL DEFAULT '', `email` varchar(50) NOT NULL DEFAULT '', `tel` varchar(50) NOT NULL DEFAULT '', `mobile` varchar(18) NOT NULL DEFAULT '', `fax` varchar(50) NOT NULL DEFAULT '', `address` varchar(80) NOT NULL DEFAULT '', `zipcode` varchar(10) NOT NULL DEFAULT '', `status` tinyint(1) unsigned NOT NULL DEFAULT '0', `ip` char(15) NOT NULL DEFAULT '', `createtime` int(11) unsigned NOT NULL DEFAULT '0', `updatetime` int(11) unsigned NOT NULL DEFAULT '0', PRIMARY KEY (`id`), KEY `sn` (`sn`) ) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8; -- -- 表的结构 `h_page` -- DROP TABLE IF EXISTS `h_page`; CREATE TABLE `h_page` ( `id` smallint(5) NOT NULL, `title` varchar(100) NOT NULL DEFAULT '' , `thumb` varchar(100) NOT NULL DEFAULT '', `keywords` varchar(250) NOT NULL DEFAULT '' , `description` mediumtext NOT NULL , `content` mediumtext NOT NULL , `template` varchar(30) NOT NULL DEFAULT '', `listorder` smallint(5) unsigned NOT NULL DEFAULT '0', PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8; -- -- 导出`h_page`表中的数据 `h_page` -- INSERT INTO `h_page` VALUES ('8','关于我们','./Uploads/201104/4d9764a7b953d.jpg','yourphp,企业建站系统,发布','yourphp,企业建站系统,发布','<p>\r\n 关于我们关于我们关于我们关于我们关于我们关于我们关于我们关于我们关于我们关于我们关于我们关于我们关于我们关于我们关于我们关于我们关于我们关于我们关于我们关于我们关于我们关于我们关于我们关于我们关于我们关于我们lllll</p>\r\n<p>\r\n [page]</p>\r\n<p>\r\n sdfgasdfaf中华人民共和国关于我们关于我们关于我们关于我们关于我们关于我们关于我们关于我们关于我们关于我们关于我们关于我们关于我们关于我们关于我们关于我</p>\r\n<p>\r\n 111</p>\r\n','','0'); INSERT INTO `h_page` VALUES ('11','公司简介','','','公司简介','<p>\r\n 公司简介</p>\r\n','','0'); INSERT INTO `h_page` VALUES ('12','联系我们','./Uploads/201104/4d96e3f1522b3.jpg','联系我们','联系我们','<p>\r\n 联系我们</p>\r\n','','0'); -- -- 表的结构 `h_picture` -- DROP TABLE IF EXISTS `h_picture`; CREATE TABLE `h_picture` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `catid` smallint(5) unsigned NOT NULL DEFAULT '0', `userid` int(11) unsigned NOT NULL DEFAULT '0', `username` varchar(40) NOT NULL DEFAULT '', `title` varchar(120) NOT NULL DEFAULT '', `title_style` varchar(40) NOT NULL DEFAULT '', `thumb` varchar(100) NOT NULL DEFAULT '', `keywords` varchar(120) NOT NULL DEFAULT '', `description` mediumtext NOT NULL, `content` mediumtext NOT NULL, `url` varchar(60) NOT NULL DEFAULT '', `template` varchar(40) NOT NULL DEFAULT '', `posid` tinyint(2) unsigned NOT NULL DEFAULT '0', `status` tinyint(1) unsigned NOT NULL DEFAULT '0', `recommend` tinyint(1) unsigned NOT NULL DEFAULT '0', `readgroup` varchar(100) NOT NULL DEFAULT '', `readpoint` smallint(5) NOT NULL DEFAULT '0', `listorder` int(10) unsigned NOT NULL DEFAULT '0', `hits` int(11) unsigned NOT NULL DEFAULT '0', `createtime` int(11) unsigned NOT NULL DEFAULT '0', `updatetime` int(11) unsigned NOT NULL DEFAULT '0', `pics` mediumtext NOT NULL, PRIMARY KEY (`id`), KEY `status` (`id`,`status`,`listorder`), KEY `catid` (`id`,`catid`,`status`), KEY `listorder` (`id`,`catid`,`status`,`listorder`) ) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8; -- -- 表的结构 `h_posid` -- DROP TABLE IF EXISTS `h_posid`; CREATE TABLE `h_posid` ( `id` tinyint(2) unsigned NOT NULL AUTO_INCREMENT, `name` varchar(40) NOT NULL DEFAULT '', `listorder` tinyint(2) unsigned NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=5 DEFAULT CHARSET=utf8; -- -- 导出`h_posid`表中的数据 `h_posid` -- INSERT INTO `h_posid` VALUES ('1','首页推荐','0'); INSERT INTO `h_posid` VALUES ('2','首页幻灯片','0'); INSERT INTO `h_posid` VALUES ('3','推荐产品','0'); INSERT INTO `h_posid` VALUES ('4','促销产品','0'); -- -- 表的结构 `h_product` -- DROP TABLE IF EXISTS `h_product`; CREATE TABLE `h_product` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `catid` smallint(5) unsigned NOT NULL DEFAULT '0' , `userid` int(11) unsigned NOT NULL DEFAULT '0' , `username` varchar(40) NOT NULL DEFAULT '' , `title` varchar(120) NOT NULL DEFAULT '' , `title_style` varchar(40) NOT NULL DEFAULT '' , `keywords` varchar(80) NOT NULL DEFAULT '', `description` mediumtext NOT NULL, `content` mediumtext NOT NULL , `template` varchar(40) NOT NULL DEFAULT '', `thumb` varchar(100) NOT NULL DEFAULT '' , `posid` tinyint(2) unsigned NOT NULL DEFAULT '0' , `status` tinyint(3) unsigned NOT NULL DEFAULT '1', `recommend` tinyint(1) unsigned NOT NULL DEFAULT '0' , `readgroup` varchar(100) NOT NULL DEFAULT '', `readpoint` smallint(5) NOT NULL DEFAULT '0', `listorder` int(10) unsigned NOT NULL DEFAULT '0' , `hits` int(11) unsigned NOT NULL DEFAULT '0' , `createtime` int(11) unsigned NOT NULL DEFAULT '0' , `updatetime` int(11) unsigned NOT NULL DEFAULT '0' , `price` decimal(10,2) unsigned NOT NULL DEFAULT '0.00', `url` varchar(60) NOT NULL DEFAULT '', `xinghao` varchar(30) NOT NULL DEFAULT '', `pics` mediumtext NOT NULL, PRIMARY KEY (`id`), KEY `status` (`id`,`status`,`listorder`), KEY `catid` (`id`,`catid`,`status`), KEY `listorder` (`id`,`catid`,`status`,`listorder`) ) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8; -- -- 表的结构 `h_role` -- DROP TABLE IF EXISTS `h_role`; CREATE TABLE `h_role` ( `id` smallint(6) unsigned NOT NULL AUTO_INCREMENT, `name` varchar(20) NOT NULL DEFAULT '', `status` tinyint(1) unsigned NOT NULL DEFAULT '0', `remark` varchar(255) NOT NULL DEFAULT '', `pid` smallint(5) unsigned NOT NULL DEFAULT '0', `listorder` smallint(6) unsigned NOT NULL DEFAULT '0', PRIMARY KEY (`id`), KEY `status` (`status`) ) ENGINE=MyISAM AUTO_INCREMENT=5 DEFAULT CHARSET=utf8; -- -- 导出`h_role`表中的数据 `h_role` -- INSERT INTO `h_role` VALUES ('1','超级管理员','1','超级管理','0','0'); INSERT INTO `h_role` VALUES ('2','普通管理员','1','普通管理员','0','0'); INSERT INTO `h_role` VALUES ('3','注册用户','1','注册用户','0','0'); INSERT INTO `h_role` VALUES ('4','游客','1','游客','0','0'); -- -- 表的结构 `h_role_user` -- DROP TABLE IF EXISTS `h_role_user`; CREATE TABLE `h_role_user` ( `role_id` mediumint(9) unsigned DEFAULT NULL DEFAULT '0', `user_id` char(32) DEFAULT NULL DEFAULT '0', KEY `group_id` (`role_id`), KEY `user_id` (`user_id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8; -- -- 表的结构 `h_type` -- DROP TABLE IF EXISTS `h_type`; CREATE TABLE `h_type` ( `typeid` smallint(5) unsigned NOT NULL AUTO_INCREMENT, `name` varchar(30) NOT NULL DEFAULT '', `parentid` smallint(5) unsigned NOT NULL DEFAULT '0', `description` varchar(200) NOT NULL DEFAULT '', `status` tinyint(1) unsigned NOT NULL DEFAULT '0', `listorder` smallint(5) unsigned NOT NULL DEFAULT '0', `keyid` smallint(5) unsigned NOT NULL DEFAULT '0', PRIMARY KEY (`typeid`), KEY `parentid` (`parentid`,`listorder`) ) ENGINE=MyISAM AUTO_INCREMENT=8 DEFAULT CHARSET=utf8; -- -- 导出`h_type`表中的数据 `h_type` -- INSERT INTO `h_type` VALUES ('1','友情链接','0','友情链接分类','1','0','1'); INSERT INTO `h_type` VALUES ('3','合作伙伴','1','合作伙伴','1','1','1'); INSERT INTO `h_type` VALUES ('2','默认分类','1','默认分类','1','0','1'); INSERT INTO `h_type` VALUES ('4','反馈类别','0','信息反馈类别','1','0','4'); INSERT INTO `h_type` VALUES ('5','产品购买','4','产品购买','1','0','5'); INSERT INTO `h_type` VALUES ('6','商务合作','4','商务合作','1','0','6'); INSERT INTO `h_type` VALUES ('7','其他反馈','4','其他反馈','1','0','7'); -- -- 表的结构 `h_user` -- DROP TABLE IF EXISTS `h_user`; CREATE TABLE `h_user` ( `id` int(11) NOT NULL AUTO_INCREMENT, `groupid` tinyint(2) unsigned NOT NULL DEFAULT '0' , `username` varchar(50) NOT NULL DEFAULT '', `password` varchar(50) NOT NULL DEFAULT '', `email` varchar(50) NOT NULL DEFAULT '', `realname` varchar(50) NOT NULL DEFAULT '', `question` varchar(50) NOT NULL DEFAULT '', `answer` varchar(50) NOT NULL DEFAULT '', `sex` tinyint(1) NOT NULL DEFAULT '0', `tel` varchar(50) NOT NULL DEFAULT '', `mobile` varchar(50) NOT NULL DEFAULT '', `fax` varchar(50) NOT NULL DEFAULT '', `web_url` varchar(100) NOT NULL DEFAULT '', `address` varchar(100) NOT NULL DEFAULT '', `login_count` int(11) unsigned NOT NULL DEFAULT '0' , `createtime` int(11) unsigned NOT NULL DEFAULT '0' , `updatetime` int(11) unsigned NOT NULL DEFAULT '0' , `last_logintime` int(11) unsigned NOT NULL DEFAULT '0' , `reg_ip` char(15) NOT NULL DEFAULT '', `last_ip` char(15) NOT NULL DEFAULT '', `status` tinyint(1) unsigned NOT NULL DEFAULT '0', PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;<file_sep>/Base/index/core/index.php <?php include_once('common.php'); #log error_log(getDatetime()." action->".phpSelfname()."\n","3",getPath()."console.log"); #main include_once(getTPL()); ?><file_sep>/House/admin/tpl/ueditor/php/action_upload.php <?php include "Uploader.class.php"; #config $config = array( "pathFormat" => $CONFIG['imagePathFormat'], "maxSize" => $CONFIG['imageMaxSize'], "allowFiles" => $CONFIG['imageAllowFiles'] ); $base64 = "upload"; $fieldName = $CONFIG['imageFieldName']; #upload $up = new Uploader($fieldName, $config, $base64); /** * 得到上传文件所对应的各个参数,数组结构 * array( * "state" => "", //上传状态,上传成功时必须返回"SUCCESS" * "url" => "", //返回的地址 * "title" => "", //新文件名 * "original" => "", //原始文件名 * "type" => "" //文件类型 * "size" => "", //文件大小 * ) */ #return return json_encode($up->getFileInfo()); ?> <file_sep>/House/admin/tpl/ueditor/php/action_upload_many.php <?php include "Uploader.class.php"; $CONFIG = json_decode(preg_replace("/\/\*[\s\S]+?\*\//", "", file_get_contents("config.json")), true); #config $config = array( "pathFormat" => $CONFIG['imagePathFormat'], "maxSize" => $CONFIG['imageMaxSize'], "allowFiles" => $CONFIG['imageAllowFiles'] ); $fieldName = "upload"; $base64 = "upload"; #这里要对$_File进行处理 $size = @$_GET["size"]; $json = array(); $temp_array=$_FILES; for($i=0;$i<$size;$i++){ $name = @$temp_array[$fieldName]["name"][$i]; $type = @$temp_array[$fieldName]["type"][$i]; $tmp_name = @$temp_array[$fieldName]["tmp_name"][$i]; $error = @$temp_array[$fieldName]["error"][$i]; $sizez = @$temp_array[$fieldName]["size"][$i]; $_FILES=array(); $_FILES[$fieldName]["name"]=$name; $_FILES[$fieldName]["type"]=$type; $_FILES[$fieldName]["tmp_name"]=$tmp_name; $_FILES[$fieldName]["error"]=$error; $_FILES[$fieldName]["size"]=$sizez; #config change $up = new Uploader($fieldName, $config, $base64); $res=$up->getFileInfo(); $json[]=$res; } #echo echo json_encode($json); ?><file_sep>/House/admin/core/house.php <?php include_once('common.php'); #log error_log(getDatetime()." action->".phpSelfname()."?t=".@$_GET["t"]."\n","3",getPath()."console.log"); #check session $user= !empty($_SESSION['user']) ? $_SESSION['user'] : header("Location:".htaccess('admin/core/login.php?t=timeout')); #op $type= @$_GET['t']; //list if(!empty($type)&&$type=="list"){ #分类 $sql_fl= "select id,catname,parent_id from ".tablePrefix()."house_category where status=0 order by id asc"; $arr_fl = _select($sql_fl); #小区 $sql_xq = "select id,name from ".tablePrefix()."house_village where status = 0 order by id asc"; $arr_xq= _select($sql_xq); #地区 $sql_dq = "select id,name,parent_id from ".tablePrefix()."house_area where status= 0 order by id asc"; $arr_dq = _select($sql_dq); #推荐位 $sql_tjw = "select id,name from ".tablePrefix()."house_posid where status= 0 order by id asc"; $arr_tjw = _select($sql_tjw); #标签 $sql_bq = "select id,name,parent_id from ".tablePrefix()."house_label where status = 0 order by id asc"; $arr_bq = _select($sql_bq); #联系人 $sql_lxr = "select id,name,mobile from ".tablePrefix()."house_contacts where status = 0 order by id asc"; $arr_lxr = _select($sql_lxr); #tpl include_once(getTPL()); exit(); } //json if(!empty($type)&&$type=="json"){ $page = @$_GET["page"]; if(empty($page)){ $page = 1; } $where = ""; $where_values = array(); #select parameter $house_category_id = @$_GET["q1"]; if(!empty($house_category_id)){ $where.=" and h.house_category_id=?"; $where_values[]=$house_category_id; } $house_village_id = @$_GET["q2"]; if(!empty($house_village_id)){ $where.=" and h.house_village_id=?"; $where_values[]=$house_village_id; } $house_area_id = @$_GET["q3"]; if(!empty($house_area_id)){ $where.=" and ha.id=?"; $where_values[]=$house_area_id; } $house_posid_id = @$_GET["q4"]; if(!empty($house_posid_id)){ $where.=" and h.house_posid_ids in (?)"; $where_values[]=$house_posid_id; } $house_label_id = @$_GET["q5"]; if(!empty($house_label_id)){ $where.=" and h.house_label_ids in (?)"; $where_values[]=$house_label_id; } $house_contacts_id = @$_GET["q6"]; if(!empty($house_contacts_id)){ $where.=" and h.house_contacts_id = ?"; $where_values[]=$house_contacts_id; } $name = @$_GET["q7"]; if(!empty($name)){ $where.=" and h.name like ?";#like 处理 $where_values[] = "%".$name."%"; } #sql data $sql = 'select h.createtime,h.id,h.name,hc.catname as hc_name,hc.id as hc_id, hv.name as hv_name,hv.id as hv_id'; $sql.=',ha.name as ha_name,ha.id as ha_id,hcs.name as hcs_name,hcs.id as hcs_id from '.tablePrefix().'house as h '; $sql.='left join '.tablePrefix().'house_category as hc on h.house_category_id=hc.id '; $sql.='left join '.tablePrefix().'house_village as hv on h.house_village_id= hv.id '; $sql.='left join '.tablePrefix().'house_area as ha on hv.house_area_id = ha.id '; $sql.='left join '.tablePrefix().'house_contacts as hcs on h.house_contacts_id= hcs.id '; $sql.='where h.status=0 '.$where.' order by h.id desc limit '.($page-1)*page_size.','.page_size; #find data $arr=_select($sql,$where_values); #sql count $count = _selectCount($sql,$where_values); #json echo json_encode(array('list'=>$arr,'count'=>$count,'status'=>1)); exit(); } //edit if(!empty($type)&&$type=="edit"){ #分类 $sql_fl= "select id,catname,parent_id from ".tablePrefix()."house_category where status=0 order by id asc"; $arr_fl = _select($sql_fl); #小区 $sql_xq = "select id,name from ".tablePrefix()."house_village where status = 0 order by id asc"; $arr_xq= _select($sql_xq); #推荐位 $sql_tjw = "select id,name from ".tablePrefix()."house_posid where status= 0 order by id asc"; $arr_tjw = _select($sql_tjw); #标签 $sql_bq = "select id,name,parent_id from ".tablePrefix()."house_label where status = 0 order by id asc"; $arr_bq = _select($sql_bq); #联系人 $sql_lxr = "select id,name,mobile from ".tablePrefix()."house_contacts where status = 0 order by id asc"; $arr_lxr = _select($sql_lxr); #判断是否有id $id= @$_GET["id"]; $map = null; $thumbs = null; if(!empty($id)){ $sql = "select * from ".tablePrefix()."house where status = 0 and id = ?"; $arr_maps = _select($sql,array($id)); if(!empty($arr_maps)){ $map = $arr_maps[0]; $sql2="select * from ".tablePrefix()."thumbs where status=0 and refer_table = 'house' and refer_id=".$map["id"]." order by createtime asc limit 5"; $thumbs = _select($sql2); } } include_once(getTPL("house-edit")); exit(); } //设置封面操作 if(!empty($type)&&$type=="set_thumb"){ $url = @$_POST["url"]; $id = @$_POST["id"]; if(!empty($id)&&!empty($url)){ $sql = "update ".tablePrefix()."house set thumb = ? where id = ?"; _execute($sql,array($url,$id)); echo json_encode(array("status"=>1)); }else{ echo json_encode(array("status"=>0)); } exit(); } //删除展示图操作 if(!empty($type)&&$type=='del_thumb'){ $id = @$_POST["id"]; if(!empty($id)){ $sql="update ".tablePrefix()."thumbs set status = 1 where id = ?"; _execute($sql,array($id)); echo json_encode(array("status"=>1)); }else{ echo json_encode(array("status"=>0)); } exit(); } //do edit if(!empty($type)&&$type=='do_edit'){ $id = @$_POST["id"]; $name = @$_POST["name"]; $house_category_id = @$_POST["house_category_id"]; $thumbs = @$_POST["thumbs"]; $thumb = @$_POST["thumb"]; $price = @$_POST["price"]; $area = @$_POST["area"]; $floor = @$_POST["floor"]; $total_floor = @$_POST['total_floor']; $oriention = @$_POST["oriention"]; $age = @$_POST['age']; $room_num = @$_POST["room_num"]; $hall_num = @$_POST["hall_num"]; $washroom_num = @$_POST["washroom_num"]; $redecoration = @$_POST["redecoration"]; $house_label_ids = @$_POST["house_label_ids"]; // is array $house_village_id = @$_POST["house_village_id"]; $house_contacts_id = @$_POST["house_contacts_id"]; $house_posid_ids = @$_POST["house_posid_ids"];// is array $hits = @$_POST["hits"]; $content = @$_POST["content"]; $error=""; #if if(!empty($name)&&!empty($house_category_id)&&!empty($house_village_id)&&!empty($house_village_id)){ $sql = "insert into ".tablePrefix()."house(name,house_category_id,thumb,price,area,floor,total_floor,oriention,age,room_num,hall_num,washroom_num,redecoration,house_label_ids,house_village_id,house_contacts_id,house_posid_ids,hits,content,user_id,createtime) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; $house_label_ids_str = implode(",", (array)$house_label_ids); $house_posid_ids_str = implode(",", (array)$house_posid_ids); $sql_data = array($name,$house_category_id,$thumb,$price,$area,$floor,$total_floor,$oriention ,$age,$room_num,$hall_num,$washroom_num,$redecoration,$house_label_ids_str,$house_village_id,$house_contacts_id ,$house_posid_ids_str,$hits,$content,$user["id"],time() ); if(!empty($id)){ #update $sql = "update ".tablePrefix()."house set name=?,house_category_id=?,thumb=?,price=?,area=?,floor=?,total_floor= ?,oriention=?,age=?,room_num=?,hall_num=?,washroom_num=?,redecoration=?,house_label_ids=?,house_village_id=?,house_contacts_id=?,house_posid_ids=?,hits=?,content=?,user_id=?,createtime=? where id = ?"; $sql_data[] = $id; _execute($sql,$sql_data); }else{ #execute by get id $id = _execute($sql,$sql_data,true); } # insert thumbs to $id if(!empty($id)&&!empty($thumbs)){ $sql2 = "insert into ".tablePrefix()."thumbs (refer_id,refer_table,url,createtime) values"; $arr = explode(",",$thumbs); for($i=0;$i<count($arr);$i++){ if($i==count($arr)-1){ $sql2.=" (".$id.",'house','".$arr[$i]."',".time().")"; }else{ $sql2.=" (".$id.",'house','".$arr[$i]."',".time()."),"; } } _execute($sql2); $error="操作成功"; } }else{ $error="操作失败,缺少必要参数"; } include_once(getTPL("tishi")); exit(); } //delete if(!empty($type)&&$type=="delete"){ $id= @$_GET["id"]; #sql $sql = "update ".tablePrefix()."house set status=1 where id=?"; #execute _execute($sql,array($id)); include_once(getTPL("tishi")); exit(); } ?><file_sep>/Base/README.md php基础开发框架 =================================== ### 安装 1.删除install.lock文件<br> 2.访问install执行安装<br> ### 介绍 @author qiyulin<br> @date 2015 08<br> 开发使用基础的php标签做开发处理的框架<br> 使用时候需使用 mysqli<br> ### 核心 1.一键安装<br> 2.原生<?php echo $str; ?>调用<br> 3.核心common.php其中包括 _select,_execute,_selectCount<br> 用法:<br> _select("select * from user");<br> _select("select * from user where id = ? and name like ?",array(1,'%好%'));<br> 获取的是一个array[object]<br> _selectCount("select * from user");<br> 获取的是 sql="select count(*) from user"的结果<br> _execute("insert into user(username,password) values(?,?)",array('zhangsan','123'));<br> 执行则该sql将会被执行<br> _execute("insert into user(username,password) values(?,?)",array('zhangsan','123'),true);<br> 执行该sql同时返回操作sql的id<br> <br> htaccess('url')方法<br> 例如:echo htaccess("admin/core/index.php?t=list");===>admin/index?t=list<br> 如果要修改url伪静态规则 则需要修改 htaccess方法和.htaccess文件即可<br> ### 提示 在后台模版操作中,最好使用如下布局<br> ~~~~~~~~~~~~~~~~~~~~~~~~ ~ ~ ~ ~ 菜 ~ iframe ~ ~ 单 ~ 嵌入窗体 ~ ~ ~ ~ ~~~~~~~~~~~~~~~~~~~~~~~~ 做的时候,只做iframe嵌入窗体的改动<br> 类似于 phpcms的做法<br><file_sep>/House/admin/core/house_category.php <?php include_once('common.php'); #log error_log(getDatetime()." action->".phpSelfname()."?t=".@$_GET["t"]."\n","3",getPath()."console.log"); #check session $user= !empty($_SESSION['user']) ? $_SESSION['user'] : header("Location:".htaccess('admin/core/login.php?t=timeout')); #op $type= @$_GET['t']; //list if(!empty($type)&&$type=="list"){ #tpl include_once(getTPL()); exit(); } //json if(!empty($type)&&$type=="json"){ $where = ""; $where_data = array(); $q1 = @$_GET["q1"]; if(!empty($q1)){ $where .=" and catname like ?"; $where_data[]= '%'.$q1.'%'; } $sql = "select * from ".tablePrefix()."house_category where 1=1 ".$where." order by id asc"; $array = _select($sql,$where_data); echo json_encode($array); exit(); } //edit if(!empty($type)&&$type=="edit"){ #list $sql_fl = "select * from ".tablePrefix()."house_category where status = 0 and parent_id=0 order by id asc"; $arr_fl = _select($sql_fl); #id $id = @$_GET['id']; $map = null; if(!empty($id)){ $sql = "select * from ".tablePrefix()."house_category where id = ?"; $array= _select($sql , array($id)); if(!empty($array)&&count($array)>0){ $map = $array[0]; } } #tpl include_once(getTPL("house_category-edit")); exit(); } //status if(!empty($type)&&$type=="status"){ #param $status = @$_GET["status"]; $id = @$_GET["id"]; #update if(!empty($id)){ if($status!=null&&$status=="0"){ $status = 1; }else{ $status = 0; } $sql ="update ".tablePrefix()."house_category set status =? where id = ?"; _execute($sql,array($status,$id)); $error ="操作成功"; }else{ $error="操作失败,缺少必要参数"; } #tpl include_once(getTPL("tishi")); exit(); } //do edit if(!empty($type)&&$type=="do_edit"){ $id = @$_POST["id"]; $catname = @$_POST["catname"]; $status = @$_POST["status"]; $template_list = @$_POST["template_list"]; $template_show = @$_POST["template_show"]; $pagesize = @$_POST["pagesize"]; #if if(!empty($catname)&&!empty($pagesize)){ if(empty($template_list)){ $template_list = "house_list.html"; } if(empty($template_show)){ $template_show = "house_show.html"; } #sql $sql = "insert into ".tablePrefix()."house_category (catname,status,template_list,template_show,pagesize) values (?,?,?,?,?)"; $sql_data = array($catname,$status,$template_list,$template_show,$pagesize); if(!empty($id)){ $sql = "update ".tablePrefix()."house_category set catname=?,status=?,template_list=?,template_show=?,pagesize=? where id = ?"; $sql_data[] = $id; } #execute _execute($sql,$sql_data); #tishi $error="操作成功"; }else{ $error="操作失败,缺少必要参数"; } include_once(getTPL("tishi")); exit(); } ?><file_sep>/Base/admin.php <?php /** *@author com.love *user admin *@date 2015 12 19 **/ header("location: ./admin"); ?><file_sep>/Base/index.php <?php /** *@author com.love *access entry *@date 2015 12 19 **/ if (!is_file('./config.php')){ header("location: ./install"); }else{ header("Content-type: text/html; charset=utf-8"); error_reporting(E_ERROR | E_WARNING | E_PARSE); header("location: ./index"); } ?><file_sep>/Base/admin/core/index.php <?php include_once('common.php'); #log error_log(getDatetime()." action->".phpSelfname()."\n","3",getPath()."console.log"); #check session //$user= !empty($_SESSION['user']) ? $_SESSION['user'] : header("Location:".htaccess('admin/core/login.php?t=timeout')); #main $str = "你好,笨蛋"; //type------------------------------------- $type = @$_GET["t"]; if(!empty($type)&&$type=="list"){ $str="你好,傻瓜"; include_once(getTPL()); exit(); } //type end---------------------------------- include_once(getTPL()); ?><file_sep>/House/index/core/config.php <?php /** *@author com.love *general methods and configuration *@date 2015 12 19 **/ $config =include('../../config.php'); //get connection function getConnection($config){ $url = $config["DB_HOST"].":".$config["DB_PORT"]; $con = mysql_connect($url,$config["DB_USER"],$config["DB_PWD"]) or die("core/config.php-> db connection failure"); mysql_query("SET NAMES UTF8"); mysql_select_db($config["DB_NAME"]); return $con; } //close connection function closeConnection($con){ mysql_close($con); } //get table prefix function getTablePrefix($config){ return $config["DB_PREFIX"]; } //get client ip function getClientIp(){ static $ip = NULL; if($_SERVER['HTTP_X_REAL_IP']){//nginx agent $ip=$_SERVER['HTTP_X_REAL_IP']; }elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {//客户端的ip $ip=$_SERVER['HTTP_CLIENT_IP']; }elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {//浏览当前页面的用户计算机的网关 $arr=explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']); $pos=array_search('unknown',$arr); if(false !== $pos) unset($arr[$pos]); $ip=trim($arr[0]); }elseif (isset($_SERVER['REMOTE_ADDR'])) { $ip=$_SERVER['REMOTE_ADDR'];//浏览当前页面的用户计算机的ip地址 }else{ $ip=$_SERVER['REMOTE_ADDR']; } return $ip; } //htaccess function htaccess($url){ return str_replace(".php", "", $url); } //get tpl function getTPL($name=null){ if($name==null){ $base=$_SERVER['SCRIPT_NAME']; $arr=explode("/",$base); $default_name = $arr[count($arr)-1]; return "../tpl/".str_replace(".php", "",$default_name).".html"; }else{ return "../tpl/".$name.".html"; } } ?><file_sep>/House/index/core/index.php <?php include_once('./config.php'); include_once(getTPL()); ?>
1b11febe14271708f75de57e1a2990b1b0f6e152
[ "Markdown", "SQL", "ApacheConf", "PHP" ]
18
Markdown
qiyulin/php_workspace-Base
96c3c3891bea23925627248a09563fb82e1dba62
dd4e7541d6c0f0be593f7dbfe3170e9e14b16d0a
refs/heads/master
<file_sep><?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>ru.lipatkin.experiments</groupId> <artifactId>spring-boot-hello-world</artifactId> <version>0.1.2-SNAPSHOT</version> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.4.0.RELEASE</version> </parent> <packaging>war</packaging> <scm> <url>https://github.com/dempj/spring-boot-openshift-hello-world </url> <connection>scm:git:git@github.com:dempj/spring-boot-openshift-hello-world.git</connection> <developerConnection>scm:git:git@github.com:dempj/spring-boot-openshift-hello-world.git</developerConnection> </scm> <distributionManagement> <repository> <id>deployment</id> <name>Release Repository</name> <url>http://nexusci.apps.test.cloudstore.run/repository/vfcloudstore-releases/</url> </repository> <snapshotRepository> <id>deployment</id> <name>Snapshot Repository</name> <url>http://nexusci.apps.test.cloudstore.run/repository/vfcloudstore-snapshots/</url> </snapshotRepository> </distributionManagement> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>com.jayway.jsonpath</groupId> <artifactId>json-path</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.3.0</version> <scope>compile</scope> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.3.0</version> <scope>compile</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <exclusions> <exclusion> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> </exclusion> </exclusions> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>buildnumber-maven-plugin</artifactId> <version>1.4</version> <executions> <execution> <phase>validate</phase> <goals> <goal>create</goal> <goal>create-metadata</goal> </goals> </execution> </executions> <configuration> <attach>true</attach> <!--make it available for jar/war classpath resource --> <addOutputDirectoryToResources>true</addOutputDirectoryToResources> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <version>2.3</version> <configuration> <failOnMissingWebXml>false</failOnMissingWebXml> <outputDirectory>target</outputDirectory> <warName>ROOT</warName> <archive> <manifest> <addDefaultImplementationEntries>true</addDefaultImplementationEntries> </manifest> <manifestEntries> <!-- Adds ${buildNumber} as an entry in the manifest file --> <Git-SHA-1>${buildNumber}</Git-SHA-1> </manifestEntries> </archive> <webResources> <webResource> <!-- Adds ${buildNumber} to index.html --> <directory>${basedir}/src/main/webapp</directory> <filtering>true</filtering> </webResource> </webResources> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-release-plugin</artifactId> <version>2.5.1</version> </plugin> </plugins></build> <repositories> <repository> <id>spring-releases</id> <url>https://repo.spring.io/libs-release</url> </repository> </repositories> <pluginRepositories> <pluginRepository> <id>spring-releases</id> <url>https://repo.spring.io/libs-release</url> </pluginRepository> </pluginRepositories> </project> <file_sep>FROM wildfly:10.0 RUN mkdir -p target/ COPY ROOT.war target/ ENTRYPOINT ["sh", "-c", "${STI_SCRIPTS_PATH}/assemble && ${STI_SCRIPTS_PATH}/run"] <file_sep>node('maven') { def mvnHome = tool name: 'M3', type: 'maven' env.PATH = "${mvnHome}/bin:${env.PATH}" stage('Checkout') { checkout changelog: false, poll: false, scm: [$class: 'GitSCM', branches: [[name: '*/master']], doGenerateSubmoduleConfigurations: false, extensions: [[$class: 'CheckoutOption'], [$class: 'LocalBranch', localBranch: 'master']], submoduleCfg: [], userRemoteConfigs: [[credentialsId: 'c5ae61df-e297-4c82-af51-133feb1f6ca4', url: '<EMAIL>:dempj/spring-boot-openshift-hello-world.git']]] } stage('Build'){ sh 'mvn -f pom.xml clean install -DskipTests' } stage('Test'){ sh 'mvn -f pom.xml test' } stage('Package'){ sh 'mvn -f pom.xml deploy' } stage('Apply definitions'){ sh 'oc apply -f definitions/deployment/' } stage('Deploy'){ sh "mkdir -p target/deploy" sh "cp Dockerfile target/deploy" sh "cp target/ROOT.war target/deploy" sh "oc start-build goop-wildfly-build --from-dir target/deploy" } } <file_sep>apiVersion: v1 kind: List metadata: {} items: - apiVersion: v1 kind: DeploymentConfig metadata: labels: app: goop-wildfly name: goop-wildfly-dc spec: replicas: 1 selector: deploymentconfig: goop-wildfly-dc template: metadata: labels: app: goop-wildfly deploymentconfig: goop-wildfly-dc spec: containers: - image: goop-wildfly name: goop-wildfly ports: - containerPort: 8080 protocol: TCP triggers: - imageChangeParams: automatic: true containerNames: - goop-wildfly from: kind: ImageStreamTag name: goop-wildfly:latest type: ImageChange - type: ConfigChange
fe8ac39a3b5bac251e64dfde2c418e02afd3ddcd
[ "Groovy", "Dockerfile", "YAML", "Maven POM" ]
4
Groovy
dempj/spring-boot-openshift-hello-world
fd829244b7f6ec101746d17bb23ea8176bbefa4d
d78afd3a1da7c680b580c13f15b26a81e6266979
refs/heads/master
<repo_name>irsl/knc-memory-exhaustion<file_sep>/README.md # Product "KNC is Kerberised NetCat. It works in basically the same way as either netcat or stunnel except that it is uses GSS-API to secure the communication. You can use it to construct client/server applications while keeping the Kerberos libraries out of your programs address space quickly and easily." ## Links Official page: http://oskt.secure-endpoints.com/knc.html Source code repository: https://github.com/elric1/knc/ ## CVE-2017-9732 vulnerability knc (Kerberised NetCat) before 1.11-1 is vulnerable to denial of service (memory exhaustion) that can be exploited remotely without authentication, possibly affecting another services running on the targeted host. The knc implementation uses a temporary buffer in read_packet() function that is not freed (memory leak). An unauthenticated attacker can abuse this by sending a blob of valid kerberos handshake structure but with unexpected type; instead of token type AP_REQ (0x0100) I sent 0x0000 at bytes 16 and 17 in my proof of concept. During the attack, gss_sec_accept_context returns G_CONTINUE_NEEDED and the memory is exhausted in the long run. The attack might not even be logged, depending on how the Open Source Kerberos Tooling stack is configured. ## Exploit ``` ./memory-exhaustion-poc.pl target-host target-port ``` Top output ~30 seconds later: ``` 2 CPUs; last pid: 20507; load averages: 1.26, 0.84, 0.38 14:11:53 268 processes: 4 running, 264 sleeping CPU states: 38.6% user, 0.0% nice, 27.1% system, 34.3% idle cpu 0: 18.7% user, 0.0% nice, 22.9% system, 58.4% idle cpu 1: 54.7% user, 0.0% nice, 30.7% system, 14.6% idle Memory: 7857M real, 7734M used, 122M free Swap: 4094M total, 0K used, 4094M free PID PSID USERNAME THR PRI NICE SIZE RES STATE TIME CPU COMMAND 20156 19806 username 1 20 0 2165M 2133M cpu1 19:41 46.19% knc ... ``` ## Bugfix https://github.com/elric1/knc/commit/f237f3e09ecbaf59c897f5046538a7b1a3fa40c1
57fa7252a573a6744534ce04d87161a525ecf6c4
[ "Markdown" ]
1
Markdown
irsl/knc-memory-exhaustion
268cbef2635204f59cbf866326c68c9f008ecac8
a5917a949a308887ab194c501db4ff155158a5ee
refs/heads/master
<file_sep># Keys ## Generate Keypair ```bash $ keytool -genkeypair -alias mykeys -keyalg RSA -keypass mypass -keystore mykeys.jks -storepass mypass ``` ## Export Public Key ```bash $ keytool -list -rfc --keystore mykeys.jks -storepass mypass | openssl x509 -inform pem -pubkey ``` # Flow ## Get Token ```bash $ curl trusted-app:secret@localhost:8080/oauth/token -d "grant_type=password&username=user&password=<PASSWORD>" | jq '.' ``` Result: ```json { "jti": "1826e5e3-4d18-4f95-bf7e-5cc2f58d0841", "scope": "read write", "expires_in": 43199, "refresh_token": "<KEY>", "token_type": "bearer", "access_token": "<KEY>" } ``` # Exttract Token and do Client Call ```bash $ TOKEN=$(curl trusted-app:secret@localhost:8080/oauth/token -d "grant_type=password&username=user&password=<PASSWORD>" | jq '.access_token' | sed 's/"//g') $ curl -H "Authorization: Bearer $TOKEN" localhost:8081/demo ```<file_sep>package de.struktuhr.oauthresource.web; public class RequestContext { public final static String AUTHORIZATION_HEADER = "Authorization"; private static final ThreadLocal<RequestContext> context = new ThreadLocal<>(); private String token; public static RequestContext getContext() { RequestContext ctx = context.get(); if (ctx == null) { ctx = new RequestContext(); context.set(ctx); } return ctx; } public String getAuthToken() { return token; } public void setAuthToken(String token) { this.token = token; } } <file_sep>package de.struktuhr.oauthauthserver.config; import org.springframework.beans.factory.annotation.Configurable; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.ldap.core.DirContextOperations; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.ldap.userdetails.LdapAuthoritiesPopulator; import java.util.Collection; import java.util.HashSet; @Configurable @EnableWebSecurity(debug = true) public class SecurityConfig extends WebSecurityConfigurerAdapter { @Value("${ldap.userSearchFilter}") private String userSearchFilter; @Value("${ldap.groupSearchFilter}") private String groupSearchFilter; @Value("${ldap.url}") private String url; @Value("${ldap.managerDN}") private String managerDN; @Value("${ldap.managerPassword}") private String managerPassword; @Override protected void configure(HttpSecurity http) throws Exception { http .formLogin().disable() // disable form authentication .anonymous().disable() // disable anonymous user .authorizeRequests().anyRequest().denyAll(); // denying all access } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() // creating user in memory .withUser("user") .password("<PASSWORD>") .roles("USER") .and() .withUser("admin") .password("<PASSWORD>") .authorities("ROLE_ADMIN"); } // @Override // public void configure(AuthenticationManagerBuilder auth) throws Exception { // auth // .ldapAuthentication() // .userSearchFilter(userSearchFilter) // .groupSearchFilter(groupSearchFilter) // .ldapAuthoritiesPopulator(ldapAuthoritiesPopulator()) // .contextSource() // .url(url) // .managerDn(managerDN) // .managerPassword(managerPassword); // // } // // @Bean // public LdapAuthoritiesPopulator ldapAuthoritiesPopulator() { // return new LdapAuthoritiesPopulator() { // @Override // public Collection<? extends GrantedAuthority> getGrantedAuthorities(DirContextOperations dirContextOperations, String s) { // final Collection<GrantedAuthority> authorities = new HashSet<>(); // // // every authenticated user has Role USER // authorities.add(new SimpleGrantedAuthority("USER")); // // // jfryer is admin // final String uid = dirContextOperations.getStringAttribute("uid"); // if ("jfryer".equalsIgnoreCase(uid)) { // authorities.add(new SimpleGrantedAuthority("ROLE_ADMIN")); // } // // System.out.println(s + " has roles " + authorities); // // return authorities; // } // }; // } @Override @Bean public AuthenticationManager authenticationManagerBean() throws Exception { // provides the default AuthenticationManager as a Bean return super.authenticationManagerBean(); } } <file_sep>package de.struktuhr.oauthauthserver.boundary; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class GenralController { @RequestMapping("/") public String home() { return "Hello from home"; } } <file_sep>package de.struktuhr.oauthresource.config; import de.struktuhr.oauthresource.web.AuthorizationFilter; import de.struktuhr.oauthresource.web.AuthorizationInterceptor; import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.client.ClientHttpRequestFactory; import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; import org.springframework.web.client.RestTemplate; import java.util.Arrays; @Configuration public class RestConfig { @Bean public RestTemplate restTemplate() { RestTemplate restTemplate = new RestTemplate(clientHttpRequestFactory()); restTemplate.setInterceptors(Arrays.asList(new AuthorizationInterceptor())); return restTemplate; } private ClientHttpRequestFactory clientHttpRequestFactory() { HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(); factory.setReadTimeout(2000); factory.setConnectTimeout(2000); return factory; } @Bean public FilterRegistrationBean authorizationFilter() { FilterRegistrationBean registration = new FilterRegistrationBean(); registration.setFilter(new AuthorizationFilter()); registration.addUrlPatterns("/*"); registration.setName("authorizationFilter"); return registration; } }
52972cc580b1f94ebe8434f4c01cd556a0922259
[ "Java", "Markdown" ]
5
Java
MathiasBoehm/oauth-demo
512bf4355d50c29308964bf9e746a73ac856cdae
39ef8a3c30f6e6409891bd3b771dee2950e1a39a
refs/heads/main
<file_sep># stad_mealapp My flutter project on mealapp
0cc44ed955dc1b446ff2ef85bacd997acf87a209
[ "Markdown" ]
1
Markdown
winnie184317y/stad_mealapp
f6675e57b2b5a9d29e5497e424054031b93ce35f
5696a7f6c40afcbd9b550580fa3917542c9ed94c
refs/heads/master
<repo_name>aparajita/SCKit<file_sep>/Tests/SCStringTest.j /* * SCStringTest.j * SCKit * * Created by <NAME>. * Copyright (c) 2010, Victory-Heart Productions. * * Released under the MIT license: * http://www.opensource.org/licenses/MIT */ @import <Foundation/CPBundle.j> @import <AppKit/AppKit.j> @import <SCKit/SCString.j> function _testValues(self, template, values, expectedString) { var actualString = [SCString stringWithTemplate:template, values]; [self assertTrue:(expectedString === actualString) message:"stringWithTemplate: expected:" + expectedString + " actual:" + actualString]; } var dateFunctions = [[CPBundle bundleForClass:[SCString class]] pathForResource:@"date-functions.js"]; // Strip the file: transport from the path dateFunctions = dateFunctions.substring(dateFunctions.indexOf("/")); require(dateFunctions); @implementation SCStringTest : OJTestCase - (void)testStringWithTemplateVariableSubstitutionWithArgs { var expectedString = @"There are 7 pizzas", template = @"There are $0 $1", actualString = [SCString stringWithTemplate:template, 7, @"pizzas"]; [self assertTrue:(expectedString === actualString) message:"stringWithTemplate: expected:" + expectedString + " actual:" + actualString]; } - (void)testStringWithTemplateVariableSubstitutionWithValues { var expectedString = @"There are 7 pizzas", template = @"There are $qty $item"; _testValues(self, template, {qty:7, item:"pizzas"}, expectedString); } - (void)testStringWithTemplateVariableSubstitutionWithDefaults { var expectedString = @"There are 7 pizzas", template = @"There are ${qty|7} ${item|pizzas}"; _testValues(self, template, {}, expectedString); } - (void)testStringWithTemplateZeroSelector { var expectedString = @"There are no pizzas", template = @"There are #qty#no#$qty# $item", values = {qty:0, item:"pizzas"}; _testValues(self, template, values, expectedString); expectedString = @"There are 7 pizzas"; values.qty = 7; _testValues(self, template, values, expectedString); } - (void)testStringWithTemplatePluralSelector { var expectedString = @"There is 1 pizza", template = @"There |qty|is|are| #qty#no#$qty# ${item}|qty||s|", values = {qty:1, item:"pizza"}; _testValues(self, template, values, expectedString); expectedString = @"There are 7 pizzas"; values.qty = 7; _testValues(self, template, values, expectedString); } - (void)testStringWithTemplateNumberFormats { var expectedString = @"There are 7 pizzas", template = @"There are ${qty:d} pizzas", values = {qty:7.07}; _testValues(self, template, values, expectedString); expectedString = @"There are 7.1 pizzas"; template = @"There are ${qty:.1f} pizzas"; _testValues(self, template, values, expectedString); expectedString = @"There are 7.07 pizzas"; template = @"There are ${qty:.2f} pizzas"; _testValues(self, template, values, expectedString); expectedString = @"There are 0.270 pizzas"; template = @"There are ${qty:0.3f} pizzas"; values.qty = 0.27; _testValues(self, template, values, expectedString); } - (void)testStringWithTemplateDateFormats { var expectedString = @"Date (YYYY-MM-DD): 1964-04-13", template = @"Date (YYYY-MM-DD): ${date:Y-m-d}", values = {date: new Date(1964, 3, 13)}; _testValues(self, template, values, expectedString); expectedString = @"Date (Weekday, Month Date, Year): Monday, April 13, 1964", template = @"Date (Weekday, Month Date, Year): ${date:l, F j, Y}", _testValues(self, template, values, expectedString); } @end // // var template = @"There |qty|is|are| #qty#no#${qty}# ${name}|qty||s|#qty#!##", // values = {name:"pizza", qty:0}; // // print([SCString stringWithTemplate:template, values]); // values.qty = 1; // print([SCString stringWithTemplate:template, values]); // values.qty = 7; // print([SCString stringWithTemplate:template, values]); // // print([SCString stringWithTemplate:@"The date is ${date:j F, Y}", {date:new Date()}]); <file_sep>/_SCConnection.j /* * _SCConnection.j * SCKit * * Created by <NAME>. * Copyright (c) 2010, Victory-Heart Productions. * * Released under the MIT license: * http://www.opensource.org/licenses/MIT */ @import <Foundation/CPObject.j> @import <Foundation/CPString.j> @import <Foundation/CPURLResponse.j> @import "SCConnectionUtils.j" /* This is a base implementation class for SCURLConnection and SCJSONPConnection. Those classes forward method calls to an instance of this class. */ @implementation _SCConnection : CPObject { int responseStatus; id connection; id delegate; CPString selectorPrefix; id receivedData; } - (void)initWithConnection:(id)aConnection identifier:(CPString)anIdentifier delegate:(id)aDelegate startImmediately:(BOOL)shouldStartImmediately { connection = aConnection; responseStatus = 200; delegate = aDelegate; receivedData = nil; if ([anIdentifier length] === 0) selectorPrefix = @"connection"; else selectorPrefix = anIdentifier + @"Connection"; if (shouldStartImmediately) [aConnection start]; } - (void)connection:(id)aConnection didReceiveResponse:(CPHTTPURLResponse)response { responseStatus = [response statusCode]; receivedData = nil; } - (void)connection:(id)aConnection didReceiveData:(id)data { if (typeof(data) === "string") { if (receivedData === nil) receivedData = data; else receivedData += data; } else // assume it's JSON data receivedData = data; if (responseStatus != 200) return; var selector = CPSelectorFromString(selectorPrefix + @":didReceiveData:"); if ([delegate respondsToSelector:selector]) { try { [delegate performSelector:selector withObject:aConnection withObject:data]; } catch (anException) { [self _handleException:anException connection:aConnection]; } } } - (void)connectionDidFinishLoading:(id)aConnection { if (responseStatus == 200) { var selector = CPSelectorFromString(selectorPrefix + @"DidSucceed:"); if ([delegate respondsToSelector:selector]) { try { [delegate performSelector:selector withObject:aConnection]; } catch (anException) { [self _handleException:anException connection:aConnection]; } } } else [self _connection:aConnection didFailWithError:responseStatus]; } - (int)responseStatus { return responseStatus } - (id)delegate { return delegate; } - (void)start { [connection start]; } - (void)cancel { [connection cancel]; } - (void)removeScriptTag { [connection removeScriptTag]; } - (CPString)receivedData { return receivedData; } - (JSObject)receivedJSONData { if ([receivedData isKindOfClass:CPString]) return [receivedData objectFromJSON]; else return receivedData; } - (void)connection:(id)aConnection didFailWithError:(id)error { [self _connection:aConnection didFailWithError:503]; // Service Unavailable } - (void)_connection:(id)aConnection didFailWithError:(id)error { var selector = CPSelectorFromString(selectorPrefix + @":didFailWithError:"); if ([delegate respondsToSelector:selector]) { [delegate performSelector:selector withObject:aConnection withObject:error]; return; } [SCConnectionUtils alertFailureWithError:error delegate:nil]; } - (void)_handleException:(CPException)anException connection:(id)aConnection { var error, type = typeof(anException); if (type === "string" || type === "number") error = anException; else if (type === "object" && anException.hasOwnProperty("message")) error = @"An error occurred when receiving data: " + anException.message; else error = -1; [self _connection:aConnection didFailWithError:error]; } @end <file_sep>/SCJSONPConnection.j /* * SCJSONPConnection.j * SCKit * * Created by <NAME>. * Copyright (c) 2010, Victory-Heart Productions. * * Released under the MIT license: * http://www.opensource.org/licenses/MIT */ @import <Foundation/CPJSONPConnection.j> @import <Foundation/CPURLRequest.j> @import "_SCConnection.j" /*! SCJSONPConnection is a drop-in replacement for CPJSONPConnection which provides more streamlined usage, automates common tasks like caching received data, and deals with some of the more tricky aspects of error handling. For more details, see the documentation for SCURLConnection. */ @implementation SCJSONPConnection : CPJSONPConnection { _SCConnection base; } + (SCJSONPConnection)connectionWithRequest:(CPURLRequest)aRequest delegate:(id)aDelegate { return [[[self class] alloc] initWithRequest:aRequest callback:@"callback" delegate:aDelegate identifier:@"" startImmediately:YES]; } + (SCJSONPConnection)connectionWithRequest:(CPURLRequest)aRequest callback:(CPString)callbackParameter delegate:(id)aDelegate { return [[[self class] alloc] initWithRequest:aRequest callback:callbackParameter delegate:aDelegate identifier:@"" startImmediately:YES]; } + (SCJSONPConnection)connectionWithRequest:(CPURLRequest)aRequest delegate:(id)aDelegate identifier:(CPString)anIdentifier { return [[[self class] alloc] initWithRequest:aRequest callback:@"callback" delegate:aDelegate identifier:anIdentifier startImmediately:YES]; } + (SCJSONPConnection)connectionWithRequest:(CPURLRequest)aRequest callback:(CPString)callbackParameter delegate:(id)aDelegate identifier:(CPString)anIdentifier { return [[[self class] alloc] initWithRequest:aRequest callback:callbackParameter delegate:aDelegate identifier:anIdentifier startImmediately:YES]; } - (id)initWithRequest:(CPURLRequest)aRequest callback:(CPString)callbackParameter delegate:(id)aDelegate identifier:(CPString)anIdentifier startImmediately:(BOOL)shouldStartImmediately { base = [_SCConnection new]; self = [super initWithRequest:aRequest callback:callbackParameter delegate:base startImmediately:NO]; if (self) [self _initWithIdentifier:anIdentifier delegate:aDelegate startImmediately:shouldStartImmediately]; return self; } - (void)_initWithIdentifier:(CPString)anIdentifier delegate:(id)aDelegate startImmediately:(BOOL)shouldStartImmediately { [base initWithConnection:self identifier:anIdentifier delegate:aDelegate startImmediately:shouldStartImmediately]; } /*! Returns 200 if the connection succeeded without error, otherwise the response code. */ - (int)responseStatus { return [base responseStatus]; } /*! Returns the JSON data received from the connection response. Note that unlike SCURLConnection, this always returns JSON data, since by definition a JSONP connection returns JSON. */ - (CPString)receivedData { return [base receivedData]; } /*! Returns the JSON data received from the connection response. */ - (JSObject)receivedJSONData { return [base receivedJSONData]; } /*! @ignore */ - (void)connection:(SCURLConnection)connection didFailWithError:(id)error { [base connection:connection didFailWithError:error]; } @end <file_sep>/SCKitClass.j /* * SCKitClass.j * SCKit * * Created by <NAME>. * Copyright (c) 2010, Victory-Heart Productions. * * Released under the MIT license: * http://www.opensource.org/licenses/MIT */ @import <Foundation/CPObject.j> /*! @ingroup sckit This class is defined to make it easier to find the bundle, for example to get an image from the framework like this: @code var path = [[CPBundle bundleForClass:SCKit] pathForResource:@"email-action.png"]; @endcode You can also use [SCKit version] to get the current version. */ @implementation SCKit : CPObject + (CPString)version { var bundle = [CPBundle bundleForClass:[self class]]; return [bundle objectForInfoDictionaryKey:@"CPBundleVersion"]; } @end <file_sep>/SCString.j /* * SCString.j * SCKit * * Created by <NAME>. * Copyright (c) 2010, Victory-Heart Productions. * * Released under the MIT license: * http://www.opensource.org/licenses/MIT */ @import <Foundation/CPArray.j> @import <Foundation/CPDictionary.j> @import <Foundation/CPString.j> /*! @ingroup sckit SCString implements a string template engine. Long ago I was poking through the resources used by the Macintosh Finder and saw strings like this: The folder ^1 contains #2#no#^2# file|2||s|#2## for ^3 byte|3||s|# I realized they had created a meta-language to allow a single string to allow dynamic argument substitution and express two types of linguistic variations: - Zero/non-zero - Singular/plural In most languages, the syntax changes based on those two factors. For example, let's suppose we want to tell users how many messages they have after logging in. In natural English, there are three distinct forms: - Zero: "You have no messages" - Singular: "You have 1 message" - Plural: "You have 7 messages" In French it would be something like this: - Zero: "Vous n'avez aucun message" - Singular: "Vous avez 1 message" - Plural: "Vous avez 7 messages" You could encode these linguistic rules in your code, but that doesn't work very well if you need to translate your application into languages that don't follow the same rules. Or you could just give up and do something like this: You have 0 message(s) If that solution doesn't satisfy you, then \c stringWithTemplate is the solution. @section patterns Template Patterns \c stringWithTemplate is an Objective-J port of the meta-language used in the original Mac Finder, but with an extended and more familiar syntax. You apply one or more arguments to a template. Argument placeholders indicated by "$key" or "${key}" in the template are replaced with the corresponding replacement arguments. Replacement arguments can be passed in several ways: - You may pass one or more unnamed parameters following the last named parameter. - If there is only unnamed parameter and it is a CPDictionary, <key> should be the key in that dictionary. - If there is only unnamed parameter and it is an array, <key> should be a numeric, zero-based index into that array. - If there is only unnamed parameter and it is an object (but not a CPDictionary), <key> should be a property of that object. - Otherwise <key> should be a numeric, zero-based index of an unnamed parameter, with 0 being the first unnamed parameter, 1 the second, and so on. Note that because \c stringWithTemplate supports indexing, the <key> can be a number in addition to an identifier. If <key> does not exist in an argument dictionary or is out of the range of positional arguments, the argument placeholder is replaced with an empty string. When using the ${key} syntax for replacement parameters, you may add a format separated by a semicolon like this: ${key:format} If the replacement argument is a date and the Date object has had the function dateFormat() added to its prototype, then [argsDict objectForKey:key].dateFormat(format) is used to format it. One such dateFormat() function is available here: http://code.google.com/p/flexible-js-formatting/ For the available date formats of this library, see: http://www.xaprb.com/articles/date-formatting-demo.html The formatting options of flexible-js-formatting are basically the same as the date() function in php: http://php.net/manual/en/function.date.php If the argument is not a date, the equivalent of: @code [CPString stringWithFormat:format, [argsDict objectForKey:key]] @endcode is performed. For example: ${total:.2f} ${date:F j, Y} is the same as: @code [CPString stringWithFormat:@"%.2f", [argsDict objectForKey:@"total"]] [argsDict objectForKey:@"date"].dateFormat("F j, Y") @endcode In addition to a format, you may also add a default value after a vertical bar: ${key|default} or ${key:format|default} The default is used if [argsDict objectForKey:key] evaluates to false, which means nil, an empty string, etc. Inline formats and defaults are nice, but the real power of \c stringWithTemplate is the meta-language that allows you to deal with linguistic rules and alternatives in a single template. In addition to argument replacement, you can specify alternate subsections of the template to be used. Which subsection is used depends on the value of the replacement arguments. Alternate subsections are marked in the form: <delim><key><delim><alt1><delim><alt2><delim> where <delim> is a delimiter character, <key> is in the same format as a replacement argument, <alt1> is the "true" choice, and <alt2> is the "false" choice. The delimiter characters are taken from the first two characters of the delimiters parameter in \c stringWithTemplate:delimiters:. If you use \c stringWithTemplate or if the length of the delimiters < 2, the default delimiters are "#|". Three passes are made over the template: 1. Zero/non-zero (false/true) subsections (<delim> == delimiters[0]) are matched. If [argsDict objectForKey:key] evaluates to zero, <alt1> is used, else <alt2> is used. An argument is considered zero if: - It is a number and == 0 - !arg == true 2. Singular/plural subsections (<delim> == delimiters[1]) are matched, and if [argsDict objectForKey:key] evaluates to 1, <alt1> is used, else <alt2> is used. An argument evaluates to 1 if: - It is a number and == 1 - It is a string and can be converted to a number which == 1.0 - It is an object with a length property which == 1 3. Any occurrence of $key or ${key} is replaced with the corresponding replacement argument according to the rules stated above. @warning Subsections with the same delimiter may not be nested. If all of the matching rules for a subsection fail, the entire subsection is replaced with an empty string. @section delimiters Escaping/changing the Delimiters If your template string uses one of the defaults delimiters ("#" or "|") or the key marker ("$") in its regular text, you have two options: - Precede the literal delimiter characters with backslashes - Change the delimiters by using \c stringWithTemplate:delimiters: instead of \c stringWithTemplate: - Use "$$" to represent a literal "$" @section examples Examples Let's look at some examples to see how we might use \c stringWithTemplate. We'll start with a simple example. We have a song object parsed from JSON for which we want to display the date it was composed and the name of the composer: var args = {composer:song.composer, date:song.dateComposed}, text = [SCString stringWithTemplate:@"Composed by $composer on $dateComposed", args] RESULT: "Composed by <NAME> on 2005-03-30" Simple enough. Now we want to format the date to be a little more friendly: text = [SCString stringWithTemplate:@"Composed by $composer on ${dateComposed:F j, Y}", args]; RESULT: "Composed by <NAME> on March 30, 2005" That's better. Now we want to translate it into French: text = [SCString stringWithTemplate:@"Composée par $composer le ${dateComposed:j F, Y}", args]; RESULT: "Composée par <NAME> le 30 March, 2005" Now we realize that that we may not know the composition date, in which case the date is nil. So we use the default value: text = [SCString stringWithTemplate:@"Composed by $composer ${dateComposed:\\o\\n F j, Y|(date unknown)}", args]; RESULT: "Composed by <NAME> (date unknown)" # if dateComposed is nil Note that we backslash escaped the characters in "on" so they would not be interpreted as format characters. Now we want to add "and translated" if the song has a translation by the composer: var args = {composer:song.composer, date:song.dateComposed, translated:song.hasTranslation}, template = @"Composed #translated##and translated #by $composer ${dateComposed:\o\n F j, Y|(date unknown)}", text = [SCString stringWithTemplate:template, args]; Note that we are using the zero/non-zero selector as a false/true selector in this case. Just for reference, here is how the template would look if you wanted to pass the arguments as positional arguments: var template = @"Composed #0##and translated #by $1 ${2:\o\n F j, Y|(date unknown)}", text = [SCString stringWithTemplate:template, song.hasTranslation, song.composer, song.dateComposed]; Finally, we find that sometimes we don't know the exact date of composition, but we know the month or year. In that case we have a text date like "February 1980". So our logic ends up like this: - If there is a text date, display that - If there is an exact date, format and display that - Otherwise display "(date unknown)" Here's how we encode all of this into the \c stringWithTemplate: var args = { composer:song.composer, date:song.dateComposed, textDate:song.textDate, translated:song.hasTranslation }; var template = @"Composed #translated##and translated #by $composer " + @"#textDate#${dateComposed:\o\n F j, Y|(date unknown)}#$textDate#", text = [SCString stringWithTemplate:template, args]; Now let's see how the singular/plural selector works. Returning to a variation on the first example at the top of this doc, we want to encode these three variations into a single template: You don't have any messages You have only 1 message You have 7 messages Here is the template: var template = @"You #count#don't ##have #count#any#|count|only ||$count# message|count||s|.", text = [SCString stringWithTemplate:template, {count:messageCount}; Let's break down the pattern: #count#don't ## If $count evaluates to zero, insert "don't ". #count#any#|count|only ||$count# Here we have a one selector and argument placeholder nested inside a zero selector. - The zero selector is evaluated first. If $count evaluates to zero, substitute "any", else substitute "|count|only ||$count". - Then the one selector is evaluated. If the zero selector returned "|count|only ||$count", that is parsed. If $count evaluates to 1, "only " is substituted, otherwise nothing. - Finally the argument placeholders are substituted. message|count||s| This is a common idiom for expressing singular/plural. If count evaluates to 1, add no suffix to "message", otherwise add "s" as a suffix to make it plural. To help you picture what is happening, let's view the steps of the transformation of the string given a count of zero, 1 and 7. count == 0 1. Zero selector applied -> "You don't have any message|count||s|." 2. One selector applied -> "You don't have any messages." 3. Arguments replaced -> "You don't have any messages." count == 1 1. Zero selector applied -> "You have |count|only ||$count message|count||s|." 2. One selector applied -> "You have only $count message." 3. Arguments replaced -> "You have only 1 message." count == 7 1. Zero selector applied -> "You have |count|only ||$count message|count||s|." 2. One selector applied -> "You have $count messages." 3. Arguments replaced -> "You have only 7 messages." Hopefully that should be enough to give you an idea how to use \c stringWithTemplate. Enjoy! */ @implementation SCString : CPObject /*! Applies a variable number of arguments to a template. */ + (id)stringWithTemplate:(CPString)template, ... { var args = [template, SCStringImpl.TemplateDefaultDelimiters]; return SCStringImpl.stringWithTemplate.apply(self, args.concat(Array.prototype.slice.call(arguments, 3))); } /*! Applies the values in an array to a template. */ + (id)stringWithTemplate:(CPString)template args:(CPArray)args { return SCStringImpl.stringWithTemplate.apply(self, [template, SCStringImpl.TemplateDefaultDelimiters].concat(args)); } /*! Applies a variable number of arguments to a template, using the given custom pattern delimiters. */ + (id)stringWithTemplate:(CPString)template delimiters:(CPString)delimiters, ... { var args = [template, delimiters]; return SCStringImpl.stringWithTemplate.apply(self, args.concat(Array.prototype.slice.call(arguments, 4))); } /*! Applies the values in an array to a template, using the given custom pattern delimiters. */ + (id)stringWithTemplate:(CPString)template delimiters:(CPString)delimiters args:(CPArray)args { return SCStringImpl.stringWithTemplate.apply(self, [template, delimiters].concat(args)); } @end SCStringImpl = (function() { var my = {}, // Template argument RE TemplateArgREPattern = '\\$' + // template argument indicator followed by... '(?:' + '(\\$)' + // another arg indicator, indicating a literal '|(\\w+)' + // or an identifer '|{' + // or the start of a braced identifier, followed by... '(\\w+)' + // an identifier '(?::([^}|]+))?' + // followed by an optional format '(?:\\|([^}]+))?' + // followed by an optional default '}' + // end of braced identifier '|(\\S+)' + // invalid stuff following arg indicator ')', TemplateArgRE = new RegExp(TemplateArgREPattern, "g"), // Tests for an integer or float DigitRE = new RegExp("^(?:\\d+|\\d*\\.\\d+)$"); // Default subsection delimiters. The first character delimits zero/non-zero subsections, // the second character delimits singular/plural subsections. my.TemplateDefaultDelimiters = "#|"; // Default argument delimiter my.TemplateDefaultArgDelimiter = "$"; function _selectorReplace(text, selector, delimiter, argsDict) { // First see if the first part of the text is <identifier>#. // If not, continue the after leading delimiter. var re = new RegExp("^[" + delimiter + "](\\w+)[" + delimiter + "]"), match = re.exec(text); if (!match) return {text:delimiter, nextIndex:1}; var identifier = match[1], valid = NO, lastChar = "", alternatives = ["", ""], haveAlternative = NO, lastIndex = match[0].length; // Now scan for the two alternatives for (var alternative = 0; alternative < 2; ++alternative) { for (; lastIndex < text.length; ++lastIndex) { var c = text.charAt(lastIndex); if (c === delimiter && lastChar !== "\\") { ++lastIndex; haveAlternative = YES; break; } else if (c !== "\\") alternatives[alternative] += c; lastChar = c; } // Make sure we didn't exhaust the source before finding the alternative. if (!haveAlternative) return {text:text, endIndex:text.length}; } // Get the specified argument, convert to a string var arg = [argsDict objectForKey:identifier], type = typeof(arg), result = nil; if (selector === 0) { var isZero; switch (type) { case "string": if (arg.length === 0) isZero = true; else isZero = DigitRE.test(arg) && parseFloat(arg) === 0; break; case "number": isZero = arg === 0; break; case "boolean": isZero = arg === false; break; case "object": isZero = arg === nil || (arg.hasOwnProperty("length") && arg.length === 0) || (arg.hasOwnProperty("isa") && [arg isKindOfClass:CPNull]); break; default: result = ""; } if (result === nil) result = isZero ? alternatives[0] : alternatives[1]; } else { var isOne; switch (type) { case "string": isOne = arg.length && DigitRE.test(arg) && parseFloat(arg) === 1; break; case "number": isOne = arg === 1; break; case "boolean": isOne = arg === true; break; case "object": isOne = arg !== nil && arg.hasOwnProperty("length") && arg.length === 1; break; default: result = ""; } if (result === nil) result = isOne ? alternatives[0] : alternatives[1]; } return {text:result, nextIndex:lastIndex}; } // Helper function for replacing args function _convert(value, format, defaultValue) { if (!value) return defaultValue ? defaultValue : ""; if (format) { if (value.constructor === Date) { if (Date.prototype.dateFormat) return value.dateFormat(format); else return value.toLocaleString(); } else { format = "%" + format; return ObjectiveJ.sprintf(format, value); } } else return String(value, 10); } my.stringWithTemplate = function(/* CPString */ template, /* CPString */ delimiters, /* CPArray | CPDictionary */ args) { if (!template) return ""; if (!delimiters || delimiters.length < 2) delimiters = my.TemplateDefaultDelimiters; // Normalize the arguments into a dictionary var argsDict = null, argsArray = []; if (arguments.length < 3) return ""; if (arguments.length === 3) { var arg = arguments[2]; if (arg === null || arg === undefined) argsArray = [null]; else if (arg.hasOwnProperty("isa")) { if ([arg isKindOfClass:CPArray]) argsArray = arg; else if ([arg isKindOfClass:CPDictionary]) argsDict = arg; else if ([arg isKindOfClass:CPNull]) argsArray = [null]; } else if (arg.constructor === Array) argsArray = arg; else if (typeof(arg) === "object") argsDict = [CPDictionary dictionaryWithJSObject:arg]; else argsArray = [arguments[2]]; } else { argsArray = Array.prototype.slice.call(arguments, 2); } if (!argsDict) { if (argsArray.length === 0) return template; argsDict = [CPDictionary dictionary]; for (var i = 0; i < argsArray.length; ++i) [argsDict setObject:argsArray[i] forKey:String(i, 10)]; } var text = template; // We have a zero/non-zero selector and one/non-one selector for (var selector = 0; selector <= 1; ++selector) { var delim = delimiters.charAt(selector), lastChar = ""; for (var i = 0; i < text.length; ++i) { var c = text.charAt(i); if (c === delim) { if (lastChar !== "\\") { var leftContext = text.slice(0, i), rightContext = text.slice(i), replacement = _selectorReplace(rightContext, selector, delim, argsDict); text = leftContext + replacement.text + rightContext.slice(replacement.nextIndex); i += replacement.text.length - 1; } } else if (c === "\\") text = text.slice(0, i) + text.slice(i + 1); lastChar = c; } } // Define as a closure so we can access argsDict var argReplace = function(str, escaped, named, braced, format, defaultValue, invalid) { named = named || braced; if (named) return _convert([argsDict objectForKey:named], format, defaultValue); if (escaped) return my.TemplateDefaultArgDelimiter; // FIXME: raise return ""; }; return text.replace(TemplateArgRE, argReplace); }; return my; }()); <file_sep>/SCKit.j /* * SCKit.j * SCKit * * Created by <NAME>. * Copyright (c) 2010, Victory-Heart Productions. * * Released under the MIT license: * http://www.opensource.org/licenses/MIT */ @import "SCKitClass.j" @import "SCBorderView.j" @import "SCJSONPConnection.j" @import "SCString.j" @import "SCStyledTextField.j" @import "SCURLConnection.j" <file_sep>/SCURLConnection.j /* * SCURLConnection.j * SCKit * * Created by <NAME>. * Copyright (c) 2010, Victory-Heart Productions. * * Released under the MIT license: * http://www.opensource.org/licenses/MIT */ @import <Foundation/CPURLConnection.j> @import "_SCConnection.j" @import "SCConnectionUtils.j" /*! SCURLConnection is a drop-in replacement for CPURLConnection which provides more streamlined usage, automates common tasks like accumulating received data, and deals with some of the more tricky aspects of error handling. With CPURLConnection, you have to keep multiple connections in separate variables and then test the connection against those variables in the connection handler. SCURLConnection allows you to eliminate the variables and delegate to separate handler methods directly. For example, here is the CPURLConnection way: @code @implementation MyClass { CPURLConnection fooConnection; CPString fooConnectionData; CPURLConnection barConnection; CPString barConnectionData; } - (void)sendFoo { var request = [CPURLRequest requestWithURL:@"foo.php"]; fooConnectionData = @""; fooConnection = [CPURLConnection connectionWithRequest:request delegate:self]; } - (void)sendBar { var request = [CPURLRequest requestWithURL:@"bar.php"]; barConnectionData = @""; barConnection = [CPURLConnection connectionWithRequest:request delegate:self]; } - (void)connection:(CPURLConnection)connection didReceiveData:(CPString)data { if (connection === fooConnection) fooConnectionData += data; else if (connection === barConnection) barConnectionData += data; } - (void)connectionDidFinishLoading:(CPURLConnection)connection { if (connection === fooConnection) { [self doSomethingWithData:fooConnectionData]; [self doFooStuff]; } else if (connection === barConnection) { [self doSomethingWithData:barConnectionData]; [self doBarStuff]; } } @end @endcode If you multiply the number of connections in the above example and increase the amount of processing that needs to be done for each connection, it gets ugly very quickly, especially if you want to deal separately with errors. Here is the same thing done with SCURLConnection: @code @implementation MyClass { // No need to store connections } - (void)sendFoo { [self sendConnection:@"foo"]; } - (void)sendBar { [self sendConnection:@"bar"]; } // A lot of common code eliminated - (void)sendConnection:(CPString)identifier { var request = [CPURLRequest requestWithURL:identifier + @".php"]; // No need to save connection to a variable [SCURLConnection connectionWithRequest:request delegate:self identifier:identifier]; } - (void)fooConnectionDidSucceed:(CPURLConnection)connection { // Received data is saved for us [self doSomethingWithData:[connection receivedData]]; [self doFooStuff]; } - (void)barConnectionDidSucceed:(CPURLConnection)connection { // Received data is saved for us [self doSomethingWithData:[connection receivedData]]; [self doBarStuff]; } @end @endcode Notice that SCURLConnection lets you use an identifier to dispatch directly to separate handler methods when the connection is completely, successfully finished. In addition, the received data is automatically accumulated and is accessible via the connection. @section delegate_methods Delegate Methods Your connection delegate can define several handler methods: @code // Implement this ONLY if you need to do custom data processing - (void)connection:(SCURLConnection)connection didReceiveData:(CPString)data // You SHOULD always implement this method - (void)connectionDidSucceed:(SCURLConnection)connection // Implement this only if you want to catch and handle errors. // By default an alert is displayed with an intelligent error message // if an error occurs. - (void)connection:(SCURLConnection)connection didFailWithError:(id)error @endcode Within any of these methods, the data received so far is available as a string via the receivedData method. The names of these methods change according to the identifier passed in the connection initializer. If no identifier is passed (or is empty), the names above will be used. If a non-empty identifier is passed, the names are as follows: <identifier>Connection:didReceiveData: <identifier>ConnectionDidSucceed: <identifier>Connection:didFailWithError: For example, if you use the identifier "saveContact", the methods names should be: saveContactConnection:didReceiveData: saveContactConnectionDidSucceed: saveContactConnection:didFailWithError: */ @implementation SCURLConnection : CPURLConnection { _SCConnection base; } /*! Create a connection with the given URL and delegate. The connection starts immediately. @param aURL A URL to send @param aDelegate A connection delegate */ + (SCURLConnection)connectionWithURL:(CPString)aURL delegate:(id)aDelegate { return [self connectionWithRequest:[CPURLRequest requestWithURL:aURL] delegate:aDelegate]; } /*! Create a connection with the given request and delegate. The connection starts immediately. @param aRequest A request @param aDelegate A connection delegate */ + (SCURLConnection)connectionWithRequest:(CPURLRequest)aRequest delegate:(id)aDelegate { return [[self alloc] initWithRequest:aRequest delegate:aDelegate identifier:@"" startImmediately:YES]; } /*! Create a connection with the given URL, delegate and identifier. The connection starts immediately. @param aURL A URL to send @param aDelegate A connection delegate @param anIdentifier An identifier to prefix to delegate handler method names */ + (SCURLConnection)connectionWithURL:(CPString)aURL delegate:(id)aDelegate identifier:(CPString)anIdentifier { return [self connectionWithRequest:[CPURLRequest requestWithURL:aURL] delegate:aDelegate identifier:anIdentifier]; } /*! Create a connection with the given request, delegate and identifier. The connection starts immediately. @param aRequest A request @param aDelegate A connection delegate @param anIdentifier An identifier to prefix to delegate handler method names */ + (SCURLConnection)connectionWithRequest:(CPURLRequest)aRequest delegate:(id)aDelegate identifier:(CPString)anIdentifier { return [[self alloc] initWithRequest:aRequest delegate:aDelegate identifier:anIdentifier startImmediately:YES]; } /*! Init a connection with the given URL and delegate. The connection starts immediately if \c shouldStartImmediately is YES. @param aURL A URL to send @param aDelegate A connection delegate @param shouldStartImmediately If YES, start the connection immediately */ - (id)initWithURL:(CPString)aURL delegate:(id)aDelegate startImmediately:(BOOL)shouldStartImmediately { return [self initWithRequest:[CPURLRequest requestWithURL:aURL] delegate:aDelegate startImmediately:shouldStartImmediately]; } /*! Init a connection with the given request and delegate. The connection starts immediately if \c shouldStartImmediately is YES. @param aRequest A request @param aDelegate A connection delegate @param shouldStartImmediately If YES, start the connection immediately */ - (id)initWithRequest:(CPURLRequest)aRequest delegate:(id)aDelegate startImmediately:(BOOL)shouldStartImmediately { base = [_SCConnection new]; self = [super initWithRequest:aRequest delegate:base startImmediately:NO]; if (self) [self _initWithIdentifier:@"" delegate:aDelegate startImmediately:shouldStartImmediately]; return self; } /*! Init a connection with the given URL, delegate and identifier. The connection starts immediately if \c shouldStartImmediately is YES. @param aURL A URL to send @param aDelegate A connection delegate @param anIdentifier An identifier to prefix to delegate handler method names @param shouldStartImmediately If YES, start the connection immediately */ - (id)initWithURL:(CPString)aURL delegate:(id)aDelegate identifier:(CPString)anIdentifier startImmediately:(BOOL)shouldStartImmediately { return [self initWithRequest:[CPURLRequest requestWithURL:aURL] delegate:aDelegate identifier:anIdentifier startImmediately:shouldStartImmediately]; } /*! Init a connection with the given request, delegate and identifier. The connection starts immediately if \c shouldStartImmediately is YES. @param aRequest A request @param aDelegate A connection delegate @param anIdentifier An identifier to prefix to delegate handler method names @param shouldStartImmediately If YES, start the connection immediately */ - (id)initWithRequest:(CPURLRequest)aRequest delegate:(id)aDelegate identifier:(CPString)anIdentifier startImmediately:(BOOL)shouldStartImmediately { base = [_SCConnection new]; self = [super initWithRequest:aRequest delegate:base startImmediately:NO]; if (self) [self _initWithIdentifier:anIdentifier delegate:aDelegate startImmediately:shouldStartImmediately]; return self; } - (void)_initWithIdentifier:(CPString)anIdentifier delegate:(id)aDelegate startImmediately:(BOOL)shouldStartImmediately { [base initWithConnection:self identifier:anIdentifier delegate:aDelegate startImmediately:shouldStartImmediately]; } /*! @ignore */ - (void)connection:(SCURLConnection)connection didReceiveResponse:(CPHTTPURLResponse)response { [base connection:connection didReceiveResponse:response]; } /*! @ignore */ - (void)connection:(SCURLConnection)connection didReceiveData:(CPString)data { [base connection:connection didReceiveData:data]; } /*! @ignore */ - (void)connectionDidFinishLoading:(SCURLConnection)connection { [base connectionDidFinishLoading:connection]; } /*! Returns 200 if the connection succeeded without error, otherwise the response code. */ - (int)responseStatus { return [base responseStatus]; } /*! Returns the accumulated data received from the connection response. */ - (CPString)receivedData { return [base receivedData]; } /*! Returns the accumulated data received from the connection response as a JSON object. */ - (JSObject)receivedJSONData { return [base receivedJSONData]; } /*! @ignore */ - (void)connection:(SCURLConnection)connection didFailWithError:(id)error { [base connection:connection didFailWithError:error]; } @end <file_sep>/Tests/AppController.j /* * AppController.j * SCKit * * Created by <NAME>. * Copyright (c) 2010, Victory-Heart Productions. * * Released under the MIT license: * http://www.opensource.org/licenses/MIT */ @import <Foundation/Foundation.j> @import <AppKit/AppKit.j> @import <LPKit/LPMultiLineTextField.j> @import <SCKit/SCString.j> @import <SCKit/SCURLConnection.j> CPLogRegister(CPLogConsole); @implementation AppController : CPObject { CPWindow theWindow; //this "outlet" is connected automatically by the Cib CPWindow stringWindow; LPMultiLineTextField theCode; LPMultiLineTextField theTemplate; LPMultiLineTextField theResult; CPWindow connectionWindow; CPTextField textToSend; CPTextField connectionResult; } - (void)applicationDidFinishLaunching:(CPNotification)aNotification { } - (void)awakeFromCib { [theWindow setFullPlatformWindow:YES]; [[theWindow contentView] setBackgroundColor:[CPColor colorWithPatternImage:CPImageInBundle(@"linen.jpg", CGSizeMake(75.0, 75.0))]]; [theCode setValue:[CPColor blackColor] forThemeAttribute:@"text-color"]; [theTemplate setValue:[CPColor blackColor] forThemeAttribute:@"text-color"]; [theResult setValue:[CPColor blackColor] forThemeAttribute:@"text-color"]; [theCode setStringValue:@"{name:\"pizza\", qty:0}"]; [theTemplate setStringValue:@"There |qty|is|are| #qty#no#${qty}# ${name}|qty||s|#qty#!##"]; [connectionResult setStringValue:@""]; } - (void)applyTemplate:(id)sender { var args = nil, template = [theTemplate stringValue]; eval("args = " + [theCode stringValue]); [theResult setStringValue:[SCString stringWithTemplate:template, args]]; } - (void)echoText:(id)sender { [self sendText:@"echo"]; } - (void)modifyText:(id)sender { [self sendText:@"modify"]; } - (void)reverseText:(id)sender { [self sendText:@"reverse"]; } - (void)forceError:(id)sender { [SCURLConnection connectionWithURL:@"foo.php" delegate:self identifier:@"error"]; } - (void)forceCustomError:(id)sender { [SCURLConnection connectionWithURL:@"foo.php" delegate:self identifier:@"customError"]; } - (void)sendText:(CPString)action { var url = [SCString stringWithTemplate:@"test.php?text=${0}&action=${1}", encodeURIComponent([textToSend stringValue]), action]; // Note that we don't even need to save the connection in a variable, // the correct delegate methods will be called automatically. [SCURLConnection connectionWithURL:url delegate:self identifier:action]; } - (void)echoConnectionDidSucceed:(SCURLConnection)connection { [connectionResult setStringValue:@"Echo: " + [connection receivedData]]; } - (void)modifyConnectionDidSucceed:(SCURLConnection)connection { [connectionResult setStringValue:@"Modify: " + [connection receivedData]]; } - (void)reverseConnectionDidSucceed:(SCURLConnection)connection { [connectionResult setStringValue:@"Reverse: " + [connection receivedData]]; } - (void)customErrorConnection:(SCURLConnection)connection didFailWithError:(id)error { alert("Bummer! " + [SCConnectionUtils errorMessageForError:error]); } @end <file_sep>/SCUtils.j /* * SCUtils.j * SCKit * * Created by <NAME>. * Copyright 2012 <NAME>. All Rights Reserved. * * Licensed LGPL 3.0 - http://www.gnu.org/licenses/lgpl.html */ @implementation SCUtils : CPObject /*! Aligns the text baseline of one view with the baseline of another. If a view does not seem to have text of any kind, it's frame is used. */ + (void)alignTextBaselineOf:(CPView)aViewToAlign withBaselineOf:(CPView)anAnchorView { var alignTextFrame = [self textFrameOfView:aViewToAlign], anchorTextFrame = [self textFrameOfView:anAnchorView], topDiff = CGRectGetMinY(anchorTextFrame) - CGRectGetMinY(alignTextFrame), ascenderDiff = [[anAnchorView font] ascender] - [[aViewToAlign font] ascender], alignOrigin = [aViewToAlign frameOrigin], anchorOrigin = [anAnchorView frameOrigin]; alignOrigin.y = anchorOrigin.y + topDiff + ascenderDiff; [aViewToAlign setFrameOrigin:alignOrigin]; } /*! Aligns the text baselines of an array of views. The first view in the array is used as the anchor view to which all of the other views are aligned. If a view does not seem to have text of any kind, it's frame is used. */ + (void)alignTextBaselineOfViews:(CPArray)views { if (views.length < 2) return; var anchorView = views[0], count = views.length; for (var i = 1; i < count; ++i) [self alignTextBaselineOf:views[i] withBaselineOf:anchorView]; } + (CGRect)textFrameOfView:(CPView)aView { [aView layoutIfNeeded]; // Most Cappuccino views use an ephemeral subview named "content-view". var contentView = [aView ephemeralSubviewNamed:@"content-view"], origin; if (contentView) origin = [contentView frameOrigin]; else { // If there is no ephemeral subview, use the view itself contentView = aView; origin = CGPointMakeCopy([contentView bounds].origin); } // Try to extract the text frame if ([contentView respondsToSelector:@selector(textFrame)]) { var textFrame = [contentView textFrame]; // We want to return the offset from the view, so add in the content view's offset origin.x += CGRectGetMinX(textFrame); origin.y += CGRectGetMinY(textFrame); return CGRectMake(origin.x, origin.y, CGRectGetWidth(textFrame), CGRectGetHeight(textFrame)); } else return [contentView bounds]; } @end <file_sep>/Tests/test.php <?php header("Content-Type: text/plain"); $action = $_GET["action"]; if ($action == "echo") echo $_GET["text"]; elseif ($action == "modify") echo '"' . $_GET["text"] . '"' . " to you, too!"; elseif ($action == "reverse") echo strrev($_GET["text"]); ?> <file_sep>/README.md # SCKit SCKit is a collection of utility classes for [Cappuccino](https://github.com/cappuccino/cappuccino). #### SCString An awesome string template engine. Handles both simple and extremely complex string formatting needs. #### SCURLConnection A drop-in replacement for CPURLConnection that is much easier to use. #### SCJSONPConnection A drop-in replacement for CPJSONPConnection that is much easier to use. #### SCConnectionUtils A set of utilities for dealing with connection errors. Used by SCURLConnection and SCJSONPConnection. #### SCStyledTextField A drop-in replacement for CPTextField that allows you to format the output with html tags in the value. #### SCBorderView To be documented. ## Usage To see what build options are available, use `jake help`. ## Examples To see SCString and SCURLConnection in action, do the following: 1. From the main directory, run `jake all`. This will build SCKit and make it available to applications. 1. Install LPKit on your system. You might try [this version](https://github.com/aljungberg/LPKit.git). 1. In a terminal, cd into the Tests directory. 1. Execute `capp gen -lf -F SCKit -F LPKit .` in a terminal. 1. Make the Tests directory accessible via a web server that supports PHP, and load index-debug.html. <file_sep>/SCBorderView.j /* * SCBorderView.j * SCKit * * Created by <NAME>. * Copyright (c) 2010, <NAME>. * * Released under the MIT license: * http://www.opensource.org/licenses/MIT */ @import <Foundation/Foundation.j> @import <AppKit/CPGraphicsContext.j> @import <AppKit/CPImage.j> @import <AppKit/CPImageView.j> @import <AppKit/CPView.j> /*! @ingroup sckit */ SCBorderViewImageTopLeft = 0; SCBorderViewImageTop = 1; SCBorderViewImageTopRight = 2; SCBorderViewImageLeft = 3; SCBorderViewImageCenter = 4; SCBorderViewImageRight = 5; SCBorderViewImageBottomLeft = 6; SCBorderViewImageBottom = 7; SCBorderViewImageBottomRight = 8; SCBorderViewModeImages = 0; SCBorderViewModeShadow = 1; var SCBorderViewPathSuffixes = [ @"TopLeft.png", @"Top.png", @"TopRight.png", @"Left.png", @"Center.png", @"Right.png", @"BottomLeft.png", @"Bottom.png", @"BottomRight.png" ]; @implementation SCBorderView : CPView { SCBorderViewMode _mode @accessors(readonly, getter=mode) CPView _contentView @accessors(readonly, getter=contentView); float _borderWidth @accessors(readonly, getter=borderWidth); CPColor _borderColor @accessors(readonly, getter=borderColor); CGSize _shadowOffset @accessors(readonly, getter=shadowOffset); float _shadowBlur @accessors(readonly, getter=shadowBlur); CPColor _shadowColor @accessors(readonly, getter=shadowColor); float _leftInset @accessors(readonly, getter=leftInset); float _rightInset @accessors(readonly, getter=rightInset); float _topInset @accessors(readonly, getter=topInset); float _bottomInset @accessors(readonly, getter=bottomInset); } + (id)borderViewEnclosingView:(CPView)aView width:(float)aWidth color:(CPColor)aColor imagePath:(CPString)anImagePath sizes:(CPArray)sizes insets:(CPArray)insets { return [[SCBorderView alloc] initWithView:aView width:aWidth color:aColor imagePath:anImagePath sizes:sizes insets:insets]; } + (id)borderViewEnclosingView:(CPView)aView width:(float)aWidth color:(CPColor)aColor shadowOffset:(CGSize)anOffset shadowBlur:(float)aBlur shadowColor:(CPColor)aShadowColor { return [[SCBorderView alloc] initWithView:aView width:aWidth color:aColor shadowOffset:anOffset shadowBlur:aBlur shadowColor:aShadowColor]; } - (id)initWithView:(CPView)aView width:(float)aWidth color:(CPColor)aColor imagePath:(CPString)anImagePath sizes:(CPArray)sizes insets:(CPArray)insets { self = [super initWithFrame:[aView frame]]; if (self) { _mode = SCBorderViewModeImages; _borderWidth = aWidth; _borderColor = aColor == nil ? [CPColor grayColor] : aColor; _shadowOffset = CGSizeMakeZero(); _shadowBlur = 0; _shadowColor = nil; _topInset = insets[0] + _borderWidth; _rightInset = insets[1] + _borderWidth; _bottomInset = insets[2] + _borderWidth; _leftInset = insets[3] + _borderWidth; var path = [[CPBundle mainBundle] pathForResource:anImagePath], slices = [CPArray arrayWithCapacity:9]; for (var i = 0; i < 9; ++i) { var size = [sizes objectAtIndex:i], image = nil; if (size != nil) image = [[CPImage alloc] initWithContentsOfFile:path + [SCBorderViewPathSuffixes objectAtIndex:i] size:size]; [slices replaceObjectAtIndex:i withObject:image]; } [self setBackgroundColor:[CPColor colorWithPatternImage:[[CPNinePartImage alloc] initWithImageSlices:slices]]]; [self _initWithView:aView]; } return self; } - (id)initWithView:(CPView)aView width:(float)aWidth color:(CPColor)aColor shadowOffset:(CGSize)anOffset shadowBlur:(float)aBlur shadowColor:(CPColor)aShadowColor { self = [super initWithFrame:[aView frame]]; if (self) { _mode = SCBorderViewModeShadow; _borderWidth = aWidth; _borderColor = aColor == nil ? [CPColor colorWithWhite:190.0 / 255.0 alpha:1.0] : aColor; _shadowOffset = anOffset; _shadowBlur = aBlur; _shadowColor = aShadowColor == nil ? [CPColor colorWithWhite:190.0 / 255.0 alpha:1.0] : aShadowColor; _topInset = _borderWidth + MAX(_shadowBlur - _shadowOffset.height, 0); _rightInset = _borderWidth + _shadowOffset.width + _shadowBlur; _bottomInset = _borderWidth + _shadowOffset.height + _shadowBlur; _leftInset = _borderWidth + MAX(_shadowBlur - _shadowOffset.width, 0); [self _initWithView:aView]; } return self; } - (void)_initWithView:(CPView)aView { _contentView = aView; var size = [self frame].size, width = size.width - _leftInset - _rightInset, height = size.height - _topInset - _bottomInset, enclosingView = [_contentView superview]; [self setHitTests:[_contentView hitTests]]; [self setAutoresizingMask:[_contentView autoresizingMask]]; [_contentView removeFromSuperview]; [self addSubview:_contentView]; [_contentView setFrame:CGRectMake(_leftInset, _topInset, width, height)] [enclosingView addSubview:self]; } - (float)horizontalInset { return _leftInset + _rightInset; } - (float)verticalInset { return _topInset + _bottomInset; } - (CGRect)frameForContentFrame:(CGRect)aFrame { return CGRectMake(CGRectGetMinX(aFrame) - _leftInset, CGRectGetMinY(aFrame) - _topInset, CGRectGetWidth(aFrame) + _leftInset + _rightInset, CGRectGetHeight(aFrame) + _topInset + _bottomInset); } - (void)setFrameForContentFrame:(CGRect)aFrame { [self setFrame:[self frameForContentFrame:aFrame]]; } - (void)drawRect:(CGRect)aRect { [super drawRect:aRect]; if (_mode == SCBorderViewModeShadow) { var context = [[CPGraphicsContext currentContext] graphicsPort], frame = [_contentView frame], fillRect = CGRectInset(frame, -_borderWidth, -_borderWidth), strokeRect = CGRectInset(frame, -_borderWidth * 0.5, -_borderWidth * 0.5); if (_shadowBlur > 0) { CGContextSaveGState(context); CGContextSetShadowWithColor(context, _shadowOffset, _shadowBlur, _shadowColor); CGContextSetFillColor(context, [CPColor whiteColor]); CGContextFillRect(context, fillRect); CGContextRestoreGState(context); } if (_borderWidth > 0) { CGContextSetLineWidth(context, _borderWidth); CGContextSetStrokeColor(context, _borderColor); CGContextStrokeRect(context, strokeRect); } } } @end <file_sep>/SCConnectionUtils.j /* * SCConnectionUtils.j * SCKit * * Created by <NAME>. * Copyright (c) 2010, Victory-Heart Productions. * * Released under the MIT license: * http://www.opensource.org/licenses/MIT */ @import <Foundation/CPString.j> @import <AppKit/CPAlert.j> @implementation SCConnectionUtils : CPObject /*! Given a numeric error code or error message, returns a message describing the type of error that occurred. */ + (CPString)errorMessageForError:(id)error { var type = typeof(error), message; if (type === "string") message = error; else if (type === "number") { switch (error) { case 400: // Bad Request message = @"The request was malformed. If this problem continues please contact the site administrator."; break; case 401: // Unauthorized case 403: // Forbidden message = @"You are not authorized to access that resource. If this problem continues please contact the site administrator."; break; case 404: // File not found message = @"The requested resource could not be found. Please notify the site administrator."; break; case -1: // Bad json data, probably an error message case 500: message = @"An internal error occurred on the server. Please notify the site administrator."; break; case 408: // Request Timeout case 502: // Bad Gateway case 503: // Service Unavailable case 504: // Gateway Timeout message = @"The server is not responding. If this problem continues please contact the site administrator."; break; default: message = [CPString stringWithFormat:@"An error occurred (%d) while trying to connect with the server. Please try again.", error]; } } else message = @"An error occurred while trying to connect with the server. Please try again."; return message; } /*! A convenience method to display an error alert. It is designed to be called from the \c connection:DidFailWithError: delegate method, passing the error. @param error A numeric error code or error message */ + (void)alertFailureWithError:(id)error { [self alertFailureWithError:error delegate:nil]; } /*! A convenience method to display an error alert. It is designed to be called from the \c connection:DidFailWithError: delegate method, passing the error. @param error A numeric error code or error message @param aDelegate An alert delegate */ + (void)alertFailureWithError:(id)error delegate:(id)aDelegate { var alert = [[CPAlert alloc] init]; [alert setDelegate:aDelegate]; [alert setTitle:@"Connection Failed"]; [alert setMessageText:[self errorMessageForError:error]]; [alert addButtonWithTitle:@"OK"]; [alert runModal]; } @end <file_sep>/SCStyledTextField.j /* * SCStyledTextField.j * SCKit * * Created by <NAME>. * Copyright (c) 2010, Victory-Heart Productions. * * Released under the MIT license: * http://www.opensource.org/licenses/MIT */ @import <AppKit/CPPlatformString.j> @import <AppKit/CPTextField.j> @import "_SCImageAndStyledTextView.j" @import "SCString.j" @implementation SCStyledTextField : CPTextField - (CPView)createEphemeralSubviewNamed:(CPString)aName { if (aName === "bezel-view") { return [super createEphemeralSubviewNamed:aName]; } else { var view = [[_SCImageAndStyledTextView alloc] initWithFrame:CGRectMakeZero()]; [view setHitTests:NO]; return view; } return [super createEphemeralSubviewNamed:aName]; } - (void)setEncodedStringValueWithFormat:(CPString)format, ... { var args = Array.prototype.slice.call(arguments, 2); for (var i = 1; i < args.length; ++i) if (typeof(args[i]) === "string") args[i] = encodeHTMLComponent(args[i]); [self setStringValue:ObjectiveJ.sprintf.apply(this, args)]; } - (void)setEncodedStringValueWithTemplate:(CPString)template, ... { var args = Array.prototype.slice.call(arguments, 3); for (var i = 0; i < args.length; ++i) if (typeof(args[i]) === "string") args[i] = encodeHTMLComponent(args[i]); [self setStringValue:[SCString stringWithTemplate:template args:args]]; } - (void)setEncodedStringValueWithTemplate:(CPString)template delimiters:(CPString)delimiters, ... { var args = Array.prototype.slice.call(arguments, 4); for (var i = 0; i < args.length; ++i) if (typeof(args[i]) === "string") args[i] = encodeHTMLComponent(args[i]); [self setStringValue:[SCString stringWithTemplate:template delimiters:delimiters args:args]]; } @end var DOMFixedWidthSpanElement = nil, DOMFlexibleWidthSpanElement = nil; @implementation SCStyledTextField (Utils) + (CGSize)sizeOfString:(CPString)aString withFont:(CPFont)font forWidth:(float)width { if (!DOMFixedWidthSpanElement) [self createDOMElements]; var span; if (!width) span = DOMFlexibleWidthSpanElement; else { span = DOMFixedWidthSpanElement; span.style.width = ROUND(width) + "px"; } span.style.font = [(font || [CPFont systemFontOfSize:CPFontCurrentSystemSize]) cssString]; span.innerHTML = aString; return CGSizeMake(span.clientWidth, span.clientHeight); } + (void)createDOMElements { var style, bodyElement = [CPPlatform mainBodyElement]; DOMFlexibleWidthSpanElement = document.createElement("span"); DOMFlexibleWidthSpanElement.className = "cpdontremove"; style = DOMFlexibleWidthSpanElement.style; style.position = "absolute"; style.left = "-100000px"; style.zIndex = -100000; style.visibility = "visible"; style.padding = "0px"; style.margin = "0px"; style.whiteSpace = "pre"; DOMFixedWidthSpanElement = document.createElement("span"); DOMFixedWidthSpanElement.className = "cpdontremove"; style = DOMFixedWidthSpanElement.style; style.display = "block"; style.position = "absolute"; style.left = "-100000px"; style.zIndex = -10000; style.visibility = "visible"; style.padding = "0px"; style.margin = "0px"; style.width = "1px"; style.wordWrap = "break-word"; try { style.whiteSpace = "pre"; style.whiteSpace = "-o-pre-wrap"; style.whiteSpace = "-pre-wrap"; style.whiteSpace = "-moz-pre-wrap"; style.whiteSpace = "pre-wrap"; } catch(e) { //some versions of IE throw exceptions for unsupported properties. style.whiteSpace = "pre"; } bodyElement.appendChild(DOMFlexibleWidthSpanElement); bodyElement.appendChild(DOMFixedWidthSpanElement); } @end var encodeHTMLComponent = function(/*String*/ aString) { return aString ? aString.replace(/&/g,'&amp;').replace(/"/g, '&quot;').replace(/'/g, '&apos;').replace(/</g,'&lt;').replace(/>/g,'&gt;') : ""; } <file_sep>/_SCImageAndStyledTextView.j /* * _SCImageAndStyledTextView.j * SCKit * * Created by <NAME>. * Copyright (c) 2010, Victory-Heart Productions. * * Released under the MIT license: * http://www.opensource.org/licenses/MIT */ @import <AppKit/_CPImageAndTextView.j> @class SCStyledTextField @global _DOMTextElement @global _DOMTextShadowElement /*! The standard _CPImageAndTextView used by Cappuccino strips all html tags from the text. This subclass, used by \ref SCStyledTextField, allows you to use full styled html in a text field. Ordinarily you will never need to interact with this class directly. */ @implementation _SCImageAndStyledTextView : _CPImageAndTextView - (void)layoutSubviews { // We have to set the innerHTML first so we can precalculate the formatted size. // Otherwise _CPImageAndTextView will calculate the size based on the raw size // of the html code. _textSize = [SCStyledTextField sizeOfString:_text withFont:_font forWidth:CGRectGetWidth([self bounds])]; [super layoutSubviews]; if (_DOMTextElement) _DOMTextElement.innerHTML = _text; if (_DOMTextShadowElement) _DOMTextShadowElement.innerHTML = ""; } @end
1d69198d0a79ffa1369fff2e0b056b15ab168502
[ "Markdown", "Objective-J", "PHP" ]
15
Markdown
aparajita/SCKit
146afa3c9e2d8e5e47fbc8c2058acafc2a8b753f
c5939a7480e0141a5a3872d8987479f2eb213648
refs/heads/master
<file_sep> import mnist_loader training_data, validation_data, test_data = \ mnist_loader.load_data_wrapper() import network net = network.Network([784, 30, 10]) net.SGD(training_data, 30, 10, 3.0, test_data=test_data) # check one digit # import numpy as np # np.argmax(net.feedforward(test_data[0][0])) # execfile('C:\\test.py') # %windir%\System32\cmd.exe "/K" d:\ProgramData\Anaconda2\Scripts\activate.bat d:\ProgramData\Anaconda2 # arr.shape<file_sep> import mnist_loader training_data, validation_data, test_data = \ mnist_loader.load_data_wrapper() ''' training_data len(5000) [ ( array(784, 1), array(10, 1) ), ] ''' ''' validation_data len(10000) [ ( array(784, 1), 0 ), ( array(784, 1), 1 ), ( array(784, 1), 9 ), ] ''' ''' test_data len(10000) [ ( array(784, 1), 0 ), ( array(784, 1), 1 ), ( array(784, 1), 9 ), ] ''' import network net = network.Network([784, 30, 10]) net.SGD(training_data, 30, 10, 3.0, test_data=test_data) # check one digit # import numpy as np # np.argmax(net.feedforward(test_data[0][0])) # np.argmax(net.feedforward( )) # execfile('C:\\test.py')<file_sep>var str='['; for(var i=0;i<748;i++){ str+='0.,' } str+=']'<file_sep> import mnist_loader training_data, validation_data, test_data = \ mnist_loader.load_data_wrapper() # print len(training_data) # 50000 # print len(training_data[0]) # 2 # print len(training_data[1]) # 2 # print len(training_data[2]) # 2 # print len(training_data[0][0]) # 784 # # print len(training_data[0][1]) # error # print training_data[0][1] # 7 # print training_data[1][1] # 2 # print len(training_data[0][0][0]) # 1 # print len(training_data[0][0][1]) # 1 # # print len(training_data[0][0][0][0]) # error ''' training_data [ ( array(784, 1) array(10, 1) ), ...5000 ] ''' ''' training_data old [ // 10000 [ [x], // 784 image data [ [ 0.], [ 0.], [ 0.], [ 0.], [ 0.], [ 1.], [ 0.], [ 0.], [ 0.], [ 0.], ], ], [ [x], // 784 image data [ [ 1.], [ 0.], [ 0.], [ 0.], [ 0.], [ 0.], [ 0.], [ 0.], [ 0.], [ 0.], ], ], ] ''' # print len(validation_data) # 10000 # print len(validation_data[0]) # 2 # print len(validation_data[1]) # 2 # print len(validation_data[2]) # 2 # print len(validation_data[0][0]) # 784 # # print len(validation_data[0][1]) # error # print validation_data[0][1] # 3 # print validation_data[1][1] # 8 # print len(validation_data[0][0][0]) # 1 # print len(validation_data[0][0][1]) # 1 # # print len(validation_data[0][0][0][0]) # error ''' validation_data[ // 10000 [ [], // 784 image data 3, // digit ], [ [], // 784 image data 8, // digit ], ] ''' # print len(test_data) # 10000 # print len(test_data[0]) # 2 # print len(test_data[1]) # 2 # print len(test_data[2]) # 2 # print len(test_data[0][0]) # 784 # # print len(test_data[0][1]) # error # print test_data[0][1] # 7 # print test_data[1][1] # 2 # print len(test_data[0][0][0]) # 1 # print len(test_data[0][0][1]) # 1 # # print len(test_data[0][0][0][0]) # error ''' test_data[ // 10000 [ [], // 784 image data 7, // digit ], [ [], // 784 image data 2, // digit ], ] ''' # raw_input() import network net = network.Network([784, 30, 10]) net.SGD(training_data, 30, 10, 3.0, test_data=test_data) # check one digit # import numpy as np # np.argmax(net.feedforward(test_data[0][0])) # np.argmax(net.feedforward( )) # execfile('C:\\test.py')
6c6c0af7da111c8299586c8b62e8e4d308cdd159
[ "JavaScript", "Python" ]
4
JavaScript
gonnavis/neural-networks-and-deep-learning
6584bf4ba8cb79c0ae71c6fbcd370e25e5be2443
4c0b3a1ba76400668d4ba79223c65e4fa59b9552
refs/heads/master
<file_sep># Time Machine UI **Iron Yard Class Assignment** Time Machine UI shows the current year and increases every second when the right button is push, decreases every second when the left botton is pressed, and stops when the middle button is pressed. See screen shot below. ## Screenshot ![Time Machine Screen Shot](/dist/assets/images/timemachine_img.png) ## Built With * [React](https://facebook.github.io/react/) - Front-End web application framework * [Node.js](https://facebook.github.io/react/) - JavaScript runtime environment ## Installation ``` git clone https://github.com/ReggEvans/timeMachine.git cd timeMachine npm install npm run go open localhost:3000 in the browser ``` ## License This project is licensed under the MIT License.<file_sep>import React from 'react' import ReactDOM from 'react-dom' import Backbone from 'backbone' import init from './init' import HomePage from './homePage' const app = function() { ReactDOM.render(<HomePage />,document.querySelector('.container')) } // x..x..x..x..x..x..x..x..x..x..x..x..x..x..x..x.. // NECESSARY FOR USER FUNCTIONALITY. DO NOT CHANGE. export const app_name = init() app() // x..x..x..x..x..x..x..x..x..x..x..x..x..x..x..x..
1bb1bb5ec59333c96e764dc87e7db9a3c331d8fb
[ "Markdown", "JavaScript" ]
2
Markdown
ReggEvans/timeMachine
89e78fdcc714f2e2f1f27d7bc8234bd5ed5f3f4d
8364b13d9239012310872fa2c62214c523ccc6db
refs/heads/master
<repo_name>mzorec/Natasha<file_sep>/src/Natasha/Builder/MethodBuilder.cs using Natasha.Template; namespace Natasha.Builder { public class MethodBuilder : MethodDelegateTemplate<MethodBuilder> { public MethodBuilder() => Link = this; } } <file_sep>/src/Natasha.Reverser/Reverser/TypeNameReverser.cs using System; using System.Collections.Concurrent; using System.Text; namespace Natasha.Reverser { /// <summary> /// 类名反解器 /// </summary> public static class TypeNameReverser { /// <summary> /// 获取类名,检查缓存 /// </summary> /// <param name="type">类型</param> /// <returns></returns> public static string GetName<T>() { return GetName(typeof(T)); } public static string GetName(Type type) { if (type == null) { return ""; } return Reverser(type); } /// <summary> /// 类名反解 /// </summary> /// <param name="type">类型</param> /// <returns></returns> internal static string Reverser(Type type) { string fatherString = default; //外部类处理 if (type.DeclaringType!=null) { fatherString = Reverser(type.DeclaringType)+"."; } //后缀 StringBuilder Suffix = new StringBuilder(); //数组判别 while (type.HasElementType) { if (type.IsArray) { var ctor = type.GetConstructors()[0]; int count = ctor.GetParameters().Length; if (count == 1) { Suffix.Append("[]"); } else { Suffix.Append("["); for (int i = 0; i < count - 1; i++) { Suffix.Append(","); } Suffix.Append("]"); } } type = type.GetElementType(); } //泛型判别 if (type.IsGenericType) { StringBuilder result = new StringBuilder(); result.Append($"{type.Name.Split('`')[0]}<"); if (type.GenericTypeArguments.Length > 0) { result.Append(Reverser(type.GenericTypeArguments[0])); for (int i = 1; i < type.GenericTypeArguments.Length; i++) { result.Append(','); result.Append(Reverser(type.GenericTypeArguments[i])); } } result.Append('>'); result.Append(Suffix); return fatherString+result.ToString(); } else { //特殊类型判别 if (type == typeof(void)) { return "void"; } return fatherString+type.Name + Suffix; } } } } <file_sep>/src/Natasha.Core/ComplierModule/Framework/IComplier.Syntax.cs using Natasha.Core.Complier.Model; namespace Natasha.Core.Complier { public abstract partial class IComplier { public SyntaxOption SyntaxInfos; } } <file_sep>/src/Natasha/Api/Level2/Operator/NewInterface.cs using Natasha.Operator; using System; namespace Natasha { public class NewInterface { public static (CompilationException Exception, Type Type) Create(Action<OopOperator> action, int classIndex = 1, int namespaceIndex = 1) { OopOperator builder = new OopOperator(); builder.Public.ChangeToInterface(); action(builder); var result = builder.GetType(classIndex, namespaceIndex); return (builder.Complier.ComplieException, result); } } } <file_sep>/src/Natasha/Api/Level1/Operator/CtorOperator.cs using Natasha.Builder; using System; namespace Natasha.Operator { /// <summary> /// 初始化操作类,生成初始化委托 /// </summary> public class CtorOperator: OnceMethodBuilder<CtorOperator> { public CtorOperator() { Link = this; } /// <summary> /// 返回初始化委托 /// </summary> /// <typeparam name="T">初始化类型</typeparam> /// <param name="type">当T为object类型时候,type为真实类型</param> /// <returns></returns> public Func<T> NewDelegate<T>(Type type=null) { if (type==null) { //直接使用T的类型作为初始化类型 type = typeof(T); } //返回构建委托 return Public .Static .PublicMember .StaticMember .UseCustomerUsing() .Using(type) .Return<T>() .UseRandomOopName() .HiddenNameSpace() .MethodBody($@"return new {type.GetDevelopName()}();") .Complie<Func<T>>(); } /// <summary> /// 返回初始化委托 /// </summary> /// <param name="type">类型</param> /// <returns></returns> public Delegate NewDelegate(Type type) { return Public .Static .PublicMember .StaticMember .UseCustomerUsing() .Using(type) .Return(type) .UseRandomOopName() .HiddenNameSpace() .MethodBody($@"return new {type.GetDevelopName()}();") .Complie(); } } } <file_sep>/docs/zh/oop/interface.md <p align="center"> <a href="https://natasha.dotnetcore.xyz/"> 返回 </a> | <a href="https://natasha.dotnetcore.xyz/en/oop/interface.html"> English </a> </p> 快速创建类: ```C# //创建一个类并获取类型 var type = new OopOperator() .Namespace<string>() .ChangeToInterface() .OopAccess(Access.None) .OopName("TestUt3") .OopBody(@"static void Test();") .GetType(); ``` 或 ```C# //创建一个类并获取类型 var type = NewInterface.Create(builder=>builder .Namespace<string>() .ChangeToInterface() .OopAccess(Access.None) .OopName("TestUt3") .OopBody(@"static void Test();") ); ``` 或 ```C# //创建一个类并获取类型 var type = new NInterface() .Namespace<string>() .Namespace<string>() .ChangeToInterface() .OopAccess(Access.None) .OopName("TestUt3") .OopBody(@"static void Test();") .GetType(); ``` <file_sep>/src/Natasha/Api/Level3/Operator/NStruct.cs using Natasha.Builder; namespace Natasha { public class NStruct : OopBuilder<NStruct> { public NStruct() { Link = this; Public.ChangeToStruct(); } } } <file_sep>/docs/zh/string-complie.md ### 整串编译 传入整个字符串进行编译,Natasha的最小编译单元为程序集。 请使用AssemblyComplier ```C# string text = @" namespace HelloWorld {public class Test{public Test(){ Name=""111""; }public string Name; public int Age{get;set;} } }"; //根据脚本创建动态类 AssemblyComplier oop = new AssemblyComplier(); oop.Add(text); Type type = oop.GetType("Test"); //或者使用三级API NAssembly var asm = new NAssembly("MyAssembly"); asm.AddScript(text); ``` 四级运算 API ```C# var handler = DomainOperator.Create("Tesst2Domain") & @"public class DomainTest1{ public string Name; public DomainOperator Operator; }" | "System" | typeof(DomainOperator); var type = handler.GetType(); Assert.Equal("DomainTest1", type.Name); ``` 使用 DomainOperator.Create 创建域, 使用 & 符合连接字符串代码, 使用 | 符号链接命名空间。 <file_sep>/src/Natasha/Builder/OnceMethodBuilder.cs using Natasha.Template; using System; namespace Natasha.Builder { /// <summary> /// 一次性方法构建器 /// </summary> /// <typeparam name="TBuilder"></typeparam> public class OnceMethodBuilder<TBuilder> : OnceMethodDelegateTemplate<TBuilder> where TBuilder : OnceMethodBuilder<TBuilder>,new() { //使用默认编译器 public readonly AssemblyComplier Complier; public OnceMethodBuilder() { Complier = new AssemblyComplier(); } public static TBuilder Default { get { return Create(); } } /// <summary> /// 如果参数为空,则使用默认域 /// 如果参数不为空,则创建以参数为名字的独立域 /// </summary> /// <param name="domainName">域名</param> /// <returns></returns> public static TBuilder Create(string domainName = default, bool complieInFile = default) { TBuilder instance = new TBuilder(); instance.Complier.ComplieInFile = complieInFile; if (domainName == default) { instance.Complier.Domain = DomainManagment.Default; } else { instance.Complier.Domain = DomainManagment.Create(domainName); } return instance; } /// <summary> /// 使用一个现成的域 /// </summary> /// <param name="domain">域</param> /// <returns></returns> public static TBuilder Create(AssemblyDomain domain, bool complieInFile = default) { TBuilder instance = new TBuilder(); instance.Complier.ComplieInFile = complieInFile; instance.Complier.Domain = domain; return instance; } /// <summary> /// 创建一个随机的域 /// </summary> /// <returns></returns> public static TBuilder Random(bool complieInFile = default) { TBuilder instance = new TBuilder() { }; instance.Complier.ComplieInFile = complieInFile; instance.Complier.Domain = DomainManagment.Random; return instance; } /// <summary> /// 编译返回委托 /// </summary> /// <returns></returns> public virtual Delegate Complie(object binder = null) { Complier.Add(this); return Complier.GetDelegate( OopNameScript, MethodNameScript, DelegateType, binder); } /// <summary> /// 将结果编译进文件 /// </summary> /// <returns></returns> public TBuilder UseFileComplie() { Complier.ComplieInFile = true; return Link; } /// <summary> /// 返回强类型委托 /// </summary> /// <typeparam name="T">委托的强类型</typeparam> /// <returns></returns> public virtual T Complie<T>(object binder = null) where T : Delegate { Complier.Add(this); return Complier.GetDelegate<T>( OopNameScript, MethodNameScript, binder); } } } <file_sep>/src/Natasha/Template/Member/Method/MethodDelegateTemplate.cs using Natasha.Builder; using System; namespace Natasha.Template { public class MethodDelegateTemplate<T>:MethodBodyTemplate<T> { public Type DelegateType { get { return DelegateBuilder.GetDelegate(ParametersTypes.ToArray(), ReturnType); } } } } <file_sep>/src/Natasha/Api/Level3/Operator/NDomain.cs using Natasha.Core; using Natasha.Operator; using System; namespace Natasha { public class NDomain { private AssemblyDomain _domain; private bool _complieInFile; private NDomain() { } public static NDomain Default { get { return Create(); } } public static NDomain Create(string domainName = default, bool complieInFile = false) { NDomain instance = new NDomain { _complieInFile = complieInFile }; if (domainName== default) { instance._domain = DomainManagment.Default; } else { instance._domain = DomainManagment.Create(domainName); } return instance; } public static NDomain Create(AssemblyDomain domain, bool complieInFile = false) { NDomain instance = new NDomain { _complieInFile = complieInFile, _domain = domain }; return instance; } public static NDomain Random(bool complieInFile = false) { NDomain instance = new NDomain { _complieInFile = complieInFile, _domain = DomainManagment.Random }; return instance; } /// <summary> /// 将结果编译进文件 /// </summary> /// <returns></returns> public NDomain UseFileComplie() { _complieInFile = true; return this; } public Type GetType(string code, string typeName = default) { OopOperator oopOperator = OopOperator.Create(_domain,_complieInFile); string result = oopOperator .GetUsingBuilder() .Append(code).ToString(); oopOperator.Complier.SyntaxInfos.Add(result,oopOperator.Usings); var text = result; if (typeName == default) { typeName = ScriptHelper.GetClassName(text); if (typeName == default) { typeName = ScriptHelper.GetInterfaceName(text); if (typeName == default) { typeName = ScriptHelper.GetStructName(text); if (typeName == default) { typeName = ScriptHelper.GetEnumName(text); } } } } return oopOperator.Complier.GetType(typeName); } public Func<T> Func<T>(string content, params NamespaceConverter[] usings) { return content == default ? null : DelegateOperator<Func<T>>.Delegate(content, _domain, _complieInFile, usings); } public Func<T> AsyncFunc<T>(string content, params NamespaceConverter[] usings) { return content == default ? null : DelegateOperator<Func<T>>.AsyncDelegate(content, _domain, _complieInFile, usings); } public Func<T> UnsafeFunc<T>(string content, params NamespaceConverter[] usings) { return content == default ? null : DelegateOperator<Func<T>>.UnsafeDelegate(content, _domain, _complieInFile, usings); } public Func<T> UnsafeAsyncFunc<T>(string content, params NamespaceConverter[] usings) { return content == default ? null : DelegateOperator<Func<T>>.UnsafeAsyncDelegate(content, _domain, _complieInFile, usings); } public Func<T1,T2> Func<T1,T2>(string content, params NamespaceConverter[] usings) { return content == default ? null : DelegateOperator<Func<T1,T2>>.Delegate(content, _domain, _complieInFile, usings); } public Func<T1,T2> AsyncFunc<T1,T2>(string content, params NamespaceConverter[] usings) { return content == default ? null : DelegateOperator<Func<T1,T2>>.AsyncDelegate(content, _domain, _complieInFile, usings); } public Func<T1,T2> UnsafeFunc<T1,T2>(string content, params NamespaceConverter[] usings) { return content == default ? null : DelegateOperator<Func<T1,T2>>.UnsafeDelegate(content, _domain, _complieInFile, usings); } public Func<T1,T2> UnsafeAsyncFunc<T1,T2>(string content, params NamespaceConverter[] usings) { return content == default ? null : DelegateOperator<Func<T1,T2>>.UnsafeAsyncDelegate(content, _domain, _complieInFile, usings); } public Func<T1,T2,T3> Func<T1,T2,T3>(string content, params NamespaceConverter[] usings) { return content == default ? null : DelegateOperator<Func<T1,T2,T3>>.Delegate(content, _domain, _complieInFile, usings); } public Func<T1,T2,T3> AsyncFunc<T1,T2,T3>(string content, params NamespaceConverter[] usings) { return content == default ? null : DelegateOperator<Func<T1,T2,T3>>.AsyncDelegate(content, _domain, _complieInFile, usings); } public Func<T1,T2,T3> UnsafeFunc<T1,T2,T3>(string content, params NamespaceConverter[] usings) { return content == default ? null : DelegateOperator<Func<T1,T2,T3>>.UnsafeDelegate(content, _domain, _complieInFile, usings); } public Func<T1,T2,T3> UnsafeAsyncFunc<T1,T2,T3>(string content, params NamespaceConverter[] usings) { return content == default ? null : DelegateOperator<Func<T1,T2,T3>>.UnsafeAsyncDelegate(content, _domain, _complieInFile, usings); } public Func<T1,T2,T3,T4> Func<T1,T2,T3,T4>(string content, params NamespaceConverter[] usings) { return content == default ? null : DelegateOperator<Func<T1,T2,T3,T4>>.Delegate(content, _domain, _complieInFile, usings); } public Func<T1,T2,T3,T4> AsyncFunc<T1,T2,T3,T4>(string content, params NamespaceConverter[] usings) { return content == default ? null : DelegateOperator<Func<T1,T2,T3,T4>>.AsyncDelegate(content, _domain, _complieInFile, usings); } public Func<T1,T2,T3,T4> UnsafeFunc<T1,T2,T3,T4>(string content, params NamespaceConverter[] usings) { return content == default ? null : DelegateOperator<Func<T1,T2,T3,T4>>.UnsafeDelegate(content, _domain, _complieInFile, usings); } public Func<T1,T2,T3,T4> UnsafeAsyncFunc<T1,T2,T3,T4>(string content, params NamespaceConverter[] usings) { return content == default ? null : DelegateOperator<Func<T1,T2,T3,T4>>.UnsafeAsyncDelegate(content, _domain, _complieInFile, usings); } public Func<T1,T2,T3,T4,T5> Func<T1,T2,T3,T4,T5>(string content, params NamespaceConverter[] usings) { return content == default ? null : DelegateOperator<Func<T1,T2,T3,T4,T5>>.Delegate(content, _domain, _complieInFile, usings); } public Func<T1,T2,T3,T4,T5> AsyncFunc<T1,T2,T3,T4,T5>(string content, params NamespaceConverter[] usings) { return content == default ? null : DelegateOperator<Func<T1,T2,T3,T4,T5>>.AsyncDelegate(content, _domain, _complieInFile, usings); } public Func<T1,T2,T3,T4,T5> UnsafeFunc<T1,T2,T3,T4,T5>(string content, params NamespaceConverter[] usings) { return content == default ? null : DelegateOperator<Func<T1,T2,T3,T4,T5>>.UnsafeDelegate(content, _domain, _complieInFile, usings); } public Func<T1,T2,T3,T4,T5> UnsafeAsyncFunc<T1,T2,T3,T4,T5>(string content, params NamespaceConverter[] usings) { return content == default ? null : DelegateOperator<Func<T1,T2,T3,T4,T5>>.UnsafeAsyncDelegate(content, _domain, _complieInFile, usings); } public Func<T1,T2,T3,T4,T5,T6> Func<T1,T2,T3,T4,T5,T6>(string content, params NamespaceConverter[] usings) { return content == default ? null : DelegateOperator<Func<T1,T2,T3,T4,T5,T6>>.Delegate(content, _domain, _complieInFile, usings); } public Func<T1,T2,T3,T4,T5,T6> AsyncFunc<T1,T2,T3,T4,T5,T6>(string content, params NamespaceConverter[] usings) { return content == default ? null : DelegateOperator<Func<T1,T2,T3,T4,T5,T6>>.AsyncDelegate(content, _domain, _complieInFile, usings); } public Func<T1,T2,T3,T4,T5,T6> UnsafeFunc<T1,T2,T3,T4,T5,T6>(string content, params NamespaceConverter[] usings) { return content == default ? null : DelegateOperator<Func<T1,T2,T3,T4,T5,T6>>.UnsafeDelegate(content, _domain, _complieInFile, usings); } public Func<T1,T2,T3,T4,T5,T6> UnsafeAsyncFunc<T1,T2,T3,T4,T5,T6>(string content, params NamespaceConverter[] usings) { return content == default ? null : DelegateOperator<Func<T1,T2,T3,T4,T5,T6>>.UnsafeAsyncDelegate(content, _domain, _complieInFile, usings); } public Func<T1,T2,T3,T4,T5,T6,T7> Func<T1,T2,T3,T4,T5,T6,T7>(string content, params NamespaceConverter[] usings) { return content == default ? null : DelegateOperator<Func<T1,T2,T3,T4,T5,T6,T7>>.Delegate(content, _domain, _complieInFile, usings); } public Func<T1,T2,T3,T4,T5,T6,T7> AsyncFunc<T1,T2,T3,T4,T5,T6,T7>(string content, params NamespaceConverter[] usings) { return content == default ? null : DelegateOperator<Func<T1,T2,T3,T4,T5,T6,T7>>.AsyncDelegate(content, _domain, _complieInFile, usings); } public Func<T1,T2,T3,T4,T5,T6,T7> UnsafeFunc<T1,T2,T3,T4,T5,T6,T7>(string content, params NamespaceConverter[] usings) { return content == default ? null : DelegateOperator<Func<T1,T2,T3,T4,T5,T6,T7>>.UnsafeDelegate(content, _domain, _complieInFile, usings); } public Func<T1,T2,T3,T4,T5,T6,T7> UnsafeAsyncFunc<T1,T2,T3,T4,T5,T6,T7>(string content, params NamespaceConverter[] usings) { return content == default ? null : DelegateOperator<Func<T1,T2,T3,T4,T5,T6,T7>>.UnsafeAsyncDelegate(content, _domain, _complieInFile, usings); } public Func<T1,T2,T3,T4,T5,T6,T7,T8> Func<T1,T2,T3,T4,T5,T6,T7,T8>(string content, params NamespaceConverter[] usings) { return content == default ? null : DelegateOperator<Func<T1,T2,T3,T4,T5,T6,T7,T8>>.Delegate(content, _domain, _complieInFile, usings); } public Func<T1,T2,T3,T4,T5,T6,T7,T8> AsyncFunc<T1,T2,T3,T4,T5,T6,T7,T8>(string content, params NamespaceConverter[] usings) { return content == default ? null : DelegateOperator<Func<T1,T2,T3,T4,T5,T6,T7,T8>>.AsyncDelegate(content, _domain, _complieInFile, usings); } public Func<T1,T2,T3,T4,T5,T6,T7,T8> UnsafeFunc<T1,T2,T3,T4,T5,T6,T7,T8>(string content, params NamespaceConverter[] usings) { return content == default ? null : DelegateOperator<Func<T1,T2,T3,T4,T5,T6,T7,T8>>.UnsafeDelegate(content, _domain, _complieInFile, usings); } public Func<T1,T2,T3,T4,T5,T6,T7,T8> UnsafeAsyncFunc<T1,T2,T3,T4,T5,T6,T7,T8>(string content, params NamespaceConverter[] usings) { return content == default ? null : DelegateOperator<Func<T1,T2,T3,T4,T5,T6,T7,T8>>.UnsafeAsyncDelegate(content, _domain, _complieInFile, usings); } public Func<T1,T2,T3,T4,T5,T6,T7,T8,T9> Func<T1,T2,T3,T4,T5,T6,T7,T8,T9>(string content, params NamespaceConverter[] usings) { return content == default ? null : DelegateOperator<Func<T1,T2,T3,T4,T5,T6,T7,T8,T9>>.Delegate(content, _domain, _complieInFile, usings); } public Func<T1,T2,T3,T4,T5,T6,T7,T8,T9> AsyncFunc<T1,T2,T3,T4,T5,T6,T7,T8,T9>(string content, params NamespaceConverter[] usings) { return content == default ? null : DelegateOperator<Func<T1,T2,T3,T4,T5,T6,T7,T8,T9>>.AsyncDelegate(content, _domain, _complieInFile, usings); } public Func<T1,T2,T3,T4,T5,T6,T7,T8,T9> UnsafeFunc<T1,T2,T3,T4,T5,T6,T7,T8,T9>(string content, params NamespaceConverter[] usings) { return content == default ? null : DelegateOperator<Func<T1,T2,T3,T4,T5,T6,T7,T8,T9>>.UnsafeDelegate(content, _domain, _complieInFile, usings); } public Func<T1,T2,T3,T4,T5,T6,T7,T8,T9> UnsafeAsyncFunc<T1,T2,T3,T4,T5,T6,T7,T8,T9>(string content, params NamespaceConverter[] usings) { return content == default ? null : DelegateOperator<Func<T1,T2,T3,T4,T5,T6,T7,T8,T9>>.UnsafeAsyncDelegate(content, _domain, _complieInFile, usings); } public Func<T1,T2,T3,T4,T5,T6,T7,T8,T9,T10> Func<T1,T2,T3,T4,T5,T6,T7,T8,T9,T10>(string content, params NamespaceConverter[] usings) { return content == default ? null : DelegateOperator<Func<T1,T2,T3,T4,T5,T6,T7,T8,T9,T10>>.Delegate(content, _domain, _complieInFile, usings); } public Func<T1,T2,T3,T4,T5,T6,T7,T8,T9,T10> AsyncFunc<T1,T2,T3,T4,T5,T6,T7,T8,T9,T10>(string content, params NamespaceConverter[] usings) { return content == default ? null : DelegateOperator<Func<T1,T2,T3,T4,T5,T6,T7,T8,T9,T10>>.AsyncDelegate(content, _domain, _complieInFile, usings); } public Func<T1,T2,T3,T4,T5,T6,T7,T8,T9,T10> UnsafeFunc<T1,T2,T3,T4,T5,T6,T7,T8,T9,T10>(string content, params NamespaceConverter[] usings) { return content == default ? null : DelegateOperator<Func<T1,T2,T3,T4,T5,T6,T7,T8,T9,T10>>.UnsafeDelegate(content, _domain, _complieInFile, usings); } public Func<T1,T2,T3,T4,T5,T6,T7,T8,T9,T10> UnsafeAsyncFunc<T1,T2,T3,T4,T5,T6,T7,T8,T9,T10>(string content, params NamespaceConverter[] usings) { return content == default ? null : DelegateOperator<Func<T1,T2,T3,T4,T5,T6,T7,T8,T9,T10>>.UnsafeAsyncDelegate(content, _domain, _complieInFile, usings); } public Func<T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11> Func<T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11>(string content, params NamespaceConverter[] usings) { return content == default ? null : DelegateOperator<Func<T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11>>.Delegate(content, _domain, _complieInFile, usings); } public Func<T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11> AsyncFunc<T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11>(string content, params NamespaceConverter[] usings) { return content == default ? null : DelegateOperator<Func<T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11>>.AsyncDelegate(content, _domain, _complieInFile, usings); } public Func<T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11> UnsafeFunc<T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11>(string content, params NamespaceConverter[] usings) { return content == default ? null : DelegateOperator<Func<T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11>>.UnsafeDelegate(content, _domain, _complieInFile, usings); } public Func<T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11> UnsafeAsyncFunc<T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11>(string content, params NamespaceConverter[] usings) { return content == default ? null : DelegateOperator<Func<T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11>>.UnsafeAsyncDelegate(content, _domain, _complieInFile, usings); } public Func<T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12> Func<T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12>(string content, params NamespaceConverter[] usings) { return content == default ? null : DelegateOperator<Func<T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12>>.Delegate(content, _domain, _complieInFile, usings); } public Func<T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12> AsyncFunc<T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12>(string content, params NamespaceConverter[] usings) { return content == default ? null : DelegateOperator<Func<T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12>>.AsyncDelegate(content, _domain, _complieInFile, usings); } public Func<T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12> UnsafeFunc<T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12>(string content, params NamespaceConverter[] usings) { return content == default ? null : DelegateOperator<Func<T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12>>.UnsafeDelegate(content, _domain, _complieInFile, usings); } public Func<T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12> UnsafeAsyncFunc<T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12>(string content, params NamespaceConverter[] usings) { return content == default ? null : DelegateOperator<Func<T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12>>.UnsafeAsyncDelegate(content, _domain, _complieInFile, usings); } public Action Action(string content, params NamespaceConverter[] usings) { return content == default ? null : DelegateOperator<Action>.Delegate(content, _domain, _complieInFile, usings); } public Action<T> Action<T>(string content, params NamespaceConverter[] usings) { return content == default ? null : DelegateOperator<Action<T>>.Delegate(content, _domain, _complieInFile, usings); } public Action<T> AsyncAction<T>(string content, params NamespaceConverter[] usings) { return content == default ? null : DelegateOperator<Action<T>>.AsyncDelegate(content, _domain, _complieInFile, usings); } public Action<T> UnsafeAction<T>(string content, params NamespaceConverter[] usings) { return content == default ? null : DelegateOperator<Action<T>>.UnsafeDelegate(content, _domain, _complieInFile, usings); } public Action<T> UnsafeAsyncAction<T>(string content, params NamespaceConverter[] usings) { return content == default ? null : DelegateOperator<Action<T>>.UnsafeAsyncDelegate(content, _domain, _complieInFile, usings); } public Action<T1, T2> Action<T1, T2>(string content, params NamespaceConverter[] usings) { return content == default ? null : DelegateOperator<Action<T1, T2>>.Delegate(content, _domain, _complieInFile, usings); } public Action<T1, T2> AsyncAction<T1, T2>(string content, params NamespaceConverter[] usings) { return content == default ? null : DelegateOperator<Action<T1, T2>>.AsyncDelegate(content, _domain, _complieInFile, usings); } public Action<T1, T2> UnsafeAction<T1, T2>(string content, params NamespaceConverter[] usings) { return content == default ? null : DelegateOperator<Action<T1, T2>>.UnsafeDelegate(content, _domain, _complieInFile, usings); } public Action<T1, T2> UnsafeAsyncAction<T1, T2>(string content, params NamespaceConverter[] usings) { return content == default ? null : DelegateOperator<Action<T1, T2>>.UnsafeAsyncDelegate(content, _domain, _complieInFile, usings); } public Action<T1, T2, T3> Action<T1, T2, T3>(string content, params NamespaceConverter[] usings) { return content == default ? null : DelegateOperator<Action<T1, T2, T3>>.Delegate(content, _domain, _complieInFile, usings); } public Action<T1, T2, T3> AsyncAction<T1, T2, T3>(string content, params NamespaceConverter[] usings) { return content == default ? null : DelegateOperator<Action<T1, T2, T3>>.AsyncDelegate(content, _domain, _complieInFile, usings); } public Action<T1, T2, T3> UnsafeAction<T1, T2, T3>(string content, params NamespaceConverter[] usings) { return content == default ? null : DelegateOperator<Action<T1, T2, T3>>.UnsafeDelegate(content, _domain, _complieInFile, usings); } public Action<T1, T2, T3> UnsafeAsyncAction<T1, T2, T3>(string content, params NamespaceConverter[] usings) { return content == default ? null : DelegateOperator<Action<T1, T2, T3>>.UnsafeAsyncDelegate(content, _domain, _complieInFile, usings); } public Action<T1, T2, T3, T4> Action<T1, T2, T3, T4>(string content, params NamespaceConverter[] usings) { return content == default ? null : DelegateOperator<Action<T1, T2, T3, T4>>.Delegate(content, _domain, _complieInFile, usings); } public Action<T1, T2, T3, T4> AsyncAction<T1, T2, T3, T4>(string content, params NamespaceConverter[] usings) { return content == default ? null : DelegateOperator<Action<T1, T2, T3, T4>>.AsyncDelegate(content, _domain, _complieInFile, usings); } public Action<T1, T2, T3, T4> UnsafeAction<T1, T2, T3, T4>(string content, params NamespaceConverter[] usings) { return content == default ? null : DelegateOperator<Action<T1, T2, T3, T4>>.UnsafeDelegate(content, _domain, _complieInFile, usings); } public Action<T1, T2, T3, T4> UnsafeAsyncAction<T1, T2, T3, T4>(string content, params NamespaceConverter[] usings) { return content == default ? null : DelegateOperator<Action<T1, T2, T3, T4>>.UnsafeAsyncDelegate(content, _domain, _complieInFile, usings); } public Action<T1, T2, T3, T4, T5> Action<T1, T2, T3, T4, T5>(string content, params NamespaceConverter[] usings) { return content == default ? null : DelegateOperator<Action<T1, T2, T3, T4, T5>>.Delegate(content, _domain, _complieInFile, usings); } public Action<T1, T2, T3, T4, T5> AsyncAction<T1, T2, T3, T4, T5>(string content, params NamespaceConverter[] usings) { return content == default ? null : DelegateOperator<Action<T1, T2, T3, T4, T5>>.AsyncDelegate(content, _domain, _complieInFile, usings); } public Action<T1, T2, T3, T4, T5> UnsafeAction<T1, T2, T3, T4, T5>(string content, params NamespaceConverter[] usings) { return content == default ? null : DelegateOperator<Action<T1, T2, T3, T4, T5>>.UnsafeDelegate(content, _domain, _complieInFile, usings); } public Action<T1, T2, T3, T4, T5> UnsafeAsyncAction<T1, T2, T3, T4, T5>(string content, params NamespaceConverter[] usings) { return content == default ? null : DelegateOperator<Action<T1, T2, T3, T4, T5>>.UnsafeAsyncDelegate(content, _domain, _complieInFile, usings); } public Action<T1, T2, T3, T4, T5, T6> Action<T1, T2, T3, T4, T5, T6>(string content, params NamespaceConverter[] usings) { return content == default ? null : DelegateOperator<Action<T1, T2, T3, T4, T5, T6>>.Delegate(content, _domain, _complieInFile, usings); } public Action<T1, T2, T3, T4, T5, T6> AsyncAction<T1, T2, T3, T4, T5, T6>(string content, params NamespaceConverter[] usings) { return content == default ? null : DelegateOperator<Action<T1, T2, T3, T4, T5, T6>>.AsyncDelegate(content, _domain, _complieInFile, usings); } public Action<T1, T2, T3, T4, T5, T6> UnsafeAction<T1, T2, T3, T4, T5, T6>(string content, params NamespaceConverter[] usings) { return content == default ? null : DelegateOperator<Action<T1, T2, T3, T4, T5, T6>>.UnsafeDelegate(content, _domain, _complieInFile, usings); } public Action<T1, T2, T3, T4, T5, T6> UnsafeAsyncAction<T1, T2, T3, T4, T5, T6>(string content, params NamespaceConverter[] usings) { return content == default ? null : DelegateOperator<Action<T1, T2, T3, T4, T5, T6>>.UnsafeAsyncDelegate(content, _domain, _complieInFile, usings); } public Action<T1, T2, T3, T4, T5, T6, T7> Action<T1, T2, T3, T4, T5, T6, T7>(string content, params NamespaceConverter[] usings) { return content == default ? null : DelegateOperator<Action<T1, T2, T3, T4, T5, T6, T7>>.Delegate(content, _domain, _complieInFile, usings); } public Action<T1, T2, T3, T4, T5, T6, T7> AsyncAction<T1, T2, T3, T4, T5, T6, T7>(string content, params NamespaceConverter[] usings) { return content == default ? null : DelegateOperator<Action<T1, T2, T3, T4, T5, T6, T7>>.AsyncDelegate(content, _domain, _complieInFile, usings); } public Action<T1, T2, T3, T4, T5, T6, T7> UnsafeAction<T1, T2, T3, T4, T5, T6, T7>(string content, params NamespaceConverter[] usings) { return content == default ? null : DelegateOperator<Action<T1, T2, T3, T4, T5, T6, T7>>.UnsafeDelegate(content, _domain, _complieInFile, usings); } public Action<T1, T2, T3, T4, T5, T6, T7> UnsafeAsyncAction<T1, T2, T3, T4, T5, T6, T7>(string content, params NamespaceConverter[] usings) { return content == default ? null : DelegateOperator<Action<T1, T2, T3, T4, T5, T6, T7>>.UnsafeAsyncDelegate(content, _domain, _complieInFile, usings); } public Action<T1, T2, T3, T4, T5, T6, T7, T8> Action<T1, T2, T3, T4, T5, T6, T7, T8>(string content, params NamespaceConverter[] usings) { return content == default ? null : DelegateOperator<Action<T1, T2, T3, T4, T5, T6, T7, T8>>.Delegate(content, _domain, _complieInFile, usings); } public Action<T1, T2, T3, T4, T5, T6, T7, T8> AsyncAction<T1, T2, T3, T4, T5, T6, T7, T8>(string content, params NamespaceConverter[] usings) { return content == default ? null : DelegateOperator<Action<T1, T2, T3, T4, T5, T6, T7, T8>>.AsyncDelegate(content, _domain, _complieInFile, usings); } public Action<T1, T2, T3, T4, T5, T6, T7, T8> UnsafeAction<T1, T2, T3, T4, T5, T6, T7, T8>(string content, params NamespaceConverter[] usings) { return content == default ? null : DelegateOperator<Action<T1, T2, T3, T4, T5, T6, T7, T8>>.UnsafeDelegate(content, _domain, _complieInFile, usings); } public Action<T1, T2, T3, T4, T5, T6, T7, T8> UnsafeAsyncAction<T1, T2, T3, T4, T5, T6, T7, T8>(string content, params NamespaceConverter[] usings) { return content == default ? null : DelegateOperator<Action<T1, T2, T3, T4, T5, T6, T7, T8>>.UnsafeAsyncDelegate(content, _domain, _complieInFile, usings); } public Action<T1, T2, T3, T4, T5, T6, T7, T8, T9> Action<T1, T2, T3, T4, T5, T6, T7, T8, T9>(string content, params NamespaceConverter[] usings) { return content == default ? null : DelegateOperator<Action<T1, T2, T3, T4, T5, T6, T7, T8, T9>>.Delegate(content, _domain, _complieInFile, usings); } public Action<T1, T2, T3, T4, T5, T6, T7, T8, T9> AsyncAction<T1, T2, T3, T4, T5, T6, T7, T8, T9>(string content, params NamespaceConverter[] usings) { return content == default ? null : DelegateOperator<Action<T1, T2, T3, T4, T5, T6, T7, T8, T9>>.AsyncDelegate(content, _domain, _complieInFile, usings); } public Action<T1, T2, T3, T4, T5, T6, T7, T8, T9> UnsafeAction<T1, T2, T3, T4, T5, T6, T7, T8, T9>(string content, params NamespaceConverter[] usings) { return content == default ? null : DelegateOperator<Action<T1, T2, T3, T4, T5, T6, T7, T8, T9>>.UnsafeDelegate(content, _domain, _complieInFile, usings); } public Action<T1, T2, T3, T4, T5, T6, T7, T8, T9> UnsafeAsyncAction<T1, T2, T3, T4, T5, T6, T7, T8, T9>(string content, params NamespaceConverter[] usings) { return content == default ? null : DelegateOperator<Action<T1, T2, T3, T4, T5, T6, T7, T8, T9>>.UnsafeAsyncDelegate(content, _domain, _complieInFile, usings); } public Action<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10> Action<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>(string content, params NamespaceConverter[] usings) { return content == default ? null : DelegateOperator<Action<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>>.Delegate(content, _domain, _complieInFile, usings); } public Action<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10> AsyncAction<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>(string content, params NamespaceConverter[] usings) { return content == default ? null : DelegateOperator<Action<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>>.AsyncDelegate(content, _domain, _complieInFile, usings); } public Action<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10> UnsafeAction<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>(string content, params NamespaceConverter[] usings) { return content == default ? null : DelegateOperator<Action<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>>.UnsafeDelegate(content, _domain, _complieInFile, usings); } public Action<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10> UnsafeAsyncAction<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>(string content, params NamespaceConverter[] usings) { return content == default ? null : DelegateOperator<Action<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>>.UnsafeAsyncDelegate(content, _domain, _complieInFile, usings); } public Action<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> Action<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>(string content, params NamespaceConverter[] usings) { return content == default ? null : DelegateOperator<Action<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>>.Delegate(content, _domain, _complieInFile, usings); } public Action<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> AsyncAction<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>(string content, params NamespaceConverter[] usings) { return content == default ? null : DelegateOperator<Action<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>>.AsyncDelegate(content, _domain, _complieInFile, usings); } public Action<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> UnsafeAction<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>(string content, params NamespaceConverter[] usings) { return content == default ? null : DelegateOperator<Action<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>>.UnsafeDelegate(content, _domain, _complieInFile, usings); } public Action<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> UnsafeAsyncAction<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>(string content, params NamespaceConverter[] usings) { return content == default ? null : DelegateOperator<Action<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>>.UnsafeAsyncDelegate(content, _domain, _complieInFile, usings); } public Action<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> Action<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>(string content, params NamespaceConverter[] usings) { return content == default ? null : DelegateOperator<Action<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>>.Delegate(content, _domain, _complieInFile, usings); } public Action<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> AsyncAction<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>(string content, params NamespaceConverter[] usings) { return content == default ? null : DelegateOperator<Action<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>>.AsyncDelegate(content, _domain, _complieInFile, usings); } public Action<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> UnsafeAction<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>(string content, params NamespaceConverter[] usings) { return content == default ? null : DelegateOperator<Action<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>>.UnsafeDelegate(content, _domain, _complieInFile, usings); } public Action<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> UnsafeAsyncAction<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>(string content, params NamespaceConverter[] usings) { return content == default ? null : DelegateOperator<Action<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>>.UnsafeAsyncDelegate(content, _domain, _complieInFile, usings); } } } <file_sep>/src/Natasha/Api/Level1/Operator/OopOperator.cs using Natasha.Builder; namespace Natasha.Operator { /// <summary> /// 类构建器 /// </summary> public class OopOperator : OopBuilder<OopOperator> { public OopOperator() { Link = this; } } } <file_sep>/src/Natasha/Api/Level4/Operator/DomainOperator.cs using Natasha.Core; using Natasha.Operator; using System; namespace Natasha { public class DomainOperator { private OopOperator _operator; private AssemblyDomain _domain; private bool _complieInFile; public DomainOperator() { _operator = new OopOperator(); } public static DomainOperator Instance { get { return new DomainOperator(); } } public static DomainOperator Default { get { return Create(); } } public static DomainOperator Create(string domainName = default, bool complieInFile = false) { DomainOperator instance = new DomainOperator { _complieInFile = complieInFile }; if (domainName == default) { instance._domain = DomainManagment.Default; } else { instance._domain = DomainManagment.Create(domainName); } return instance; } public static DomainOperator Create(AssemblyDomain domain, bool complieInFile = false) { DomainOperator instance = new DomainOperator { _complieInFile = complieInFile, _domain = domain }; return instance; } public static DomainOperator Random(bool complieInFile = false) { DomainOperator instance = new DomainOperator { _complieInFile = complieInFile, _domain = DomainManagment.Random }; return instance; } public static DomainOperator operator &(string code, DomainOperator @operator) { @operator._operator.OopBody(code); return @operator; } public static DomainOperator operator &(DomainOperator @operator, string code) { @operator._operator.OopBody(code); return @operator; } public static DomainOperator operator |(DomainOperator @operator, NamespaceConverter @using) { @operator._operator.Using(@using); return @operator; } public static DomainOperator operator |(NamespaceConverter @using, DomainOperator @operator) { @operator._operator.Using(@using); return @operator; } public static DomainOperator operator +(DomainOperator @operator, string domainName) { @operator._domain = DomainManagment.Create(domainName); return @operator; } public static DomainOperator operator +(string domainName, DomainOperator @operator) { @operator._domain = DomainManagment.Create(domainName); return @operator; } public static DomainOperator operator +(DomainOperator @operator, AssemblyDomain domain) { @operator._domain = domain; return @operator; } public static DomainOperator operator +(AssemblyDomain domain, DomainOperator @operator) { @operator._domain = domain; return @operator; } public Type GetType(string typeName = default) { AssemblyComplier complier = new AssemblyComplier(); complier.ComplieInFile = _complieInFile; complier.Domain = _domain; var text = _operator .GetUsingBuilder() .Append(_operator.OopContentScript) .ToString(); if (typeName == default) { typeName = ScriptHelper.GetClassName(text); if (typeName == default) { typeName = ScriptHelper.GetInterfaceName(text); if (typeName == default) { typeName = ScriptHelper.GetStructName(text); if (typeName == default) { typeName = ScriptHelper.GetEnumName(text); } } } } complier.Add(text); return complier.GetType(typeName); } } } <file_sep>/docs/zh/api/index.md <p align="center"> <a href="https://natasha.dotnetcore.xyz/"> 返回 </a> | <a href="https://natasha.dotnetcore.xyz/en/api/index.html"> English </a> </p> ## API速查表 <br/> | 类名 | 作用 | 命名空间 | 操作类型 | |:---:|:---:|:---:|:---:| | NAssembly | 快速创建同程序集的 oop 及委托等操作类 | Natasha | 静态初始化:Create / Random / Default 或 动态:实例化 | | NDomain | 快速创建指定域的 Action/Func 委托 | Natasha | 静态初始化:Create / Random / Default 或 动态:实例化 | | NClass | 快速创建一个公有类 | Natasha | 静态初始化:Create / Random / Default 或 动态:实例化 | | NInterface | 快速创建一个公有接口 | Natasha | 静态初始化:Create / Random / Default 或 动态:实例化 | | NEnum | 快速创建一个公有枚举类 | Natasha | 静态初始化:Create / Random / Default 或 动态:实例化 | | NStruct | 快速创建一个公有结构体 | Natasha | 静态初始化:Create / Random / Default 或 动态:实例化 | | NewMethod | 创建委托 | Natasha | 静态 | | NewClass | 创建类| Natasha | 静态 | | NewStruct | 创建结构体| Natasha | 静态 | | NewInterface | 创建接口 | Natasha | 静态 | | FakeMethodOperator | 仿造MethodInfo创建方法 | Natasha.Operator | 静态初始化:Create / Random / Default 或 动态:实例化 | | FastMethodOperator | 快速创建方法 | Natasha.Operator | 静态初始化:Create / Random / Default 或 动态:实例化 | | DelegateOperator | 快速实现委托 | Natasha.Operator | 静态 | | ProxyOperator | 动态实现接口/抽象类/虚方法 | Natasha.Operator | 实例化 | | OopOperator | 动态构建类/接口/结构体 | Natasha.Operator | 静态初始化:Create / Random / Default 或 动态:实例化 | | CtorOperator | 动态初始化 | Natasha.Operator | 静态初始化:Create / Random / Default 或 动态:实例化 | | DomainOperator(待升级) | 动态初始化 | Natasha.Operator | 静态初始化:Create / Random / Default 或 动态:实例化 | <file_sep>/test/NatashaUT/TypeGetterTest.cs using Natasha; using NatashaUT.Model; using System; using System.Collections.Generic; using Xunit; namespace NatashaUT { [Trait("类型获取", "")] public class TypeGetterTest { [Fact(DisplayName = "获取类型1")] public void TestBuilder2() { var result = NewMethod.Create<Func<Type>>(builder => builder .Using("NatashaUT.Model") .MethodBody($@"return typeof(FieldSelfLinkModel);") ); Assert.NotNull(result.Method()); Assert.Equal(typeof(FieldSelfLinkModel),result.Method()); } [Fact(DisplayName = "获取所有类型")] public void TestBuilder3() { var types = new HashSet<Type>(typeof(Dictionary<String, FieldCloneNormalModel[]>[]).GetAllTypes()); Assert.Contains(typeof(FieldCloneNormalModel), types); Assert.Contains(typeof(FieldCloneNormalModel[]), types); Assert.Contains(typeof(String), types); Assert.Contains(typeof(Dictionary<String, FieldCloneNormalModel[]>[]), types); Assert.Contains(typeof(Dictionary<String, FieldCloneNormalModel[]>), types); } } } <file_sep>/src/Natasha/Api/Level2/Operator/NewMethod.cs using Natasha.Operator; using System; namespace Natasha { public static class NewMethod { public static (CompilationException Exception, Delegate Method) Create(Action<FastMethodOperator> action) { FastMethodOperator builder = FastMethodOperator.Random(); action(builder); var result = builder.Complie(); return (builder.Complier.ComplieException, result); } public static (CompilationException Exception, T Method) Create<T>(Action<FastMethodOperator> action) where T: Delegate { FastMethodOperator builder = FastMethodOperator.Random(); action(builder); var result = builder.Complie<T>(); return (builder.Complier.ComplieException, result); } } }
697a54813d2c91e7ac446202e95843a4ffa0155b
[ "C#", "Markdown" ]
16
C#
mzorec/Natasha
bef18006af092c14d4ab3a40b959129e6c4266f0
5e3fe219c0e9ec83ee89ca863dcdf1d464652ddb
refs/heads/master
<file_sep>package com.johnfe.login; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.EditText; import android.widget.Toast; import com.johnfe.login.R; public class Main extends AppCompatActivity { EditText etUsuario, etPassword; private Cursor fila; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); etUsuario= (EditText) findViewById(R.id.etusuario); etPassword = (EditText) findViewById(R.id.etcontrasena); } public void ingresar(View v){ DBHelper admin=new DBHelper(this,"clase",null,1); SQLiteDatabase db=admin.getWritableDatabase(); String usuario=etUsuario.getText().toString().trim(); String contrasena= etPassword.getText().toString(); fila=db.rawQuery("select usuario,contrasena from usuarios where usuario='"+usuario+"' and contrasena='"+contrasena+"'",null); System.out.println(fila.getCount()); if (fila.moveToFirst()){ System.out.println("entro"); Toast.makeText(this,"consulto la db",Toast.LENGTH_SHORT).show(); String usua=fila.getString(0); String pass=fila.getString(1); if (usuario.equals(usua)&&contrasena.equals(pass)){ Intent ven=new Intent(this,Menu.class); startActivity(ven); etUsuario.setText(""); etPassword.setText(""); }else{ Toast.makeText(this,"No existe usuario 1",Toast.LENGTH_SHORT).show(); } }else { Toast.makeText(this,"No existe usuario 2",Toast.LENGTH_SHORT).show(); } } public void registro(View v){ Intent ven=new Intent(this,Registro.class); startActivity(ven); } public void salir(View v){ System.exit(0); } } <file_sep>package com.johnfe.login; import android.content.ContentValues; import android.content.Intent; import android.database.sqlite.SQLiteDatabase; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.EditText; import android.widget.Toast; import com.johnfe.login.R; public class Registro extends AppCompatActivity { EditText et2,et3; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.registro); et2= (EditText) findViewById(R.id.etuser); et3= (EditText) findViewById(R.id.etcontra); } public void registrar(View view){ DBHelper admin=new DBHelper(this,"clase",null,1); SQLiteDatabase db=admin.getWritableDatabase(); String usuario=et2.getText().toString(); String contrasena=et3.getText().toString(); db.execSQL("insert into usuarios (usuario,contrasena) values('"+usuario+"','"+contrasena+"')"); db.close(); Toast.makeText(this,"Registro exitoso",Toast.LENGTH_SHORT).show(); Intent ven=new Intent(this,Main.class); startActivity(ven); } public void cancelar(View view){ finish(); } }
3011ed2eb365b99e49cf402e068a5a17d0622fb6
[ "Java" ]
2
Java
eulosoft/Login
b84c097b414a866770202951a9a62dada38752d4
d423f9fa68300efd77493cfd1341f67821c4df40
refs/heads/master
<file_sep>====== object ====== Object Storage v1 object create ------------- Upload object to container .. program:: object create .. code:: bash os object create <container> <filename> [<filename> ...] .. describe:: <container> Container for new object .. describe:: <filename> Local filename(s) to upload object delete ------------- Delete object from container .. program:: object delete .. code:: bash os object delete <container> <object> [<object> ...] .. describe:: <container> Delete object(s) from <container> .. describe:: <object> Object(s) to delete object list ----------- List objects .. program object list .. code:: bash os object list [--prefix <prefix>] [--delimiter <delimiter>] [--marker <marker>] [--end-marker <end-marker>] [--limit <limit>] [--long] [--all] <container>] .. option:: --prefix <prefix> Filter list using <prefix> .. option:: --delimiter <delimiter> Roll up items with <delimiter> .. option:: --marker <marker> Anchor for paging .. option:: --end-marker <end-marker> End anchor for paging .. option:: --limit <limit> Limit number of objects returned .. option:: --long List additional fields in output .. option:: --all List all objects in <container> (default is 10000) .. describe:: <container> Container to list object save ----------- Save object locally .. program:: object save .. code:: bash os object save [--file <filename>] [<container>] [<object>] .. option:: --file <filename> Destination filename (defaults to object name) .. describe:: <container> Download <object> from <container> .. describe:: <object> Object to save object set ---------- Set object properties .. program:: object set .. code:: bash os object set [--property <key=value> [...] ] <container> [<object>] .. option:: --property <key=value> Set a property on this object (repeat option to set multiple properties) .. describe:: <container> Modify <object> from <container> .. describe:: <object> Object to modify object show ----------- Display object details .. program:: object show .. code:: bash os object show <container> <object> .. describe:: <container> Display <object> from <container> .. describe:: <object> Object to display object unset ------------ Unset object properties .. program:: object unset .. code:: bash os object unset [--property <key>] <container> [<object>] .. option:: --property <key> Property to remove from object (repeat option to remove multiple properties) .. describe:: <container> Modify <object> from <container> .. describe:: <object> Object to modify <file_sep>====== module ====== Internal Installed Python modules in the OSC process. module list ----------- List module versions .. program:: module list .. code:: bash os module list [--all] .. option:: --all Show all modules that have version information <file_sep>=============== OpenStackClient =============== OpenStackClient (aka OSC) is a command-line client for OpenStack that brings the command set for Compute, Identity, Image, Object Storage and Block Storage APIs together in a single shell with a uniform command structure. User Documentation ------------------ .. toctree:: :maxdepth: 1 command-list commands configuration plugins plugin-commands authentication interactive humaninterfaceguide backwards-incompatible man/openstack Getting Started --------------- * Try :doc:`some commands <command-list>` * Read the source `on OpenStack's Git server`_ * Install OpenStackClient from `PyPi`_ or a `tarball`_ Release Notes ------------- .. toctree:: :maxdepth: 1 releases history Developer Documentation ----------------------- .. toctree:: :maxdepth: 1 developing command-options command-wrappers specs/commands Project Goals ------------- * Use the OpenStack Python API libraries, extending or replacing them as required * Use a consistent naming and structure for commands and arguments * Provide consistent output formats with optional machine parseable formats * Use a single-binary approach that also contains an embedded shell that can execute multiple commands on a single authentication (see libvirt's virsh for an example) * Independence from the OpenStack project names; only API names are referenced (to the extent possible) Contributing ============ OpenStackClient utilizes all of the usual OpenStack processes and requirements for contributions. The code is hosted `on OpenStack's Git server`_. `Bug reports`_ and `blueprints`_ may be submitted to the :code:`python-openstackclient` project on `Launchpad`_. Code may be submitted to the :code:`openstack/python-openstackclient` project using `Gerrit`_. Developers may also be found in the `IRC channel`_ ``#openstack-sdks``. .. _`on OpenStack's Git server`: https://git.openstack.org/cgit/openstack/python-openstackclient/tree .. _Launchpad: https://launchpad.net/python-openstackclient .. _Gerrit: http://docs.openstack.org/infra/manual/developers.html#development-workflow .. _Bug reports: https://bugs.launchpad.net/python-openstackclient/+bugs .. _blueprints: https://blueprints.launchpad.net/python-openstackclient .. _PyPi: https://pypi.python.org/pypi/python-openstackclient .. _tarball: http://tarballs.openstack.org/python-openstackclient .. _IRC channel: https://wiki.openstack.org/wiki/IRC Indices and Tables ================== * :ref:`genindex` * :ref:`modindex` * :ref:`search` <file_sep># Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # import mock from openstackclient.common import utils from openstackclient.network.v2 import subnet as subnet_v2 from openstackclient.tests.network.v2 import fakes as network_fakes from openstackclient.tests import utils as tests_utils class TestSubnet(network_fakes.TestNetworkV2): def setUp(self): super(TestSubnet, self).setUp() # Get a shortcut to the network client self.network = self.app.client_manager.network class TestDeleteSubnet(TestSubnet): # The subnet to delete. _subnet = network_fakes.FakeSubnet.create_one_subnet() def setUp(self): super(TestDeleteSubnet, self).setUp() self.network.delete_subnet = mock.Mock(return_value=None) self.network.find_subnet = mock.Mock(return_value=self._subnet) # Get the command object to test self.cmd = subnet_v2.DeleteSubnet(self.app, self.namespace) def test_delete(self): arglist = [ self._subnet.name, ] verifylist = [ ('subnet', self._subnet.name), ] parsed_args = self.check_parser(self.cmd, arglist, verifylist) result = self.cmd.take_action(parsed_args) self.network.delete_subnet.assert_called_with(self._subnet) self.assertIsNone(result) class TestListSubnet(TestSubnet): # The subnets going to be listed up. _subnet = network_fakes.FakeSubnet.create_subnets(count=3) columns = ( 'ID', 'Name', 'Network', 'Subnet' ) columns_long = columns + ( 'Project', 'DHCP', 'Name Servers', 'Allocation Pools', 'Host Routes', 'IP Version', 'Gateway' ) data = [] for subnet in _subnet: data.append(( subnet.id, subnet.name, subnet.network_id, subnet.cidr, )) data_long = [] for subnet in _subnet: data_long.append(( subnet.id, subnet.name, subnet.network_id, subnet.cidr, subnet.tenant_id, subnet.enable_dhcp, utils.format_list(subnet.dns_nameservers), subnet_v2._format_allocation_pools(subnet.allocation_pools), utils.format_list(subnet.host_routes), subnet.ip_version, subnet.gateway_ip )) def setUp(self): super(TestListSubnet, self).setUp() # Get the command object to test self.cmd = subnet_v2.ListSubnet(self.app, self.namespace) self.network.subnets = mock.Mock(return_value=self._subnet) def test_subnet_list_no_options(self): arglist = [] verifylist = [ ('long', False), ] parsed_args = self.check_parser(self.cmd, arglist, verifylist) columns, data = self.cmd.take_action(parsed_args) self.network.subnets.assert_called_with() self.assertEqual(self.columns, columns) self.assertEqual(self.data, list(data)) def test_subnet_list_long(self): arglist = [ '--long', ] verifylist = [ ('long', True), ] parsed_args = self.check_parser(self.cmd, arglist, verifylist) columns, data = self.cmd.take_action(parsed_args) self.network.subnets.assert_called_with() self.assertEqual(self.columns_long, columns) self.assertEqual(self.data_long, list(data)) class TestShowSubnet(TestSubnet): # The subnets to be shown _subnet = network_fakes.FakeSubnet.create_one_subnet() columns = ( 'allocation_pools', 'cidr', 'dns_nameservers', 'enable_dhcp', 'gateway_ip', 'host_routes', 'id', 'ip_version', 'ipv6_address_mode', 'ipv6_ra_mode', 'name', 'network_id', 'project_id', 'subnetpool_id', ) data = ( subnet_v2._format_allocation_pools(_subnet.allocation_pools), _subnet.cidr, utils.format_list(_subnet.dns_nameservers), _subnet.enable_dhcp, _subnet.gateway_ip, utils.format_list(_subnet.host_routes), _subnet.id, _subnet.ip_version, _subnet.ipv6_address_mode, _subnet.ipv6_ra_mode, _subnet.name, _subnet.network_id, _subnet.tenant_id, _subnet.subnetpool_id, ) def setUp(self): super(TestShowSubnet, self).setUp() # Get the command object to test self.cmd = subnet_v2.ShowSubnet(self.app, self.namespace) self.network.find_subnet = mock.Mock(return_value=self._subnet) def test_show_no_options(self): arglist = [] verifylist = [] # Testing that a call without the required argument will fail and # throw a "ParserExecption" self.assertRaises(tests_utils.ParserException, self.check_parser, self.cmd, arglist, verifylist) def test_show_all_options(self): arglist = [ self._subnet.name, ] verifylist = [ ('subnet', self._subnet.name), ] parsed_args = self.check_parser(self.cmd, arglist, verifylist) columns, data = self.cmd.take_action(parsed_args) self.network.find_subnet.assert_called_with(self._subnet.name, ignore_missing=False) self.assertEqual(self.columns, columns) self.assertEqual(list(self.data), list(data)) <file_sep>====== policy ====== Identity v3 policy create ------------- Create new policy .. program:: policy create .. code:: bash os policy create [--type <type>] <filename> .. option:: --type <type> New MIME type of the policy rules file (defaults to application/json) .. describe:: <filename> New serialized policy rules file policy delete ------------- Delete policy .. program:: policy delete .. code:: bash os policy delete <policy> .. describe:: <policy> Policy to delete policy list ----------- List policies .. program:: policy list .. code:: bash os policy list [--long] .. option:: --long List additional fields in output policy set ---------- Set policy properties .. program:: policy set .. code:: bash os policy set [--type <type>] [--rules <filename>] <policy> .. option:: --type <type> New MIME type of the policy rules file .. describe:: --rules <filename> New serialized policy rules file .. describe:: <policy> Policy to modify policy show ----------- Display policy details .. program:: policy show .. code:: bash os policy show <policy> .. describe:: <policy> Policy to display <file_sep>======= project ======= Identity v2, v3 project create -------------- Create new project .. program:: project create .. code:: bash os project create [--domain <domain>] [--parent <project>] [--description <description>] [--enable | --disable] [--property <key=value>] [--or-show] <name> .. option:: --domain <domain> Domain owning the project (name or ID) .. versionadded:: 3 .. option:: --parent <project> Parent of the project (name or ID) .. versionadded:: 3 .. option:: --description <description> Project description .. option:: --enable Enable project (default) .. option:: --disable Disable project .. option:: --property <key=value> Add a property to :ref:`\<name\> <project_create-name>` (repeat option to set multiple properties) .. option:: --or-show Return existing project If the project already exists return the existing project data and do not fail. .. _project_create-name: .. describe:: <name> New project name project delete -------------- Delete project(s) .. program:: project delete .. code:: bash os project delete [--domain <domain>] <project> [<project> ...] .. option:: --domain <domain> Domain owning :ref:`\<project\> <project_delete-project>` (name or ID) .. versionadded:: 3 .. _project_delete-project: .. describe:: <project> Project to delete (name or ID) project list ------------ List projects .. program:: project list .. code:: bash os project list [--domain <domain>] [--user <user>] [--long] .. option:: --domain <domain> Filter projects by :option:`\<domain\> <--domain>` (name or ID) .. versionadded:: 3 .. option:: --user <user> Filter projects by :option:`\<user\> <--user>` (name or ID) .. versionadded:: 3 .. option:: --long List additional fields in output project set ----------- Set project properties .. program:: project set .. code:: bash os project set [--name <name>] [--domain <domain>] [--description <description>] [--enable | --disable] [--property <key=value>] <project> .. option:: --name <name> Set project name .. option:: --domain <domain> Domain owning :ref:`\<project\> <project_set-project>` (name or ID) .. versionadded:: 3 .. option:: --description <description> Set project description .. option:: --enable Enable project (default) .. option:: --disable Disable project .. option:: --property <key=value> Set a property on :ref:`\<project\> <project_set-project>` (repeat option to set multiple properties) *Identity version 2 only* .. _project_set-project: .. describe:: <project> Project to modify (name or ID) project show ------------ Display project details .. program:: project show .. code:: bash os project show [--domain <domain>] <project> .. option:: --domain <domain> Domain owning :ref:`\<project\> <project_show-project>` (name or ID) .. versionadded:: 3 .. option:: --parents Show the project\'s parents as a list .. versionadded:: 3 .. option:: --children Show project\'s subtree (children) as a list .. versionadded:: 3 .. _project_show-project: .. describe:: <project> Project to display (name or ID) project unset ------------- Unset project properties *Identity version 2 only* .. program:: project unset .. code:: bash os project unset --property <key> [--property <key> ...] <project> .. option:: --property <key> Property key to remove from project (repeat option to remove multiple properties) .. describe:: <project> Project to modify (name or ID) <file_sep># Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # import mock from openstackclient.network.v2 import security_group from openstackclient.tests.compute.v2 import fakes as compute_fakes from openstackclient.tests.network.v2 import fakes as network_fakes from openstackclient.tests import utils as tests_utils class TestSecurityGroupNetwork(network_fakes.TestNetworkV2): def setUp(self): super(TestSecurityGroupNetwork, self).setUp() # Get a shortcut to the network client self.network = self.app.client_manager.network class TestSecurityGroupCompute(compute_fakes.TestComputev2): def setUp(self): super(TestSecurityGroupCompute, self).setUp() # Get a shortcut to the compute client self.compute = self.app.client_manager.compute class TestCreateSecurityGroupNetwork(TestSecurityGroupNetwork): # The security group to be created. _security_group = \ network_fakes.FakeSecurityGroup.create_one_security_group() columns = ( 'description', 'id', 'name', 'project_id', 'rules', ) data = ( _security_group.description, _security_group.id, _security_group.name, _security_group.project_id, '', ) def setUp(self): super(TestCreateSecurityGroupNetwork, self).setUp() self.network.create_security_group = mock.Mock( return_value=self._security_group) # Get the command object to test self.cmd = security_group.CreateSecurityGroup(self.app, self.namespace) def test_create_no_options(self): self.assertRaises(tests_utils.ParserException, self.check_parser, self.cmd, [], []) def test_create_min_options(self): arglist = [ self._security_group.name, ] verifylist = [ ('name', self._security_group.name), ] parsed_args = self.check_parser(self.cmd, arglist, verifylist) columns, data = self.cmd.take_action(parsed_args) self.network.create_security_group.assert_called_once_with(**{ 'description': self._security_group.name, 'name': self._security_group.name, }) self.assertEqual(tuple(self.columns), columns) self.assertEqual(self.data, data) def test_create_all_options(self): arglist = [ '--description', self._security_group.description, self._security_group.name, ] verifylist = [ ('description', self._security_group.description), ('name', self._security_group.name), ] parsed_args = self.check_parser(self.cmd, arglist, verifylist) columns, data = self.cmd.take_action(parsed_args) self.network.create_security_group.assert_called_once_with(**{ 'description': self._security_group.description, 'name': self._security_group.name, }) self.assertEqual(tuple(self.columns), columns) self.assertEqual(self.data, data) class TestCreateSecurityGroupCompute(TestSecurityGroupCompute): # The security group to be shown. _security_group = \ compute_fakes.FakeSecurityGroup.create_one_security_group() columns = ( 'description', 'id', 'name', 'project_id', 'rules', ) data = ( _security_group.description, _security_group.id, _security_group.name, _security_group.tenant_id, '', ) def setUp(self): super(TestCreateSecurityGroupCompute, self).setUp() self.app.client_manager.network_endpoint_enabled = False self.compute.security_groups.create.return_value = self._security_group # Get the command object to test self.cmd = security_group.CreateSecurityGroup(self.app, None) def test_create_no_options(self): self.assertRaises(tests_utils.ParserException, self.check_parser, self.cmd, [], []) def test_create_min_options(self): arglist = [ self._security_group.name, ] verifylist = [ ('name', self._security_group.name), ] parsed_args = self.check_parser(self.cmd, arglist, verifylist) columns, data = self.cmd.take_action(parsed_args) self.compute.security_groups.create.assert_called_once_with( self._security_group.name, self._security_group.name) self.assertEqual(self.columns, columns) self.assertEqual(self.data, data) def test_create_all_options(self): arglist = [ '--description', self._security_group.description, self._security_group.name, ] verifylist = [ ('description', self._security_group.description), ('name', self._security_group.name), ] parsed_args = self.check_parser(self.cmd, arglist, verifylist) columns, data = self.cmd.take_action(parsed_args) self.compute.security_groups.create.assert_called_once_with( self._security_group.name, self._security_group.description) self.assertEqual(self.columns, columns) self.assertEqual(self.data, data) class TestDeleteSecurityGroupNetwork(TestSecurityGroupNetwork): # The security group to be deleted. _security_group = \ network_fakes.FakeSecurityGroup.create_one_security_group() def setUp(self): super(TestDeleteSecurityGroupNetwork, self).setUp() self.network.delete_security_group = mock.Mock(return_value=None) self.network.find_security_group = mock.Mock( return_value=self._security_group) # Get the command object to test self.cmd = security_group.DeleteSecurityGroup(self.app, self.namespace) def test_security_group_delete(self): arglist = [ self._security_group.name, ] verifylist = [ ('group', self._security_group.name), ] parsed_args = self.check_parser(self.cmd, arglist, verifylist) result = self.cmd.take_action(parsed_args) self.network.delete_security_group.assert_called_once_with( self._security_group) self.assertIsNone(result) class TestDeleteSecurityGroupCompute(TestSecurityGroupCompute): # The security group to be deleted. _security_group = \ compute_fakes.FakeSecurityGroup.create_one_security_group() def setUp(self): super(TestDeleteSecurityGroupCompute, self).setUp() self.app.client_manager.network_endpoint_enabled = False self.compute.security_groups.delete = mock.Mock(return_value=None) self.compute.security_groups.get = mock.Mock( return_value=self._security_group) # Get the command object to test self.cmd = security_group.DeleteSecurityGroup(self.app, None) def test_security_group_delete(self): arglist = [ self._security_group.name, ] verifylist = [ ('group', self._security_group.name), ] parsed_args = self.check_parser(self.cmd, arglist, verifylist) result = self.cmd.take_action(parsed_args) self.compute.security_groups.delete.assert_called_once_with( self._security_group.id) self.assertIsNone(result) class TestListSecurityGroupNetwork(TestSecurityGroupNetwork): # The security group to be listed. _security_group = \ network_fakes.FakeSecurityGroup.create_one_security_group() expected_columns = ( 'ID', 'Name', 'Description', 'Project', ) expected_data = (( _security_group.id, _security_group.name, _security_group.description, _security_group.tenant_id, ),) def setUp(self): super(TestListSecurityGroupNetwork, self).setUp() self.network.security_groups = mock.Mock( return_value=[self._security_group]) # Get the command object to test self.cmd = security_group.ListSecurityGroup(self.app, self.namespace) def test_security_group_list_no_options(self): arglist = [] verifylist = [ ('all_projects', False), ] parsed_args = self.check_parser(self.cmd, arglist, verifylist) columns, data = self.cmd.take_action(parsed_args) self.network.security_groups.assert_called_once_with() self.assertEqual(self.expected_columns, columns) self.assertEqual(self.expected_data, tuple(data)) def test_security_group_list_all_projects(self): arglist = [ '--all-projects', ] verifylist = [ ('all_projects', True), ] parsed_args = self.check_parser(self.cmd, arglist, verifylist) columns, data = self.cmd.take_action(parsed_args) self.network.security_groups.assert_called_once_with() self.assertEqual(self.expected_columns, columns) self.assertEqual(self.expected_data, tuple(data)) class TestListSecurityGroupCompute(TestSecurityGroupCompute): # The security group to be listed. _security_group = \ compute_fakes.FakeSecurityGroup.create_one_security_group() expected_columns = ( 'ID', 'Name', 'Description', ) expected_columns_all_projects = ( 'ID', 'Name', 'Description', 'Project', ) expected_data = (( _security_group.id, _security_group.name, _security_group.description, ),) expected_data_all_projects = (( _security_group.id, _security_group.name, _security_group.description, _security_group.tenant_id, ),) def setUp(self): super(TestListSecurityGroupCompute, self).setUp() self.app.client_manager.network_endpoint_enabled = False self.compute.security_groups.list.return_value = [self._security_group] # Get the command object to test self.cmd = security_group.ListSecurityGroup(self.app, None) def test_security_group_list_no_options(self): arglist = [] verifylist = [ ('all_projects', False), ] parsed_args = self.check_parser(self.cmd, arglist, verifylist) columns, data = self.cmd.take_action(parsed_args) kwargs = {'search_opts': {'all_tenants': False}} self.compute.security_groups.list.assert_called_once_with(**kwargs) self.assertEqual(self.expected_columns, columns) self.assertEqual(self.expected_data, tuple(data)) def test_security_group_list_all_projects(self): arglist = [ '--all-projects', ] verifylist = [ ('all_projects', True), ] parsed_args = self.check_parser(self.cmd, arglist, verifylist) columns, data = self.cmd.take_action(parsed_args) kwargs = {'search_opts': {'all_tenants': True}} self.compute.security_groups.list.assert_called_once_with(**kwargs) self.assertEqual(self.expected_columns_all_projects, columns) self.assertEqual(self.expected_data_all_projects, tuple(data)) class TestSetSecurityGroupNetwork(TestSecurityGroupNetwork): # The security group to be set. _security_group = \ network_fakes.FakeSecurityGroup.create_one_security_group() def setUp(self): super(TestSetSecurityGroupNetwork, self).setUp() self.network.update_security_group = mock.Mock(return_value=None) self.network.find_security_group = mock.Mock( return_value=self._security_group) # Get the command object to test self.cmd = security_group.SetSecurityGroup(self.app, self.namespace) def test_set_no_options(self): self.assertRaises(tests_utils.ParserException, self.check_parser, self.cmd, [], []) def test_set_no_updates(self): arglist = [ self._security_group.name, ] verifylist = [ ('group', self._security_group.name), ] parsed_args = self.check_parser(self.cmd, arglist, verifylist) result = self.cmd.take_action(parsed_args) self.network.update_security_group.assert_called_once_with( self._security_group, **{} ) self.assertIsNone(result) def test_set_all_options(self): new_name = 'new-' + self._security_group.name new_description = 'new-' + self._security_group.description arglist = [ '--name', new_name, '--description', new_description, self._security_group.name, ] verifylist = [ ('description', new_description), ('group', self._security_group.name), ('name', new_name), ] parsed_args = self.check_parser(self.cmd, arglist, verifylist) result = self.cmd.take_action(parsed_args) attrs = { 'description': new_description, 'name': new_name, } self.network.update_security_group.assert_called_once_with( self._security_group, **attrs ) self.assertIsNone(result) class TestSetSecurityGroupCompute(TestSecurityGroupCompute): # The security group to be set. _security_group = \ compute_fakes.FakeSecurityGroup.create_one_security_group() def setUp(self): super(TestSetSecurityGroupCompute, self).setUp() self.app.client_manager.network_endpoint_enabled = False self.compute.security_groups.update = mock.Mock(return_value=None) self.compute.security_groups.get = mock.Mock( return_value=self._security_group) # Get the command object to test self.cmd = security_group.SetSecurityGroup(self.app, None) def test_set_no_options(self): self.assertRaises(tests_utils.ParserException, self.check_parser, self.cmd, [], []) def test_set_no_updates(self): arglist = [ self._security_group.name, ] verifylist = [ ('group', self._security_group.name), ] parsed_args = self.check_parser(self.cmd, arglist, verifylist) result = self.cmd.take_action(parsed_args) self.compute.security_groups.update.assert_called_once_with( self._security_group, self._security_group.name, self._security_group.description ) self.assertIsNone(result) def test_set_all_options(self): new_name = 'new-' + self._security_group.name new_description = 'new-' + self._security_group.description arglist = [ '--name', new_name, '--description', new_description, self._security_group.name, ] verifylist = [ ('description', new_description), ('group', self._security_group.name), ('name', new_name), ] parsed_args = self.check_parser(self.cmd, arglist, verifylist) result = self.cmd.take_action(parsed_args) self.compute.security_groups.update.assert_called_once_with( self._security_group, new_name, new_description ) self.assertIsNone(result) class TestShowSecurityGroupNetwork(TestSecurityGroupNetwork): # The security group rule to be shown with the group. _security_group_rule = \ network_fakes.FakeSecurityGroupRule.create_one_security_group_rule() # The security group to be shown. _security_group = \ network_fakes.FakeSecurityGroup.create_one_security_group( attrs={'security_group_rules': [_security_group_rule._info]} ) columns = ( 'description', 'id', 'name', 'project_id', 'rules', ) data = ( _security_group.description, _security_group.id, _security_group.name, _security_group.project_id, security_group._format_network_security_group_rules( [_security_group_rule._info]), ) def setUp(self): super(TestShowSecurityGroupNetwork, self).setUp() self.network.find_security_group = mock.Mock( return_value=self._security_group) # Get the command object to test self.cmd = security_group.ShowSecurityGroup(self.app, self.namespace) def test_show_no_options(self): self.assertRaises(tests_utils.ParserException, self.check_parser, self.cmd, [], []) def test_show_all_options(self): arglist = [ self._security_group.id, ] verifylist = [ ('group', self._security_group.id), ] parsed_args = self.check_parser(self.cmd, arglist, verifylist) columns, data = self.cmd.take_action(parsed_args) self.network.find_security_group.assert_called_once_with( self._security_group.id, ignore_missing=False) self.assertEqual(self.columns, columns) self.assertEqual(self.data, data) class TestShowSecurityGroupCompute(TestSecurityGroupCompute): # The security group rule to be shown with the group. _security_group_rule = \ compute_fakes.FakeSecurityGroupRule.create_one_security_group_rule() # The security group to be shown. _security_group = \ compute_fakes.FakeSecurityGroup.create_one_security_group( attrs={'rules': [_security_group_rule._info]} ) columns = ( 'description', 'id', 'name', 'project_id', 'rules', ) data = ( _security_group.description, _security_group.id, _security_group.name, _security_group.tenant_id, security_group._format_compute_security_group_rules( [_security_group_rule._info]), ) def setUp(self): super(TestShowSecurityGroupCompute, self).setUp() self.app.client_manager.network_endpoint_enabled = False self.compute.security_groups.get.return_value = self._security_group # Get the command object to test self.cmd = security_group.ShowSecurityGroup(self.app, None) def test_show_no_options(self): self.assertRaises(tests_utils.ParserException, self.check_parser, self.cmd, [], []) def test_show_all_options(self): arglist = [ self._security_group.id, ] verifylist = [ ('group', self._security_group.id), ] parsed_args = self.check_parser(self.cmd, arglist, verifylist) columns, data = self.cmd.take_action(parsed_args) self.compute.security_groups.get.assert_called_once_with( self._security_group.id) self.assertEqual(self.columns, columns) self.assertEqual(self.data, data) <file_sep>=========== console log =========== Server console text dump Compute v2 console log show ---------------- Show server's console output .. program:: console log show .. code:: bash os console log show [--lines <num-lines>] <server> .. option:: --lines <num-lines> Number of lines to display from the end of the log (default=all) .. describe:: <server> Server to show log console log (name or ID) <file_sep>=========== console url =========== Server remote console URL Compute v2 console url show ---------------- Show server's remote console URL .. program:: console url show .. code:: bash os console url show [--novnc | --xvpvnc | --spice] <server> .. option:: --novnc Show noVNC console URL (default) .. option:: --xvpvnc Show xpvnc console URL .. option:: --spice Show SPICE console URL .. describe:: <server> Server to show URL (name or ID) <file_sep>======== ip fixed ======== Compute v2 ip fixed add ------------ Add fixed IP address to server .. program:: ip fixed add .. code:: bash os ip fixed add <network> <server> .. describe:: <network> Network to fetch an IP address from (name or ID) .. describe:: <server> Server to receive the IP address (name or ID) ip fixed remove --------------- Remove fixed IP address from server .. program:: ip fixed remove .. code:: bash os ip fixed remove <ip-address> <server> .. describe:: <ip-address> IP address to remove from server (name only) .. describe:: <server> Server to remove the IP address from (name or ID) <file_sep># Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from functional.common import test class QuotaTests(test.TestCase): """Functional tests for quota. """ # Test quota information for compute, network and volume. EXPECTED_FIELDS = ['instances', 'network', 'volumes'] PROJECT_NAME = None @classmethod def setUpClass(cls): cls.PROJECT_NAME =\ cls.get_openstack_configuration_value('auth.project_name') def test_quota_set(self): # TODO(rtheis): Add --network option once supported on set. self.openstack('quota set --instances 11 --volumes 11 ' + self.PROJECT_NAME) opts = self.get_show_opts(self.EXPECTED_FIELDS) raw_output = self.openstack('quota show ' + self.PROJECT_NAME + opts) self.assertEqual("11\n10\n11\n", raw_output) def test_quota_show(self): raw_output = self.openstack('quota show ' + self.PROJECT_NAME) for expected_field in self.EXPECTED_FIELDS: self.assertInOutput(expected_field, raw_output) <file_sep># Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # import copy import mock from openstackclient.network.v2 import security_group_rule from openstackclient.tests.compute.v2 import fakes as compute_fakes from openstackclient.tests import fakes from openstackclient.tests.network.v2 import fakes as network_fakes from openstackclient.tests import utils as tests_utils class TestSecurityGroupRuleNetwork(network_fakes.TestNetworkV2): def setUp(self): super(TestSecurityGroupRuleNetwork, self).setUp() # Get a shortcut to the network client self.network = self.app.client_manager.network class TestSecurityGroupRuleCompute(compute_fakes.TestComputev2): def setUp(self): super(TestSecurityGroupRuleCompute, self).setUp() # Get a shortcut to the network client self.compute = self.app.client_manager.compute class TestDeleteSecurityGroupRuleNetwork(TestSecurityGroupRuleNetwork): # The security group rule to be deleted. _security_group_rule = \ network_fakes.FakeSecurityGroupRule.create_one_security_group_rule() def setUp(self): super(TestDeleteSecurityGroupRuleNetwork, self).setUp() self.network.delete_security_group_rule = mock.Mock(return_value=None) self.network.find_security_group_rule = mock.Mock( return_value=self._security_group_rule) # Get the command object to test self.cmd = security_group_rule.DeleteSecurityGroupRule( self.app, self.namespace) def test_security_group_rule_delete(self): arglist = [ self._security_group_rule.id, ] verifylist = [ ('rule', self._security_group_rule.id), ] parsed_args = self.check_parser(self.cmd, arglist, verifylist) result = self.cmd.take_action(parsed_args) self.network.delete_security_group_rule.assert_called_with( self._security_group_rule) self.assertIsNone(result) class TestDeleteSecurityGroupRuleCompute(TestSecurityGroupRuleCompute): # The security group rule to be deleted. _security_group_rule = \ compute_fakes.FakeSecurityGroupRule.create_one_security_group_rule() def setUp(self): super(TestDeleteSecurityGroupRuleCompute, self).setUp() self.app.client_manager.network_endpoint_enabled = False # Get the command object to test self.cmd = security_group_rule.DeleteSecurityGroupRule(self.app, None) def test_security_group_rule_delete(self): arglist = [ self._security_group_rule.id, ] verifylist = [ ('rule', self._security_group_rule.id), ] parsed_args = self.check_parser(self.cmd, arglist, verifylist) result = self.cmd.take_action(parsed_args) self.compute.security_group_rules.delete.assert_called_with( self._security_group_rule.id) self.assertIsNone(result) class TestShowSecurityGroupRuleNetwork(TestSecurityGroupRuleNetwork): # The security group rule to be shown. _security_group_rule = \ network_fakes.FakeSecurityGroupRule.create_one_security_group_rule() columns = ( 'direction', 'ethertype', 'id', 'port_range_max', 'port_range_min', 'project_id', 'protocol', 'remote_group_id', 'remote_ip_prefix', 'security_group_id', ) data = ( _security_group_rule.direction, _security_group_rule.ethertype, _security_group_rule.id, _security_group_rule.port_range_max, _security_group_rule.port_range_min, _security_group_rule.project_id, _security_group_rule.protocol, _security_group_rule.remote_group_id, _security_group_rule.remote_ip_prefix, _security_group_rule.security_group_id, ) def setUp(self): super(TestShowSecurityGroupRuleNetwork, self).setUp() self.network.find_security_group_rule = mock.Mock( return_value=self._security_group_rule) # Get the command object to test self.cmd = security_group_rule.ShowSecurityGroupRule( self.app, self.namespace) def test_show_no_options(self): self.assertRaises(tests_utils.ParserException, self.check_parser, self.cmd, [], []) def test_show_all_options(self): arglist = [ self._security_group_rule.id, ] verifylist = [ ('rule', self._security_group_rule.id), ] parsed_args = self.check_parser(self.cmd, arglist, verifylist) columns, data = self.cmd.take_action(parsed_args) self.network.find_security_group_rule.assert_called_with( self._security_group_rule.id, ignore_missing=False) self.assertEqual(tuple(self.columns), columns) self.assertEqual(self.data, data) class TestShowSecurityGroupRuleCompute(TestSecurityGroupRuleCompute): # The security group rule to be shown. _security_group_rule = \ compute_fakes.FakeSecurityGroupRule.create_one_security_group_rule() columns, data = \ security_group_rule._format_security_group_rule_show( _security_group_rule._info) def setUp(self): super(TestShowSecurityGroupRuleCompute, self).setUp() self.app.client_manager.network_endpoint_enabled = False # Build a security group fake customized for this test. security_group_rules = [self._security_group_rule._info] security_group = fakes.FakeResource( info=copy.deepcopy({'rules': security_group_rules}), loaded=True) security_group.rules = security_group_rules self.compute.security_groups.list.return_value = [security_group] # Get the command object to test self.cmd = security_group_rule.ShowSecurityGroupRule(self.app, None) def test_show_no_options(self): self.assertRaises(tests_utils.ParserException, self.check_parser, self.cmd, [], []) def test_show_all_options(self): arglist = [ self._security_group_rule.id, ] verifylist = [ ('rule', self._security_group_rule.id), ] parsed_args = self.check_parser(self.cmd, arglist, verifylist) columns, data = self.cmd.take_action(parsed_args) self.compute.security_groups.list.assert_called_with() self.assertEqual(self.columns, columns) self.assertEqual(self.data, data) <file_sep>========= user role ========= Identity v2 user role list -------------- List user-role assignments *Removed in version 3.* .. program:: user role list .. code:: bash os user role list [--project <project>] [<user>] .. option:: --project <project> Filter users by `<project>` (name or ID) .. describe:: <user> User to list (name or ID) <file_sep>===== group ===== Identity v3 group add user -------------- Add user to group .. program:: group add user .. code:: bash os group add user [--group-domain <group-domain>] [--user-domain <user-domain>] <group> <user> .. option:: --group-domain <group-domain> Domain the group belongs to (name or ID). This can be used in case collisions between group names exist. .. versionadded:: 3 .. option:: --user-domain <user-domain> Domain the user belongs to (name or ID). This can be used in case collisions between user names exist. .. versionadded:: 3 .. describe:: <group> Group to contain <user> (name or ID) .. describe:: <user> User to add to <group> (name or ID) group contains user ------------------- Check user membership in group .. program:: group contains user .. code:: bash os group contains user [--group-domain <group-domain>] [--user-domain <user-domain>] <group> <user> .. option:: --group-domain <group-domain> Domain the group belongs to (name or ID). This can be used in case collisions between group names exist. .. versionadded:: 3 .. option:: --user-domain <user-domain> Domain the user belongs to (name or ID). This can be used in case collisions between user names exist. .. versionadded:: 3 .. describe:: <group> Group to check (name or ID) .. describe:: <user> User to check (name or ID) group create ------------ Create new group .. program:: group create .. code:: bash os group create [--domain <domain>] [--description <description>] [--or-show] <group-name> .. option:: --domain <domain> Domain to contain new group (name or ID) .. option:: --description <description> New group description .. option:: --or-show Return existing group If the group already exists, return the existing group data and do not fail. .. describe:: <group-name> New group name group delete ------------ Delete group .. program:: group delete .. code:: bash os group delete [--domain <domain>] <group> [<group> ...] .. option:: --domain <domain> Domain containing group(s) (name or ID) .. describe:: <group> Group(s) to delete (name or ID) group list ---------- List groups .. program:: group list .. code:: bash os group list [--domain <domain>] [--user <user> [--user-domain <user-domain>]] [--long] .. option:: --domain <domain> Filter group list by <domain> (name or ID) .. option:: --user <user> Filter group list by <user> (name or ID) .. option:: --user-domain <user-domain> Domain the user belongs to (name or ID). This can be used in case collisions between user names exist. .. versionadded:: 3 .. option:: --long List additional fields in output group remove user ----------------- Remove user from group .. program:: group remove user .. code:: bash os group remove user [--group-domain <group-domain>] [--user-domain <user-domain>] <group> <user> .. option:: --group-domain <group-domain> Domain the group belongs to (name or ID). This can be used in case collisions between group names exist. .. versionadded:: 3 .. option:: --user-domain <user-domain> Domain the user belongs to (name or ID). This can be used in case collisions between user names exist. .. versionadded:: 3 .. describe:: <group> Group containing <user> (name or ID) .. describe:: <user> User to remove from <group> (name or ID) group set --------- Set group properties .. program:: group set .. code:: bash os group set [--domain <domain>] [--name <name>] [--description <description>] <group> .. option:: --domain <domain> Domain containing <group> (name or ID) .. option:: --name <name> New group name .. option:: --description <description> New group description .. describe:: <group> Group to modify (name or ID) group show ---------- Display group details .. program:: group show .. code:: bash os group show [--domain <domain>] <group> .. option:: --domain <domain> Domain containing <group> (name or ID) .. describe:: <group> Group to display (name or ID) <file_sep>=================== federation protocol =================== Identity v3 `Requires: OS-FEDERATION extension` federation protocol create -------------------------- Create new federation protocol .. program:: federation protocol create .. code:: bash os federation protocol create --identity-provider <identity-provider> --mapping <mapping> <name> .. option:: --identity-provider <identity-provider> Identity provider that will support the new federation protocol (name or ID) (required) .. option:: --mapping <mapping> Mapping that is to be used (name or ID) (required) .. describe:: <name> New federation protocol name (must be unique per identity provider) federation protocol delete -------------------------- Delete federation protocol .. program:: federation protocol delete .. code:: bash os federation protocol delete --identity-provider <identity-provider> <federation-protocol> .. option:: --identity-provider <identity-provider> Identity provider that supports <federation-protocol> (name or ID) (required) .. describe:: <federation-protocol> Federation protocol to delete (name or ID) federation protocol list ------------------------ List federation protocols .. program:: federation protocol list .. code:: bash os federation protocol list --identity-provider <identity-provider> .. option:: --identity-provider <identity-provider> Identity provider to list (name or ID) (required) federation protocol set ----------------------- Set federation protocol properties .. program:: federation protocol set .. code:: bash os federation protocol set --identity-provider <identity-provider> [--mapping <mapping>] <federation-protocol> .. option:: --identity-provider <identity-provider> Identity provider that supports <federation-protocol> (name or ID) (required) .. option:: --mapping <mapping> Mapping that is to be used (name or ID) .. describe:: <federation-protocol> Federation protocol to modify (name or ID) federation protocol show ------------------------ Display federation protocol details .. program:: federation protocol show .. code:: bash os federation protocol show --identity-provider <identity-provider> <federation-protocol> .. option:: --identity-provider <identity-provider> Identity provider that supports <federation-protocol> (name or ID) (required) .. describe:: <federation-protocol> Federation protocol to display (name or ID) <file_sep>======= service ======= Identity v2, v3 service create -------------- Create new service .. program:: service create .. code-block:: bash os service create [--name <name>] [--description <description>] [--enable | --disable] <type> .. option:: --name <name> New service name .. option:: --description <description> New service description .. option:: --enable Enable service (default) *Identity version 3 only* .. option:: --disable Disable service *Identity version 3 only* .. _service_create-type: .. describe:: <type> New service type (compute, image, identity, volume, etc) service delete -------------- Delete service .. program:: service delete .. code-block:: bash os service delete <service> .. _service_delete-type: .. describe:: <service> Service to delete (type, name or ID) service list ------------ List services .. program:: service list .. code-block:: bash os service list [--long] .. option:: --long List additional fields in output Returns service fields ID, Name and Type. :option:`--long` adds Description and Enabled (*Identity version 3 only*) to the output. service set ----------- Set service properties * Identity version 3 only* .. program:: service set .. code-block:: bash os service set [--type <type>] [--name <name>] [--description <description>] [--enable | --disable] <service> .. option:: --type <type> New service type (compute, image, identity, volume, etc) .. option:: --name <name> New service name .. option:: --description <description> New service description .. option:: --enable Enable service .. option:: --disable Disable service .. _service_set-service: .. describe:: <service> Service to update (type, name or ID) service show ------------ Display service details .. program:: service show .. code-block:: bash os service show [--catalog] <service> .. option:: --catalog Show service catalog information *Identity version 2 only* .. _service_show-service: .. describe:: <service> Service to display (type, name or ID) <file_sep>================= identity provider ================= Identity v3 `Requires: OS-FEDERATION extension` identity provider create ------------------------ Create new identity provider .. program:: identity provider create .. code:: bash os identity provider create [--remote-id <remote-id> [...] | --remote-id-file <file-name>] [--description <description>] [--enable | --disable] <name> .. option:: --remote-id <remote-id> Remote IDs to associate with the Identity Provider (repeat to provide multiple values) .. option:: --remote-id-file <file-name> Name of a file that contains many remote IDs to associate with the identity provider, one per line .. option:: --description New identity provider description .. option:: --enable Enable the identity provider (default) .. option:: --disable Disable the identity provider .. describe:: <name> New identity provider name (must be unique) identity provider delete ------------------------ Delete identity provider .. program:: identity provider delete .. code:: bash os identity provider delete <identity-provider> .. describe:: <identity-provider> Identity provider to delete identity provider list ---------------------- List identity providers .. program:: identity provider list .. code:: bash os identity provider list identity provider set --------------------- Set identity provider properties .. program:: identity provider set .. code:: bash os identity provider set [--remote-id <remote-id> [...] | --remote-id-file <file-name>] [--description <description>] [--enable | --disable] <identity-provider> .. option:: --remote-id <remote-id> Remote IDs to associate with the Identity Provider (repeat to provide multiple values) .. option:: --remote-id-file <file-name> Name of a file that contains many remote IDs to associate with the identity provider, one per line .. option:: --description Set identity provider description .. option:: --enable Enable the identity provider .. option:: --disable Disable the identity provider .. describe:: <identity-provider> Identity provider to modify identity provider show ---------------------- Display identity provider details .. program:: identity provider show .. code:: bash os identity provider show <identity-provider> .. describe:: <identity-provider> Identity provider to display <file_sep>====== backup ====== Block Storage v1 backup create ------------- Create new backup .. program:: backup create .. code:: bash os backup create [--container <container>] [--name <name>] [--description <description>] <volume> .. option:: --container <container> Optional backup container name .. option:: --name <name> Name of the backup .. option:: --description <description> Description of the backup .. _backup_create-backup: .. describe:: <volume> Volume to backup (name or ID) backup delete ------------- Delete backup(s) .. program:: backup delete .. code:: bash os backup delete <backup> [<backup> ...] .. _backup_delete-backup: .. describe:: <backup> Backup(s) to delete (ID only) backup list ----------- List backups .. program:: backup list .. code:: bash os backup list .. _backup_list-backup: .. option:: --long List additional fields in output backup restore -------------- Restore backup .. program:: backup restore .. code:: bash os backup restore <backup> <volume> .. _backup_restore-backup: .. describe:: <backup> Backup to restore (ID only) .. describe:: <volume> Volume to restore to (name or ID) backup show ----------- Display backup details .. program:: backup show .. code:: bash os backup show <backup> .. _backup_show-backup: .. describe:: <backup> Backup to display (ID only) <file_sep>============= compute agent ============= Compute v2 compute agent create -------------------- Create compute agent .. program:: compute agent create .. code:: bash os compute agent create <os> <architecture> <version> <url> <md5hash> <hypervisor> .. _compute_agent-create: .. describe:: <os> Type of OS .. describe:: <architecture> Type of architecture .. describe:: <version> Version .. describe:: <url> URL .. describe:: <md5hash> MD5 hash .. describe:: <hypervisor> Type of hypervisor compute agent delete -------------------- Delete compute agent command .. program:: compute agent delete .. code:: bash os compute agent delete <id> .. _compute_agent-delete: .. describe:: <id> ID of agent to delete compute agent list ------------------ List compute agent command .. program:: compute agent list .. code:: bash os compute agent list [--hypervisor <hypervisor>] .. _compute_agent-list: .. describe:: --hypervisor <hypervisor> Optional type of hypervisor compute agent set ----------------- Set compute agent command .. program:: agent set .. code:: bash os compute agent set <id> <version> <url> <md5hash> .. _compute_agent-set: .. describe:: <id> ID of the agent .. describe:: <version> Version of the agent .. describe:: <url> URL .. describe:: <md5hash> MD5 hash <file_sep># Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # import argparse import mock from openstackclient.network import common from openstackclient.tests import utils def _add_common_argument(parser): parser.add_argument( 'common', metavar='<common>', help='Common argument', ) return parser def _add_network_argument(parser): parser.add_argument( 'network', metavar='<network>', help='Network argument', ) return parser def _add_compute_argument(parser): parser.add_argument( 'compute', metavar='<compute>', help='Compute argument', ) return parser class FakeNetworkAndComputeCommand(common.NetworkAndComputeCommand): def update_parser_common(self, parser): return _add_common_argument(parser) def update_parser_network(self, parser): return _add_network_argument(parser) def update_parser_compute(self, parser): return _add_compute_argument(parser) def take_action_network(self, client, parsed_args): return client.network_action(parsed_args) def take_action_compute(self, client, parsed_args): return client.compute_action(parsed_args) class FakeNetworkAndComputeLister(common.NetworkAndComputeLister): def update_parser_common(self, parser): return _add_common_argument(parser) def update_parser_network(self, parser): return _add_network_argument(parser) def update_parser_compute(self, parser): return _add_compute_argument(parser) def take_action_network(self, client, parsed_args): return client.network_action(parsed_args) def take_action_compute(self, client, parsed_args): return client.compute_action(parsed_args) class FakeNetworkAndComputeShowOne(common.NetworkAndComputeShowOne): def update_parser_common(self, parser): return _add_common_argument(parser) def update_parser_network(self, parser): return _add_network_argument(parser) def update_parser_compute(self, parser): return _add_compute_argument(parser) def take_action_network(self, client, parsed_args): return client.network_action(parsed_args) def take_action_compute(self, client, parsed_args): return client.compute_action(parsed_args) class TestNetworkAndCompute(utils.TestCommand): def setUp(self): super(TestNetworkAndCompute, self).setUp() self.namespace = argparse.Namespace() # Create network client mocks. self.app.client_manager.network = mock.Mock() self.network = self.app.client_manager.network self.network.network_action = mock.Mock( return_value='take_action_network') # Create compute client mocks. self.app.client_manager.compute = mock.Mock() self.compute = self.app.client_manager.compute self.compute.compute_action = mock.Mock( return_value='take_action_compute') # Subclasses can override the command object to test. self.cmd = FakeNetworkAndComputeCommand(self.app, self.namespace) def test_take_action_network(self): arglist = [ 'common', 'network' ] verifylist = [ ('common', 'common'), ('network', 'network') ] parsed_args = self.check_parser(self.cmd, arglist, verifylist) result = self.cmd.take_action(parsed_args) self.network.network_action.assert_called_with(parsed_args) self.assertEqual('take_action_network', result) def test_take_action_compute(self): arglist = [ 'common', 'compute' ] verifylist = [ ('common', 'common'), ('compute', 'compute') ] self.app.client_manager.network_endpoint_enabled = False parsed_args = self.check_parser(self.cmd, arglist, verifylist) result = self.cmd.take_action(parsed_args) self.compute.compute_action.assert_called_with(parsed_args) self.assertEqual('take_action_compute', result) class TestNetworkAndComputeCommand(TestNetworkAndCompute): def setUp(self): super(TestNetworkAndComputeCommand, self).setUp() self.cmd = FakeNetworkAndComputeCommand(self.app, self.namespace) class TestNetworkAndComputeLister(TestNetworkAndCompute): def setUp(self): super(TestNetworkAndComputeLister, self).setUp() self.cmd = FakeNetworkAndComputeLister(self.app, self.namespace) class TestNetworkAndComputeShowOne(TestNetworkAndCompute): def setUp(self): super(TestNetworkAndComputeShowOne, self).setUp() self.cmd = FakeNetworkAndComputeShowOne(self.app, self.namespace) <file_sep>======= command ======= Internal Installed commands in the OSC process. command list ------------ List recognized commands by group .. program:: command list .. code:: bash os command list <file_sep>====== server ====== Compute v2 server add security group ------------------------- Add security group to server .. program:: server add security group .. code:: bash os server add security group <server> <group> .. describe:: <server> Server (name or ID) .. describe:: <group> Security group to add (name or ID) server add volume ----------------- Add volume to server .. program:: server add volume .. code:: bash os server add volume [--device <device>] <server> <volume> .. option:: --device <device> Server internal device name for volume .. describe:: <server> Server (name or ID) .. describe:: <volume> Volume to add (name or ID) server create ------------- Create a new server .. program:: server create .. code:: bash os server create --image <image> | --volume <volume> --flavor <flavor> [--security-group <security-group-name> [...] ] [--key-name <key-name>] [--property <key=value> [...] ] [--file <dest-filename=source-filename>] [...] ] [--user-data <user-data>] [--availability-zone <zone-name>] [--block-device-mapping <dev-name=mapping> [...] ] [--nic <net-id=net-uuid,v4-fixed-ip=ip-addr,v6-fixed-ip=ip-addr,port-id=port-uuid> [...] ] [--hint <key=value> [...] ] [--config-drive <value>|True ] [--min <count>] [--max <count>] [--wait] <server-name> .. option:: --image <image> Create server from this image (name or ID) .. option:: --volume <volume> Create server from this volume (name or ID) .. option:: --flavor <flavor> Create server with this flavor (name or ID) .. option:: --security-group <security-group-name> Security group to assign to this server (name or ID) (repeat for multiple groups) .. option:: --key-name <key-name> Keypair to inject into this server (optional extension) .. option:: --property <key=value> Set a property on this server (repeat for multiple values) .. option:: --file <dest-filename=source-filename> File to inject into image before boot (repeat for multiple files) .. option:: --user-data <user-data> User data file to serve from the metadata server .. option:: --availability-zone <zone-name> Select an availability zone for the server .. option:: --block-device-mapping <dev-name=mapping> Map block devices; map is <id>:<type>:<size(GB)>:<delete_on_terminate> (optional extension) .. option:: --nic <net-id=net-uuid,v4-fixed-ip=ip-addr,v6-fixed-ip=ip-addr,port-id=port-uuid> Create a NIC on the server. Specify option multiple times to create multiple NICs. Either net-id or port-id must be provided, but not both. net-id: attach NIC to network with this UUID, port-id: attach NIC to port with this UUID, v4-fixed-ip: IPv4 fixed address for NIC (optional), v6-fixed-ip: IPv6 fixed address for NIC (optional). .. option:: --hint <key=value> Hints for the scheduler (optional extension) .. option:: --config-drive <config-drive-volume>|True Use specified volume as the config drive, or 'True' to use an ephemeral drive .. option:: --min <count> Minimum number of servers to launch (default=1) .. option:: --max <count> Maximum number of servers to launch (default=1) .. option:: --wait Wait for build to complete .. describe:: <server-name> New server name server delete ------------- Delete server(s) .. program:: server delete .. code:: bash os server delete <server> [<server> ...] [--wait] .. option:: --wait Wait for delete to complete .. describe:: <server> Server(s) to delete (name or ID) server dump create ------------------ Create a dump file in server(s) Trigger crash dump in server(s) with features like kdump in Linux. It will create a dump file in the server(s) dumping the server(s)' memory, and also crash the server(s). OSC sees the dump file (server dump) as a kind of resource. .. program:: server dump create .. code:: bash os server dump create <server> [<server> ...] .. describe:: <server> Server(s) to create dump file (name or ID) server list ----------- List servers .. code:: bash os server list [--reservation-id <reservation-id>] [--ip <ip-address-regex>] [--ip6 <ip6-address-regex>] [--name <name-regex>] [--instance-name <instance-name-regex>] [--status <status>] [--flavor <flavor>] [--image <image>] [--host <hostname>] [--all-projects] [--project <project> [--project-domain <project-domain>]] [--long] [--marker <server>] [--limit <limit>] .. option:: --reservation-id <reservation-id> Only return instances that match the reservation .. option:: --ip <ip-address-regex> Regular expression to match IP addresses .. option:: --ip6 <ip-address-regex> Regular expression to match IPv6 addresses .. option:: --name <name-regex> Regular expression to match names .. option:: --instance-name <server-name-regex> Regular expression to match instance name (admin only) .. option:: --status <status> Search by server status .. option:: --flavor <flavor> Search by flavor (name or ID) .. option:: --image <image> Search by image (name or ID) .. option:: --host <hostname> Search by hostname .. option:: --all-projects Include all projects (admin only) .. option:: --project <project> Search by project (admin only) (name or ID) .. option:: --project-domain <project-domain> Domain the project belongs to (name or ID). This can be used in case collisions between project names exist. .. option:: --user <user> Search by user (admin only) (name or ID) .. option:: --user-domain <user-domain> Domain the user belongs to (name or ID). This can be used in case collisions between user names exist. .. option:: --long List additional fields in output .. option:: --marker <server> The last server (name or ID) of the previous page. Display list of servers after marker. Display all servers if not specified. .. option:: --limit <limit> Maximum number of servers to display. If limit equals -1, all servers will be displayed. If limit is greater than 'osapi_max_limit' option of Nova API, 'osapi_max_limit' will be used instead. server lock ----------- Lock server(s). A non-admin user will not be able to execute actions .. program:: server lock .. code:: bash os server lock <server> [<server> ...] .. describe:: <server> Server(s) to lock (name or ID) server migrate -------------- Migrate server to different host .. program:: server migrate .. code:: bash os server migrate --live <host> [--shared-migration | --block-migration] [--disk-overcommit | --no-disk-overcommit] [--wait] <server> .. option:: --live <hostname> Target hostname .. option:: --shared-migration Perform a shared live migration (default) .. option:: --block-migration Perform a block live migration .. option:: --disk-overcommit Allow disk over-commit on the destination host .. option:: --no-disk-overcommit Do not over-commit disk on the destination host (default) .. option:: --wait Wait for resize to complete .. describe:: <server> Server to migrate (name or ID) server pause ------------ Pause server(s) .. program:: server pause .. code:: bash os server pause <server> [<server> ...] .. describe:: <server> Server(s) to pause (name or ID) server reboot ------------- Perform a hard or soft server reboot .. program:: server reboot .. code:: bash os server reboot [--hard | --soft] [--wait] <server> .. option:: --hard Perform a hard reboot .. option:: --soft Perform a soft reboot .. option:: --wait Wait for reboot to complete .. describe:: <server> Server (name or ID) server rebuild -------------- Rebuild server .. program:: server rebuild .. code:: bash os server rebuild [--image <image>] [--password <<PASSWORD>>] [--wait] <server> .. option:: --image <image> Recreate server from the specified image (name or ID). Defaults to the currently used one. .. option:: --password <<PASSWORD>> Set the password on the rebuilt instance .. option:: --wait Wait for rebuild to complete .. describe:: <server> Server (name or ID) server remove security group ---------------------------- Remove security group from server .. program:: server remove security group .. code:: bash os server remove security group <server> <group> .. describe:: <server> Name or ID of server to use .. describe:: <group> Name or ID of security group to remove from server server remove volume -------------------- Remove volume from server .. program:: server remove volume .. code:: bash os server remove volume <server> <volume> .. describe:: <server> Server (name or ID) .. describe:: <volume> Volume to remove (name or ID) server rescue ------------- Put server in rescue mode .. program:: server rescure .. code:: bash os server rescue <server> .. describe:: <server> Server (name or ID) server resize ------------- Scale server to a new flavor .. program:: server resize .. code:: bash os server resize --flavor <flavor> [--wait] <server> os server resize --confirm | --revert <server> .. option:: --flavor <flavor> Resize server to specified flavor .. option:: --confirm Confirm server resize is complete .. option:: --revert Restore server state before resize .. option:: --wait Wait for resize to complete .. describe:: <server> Server (name or ID) A resize operation is implemented by creating a new server and copying the contents of the original disk into a new one. It is also a two-step process for the user: the first is to perform the resize, the second is to either confirm (verify) success and release the old server, or to declare a revert to release the new server and restart the old one. server restore -------------- Restore server(s) from soft-deleted state .. program:: server restore .. code:: bash os server restore <server> [<server> ...] .. describe:: <server> Server(s) to restore (name or ID) server resume ------------- Resume server(s) .. program:: server resume .. code:: bash os server resume <server> [<server> ...] .. describe:: <server> Server(s) to resume (name or ID) server set ---------- Set server properties .. program:: server set .. code:: bash os server set --name <new-name> --property <key=value> [--property <key=value>] ... --root-password <server> .. option:: --name <new-name> New server name .. option:: --root-password Set new root password (interactive only) .. option:: --property <key=value> Property to add/change for this server (repeat option to set multiple properties) .. describe:: <server> Server (name or ID) server shelve ------------- Shelve server(s) .. program:: server shelve .. code:: bash os server shelve <server> [<server> ...] .. describe:: <server> Server(s) to shelve (name or ID) server show ----------- Show server details .. program:: server show .. code:: bash os server show [--diagnostics] <server> .. option:: --diagnostics Display server diagnostics information .. describe:: <server> Server (name or ID) server ssh ---------- SSH to server .. program:: server ssh .. code:: bash os server ssh [--login <login-name>] [--port <port>] [--identity <keyfile>] [--option <config-options>] [--public | --private | --address-type <address-type>] <server> .. option:: --login <login-name> Login name (ssh -l option) .. option:: --port <port> Destination port (ssh -p option) .. option:: --identity <keyfile> Private key file (ssh -i option) .. option:: --option <config-options> Options in ssh_config(5) format (ssh -o option) .. option:: --public Use public IP address .. option:: --private Use private IP address .. option:: --address-type <address-type> Use other IP address (public, private, etc) .. describe:: <server> Server (name or ID) server start ------------ Start server(s) .. program:: server start .. code:: bash os server start <server> [<server> ...] .. describe:: <server> Server(s) to start (name or ID) server stop ----------- Stop server(s) .. program:: server stop .. code:: bash os server stop <server> [<server> ...] .. describe:: <server> Server(s) to stop (name or ID) server suspend -------------- Suspend server(s) .. program:: server suspend .. code:: bash os server suspend <server> [<server> ...] .. describe:: <server> Server(s) to suspend (name or ID) server unlock ------------- Unlock server(s) .. program:: server unlock .. code:: bash os server unlock <server> [<server> ...] .. describe:: <server> Server(s) to unlock (name or ID) server unpause -------------- Unpause server(s) .. program:: server unpause .. code:: bash os server unpause <server> [<server> ...] .. describe:: <server> Server(s) to unpause (name or ID) server unrescue --------------- Restore server from rescue mode .. program:: server unrescue .. code:: bash os server unrescue <server> .. describe:: <server> Server (name or ID) server unset ------------ Unset server properties .. program:: server unset .. code:: bash os server unset --property <key> [--property <key>] ... <server> .. option:: --property <key> Property key to remove from server (repeat to set multiple values) .. describe:: <server> Server (name or ID) server unshelve --------------- Unshelve server(s) .. program:: server unshelve .. code:: bash os server unshelve <server> [<server> ...] .. describe:: <server> Server(s) to unshelve (name or ID) <file_sep># Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # """IP Floating action implementations""" from openstackclient.common import utils from openstackclient.network import common def _get_columns(item): columns = item.keys() if 'tenant_id' in columns: columns.remove('tenant_id') columns.append('project_id') return tuple(sorted(columns)) class DeleteFloatingIP(common.NetworkAndComputeCommand): """Delete floating IP""" def update_parser_common(self, parser): parser.add_argument( 'floating_ip', metavar="<floating-ip>", help=("Floating IP to delete (IP address or ID)") ) return parser def take_action_network(self, client, parsed_args): obj = client.find_ip(parsed_args.floating_ip) client.delete_ip(obj) def take_action_compute(self, client, parsed_args): obj = utils.find_resource( client.floating_ips, parsed_args.floating_ip, ) client.floating_ips.delete(obj.id) class ListFloatingIP(common.NetworkAndComputeLister): """List floating IP(s)""" def take_action_network(self, client, parsed_args): columns = ( 'id', 'floating_ip_address', 'fixed_ip_address', 'port_id', ) headers = ( 'ID', 'Floating IP Address', 'Fixed IP Address', 'Port', ) query = {} data = client.ips(**query) return (headers, (utils.get_item_properties( s, columns, formatters={}, ) for s in data)) def take_action_compute(self, client, parsed_args): columns = ( 'ID', 'IP', 'Fixed IP', 'Instance ID', 'Pool', ) headers = ( 'ID', 'Floating IP Address', 'Fixed IP Address', 'Server', 'Pool', ) data = client.floating_ips.list() return (headers, (utils.get_item_properties( s, columns, formatters={}, ) for s in data)) class ShowFloatingIP(common.NetworkAndComputeShowOne): """Show floating IP details""" def update_parser_common(self, parser): parser.add_argument( 'floating_ip', metavar="<floating-ip>", help=("Floating IP to display (IP address or ID)") ) return parser def take_action_network(self, client, parsed_args): obj = client.find_ip(parsed_args.floating_ip, ignore_missing=False) columns = _get_columns(obj) data = utils.get_item_properties(obj, columns) return (columns, data) def take_action_compute(self, client, parsed_args): obj = utils.find_resource( client.floating_ips, parsed_args.floating_ip, ) columns = _get_columns(obj._info) data = utils.get_dict_properties(obj._info, columns) return (columns, data) <file_sep>============== security group ============== Compute v2, Network v2 security group create --------------------- Create a new security group .. program:: security group create .. code:: bash os security group create [--description <description>] <name> .. option:: --description <description> Security group description .. describe:: <name> New security group name security group delete --------------------- Delete a security group .. program:: security group delete .. code:: bash os security group delete <group> .. describe:: <group> Security group to delete (name or ID) security group list ------------------- List security groups .. program:: security group list .. code:: bash os security group list [--all-projects] .. option:: --all-projects Display information from all projects (admin only) *Network version 2 ignores this option and will always display information* *for all projects.* security group set ------------------ Set security group properties .. program:: security group set .. code:: bash os security group set [--name <new-name>] [--description <description>] <group> .. option:: --name <new-name> New security group name .. option:: --description <description> New security group description .. describe:: <group> Security group to modify (name or ID) security group show ------------------- Display security group details .. program:: security group show .. code:: bash os security group show <group> .. describe:: <group> Security group to display (name or ID) <file_sep>================ ip floating pool ================ Compute v2 ip floating pool list --------------------- List pools of floating IP addresses .. program:: ip floating pool list .. code:: bash os ip floating pool list <file_sep>==== role ==== Identity v2, v3 role add -------- Add role to a user or group in a project or domain .. program:: role add .. code:: bash os role add --domain <domain> | --project <project> [--project-domain <project-domain>] --user <user> [--user-domain <user-domain>] | --group <group> [--group-domain <group-domain>] --inherited <role> .. option:: --domain <domain> Include <domain> (name or ID) .. versionadded:: 3 .. option:: --project <project> Include <project> (name or ID) .. option:: --user <user> Include <user> (name or ID) .. option:: --group <group> Include <group> (name or ID) .. versionadded:: 3 .. option:: --user-domain <user-domain> Domain the user belongs to (name or ID). This can be used in case collisions between user names exist. .. versionadded:: 3 .. option:: --group-domain <group-domain> Domain the group belongs to (name or ID). This can be used in case collisions between group names exist. .. versionadded:: 3 .. option:: --project-domain <project-domain> Domain the project belongs to (name or ID). This can be used in case collisions between project names exist. .. versionadded:: 3 .. option:: --inherited Specifies if the role grant is inheritable to the sub projects. .. versionadded:: 3 .. describe:: <role> Role to add to <project>:<user> (name or ID) role create ----------- Create new role .. program:: role create .. code:: bash os role create [--or-show] <name> .. option:: --or-show Return existing role If the role already exists return the existing role data and do not fail. .. describe:: <name> New role name role delete ----------- Delete role(s) .. program:: role delete .. code:: bash os role delete <role> [<role> ...] .. describe:: <role> Role to delete (name or ID) role list --------- List roles .. program:: role list .. code:: bash os role list --domain <domain> | --project <project> [--project-domain <project-domain>] --user <user> [--user-domain <user-domain>] | --group <group> [--group-domain <group-domain>] --inherited .. option:: --domain <domain> Filter roles by <domain> (name or ID) .. versionadded:: 3 .. option:: --project <project> Filter roles by <project> (name or ID) .. versionadded:: 3 .. option:: --user <user> Filter roles by <user> (name or ID) .. versionadded:: 3 .. option:: --group <group> Filter roles by <group> (name or ID) .. versionadded:: 3 .. option:: --user-domain <user-domain> Domain the user belongs to (name or ID). This can be used in case collisions between user names exist. .. versionadded:: 3 .. option:: --group-domain <group-domain> Domain the group belongs to (name or ID). This can be used in case collisions between group names exist. .. versionadded:: 3 .. option:: --project-domain <project-domain> Domain the project belongs to (name or ID). This can be used in case collisions between project names exist. .. versionadded:: 3 .. option:: --inherited Specifies if the role grant is inheritable to the sub projects. .. versionadded:: 3 role remove ----------- Remove role from domain/project : user/group .. program:: role remove .. code:: bash os role remove --domain <domain> | --project <project> [--project-domain <project-domain>] --user <user> [--user-domain <user-domain>] | --group <group> [--group-domain <group-domain>] --inherited <role> .. option:: --domain <domain> Include <domain> (name or ID) .. versionadded:: 3 .. option:: --project <project> Include <project> (name or ID) .. option:: --user <user> Include <user> (name or ID) .. option:: --group <group> Include <group> (name or ID) .. versionadded:: 3 .. option:: --user-domain <user-domain> Domain the user belongs to (name or ID). This can be used in case collisions between user names exist. .. versionadded:: 3 .. option:: --group-domain <group-domain> Domain the group belongs to (name or ID). This can be used in case collisions between group names exist. .. versionadded:: 3 .. option:: --project-domain <project-domain> Domain the project belongs to (name or ID). This can be used in case collisions between project names exist. .. versionadded:: 3 .. option:: --inherited Specifies if the role grant is inheritable to the sub projects. .. versionadded:: 3 .. describe:: <role> Role to remove (name or ID) role set -------- Set role properties .. versionadded:: 3 .. program:: role set .. code:: bash os role set [--name <name>] <role> .. option:: --name <name> Set role name .. describe:: <role> Role to modify (name or ID) role show --------- Display role details .. program:: role show .. code:: bash os role show <role> .. describe:: <role> Role to display (name or ID) <file_sep>=============== compute service =============== Compute v2 compute service delete ---------------------- Delete service command .. program:: compute service delete .. code:: bash os compute service delete <service> .. _compute-service-delete: .. describe:: <service> Compute service to delete (ID only) compute service list -------------------- List service command .. program:: compute service list .. code:: bash os compute service list [--host <host>] [--service <service>] .. _compute-service-list: .. describe:: --host <host> Name of host .. describe:: --service <service> Name of service compute service set ------------------- Set service command .. program:: compute service set .. code:: bash os compute service set [--enable | --disable] [--disable-reason <reason>] <host> <service> .. _compute-service-set: .. option:: --enable Enable service (default) .. option:: --disable Disable service .. option:: --disable-reason <reason> Reason for disabling the service (in quotes) .. describe:: <host> Name of host .. describe:: <service> Name of service <file_sep>============ server image ============ A server image is a disk image created from a running server instance. The image is created in the Image store. Compute v2 server image create ------------------- Create a new disk image from a running server .. program:: server image create .. code:: bash os server image create [--name <image-name>] [--wait] <server> .. option:: --name <image-name> Name of new image (default is server name) .. option:: --wait Wait for image create to complete .. describe:: <server> Server (name or ID) <file_sep>========= container ========= Object Storage v1 container create ---------------- Create new container .. program:: container create .. code:: bash os container create <container-name> [<container-name> ...] .. describe:: <container-name> New container name(s) container delete ---------------- Delete container .. program:: container delete .. code:: bash os container delete [-r] | [--recursive] <container> [<container> ...] .. option:: --recursive, -r Recursively delete objects in container before container delete .. describe:: <container> Container(s) to delete container list -------------- List containers .. program:: container list .. code:: bash os container list [--prefix <prefix>] [--marker <marker>] [--end-marker <end-marker>] [--limit <limit>] [--long] [--all] .. option:: --prefix <prefix> Filter list using <prefix> .. option:: --marker <marker> Anchor for paging .. option:: --end-marker <end-marker> End anchor for paging .. option:: --limit <limit> Limit the number of containers returned .. option:: --long List additional fields in output .. option:: --all List all containers (default is 10000) container save -------------- Save container contents locally .. program:: container save .. code:: bash os container save <container> .. describe:: <container> Container to save container set ------------- Set container properties .. program:: container set .. code:: bash os container set [--property <key=value> [...] ] [<container>] .. option:: --property <key=value> Set a property on this container (repeat option to set multiple properties) .. describe:: <container> Container to modify container show -------------- Display container details .. program:: container show .. code:: bash os container show [<container>] .. describe:: <container> Container to display container unset --------------- Unset container properties .. program:: container unset .. code:: bash os container unset [--property <key>] [<container>] .. option:: --property <key> Property to remove from container (repeat option to remove multiple properties) .. describe:: <container> Container to modify <file_sep>======= keypair ======= The badly named keypair is really the public key of an OpenSSH key pair to be used for access to created servers. Compute v2 keypair create -------------- Create new public key .. program:: keypair create .. code:: bash os keypair create [--public-key <file>] <name> .. option:: --public-key <file> Filename for public key to add .. describe:: <name> New public key name keypair delete -------------- Delete public key .. program:: keypair delete .. code:: bash os keypair delete <key> .. describe:: <key> Public key to delete keypair list ------------ List public key fingerprints .. program:: keypair list .. code:: bash os keypair list keypair show ------------ Display public key details .. program:: keypair show .. code:: bash os keypair show [--public-key] <key> .. option:: --public-key Show only bare public key .. describe:: <key> Public key to display <file_sep>======= mapping ======= Identity v3 `Requires: OS-FEDERATION extension` mapping create -------------- Create new mapping .. program:: mapping create .. code:: bash os mapping create --rules <filename> <name> .. option:: --rules <filename> Filename that contains a set of mapping rules (required) .. _mapping_create-mapping: .. describe:: <name> New mapping name (must be unique) mapping delete -------------- Delete mapping .. program:: mapping delete .. code:: bash os mapping delete <mapping> .. _mapping_delete-mapping: .. describe:: <mapping> Mapping to delete mapping list ------------ List mappings .. program:: mapping list .. code:: bash os mapping list mapping set ----------- Set mapping properties .. program:: mapping set .. code:: bash os mapping set [--rules <filename>] <mapping> .. option:: --rules <filename> Filename that contains a new set of mapping rules .. _mapping_set-mapping: .. describe:: <mapping> Mapping to modify mapping show ------------ Display mapping details .. program:: mapping show .. code:: bash os mapping show <mapping> .. _mapping_show-mapping: .. describe:: <mapping> Mapping to display <file_sep>========= aggregate ========= Server aggregates provide a mechanism to group servers according to certain criteria. Compute v2 aggregate add host ------------------ Add host to aggregate .. program:: aggregate add host .. code:: bash os aggregate add host <aggregate> <host> .. _aggregate_add_host-aggregate: .. describe:: <aggregate> Aggregate (name or ID) .. describe:: <host> Host to add to :ref:`\<aggregate\> <aggregate_add_host-aggregate>` aggregate create ---------------- Create a new aggregate .. program:: aggregate create .. code:: bash os aggregate create [--zone <availability-zone>] [--property <key=value>] <name> .. option:: --zone <availability-zone> Availability zone name .. option:: --property <key=value> Property to add to this aggregate (repeat option to set multiple properties) .. describe:: <name> New aggregate name aggregate delete ---------------- Delete an existing aggregate .. program:: aggregate delete .. code:: bash os aggregate delete <aggregate> .. describe:: <aggregate> Aggregate to delete (name or ID) aggregate list -------------- List all aggregates .. program:: aggregate list .. code:: bash os aggregate list [--long] .. option:: --long List additional fields in output aggregate remove host --------------------- Remove host from aggregate .. program:: aggregate remove host .. code:: bash os aggregate remove host <aggregate> <host> .. _aggregate_remove_host-aggregate: .. describe:: <aggregate> Aggregate (name or ID) .. describe:: <host> Host to remove from :ref:`\<aggregate\> <aggregate_remove_host-aggregate>` aggregate set ------------- Set aggregate properties .. program:: aggregate set .. code:: bash os aggregate set [--name <new-name>] [--zone <availability-zone>] [--property <key=value>] <aggregate> .. option:: --name <name> Set aggregate name .. option:: --zone <availability-zone> Set availability zone name .. option:: --property <key=value> Property to set on :ref:`\<aggregate\> <aggregate_set-aggregate>` (repeat option to set multiple properties) .. _aggregate_set-aggregate: .. describe:: <aggregate> Aggregate to modify (name or ID) aggregate show -------------- Display aggregate details .. program:: aggregate show .. code:: bash os aggregate show <aggregate> .. describe:: <aggregate> Aggregate to display (name or ID) <file_sep># Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import time import uuid from functional.common import test class SnapshotTests(test.TestCase): """Functional tests for snapshot. """ VOLLY = uuid.uuid4().hex NAME = uuid.uuid4().hex OTHER_NAME = uuid.uuid4().hex HEADERS = ['"Name"'] @classmethod def wait_for_status(cls, command, status, tries): opts = cls.get_show_opts(['status']) for attempt in range(tries): time.sleep(1) raw_output = cls.openstack(command + opts) if (raw_output == status): return cls.assertOutput(status, raw_output) @classmethod def setUpClass(cls): cls.openstack('volume create --size 1 ' + cls.VOLLY) cls.wait_for_status('volume show ' + cls.VOLLY, 'available\n', 3) opts = cls.get_show_opts(['status']) raw_output = cls.openstack('snapshot create --name ' + cls.NAME + ' ' + cls.VOLLY + opts) cls.assertOutput('creating\n', raw_output) cls.wait_for_status('snapshot show ' + cls.NAME, 'available\n', 3) @classmethod def tearDownClass(cls): # Rename test raw_output = cls.openstack( 'snapshot set --name ' + cls.OTHER_NAME + ' ' + cls.NAME) cls.assertOutput('', raw_output) # Delete test raw_output = cls.openstack('snapshot delete ' + cls.OTHER_NAME) cls.assertOutput('', raw_output) cls.openstack('volume delete --force ' + cls.VOLLY, fail_ok=True) def test_snapshot_list(self): opts = self.get_list_opts(self.HEADERS) raw_output = self.openstack('snapshot list' + opts) self.assertIn(self.NAME, raw_output) def test_snapshot_properties(self): raw_output = self.openstack( 'snapshot set --property a=b --property c=d ' + self.NAME) self.assertEqual("", raw_output) opts = self.get_show_opts(["properties"]) raw_output = self.openstack('snapshot show ' + self.NAME + opts) self.assertEqual("a='b', c='d'\n", raw_output) raw_output = self.openstack('snapshot unset --property a ' + self.NAME) self.assertEqual("", raw_output) raw_output = self.openstack('snapshot show ' + self.NAME + opts) self.assertEqual("c='d'\n", raw_output) def test_snapshot_set(self): raw_output = self.openstack( 'snapshot set --description backup ' + self.NAME) self.assertEqual("", raw_output) opts = self.get_show_opts(["description", "name"]) raw_output = self.openstack('snapshot show ' + self.NAME + opts) self.assertEqual("backup\n" + self.NAME + "\n", raw_output) <file_sep>======= catalog ======= Identity v2, v3 catalog list ------------ List services in the service catalog .. program:: catalog list .. code:: bash os catalog list catalog show ------------ Display service catalog details .. program:: catalog show .. code:: bash os catalog show <service> .. describe:: <service> Service to display (type or name) <file_sep>=========== subnet pool =========== Network v2 subnet pool create ------------------ Create subnet pool .. program:: subnet pool create .. code:: bash os subnet pool create [--pool-prefix <pool-prefix> [...]] [--default-prefix-length <default-prefix-length>] [--min-prefix-length <min-prefix-length>] [--max-prefix-length <max-prefix-length>] <name> .. option:: --pool-prefix <pool-prefix> Set subnet pool prefixes (in CIDR notation). Repeat this option to set multiple prefixes. .. option:: --default-prefix-length <default-prefix-length> Set subnet pool default prefix length .. option:: --min-prefix-length <min-prefix-length> Set subnet pool minimum prefix length .. option:: --max-prefix-length <max-prefix-length> Set subnet pool maximum prefix length .. _subnet_pool_create-name: .. describe:: <name> Name of the new subnet pool subnet pool delete ------------------ Delete subnet pool .. program:: subnet pool delete .. code:: bash os subnet pool delete <subnet-pool> .. _subnet_pool_delete-subnet-pool: .. describe:: <subnet-pool> Subnet pool to delete (name or ID) subnet pool list ---------------- List subnet pools .. program:: subnet pool list .. code:: bash os subnet pool list [--long] .. option:: --long List additional fields in output subnet pool set --------------- Set subnet pool properties .. program:: subnet pool set .. code:: bash os subnet pool set [--name <name>] [--pool-prefix <pool-prefix> [...]] [--default-prefix-length <default-prefix-length>] [--min-prefix-length <min-prefix-length>] [--max-prefix-length <max-prefix-length>] <subnet-pool> .. option:: --name <name> Set subnet pool name .. option:: --pool-prefix <pool-prefix> Set subnet pool prefixes (in CIDR notation). Repeat this option to set multiple prefixes. .. option:: --default-prefix-length <default-prefix-length> Set subnet pool default prefix length .. option:: --min-prefix-length <min-prefix-length> Set subnet pool minimum prefix length .. option:: --max-prefix-length <max-prefix-length> Set subnet pool maximum prefix length .. _subnet_pool_set-subnet-pool: .. describe:: <subnet-pool> Subnet pool to modify (name or ID) subnet pool show ---------------- Display subnet pool details .. program:: subnet pool show .. code:: bash os subnet pool show <subnet-pool> .. _subnet_pool_show-subnet-pool: .. describe:: <subnet-pool> Subnet pool to display (name or ID) <file_sep>====== image ====== Image v1, v2 image create ------------ *Image v1, v2* Create/upload an image .. program:: image create .. code:: bash os image create [--id <id>] [--store <store>] [--container-format <container-format>] [--disk-format <disk-format>] [--size <size>] [--min-disk <disk-gb>] [--min-ram <ram-mb>] [--location <image-url>] [--copy-from <image-url>] [--file <file>] [--volume <volume>] [--force] [--checksum <checksum>] [--protected | --unprotected] [--public | --private] [--property <key=value> [...] ] [--tag <tag> [...] ] [--project <project> [--project-domain <project-domain>]] <image-name> .. option:: --id <id> Image ID to reserve .. option:: --store <store> Upload image to this store *Image version 1 only.* .. option:: --container-format <container-format> Image container format (default: bare) .. option:: --disk-format <disk-format> Image disk format (default: raw) .. option:: --size <size> Image size, in bytes (only used with --location and --copy-from) *Image version 1 only.* .. option:: --min-disk <disk-gb> Minimum disk size needed to boot image, in gigabytes .. option:: --min-ram <disk-ram> Minimum RAM size needed to boot image, in megabytes .. option:: --location <image-url> Download image from an existing URL *Image version 1 only.* .. option:: --copy-from <image-url> Copy image from the data store (similar to --location) *Image version 1 only.* .. option:: --file <file> Upload image from local file .. option:: --volume <volume> Create image from a volume .. option:: --force Force image creation if volume is in use (only meaningful with --volume) .. option:: --checksum <checksum> Image hash used for verification *Image version 1 only.* .. option:: --protected Prevent image from being deleted .. option:: --unprotected Allow image to be deleted (default) .. option:: --public Image is accessible to the public .. option:: --private Image is inaccessible to the public (default) .. option:: --property <key=value> Set a property on this image (repeat for multiple values) .. option:: --tag <tag> Set a tag on this image (repeat for multiple values) .. versionadded:: 2 .. option:: --project <project> Set an alternate project on this image (name or ID). Previously known as `--owner`. .. option:: --project-domain <project-domain> Domain the project belongs to (name or ID). This can be used in case collisions between project names exist. .. versionadded:: 2 .. describe:: <image-name> New image name image delete ------------ Delete image(s) .. program:: image delete .. code:: bash os image delete <image> .. describe:: <image> Image(s) to delete (name or ID) image list ---------- List available images .. program:: image list .. code:: bash os image list [--public | --private | --shared] [--property <key=value>] [--long] [--sort <key>[:<direction>]] [--limit <limit>] [--marker <marker>] .. option:: --public List only public images .. option:: --private List only private images .. option:: --shared List only shared images *Image version 2 only.* .. option:: --property <key=value> Filter output based on property .. option:: --long List additional fields in output .. option:: --sort <key>[:<direction>] Sort output by selected keys and directions(asc or desc) (default: asc), multiple keys and directions can be specified separated by comma .. option:: --limit <limit> Maximum number of images to display. .. option:: --marker <marker> The last image (name or ID) of the previous page. Display list of images after marker. Display all images if not specified. image save ---------- Save an image locally .. program:: image save .. code:: bash os image save --file <filename> <image> .. option:: --file <filename> Downloaded image save filename (default: stdout) .. describe:: <image> Image to save (name or ID) image set --------- *Image v1, v2* Set image properties .. program:: image set .. code:: bash os image set [--name <name>] [--min-disk <disk-gb>] [--min-ram <disk-ram>] [--container-format <container-format>] [--disk-format <disk-format>] [--size <size>] [--protected | --unprotected] [--public | --private] [--store <store>] [--location <image-url>] [--copy-from <image-url>] [--file <file>] [--volume <volume>] [--force] [--checksum <checksum>] [--stdin] [--property <key=value> [...] ] [--tag <tag> [...] ] [--architecture <architecture>] [--instance-id <instance-id>] [--kernel-id <kernel-id>] [--os-distro <os-distro>] [--os-version <os-version>] [--ramdisk-id <ramdisk-id>] [--activate|--deactivate] [--project <project> [--project-domain <project-domain>]] <image> .. option:: --name <name> New image name .. option:: --min-disk <disk-gb> Minimum disk size needed to boot image, in gigabytes .. option:: --min-ram <disk-ram> Minimum RAM size needed to boot image, in megabytes .. option:: --container-format <container-format> Image container format (default: bare) .. option:: --disk-format <disk-format> Image disk format (default: raw) .. option:: --size <size> Size of image data (in bytes) *Image version 1 only.* .. option:: --protected Prevent image from being deleted .. option:: --unprotected Allow image to be deleted (default) .. option:: --public Image is accessible to the public .. option:: --private Image is inaccessible to the public (default) .. option:: --store <store> Upload image to this store *Image version 1 only.* .. option:: --location <image-url> Download image from an existing URL *Image version 1 only.* .. option:: --copy-from <image-url> Copy image from the data store (similar to --location) *Image version 1 only.* .. option:: --file <file> Upload image from local file *Image version 1 only.* .. option:: --volume <volume> Update image with a volume *Image version 1 only.* .. option:: --force Force image update if volume is in use (only meaningful with --volume) *Image version 1 only.* .. option:: --checksum <checksum> Image hash used for verification *Image version 1 only.* .. option:: --stdin Allow to read image data from standard input *Image version 1 only.* .. option:: --property <key=value> Set a property on this image (repeat option to set multiple properties) .. versionadded:: 2 .. option:: --tag <tag> Set a tag on this image (repeat for multiple values) .. versionadded:: 2 .. option:: --architecture <architecture> Operating system architecture .. versionadded:: 2 .. option:: --instance-id <instance-id> ID of server instance used to create this image .. versionadded:: 2 .. option:: --kernel-id <kernel-id> ID of kernel image used to boot this disk image .. versionadded:: 2 .. option:: --os-distro <os-distro> Operating system distribution name .. versionadded:: 2 .. option:: --os-version <os-version> Operating system distribution version .. versionadded:: 2 .. option:: --ramdisk-id <ramdisk-id> ID of ramdisk image used to boot this disk image .. versionadded:: 2 .. option:: --activate Activate the image. .. versionadded:: 2 .. option:: --deactivate Deactivate the image. .. versionadded:: 2 .. option:: --project <project> Set an alternate project on this image (name or ID). Previously known as `--owner`. .. option:: --project-domain <project-domain> Domain the project belongs to (name or ID). This can be used in case collisions between project names exist. .. versionadded:: 2 .. describe:: <image> Image to modify (name or ID) image show ---------- Display image details .. program:: image show .. code:: bash os image show <image> .. describe:: <image> Image to display (name or ID) image add project ----------------- *Only supported for Image v2* Associate project with image .. program:: image add project .. code:: bash os image add project [--project-domain <project-domain>] <image> <project> .. option:: --project-domain <project-domain> Domain the project belongs to (name or ID). This can be used in case collisions between project names exist. .. describe:: <image> Image to share (name or ID). .. describe:: <project> Project to associate with image (name or ID) image remove project -------------------- *Only supported for Image v2* Disassociate project with image .. program:: image remove project .. code:: bash os image remove remove [--project-domain <project-domain>] <image> <project> .. option:: --project-domain <project-domain> Domain the project belongs to (name or ID). This can be used in case collisions between project names exist. .. describe:: <image> Image to unshare (name or ID). .. describe:: <project> Project to disassociate with image (name or ID) <file_sep># Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from functional.common import test class ExampleTests(test.TestCase): """Functional tests for running examples.""" def test_common(self): # NOTE(stevemar): If an examples has a non-zero return # code, then execute will raise an error by default. test.execute('python', test.EXAMPLE_DIR + '/common.py --debug') def test_object_api(self): test.execute('python', test.EXAMPLE_DIR + '/object_api.py --debug') def test_osc_lib(self): test.execute('python', test.EXAMPLE_DIR + '/osc-lib.py --debug') <file_sep># Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import copy import mock from openstackclient.common import quota from openstackclient.tests.compute.v2 import fakes as compute_fakes from openstackclient.tests import fakes from openstackclient.tests.identity.v2_0 import fakes as identity_fakes from openstackclient.tests.network.v2 import fakes as network_fakes class FakeQuotaResource(fakes.FakeResource): _keys = {'property': 'value'} def set_keys(self, args): self._keys.update(args) def unset_keys(self, keys): for key in keys: self._keys.pop(key, None) def get_keys(self): return self._keys class TestQuota(compute_fakes.TestComputev2): def setUp(self): super(TestQuota, self).setUp() self.quotas_mock = self.app.client_manager.compute.quotas self.quotas_mock.reset_mock() self.quotas_class_mock = self.app.client_manager.compute.quota_classes self.quotas_class_mock.reset_mock() volume_mock = mock.Mock() volume_mock.quotas = mock.Mock() self.app.client_manager.volume = volume_mock self.volume_quotas_mock = volume_mock.quotas self.volume_quotas_mock.reset_mock() self.volume_quotas_class_mock = \ self.app.client_manager.volume.quota_classes self.volume_quotas_class_mock.reset_mock() self.projects_mock = self.app.client_manager.identity.projects self.projects_mock.reset_mock() self.app.client_manager.auth_ref = mock.Mock() self.app.client_manager.auth_ref.service_catalog = mock.Mock() self.service_catalog_mock = \ self.app.client_manager.auth_ref.service_catalog self.service_catalog_mock.reset_mock() class TestQuotaSet(TestQuota): def setUp(self): super(TestQuotaSet, self).setUp() self.quotas_mock.find.return_value = FakeQuotaResource( None, copy.deepcopy(compute_fakes.QUOTA), loaded=True, ) self.quotas_mock.update.return_value = FakeQuotaResource( None, copy.deepcopy(compute_fakes.QUOTA), loaded=True, ) self.volume_quotas_mock.find.return_value = FakeQuotaResource( None, copy.deepcopy(compute_fakes.QUOTA), loaded=True, ) self.volume_quotas_mock.update.return_value = FakeQuotaResource( None, copy.deepcopy(compute_fakes.QUOTA), loaded=True, ) self.projects_mock.get.return_value = fakes.FakeResource( None, copy.deepcopy(identity_fakes.PROJECT), loaded=True, ) self.cmd = quota.SetQuota(self.app, None) def test_quota_set(self): arglist = [ '--floating-ips', str(compute_fakes.floating_ip_num), '--fixed-ips', str(compute_fakes.fix_ip_num), '--injected-files', str(compute_fakes.injected_file_num), '--injected-file-size', str(compute_fakes.injected_file_size_num), '--injected-path-size', str(compute_fakes.injected_path_size_num), '--key-pairs', str(compute_fakes.key_pair_num), '--cores', str(compute_fakes.core_num), '--ram', str(compute_fakes.ram_num), '--instances', str(compute_fakes.instance_num), '--properties', str(compute_fakes.property_num), '--secgroup-rules', str(compute_fakes.secgroup_rule_num), '--secgroups', str(compute_fakes.secgroup_num), identity_fakes.project_name, ] verifylist = [ ('floating_ips', compute_fakes.floating_ip_num), ('fixed_ips', compute_fakes.fix_ip_num), ('injected_files', compute_fakes.injected_file_num), ('injected_file_content_bytes', compute_fakes.injected_file_size_num), ('injected_file_path_bytes', compute_fakes.injected_path_size_num), ('key_pairs', compute_fakes.key_pair_num), ('cores', compute_fakes.core_num), ('ram', compute_fakes.ram_num), ('instances', compute_fakes.instance_num), ('metadata_items', compute_fakes.property_num), ('security_group_rules', compute_fakes.secgroup_rule_num), ('security_groups', compute_fakes.secgroup_num), ('project', identity_fakes.project_name), ] parsed_args = self.check_parser(self.cmd, arglist, verifylist) self.cmd.take_action(parsed_args) kwargs = { 'floating_ips': compute_fakes.floating_ip_num, 'fixed_ips': compute_fakes.fix_ip_num, 'injected_files': compute_fakes.injected_file_num, 'injected_file_content_bytes': compute_fakes.injected_file_size_num, 'injected_file_path_bytes': compute_fakes.injected_path_size_num, 'key_pairs': compute_fakes.key_pair_num, 'cores': compute_fakes.core_num, 'ram': compute_fakes.ram_num, 'instances': compute_fakes.instance_num, 'metadata_items': compute_fakes.property_num, 'security_group_rules': compute_fakes.secgroup_rule_num, 'security_groups': compute_fakes.secgroup_num, } self.quotas_mock.update.assert_called_with( identity_fakes.project_id, **kwargs ) def test_quota_set_volume(self): arglist = [ '--gigabytes', str(compute_fakes.floating_ip_num), '--snapshots', str(compute_fakes.fix_ip_num), '--volumes', str(compute_fakes.injected_file_num), identity_fakes.project_name, ] verifylist = [ ('gigabytes', compute_fakes.floating_ip_num), ('snapshots', compute_fakes.fix_ip_num), ('volumes', compute_fakes.injected_file_num), ] parsed_args = self.check_parser(self.cmd, arglist, verifylist) self.cmd.take_action(parsed_args) kwargs = { 'gigabytes': compute_fakes.floating_ip_num, 'snapshots': compute_fakes.fix_ip_num, 'volumes': compute_fakes.injected_file_num, } self.volume_quotas_mock.update.assert_called_with( identity_fakes.project_id, **kwargs ) class TestQuotaShow(TestQuota): def setUp(self): super(TestQuotaShow, self).setUp() self.quotas_mock.get.return_value = FakeQuotaResource( None, copy.deepcopy(compute_fakes.QUOTA), loaded=True, ) self.quotas_mock.defaults.return_value = FakeQuotaResource( None, copy.deepcopy(compute_fakes.QUOTA), loaded=True, ) self.volume_quotas_mock.get.return_value = FakeQuotaResource( None, copy.deepcopy(compute_fakes.QUOTA), loaded=True, ) self.volume_quotas_mock.defaults.return_value = FakeQuotaResource( None, copy.deepcopy(compute_fakes.QUOTA), loaded=True, ) fake_network_endpoint = fakes.FakeResource( None, copy.deepcopy(identity_fakes.ENDPOINT), loaded=True, ) self.service_catalog_mock.get_endpoints.return_value = { 'network': fake_network_endpoint } self.quotas_class_mock.get.return_value = FakeQuotaResource( None, copy.deepcopy(compute_fakes.QUOTA), loaded=True, ) self.volume_quotas_class_mock.get.return_value = FakeQuotaResource( None, copy.deepcopy(compute_fakes.QUOTA), loaded=True, ) self.projects_mock.get.return_value = fakes.FakeResource( None, copy.deepcopy(identity_fakes.PROJECT), loaded=True, ) self.app.client_manager.network = network_fakes.FakeNetworkV2Client( endpoint=fakes.AUTH_URL, token=fakes.AUTH_TOKEN, ) self.network = self.app.client_manager.network self.network.get_quota = mock.Mock(return_value=network_fakes.QUOTA) self.cmd = quota.ShowQuota(self.app, None) def test_quota_show(self): arglist = [ identity_fakes.project_name, ] verifylist = [ ('project', identity_fakes.project_name), ] parsed_args = self.check_parser(self.cmd, arglist, verifylist) self.cmd.take_action(parsed_args) self.quotas_mock.get.assert_called_with(identity_fakes.project_id) self.volume_quotas_mock.get.assert_called_with( identity_fakes.project_id) self.network.get_quota.assert_called_with(identity_fakes.project_id) def test_quota_show_with_default(self): arglist = [ '--default', identity_fakes.project_name, ] verifylist = [ ('default', True), ('project', identity_fakes.project_name), ] parsed_args = self.check_parser(self.cmd, arglist, verifylist) self.cmd.take_action(parsed_args) self.quotas_mock.defaults.assert_called_with(identity_fakes.project_id) self.volume_quotas_mock.defaults.assert_called_with( identity_fakes.project_id) def test_quota_show_with_class(self): arglist = [ '--class', identity_fakes.project_name, ] verifylist = [ ('quota_class', True), ('project', identity_fakes.project_name), ] parsed_args = self.check_parser(self.cmd, arglist, verifylist) self.cmd.take_action(parsed_args) self.quotas_class_mock.get.assert_called_with( identity_fakes.project_id) self.volume_quotas_class_mock.get.assert_called_with( identity_fakes.project_id) <file_sep>=============== ec2 credentials =============== Identity v2 ec2 credentials create ---------------------- Create EC2 credentials .. program:: ec2 credentials create .. code-block:: bash os ec2 credentials create [--project <project>] [--user <user>] [--user-domain <user-domain>] [--project-domain <project-domain>] .. option:: --project <project> Create credentials in project (name or ID; default: current authenticated project) .. option:: --user <user> Create credentials for user (name or ID; default: current authenticated user) .. option:: --user-domain <user-domain> Domain the user belongs to (name or ID). This can be used in case collisions between user names exist. .. versionadded:: 3 .. option:: --project-domain <project-domain> Domain the project belongs to (name or ID). This can be used in case collisions between user names exist. .. versionadded:: 3 The :option:`--project` and :option:`--user` options are typically only useful for admin users, but may be allowed for other users depending on the policy of the cloud and the roles granted to the user. ec2 credentials delete ---------------------- Delete EC2 credentials .. program:: ec2 credentials delete .. code-block:: bash os ec2 credentials delete [--user <user>] [--user-domain <user-domain>] <access-key> .. option:: --user <user> Delete credentials for user (name or ID) .. option:: --user-domain <user-domain> Select user from a specific domain (name or ID) This can be used in case collisions between user names exist. .. versionadded:: 3 .. _ec2_credentials_delete-access-key: .. describe:: access-key Credentials access key The :option:`--user` option is typically only useful for admin users, but may be allowed for other users depending on the policy of the cloud and the roles granted to the user. ec2 credentials list -------------------- List EC2 credentials .. program:: ec2 credentials list .. code-block:: bash os ec2 credentials list [--user <user>] [--user-domain <user-domain>] .. option:: --user <user> Filter list by <user> (name or ID) .. option:: --user-domain <user-domain> Select user from a specific domain (name or ID) This can be used in case collisions between user names exist. .. versionadded:: 3 The :option:`--user` option is typically only useful for admin users, but may be allowed for other users depending on the policy of the cloud and the roles granted to the user. ec2 credentials show -------------------- Display EC2 credentials details .. program:: ec2 credentials show .. code-block:: bash os ec2 credentials show [--user <user>] [--user-domain <user-domain>] <access-key> .. option:: --user <user> Show credentials for user (name or ID) .. option:: --user-domain <user-domain> Select user from a specific domain (name or ID) This can be used in case collisions between user names exist. .. versionadded:: 3 .. _ec2_credentials_show-access-key: .. describe:: access-key Credentials access key The :option:`--user` option is typically only useful for admin users, but may be allowed for other users depending on the policy of the cloud and the roles granted to the user. <file_sep>#!/bin/bash # This is a script that kicks off a series of functional tests against an # OpenStack cloud. It will attempt to create an instance if one is not # available. Do not run this script unless you know what you're doing. # For more information refer to: # http://docs.openstack.org/developer/python-openstackclient/ set -xe OPENSTACKCLIENT_DIR=$(cd $(dirname "$0") && pwd) echo "Running openstackclient functional test suite" sudo -H -u stack -i <<! source ~stack/devstack/openrc admin admin echo 'Running tests with:' env | grep OS_ cd ${OPENSTACKCLIENT_DIR} tox -e functional ! <file_sep>=========== volume type =========== Block Storage v1, v2 volume type create ------------------ Create new volume type .. program:: volume type create .. code:: bash os volume type create [--description <description>] [--public | --private] [--property <key=value> [...] ] <name> .. option:: --description <description> New volume type description .. versionadded:: 2 .. option:: --public Volume type is accessible to the public .. versionadded:: 2 .. option:: --private Volume type is not accessible to the public .. versionadded:: 2 .. option:: --property <key=value> Set a property on this volume type (repeat option to set multiple properties) .. describe:: <name> New volume type name volume type delete ------------------ Delete volume type .. program:: volume type delete .. code:: bash os volume type delete <volume-type> .. describe:: <volume-type> Volume type to delete (name or ID) volume type list ---------------- List volume types .. program:: volume type list .. code:: bash os volume type list [--long] .. option:: --long List additional fields in output volume type set --------------- Set volume type properties .. program:: volume type set .. code:: bash os volume type set [--name <name>] [--description <description>] [--property <key=value> [...] ] <volume-type> .. option:: --name <name> Set volume type name .. versionadded:: 2 .. option:: --description <description> Set volume type description .. versionadded:: 2 .. option:: --property <key=value> Property to add or modify for this volume type (repeat option to set multiple properties) .. describe:: <volume-type> Volume type to modify (name or ID) volume type unset ----------------- Unset volume type properties .. program:: volume type unset .. code:: bash os volume type unset [--property <key>] <volume-type> .. option:: --property <key> Property to remove from volume type (repeat option to remove multiple properties) .. describe:: <volume-type> Volume type to modify (name or ID) <file_sep># Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import os import re import shlex import subprocess import testtools import six from functional.common import exceptions COMMON_DIR = os.path.dirname(os.path.abspath(__file__)) FUNCTIONAL_DIR = os.path.normpath(os.path.join(COMMON_DIR, '..')) ROOT_DIR = os.path.normpath(os.path.join(FUNCTIONAL_DIR, '..')) EXAMPLE_DIR = os.path.join(ROOT_DIR, 'examples') def execute(cmd, fail_ok=False, merge_stderr=False): """Executes specified command for the given action.""" cmdlist = shlex.split(cmd) result = '' result_err = '' stdout = subprocess.PIPE stderr = subprocess.STDOUT if merge_stderr else subprocess.PIPE proc = subprocess.Popen(cmdlist, stdout=stdout, stderr=stderr) result, result_err = proc.communicate() result = result.decode('utf-8') if not fail_ok and proc.returncode != 0: raise exceptions.CommandFailed(proc.returncode, cmd, result, result_err) return result class TestCase(testtools.TestCase): delimiter_line = re.compile('^\+\-[\+\-]+\-\+$') @classmethod def openstack(cls, cmd, fail_ok=False): """Executes openstackclient command for the given action.""" return execute('openstack ' + cmd, fail_ok=fail_ok) @classmethod def get_openstack_configuration_value(cls, configuration): opts = cls.get_show_opts([configuration]) return cls.openstack('configuration show ' + opts) @classmethod def get_show_opts(cls, fields=[]): return ' -f value ' + ' '.join(['-c ' + it for it in fields]) @classmethod def get_list_opts(cls, headers=[]): opts = ' -f csv ' opts = opts + ' '.join(['-c ' + it for it in headers]) return opts @classmethod def assertOutput(cls, expected, actual): if expected != actual: raise Exception(expected + ' != ' + actual) @classmethod def assertInOutput(cls, expected, actual): if expected not in actual: raise Exception(expected + ' not in ' + actual) @classmethod def cleanup_tmpfile(cls, filename): try: os.remove(filename) except OSError: pass def assert_table_structure(self, items, field_names): """Verify that all items have keys listed in field_names.""" for item in items: for field in field_names: self.assertIn(field, item) def assert_show_fields(self, items, field_names): """Verify that all items have keys listed in field_names.""" for item in items: for key in six.iterkeys(item): self.assertIn(key, field_names) def assert_show_structure(self, items, field_names): """Verify that all field_names listed in keys of all items.""" if isinstance(items, list): o = {} for d in items: o.update(d) else: o = items item_keys = o.keys() for field in field_names: self.assertIn(field, item_keys) def parse_show_as_object(self, raw_output): """Return a dict with values parsed from cli output.""" items = self.parse_show(raw_output) o = {} for item in items: o.update(item) return o def parse_show(self, raw_output): """Return list of dicts with item values parsed from cli output.""" items = [] table_ = self.table(raw_output) for row in table_['values']: item = {} item[row[0]] = row[1] items.append(item) return items def parse_listing(self, raw_output): """Return list of dicts with basic item parsed from cli output.""" items = [] table_ = self.table(raw_output) for row in table_['values']: item = {} for col_idx, col_key in enumerate(table_['headers']): item[col_key] = row[col_idx] items.append(item) return items def table(self, output_lines): """Parse single table from cli output. Return dict with list of column names in 'headers' key and rows in 'values' key. """ table_ = {'headers': [], 'values': []} columns = None if not isinstance(output_lines, list): output_lines = output_lines.split('\n') if not output_lines[-1]: # skip last line if empty (just newline at the end) output_lines = output_lines[:-1] for line in output_lines: if self.delimiter_line.match(line): columns = self._table_columns(line) continue if '|' not in line: continue row = [] for col in columns: row.append(line[col[0]:col[1]].strip()) if table_['headers']: table_['values'].append(row) else: table_['headers'] = row return table_ def _table_columns(self, first_table_row): """Find column ranges in output line. Return list of tuples (start,end) for each column detected by plus (+) characters in delimiter line. """ positions = [] start = 1 # there is '+' at 0 while start < len(first_table_row): end = first_table_row.find('+', start) if end == -1: break positions.append((start, end)) start = end + 1 return positions <file_sep>======= network ======= Compute v2, Network v2 network create -------------- Create new network .. program:: network create .. code:: bash os network create [--project <project> [--project-domain <project-domain>]] [--enable | --disable] [--share | --no-share] [--availability-zone-hint <availability-zone>] <name> .. option:: --project <project> Owner's project (name or ID) (Network v2 only) .. option:: --project-domain <project-domain> Domain the project belongs to (name or ID). This can be used in case collisions between project names exist. (Network v2 only) .. option:: --enable Enable network (default) (Network v2 only) .. option:: --disable Disable network (Network v2 only) .. option:: --share Share the network between projects .. option:: --no-share Do not share the network between projects .. option:: --availability-zone-hint <availability-zone> Availability Zone in which to create this network (requires the Network Availability Zone extension, this option can be repeated). (Network v2 only) .. option:: --subnet <subnet> IPv4 subnet for fixed IPs (in CIDR notation) (Compute v2 network only) .. _network_create-name: .. describe:: <name> New network name network delete -------------- Delete network(s) .. program:: network delete .. code:: bash os network delete <network> [<network> ...] .. _network_delete-network: .. describe:: <network> Network(s) to delete (name or ID) network list ------------ List networks .. program:: network list .. code:: bash os network list [--external] [--long] .. option:: --external List external networks .. option:: --long List additional fields in output network set ----------- Set network properties .. program:: network set .. code:: bash os network set [--name <name>] [--enable | --disable] [--share | --no-share] <network> .. option:: --name <name> Set network name .. option:: --enable Enable network .. option:: --disable Disable network .. option:: --share Share the network between projects .. option:: --no-share Do not share the network between projects .. _network_set-network: .. describe:: <network> Network to modify (name or ID) network show ------------ Display network details .. program:: network show .. code:: bash os network show <network> .. _network_show-network: .. describe:: <network> Network to display (name or ID) <file_sep># Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # """Security Group Rule action implementations""" import six from openstackclient.common import exceptions from openstackclient.common import utils from openstackclient.network import common from openstackclient.network import utils as network_utils def _format_security_group_rule_show(obj): data = network_utils.transform_compute_security_group_rule(obj) return zip(*sorted(six.iteritems(data))) def _get_columns(item): columns = item.keys() if 'tenant_id' in columns: columns.remove('tenant_id') columns.append('project_id') return tuple(sorted(columns)) class DeleteSecurityGroupRule(common.NetworkAndComputeCommand): """Delete a security group rule""" def update_parser_common(self, parser): parser.add_argument( 'rule', metavar='<rule>', help='Security group rule to delete (ID only)', ) return parser def take_action_network(self, client, parsed_args): obj = client.find_security_group_rule(parsed_args.rule) client.delete_security_group_rule(obj) def take_action_compute(self, client, parsed_args): client.security_group_rules.delete(parsed_args.rule) class ShowSecurityGroupRule(common.NetworkAndComputeShowOne): """Display security group rule details""" def update_parser_common(self, parser): parser.add_argument( 'rule', metavar="<rule>", help="Security group rule to display (ID only)" ) return parser def take_action_network(self, client, parsed_args): obj = client.find_security_group_rule(parsed_args.rule, ignore_missing=False) columns = _get_columns(obj) data = utils.get_item_properties(obj, columns) return (columns, data) def take_action_compute(self, client, parsed_args): # NOTE(rtheis): Unfortunately, compute does not have an API # to get or list security group rules so parse through the # security groups to find all accessible rules in search of # the requested rule. obj = None security_group_rules = [] for security_group in client.security_groups.list(): security_group_rules.extend(security_group.rules) for security_group_rule in security_group_rules: if parsed_args.rule == str(security_group_rule.get('id')): obj = security_group_rule break if obj is None: msg = "Could not find security group rule " \ "with ID %s" % parsed_args.rule raise exceptions.CommandError(msg) # NOTE(rtheis): Format security group rule return _format_security_group_rule_show(obj) <file_sep>======== snapshot ======== Block Storage v1 snapshot create --------------- Create new snapshot .. program:: snapshot create .. code:: bash os snapshot create [--name <name>] [--description <description>] [--force] <volume> .. option:: --name <name> Name of the snapshot .. option:: --description <description> Description of the snapshot .. option:: --force Create a snapshot attached to an instance. Default is False .. _snapshot_create-snapshot: .. describe:: <volume> Volume to snapshot (name or ID) snapshot delete --------------- Delete snapshot(s) .. program:: snapshot delete .. code:: bash os snapshot delete <snapshot> [<snapshot> ...] .. _snapshot_delete-snapshot: .. describe:: <snapshot> Snapshot(s) to delete (name or ID) snapshot list ------------- List snapshots .. program:: snapshot list .. code:: bash os snapshot list [--all-projects] .. option:: --all-projects Include all projects (admin only) .. option:: --long List additional fields in output snapshot set ------------ Set snapshot properties .. program:: snapshot set .. code:: bash os snapshot set [--name <name>] [--description <description>] [--property <key=value> [...] ] <snapshot> .. _snapshot_restore-snapshot: .. option:: --name <name> New snapshot name .. option:: --description <description> New snapshot description .. option:: --property <key=value> Property to add or modify for this snapshot (repeat option to set multiple properties) .. describe:: <snapshot> Snapshot to modify (name or ID) snapshot show ------------- Display snapshot details .. program:: snapshot show .. code:: bash os snapshot show <snapshot> .. _snapshot_show-snapshot: .. describe:: <snapshot> Snapshot to display (name or ID) snapshot unset -------------- Unset snapshot properties .. program:: snapshot unset .. code:: bash os snapshot unset [--property <key>] <snapshot> .. option:: --property <key> Property to remove from snapshot (repeat option to remove multiple properties) .. describe:: <snapshot> Snapshot to modify (name or ID) <file_sep>==== host ==== Compute v2 The physical computer running a hypervisor. host list --------- List all hosts .. program:: host list .. code:: bash os host list [--zone <availability-zone>] .. option:: --zone <availability-zone> Only return hosts in the availability zone host show --------- Display host details .. program:: host show .. code:: bash os host show <host> .. describe:: <host> Name of host <file_sep>===== trust ===== Identity v3 trust create ------------ Create new trust .. program:: trust create .. code:: bash os trust create --project <project> --role <role> [--impersonate] [--expiration <expiration>] [--project-domain <domain>] [--trustor-domain <domain>] [--trustee-domain <domain>] <trustor> <trustee> .. option:: --project <project> Project being delegated (name or ID) (required) .. option:: --role <role> Roles to authorize (name or ID) (repeat to set multiple values) (required) .. option:: --impersonate Tokens generated from the trust will represent <trustor> (defaults to False) .. option:: --expiration <expiration> Sets an expiration date for the trust (format of YYYY-mm-ddTHH:MM:SS) .. option:: --project-domain <project-domain> Domain the project belongs to (name or ID). This can be used in case collisions between user names exist. .. option:: --trustor-domain <trustor-domain> Domain that contains <trustor> (name or ID) .. option:: --trustee-domain <trustee-domain> Domain that contains <trustee> (name or ID) .. describe:: <trustor-user> User that is delegating authorization (name or ID) .. describe:: <trustee-user> User that is assuming authorization (name or ID) trust delete ------------ Delete trust(s) .. program:: trust delete .. code:: bash os trust delete <trust> [<trust> ...] .. describe:: <trust> Trust(s) to delete trust list ---------- List trusts .. program:: trust list .. code:: bash os trust list trust show ---------- Display trust details .. program:: trust show .. code:: bash os trust show <trust> .. describe:: <trust> Trust to display <file_sep>--- features: - | Add support for the ``--disable-reason`` of ``service set`` command <file_sep>============= configuration ============= Available for all services configuration show ------------------ Show the current openstack client configuration. This command is a little different from other show commands because it does not take a resource name or id to show. The command line options, such as --os-cloud, can be used to show different configurations. .. program:: configuration show .. code:: bash os configuration show [--mask | --unmask] .. option:: --mask Attempt to mask passwords (default) .. option:: --unmask Show password in clear text <file_sep>================= Plugin Commands ================= Note: To see the complete syntax for the plugin commands, see the `CLI_Ref`_ .. list-plugins:: openstack.cli.extension .. list-plugins:: openstack.key_manager.v1 :detailed: .. list-plugins:: openstack.baremetal.v1 :detailed: .. list-plugins:: openstack.congressclient.v1 :detailed: .. list-plugins:: openstack.workflow_engine.v2 :detailed: .. list-plugins:: openstack.data_processing.v1 :detailed: .. list-plugins:: openstack.dns.v1 :detailed: .. list-plugins:: openstack.management.v1 :detailed: .. list-plugins:: openstack.messaging.v1 :detailed: .. list-plugins:: openstack.orchestration.v1 :detailed: .. _CLI_Ref: http://docs.openstack.org/cli-reference/openstack.html<file_sep>======== endpoint ======== Identity v2, v3 endpoint create --------------- Create new endpoint *Identity version 2 only* .. program:: endpoint create .. code:: bash os endpoint create --publicurl <url> [--adminurl <url>] [--internalurl <url>] [--region <region-id>] <service> .. option:: --publicurl <url> New endpoint public URL (required) .. option:: --adminurl <url> New endpoint admin URL .. option:: --internalurl <url> New endpoint internal URL .. option:: --region <region-id> New endpoint region ID .. _endpoint_create-endpoint: .. describe:: <service> New endpoint service (name or ID) *Identity version 3 only* .. program:: endpoint create .. code:: bash os endpoint create [--region <region-id>] [--enable | --disable] <service> <interface> <url> .. option:: --region <region-id> New endpoint region ID .. option:: --enable Enable endpoint (default) .. option:: --disable Disable endpoint .. describe:: <service> New endpoint service (name or ID) .. describe:: <interface> New endpoint interface type (admin, public or internal) .. describe:: <url> New endpoint URL endpoint delete --------------- Delete endpoint .. program:: endpoint delete .. code:: bash os endpoint delete <endpoint-id> .. _endpoint_delete-endpoint: .. describe:: <endpoint-id> Endpoint ID to delete endpoint list ------------- List endpoints .. program:: endpoint list .. code:: bash os endpoint list [--service <service] [--interface <interface>] [--region <region-id>] [--long] .. option:: --service <service> Filter by service *Identity version 3 only* .. option:: --interface <interface> Filter by interface type (admin, public or internal) *Identity version 3 only* .. option:: --region <region-id> Filter by region ID *Identity version 3 only* .. option:: --long List additional fields in output *Identity version 2 only* endpoint set ------------ Set endpoint properties *Identity version 3 only* .. program:: endpoint set .. code:: bash os endpoint set [--region <region-id>] [--interface <interface>] [--url <url>] [--service <service>] [--enable | --disable] <endpoint-id> .. option:: --region <region-id> New endpoint region ID .. option:: --interface <interface> New endpoint interface type (admin, public or internal) .. option:: --url <url> New endpoint URL .. option:: --service <service> New endpoint service (name or ID) .. option:: --enable Enable endpoint .. option:: --disable Disable endpoint .. _endpoint_set-endpoint: .. describe:: <endpoint-id> Endpoint ID to modify endpoint show ------------- Display endpoint details .. program:: endpoint show .. code:: bash os endpoint show <endpoint-id> .. _endpoint_show-endpoint: .. describe:: <endpoint-id> Endpoint ID to display <file_sep># Copyright 2013 Nebula Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # import copy import mock import random import uuid from openstackclient.common import utils as common_utils from openstackclient.tests import fakes from openstackclient.tests import utils from openstackclient.tests.identity.v3 import fakes as identity_fakes image_id = '0f41529e-7c12-4de8-be2d-181abb825b3c' image_name = 'graven' image_owner = 'baal' image_protected = False image_visibility = 'public' image_tags = [] IMAGE = { 'id': image_id, 'name': image_name, 'owner': image_owner, 'protected': image_protected, 'visibility': image_visibility, 'tags': image_tags } IMAGE_columns = tuple(sorted(IMAGE)) IMAGE_data = tuple((IMAGE[x] for x in sorted(IMAGE))) IMAGE_SHOW = copy.copy(IMAGE) IMAGE_SHOW['tags'] = '' IMAGE_SHOW_data = tuple((IMAGE_SHOW[x] for x in sorted(IMAGE_SHOW))) member_status = 'pending' MEMBER = { 'member_id': identity_fakes.project_id, 'image_id': image_id, 'status': member_status, } # Just enough v2 schema to do some testing IMAGE_schema = { "additionalProperties": { "type": "string" }, "name": "image", "links": [ { "href": "{self}", "rel": "self" }, { "href": "{file}", "rel": "enclosure" }, { "href": "{schema}", "rel": "describedby" } ], "properties": { "id": { "pattern": "^([0-9a-fA-F]){8}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){12}$", # noqa "type": "string", "description": "An identifier for the image" }, "name": { "type": [ "null", "string" ], "description": "Descriptive name for the image", "maxLength": 255 }, "owner": { "type": [ "null", "string" ], "description": "Owner of the image", "maxLength": 255 }, "protected": { "type": "boolean", "description": "If true, image will not be deletable." }, "self": { "type": "string", "description": "(READ-ONLY)" }, "schema": { "type": "string", "description": "(READ-ONLY)" }, "size": { "type": [ "null", "integer" ], "description": "Size of image file in bytes (READ-ONLY)" }, "status": { "enum": [ "queued", "saving", "active", "killed", "deleted", "pending_delete" ], "type": "string", "description": "Status of the image (READ-ONLY)" }, "tags": { "items": { "type": "string", "maxLength": 255 }, "type": "array", "description": "List of strings related to the image" }, "visibility": { "enum": [ "public", "private" ], "type": "string", "description": "Scope of image accessibility" }, } } class FakeImagev2Client(object): def __init__(self, **kwargs): self.images = mock.Mock() self.images.resource_class = fakes.FakeResource(None, {}) self.image_members = mock.Mock() self.image_members.resource_class = fakes.FakeResource(None, {}) self.auth_token = kwargs['token'] self.management_url = kwargs['endpoint'] class TestImagev2(utils.TestCommand): def setUp(self): super(TestImagev2, self).setUp() self.app.client_manager.image = FakeImagev2Client( endpoint=fakes.AUTH_URL, token=fakes.AUTH_TOKEN, ) self.app.client_manager.identity = identity_fakes.FakeIdentityv3Client( endpoint=fakes.AUTH_URL, token=fakes.AUTH_TOKEN, ) class FakeImage(object): """Fake one or more images. TODO(xiexs): Currently, only image API v2 is supported by this class. """ @staticmethod def create_one_image(attrs={}): """Create a fake image. :param Dictionary attrs: A dictionary with all attrbutes of image :retrun: A FakeResource object with id, name, owner, protected, visibility and tags attrs """ # Set default attribute image_info = { 'id': 'image-id' + uuid.uuid4().hex, 'name': 'image-name' + uuid.uuid4().hex, 'owner': 'image-owner' + uuid.uuid4().hex, 'protected': bool(random.choice([0, 1])), 'visibility': random.choice(['public', 'private']), 'tags': [uuid.uuid4().hex for r in range(2)], } # Overwrite default attributes if there are some attributes set image_info.update(attrs) image = fakes.FakeResource( None, image_info, loaded=True) return image @staticmethod def create_images(attrs={}, count=2): """Create multiple fake images. :param Dictionary attrs: A dictionary with all attributes of image :param Integer count: The number of images to be faked :return: A list of FakeResource objects """ images = [] for n in range(0, count): images.append(FakeImage.create_one_image(attrs)) return images @staticmethod def get_images(images=None, count=2): """Get an iterable MagicMock object with a list of faked images. If images list is provided, then initialize the Mock object with the list. Otherwise create one. :param List images: A list of FakeResource objects faking images :param Integer count: The number of images to be faked :return An iterable Mock object with side_effect set to a list of faked images """ if images is None: images = FakeImage.create_images(count) return mock.MagicMock(side_effect=images) @staticmethod def get_image_info(image=None): """Get the image info from a faked image object. :param image: A FakeResource objects faking image :return A dictionary which includes the faked image info as follows: { 'id': image_id, 'name': image_name, 'owner': image_owner, 'protected': image_protected, 'visibility': image_visibility, 'tags': image_tags } """ if image is not None: return image._info return {} @staticmethod def get_image_columns(image=None): """Get the image columns from a faked image object. :param image: A FakeResource objects faking image :return A tuple which may include the following keys: ('id', 'name', 'owner', 'protected', 'visibility', 'tags') """ if image is not None: return tuple(k for k in sorted( FakeImage.get_image_info(image).keys())) return tuple([]) @staticmethod def get_image_data(image=None): """Get the image data from a faked image object. :param image: A FakeResource objects faking image :return A tuple which may include the following values: ('image-123', 'image-foo', 'admin', False, 'public', 'bar, baz') """ data_list = [] if image is not None: for x in sorted(FakeImage.get_image_info(image).keys()): if x == 'tags': # The 'tags' should be format_list data_list.append( common_utils.format_list(getattr(image, x))) else: data_list.append(getattr(image, x)) return tuple(data_list) <file_sep>===== usage ===== Compute v2 usage list ---------- List resource usage per project .. program:: usage list .. code:: bash os usage list --start <start> --end <end> .. option:: --start <start> Usage range start date, ex 2012-01-20 (default: 4 weeks ago) .. option:: --end <end> Usage range end date, ex 2012-01-20 (default: tomorrow) usage show ---------- Show resource usage for a single project .. program:: usage show .. code:: bash os usage show --project <project> --start <start> --end <end> .. option:: --project <project> Name or ID of project to show usage for .. option:: --start <start> Usage range start date, ex 2012-01-20 (default: 4 weeks ago) .. option:: --end <end> Usage range end date, ex 2012-01-20 (default: tomorrow) <file_sep>====== limits ====== The Compute and Block Storage APIs have resource usage limits. Compute v2, Block Storage v1 limits show ----------- Show compute and block storage limits .. program:: limits show .. code:: bash os limits show --absolute [--reserved] | --rate [--project <project>] [--domain <domain>] .. option:: --absolute Show absolute limits .. option:: --rate Show rate limits .. option:: --reserved Include reservations count [only valid with :option:`--absolute`] .. option:: --project <project> Show limits for a specific project (name or ID) [only valid with --absolute] .. option:: --domain <domain> Domain that owns --project (name or ID) [only valid with --absolute] <file_sep>=========== credentials =========== Identity v3 credentials create ------------------ .. ''[consider rolling the ec2 creds into this too]'' .. code:: bash os credentials create --x509 [<private-key-file>] [<certificate-file>] credentials show ---------------- .. code:: bash os credentials show [--token] [--user] [--x509 [--root]] <file_sep># Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # """Network action implementations""" from openstackclient.common import command from openstackclient.common import exceptions from openstackclient.common import utils from openstackclient.identity import common as identity_common from openstackclient.network import common def _format_admin_state(item): return 'UP' if item else 'DOWN' def _format_router_external(item): return 'External' if item else 'Internal' _formatters = { 'subnets': utils.format_list, 'admin_state_up': _format_admin_state, 'router_external': _format_router_external, 'availability_zones': utils.format_list, 'availability_zone_hints': utils.format_list, } def _get_columns(item): columns = item.keys() if 'tenant_id' in columns: columns.remove('tenant_id') columns.append('project_id') if 'router:external' in columns: columns.remove('router:external') columns.append('router_external') return tuple(sorted(columns)) def _get_attrs(client_manager, parsed_args): attrs = {} if parsed_args.name is not None: attrs['name'] = str(parsed_args.name) if parsed_args.admin_state is not None: attrs['admin_state_up'] = parsed_args.admin_state if parsed_args.shared is not None: attrs['shared'] = parsed_args.shared # "network set" command doesn't support setting project. if 'project' in parsed_args and parsed_args.project is not None: identity_client = client_manager.identity project_id = identity_common.find_project( identity_client, parsed_args.project, parsed_args.project_domain, ).id attrs['tenant_id'] = project_id # "network set" command doesn't support setting availability zone hints. if 'availability_zone_hints' in parsed_args and \ parsed_args.availability_zone_hints is not None: attrs['availability_zone_hints'] = parsed_args.availability_zone_hints return attrs def _get_attrs_compute(client_manager, parsed_args): attrs = {} if parsed_args.name is not None: attrs['label'] = str(parsed_args.name) if parsed_args.shared is not None: attrs['share_address'] = parsed_args.shared if parsed_args.subnet is not None: attrs['cidr'] = parsed_args.subnet return attrs class CreateNetwork(common.NetworkAndComputeShowOne): """Create new network""" def update_parser_common(self, parser): parser.add_argument( 'name', metavar='<name>', help='New network name', ) share_group = parser.add_mutually_exclusive_group() share_group.add_argument( '--share', dest='shared', action='store_true', default=None, help='Share the network between projects', ) share_group.add_argument( '--no-share', dest='shared', action='store_false', help='Do not share the network between projects', ) return parser def update_parser_network(self, parser): admin_group = parser.add_mutually_exclusive_group() admin_group.add_argument( '--enable', dest='admin_state', action='store_true', default=True, help='Enable network (default)', ) admin_group.add_argument( '--disable', dest='admin_state', action='store_false', help='Disable network', ) parser.add_argument( '--project', metavar='<project>', help="Owner's project (name or ID)" ) identity_common.add_project_domain_option_to_parser(parser) parser.add_argument( '--availability-zone-hint', action='append', dest='availability_zone_hints', metavar='<availability-zone>', help='Availability Zone in which to create this network ' '(requires the Network Availability Zone extension, ' 'this option can be repeated).', ) return parser def update_parser_compute(self, parser): parser.add_argument( '--subnet', metavar='<subnet>', help="IPv4 subnet for fixed IPs (in CIDR notation)" ) return parser def take_action_network(self, client, parsed_args): attrs = _get_attrs(self.app.client_manager, parsed_args) obj = client.create_network(**attrs) columns = _get_columns(obj) data = utils.get_item_properties(obj, columns, formatters=_formatters) return (columns, data) def take_action_compute(self, client, parsed_args): attrs = _get_attrs_compute(self.app.client_manager, parsed_args) obj = client.networks.create(**attrs) columns = _get_columns(obj._info) data = utils.get_dict_properties(obj._info, columns) return (columns, data) class DeleteNetwork(common.NetworkAndComputeCommand): """Delete network(s)""" def update_parser_common(self, parser): parser.add_argument( 'network', metavar="<network>", nargs="+", help=("Network(s) to delete (name or ID)") ) return parser def take_action_network(self, client, parsed_args): for network in parsed_args.network: obj = client.find_network(network) client.delete_network(obj) def take_action_compute(self, client, parsed_args): for network in parsed_args.network: network = utils.find_resource( client.networks, network, ) client.networks.delete(network.id) class ListNetwork(common.NetworkAndComputeLister): """List networks""" def update_parser_common(self, parser): parser.add_argument( '--external', action='store_true', default=False, help='List external networks', ) parser.add_argument( '--long', action='store_true', default=False, help='List additional fields in output', ) return parser def take_action_network(self, client, parsed_args): if parsed_args.long: columns = ( 'id', 'name', 'status', 'tenant_id', 'admin_state_up', 'shared', 'subnets', 'provider_network_type', 'router_external', 'availability_zones', ) column_headers = ( 'ID', 'Name', 'Status', 'Project', 'State', 'Shared', 'Subnets', 'Network Type', 'Router Type', 'Availability Zones', ) else: columns = ( 'id', 'name', 'subnets' ) column_headers = ( 'ID', 'Name', 'Subnets', ) if parsed_args.external: args = {'router:external': True} else: args = {} data = client.networks(**args) return (column_headers, (utils.get_item_properties( s, columns, formatters=_formatters, ) for s in data)) def take_action_compute(self, client, parsed_args): columns = ( 'id', 'label', 'cidr', ) column_headers = ( 'ID', 'Name', 'Subnet', ) data = client.networks.list() return (column_headers, (utils.get_item_properties( s, columns, formatters=_formatters, ) for s in data)) class SetNetwork(command.Command): """Set network properties""" def get_parser(self, prog_name): parser = super(SetNetwork, self).get_parser(prog_name) parser.add_argument( 'network', metavar="<network>", help=("Network to modify (name or ID)") ) parser.add_argument( '--name', metavar='<name>', help='Set network name', ) admin_group = parser.add_mutually_exclusive_group() admin_group.add_argument( '--enable', dest='admin_state', action='store_true', default=None, help='Enable network', ) admin_group.add_argument( '--disable', dest='admin_state', action='store_false', help='Disable network', ) share_group = parser.add_mutually_exclusive_group() share_group.add_argument( '--share', dest='shared', action='store_true', default=None, help='Share the network between projects', ) share_group.add_argument( '--no-share', dest='shared', action='store_false', help='Do not share the network between projects', ) return parser def take_action(self, parsed_args): client = self.app.client_manager.network obj = client.find_network(parsed_args.network, ignore_missing=False) attrs = _get_attrs(self.app.client_manager, parsed_args) if attrs == {}: msg = "Nothing specified to be set" raise exceptions.CommandError(msg) client.update_network(obj, **attrs) class ShowNetwork(common.NetworkAndComputeShowOne): """Show network details""" def update_parser_common(self, parser): parser.add_argument( 'network', metavar="<network>", help=("Network to display (name or ID)") ) return parser def take_action_network(self, client, parsed_args): obj = client.find_network(parsed_args.network, ignore_missing=False) columns = _get_columns(obj) data = utils.get_item_properties(obj, columns, formatters=_formatters) return (columns, data) def take_action_compute(self, client, parsed_args): obj = utils.find_resource( client.networks, parsed_args.network, ) columns = _get_columns(obj._info) data = utils.get_dict_properties(obj._info, columns) return (columns, data) <file_sep># Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # import copy import mock from openstackclient.common import extension from openstackclient.tests import fakes from openstackclient.tests import utils from openstackclient.tests.compute.v2 import fakes as compute_fakes from openstackclient.tests.identity.v2_0 import fakes as identity_fakes from openstackclient.tests.network.v2 import fakes as network_fakes from openstackclient.tests.volume.v2 import fakes as volume_fakes class TestExtension(utils.TestCommand): def setUp(self): super(TestExtension, self).setUp() self.app.client_manager.identity = identity_fakes.FakeIdentityv2Client( endpoint=fakes.AUTH_URL, token=fakes.AUTH_TOKEN, ) self.identity_extensions_mock = ( self.app.client_manager.identity.extensions) self.identity_extensions_mock.reset_mock() self.app.client_manager.compute = compute_fakes.FakeComputev2Client( endpoint=fakes.AUTH_URL, token=fakes.AUTH_TOKEN, ) self.app.client_manager.volume = volume_fakes.FakeVolumeClient( endpoint=fakes.AUTH_URL, token=fakes.AUTH_TOKEN, ) network_client = network_fakes.FakeNetworkV2Client() self.app.client_manager.network = network_client self.network_extensions_mock = network_client.extensions self.network_extensions_mock.reset_mock() class TestExtensionList(TestExtension): columns = ('Name', 'Alias', 'Description') long_columns = ('Name', 'Namespace', 'Description', 'Alias', 'Updated', 'Links') def setUp(self): super(TestExtensionList, self).setUp() self.identity_extensions_mock.list.return_value = [ fakes.FakeResource( None, copy.deepcopy(identity_fakes.EXTENSION), loaded=True, ), ] self.app.client_manager.compute.list_extensions = mock.Mock() self.compute_extensions_mock = ( self.app.client_manager.compute.list_extensions) self.compute_extensions_mock.show_all.return_value = [ fakes.FakeResource( None, copy.deepcopy(compute_fakes.EXTENSION), loaded=True, ), ] self.app.client_manager.volume.list_extensions = mock.Mock() self.volume_extensions_mock = ( self.app.client_manager.volume.list_extensions) self.volume_extensions_mock.show_all.return_value = [ fakes.FakeResource( None, copy.deepcopy(volume_fakes.EXTENSION), loaded=True, ), ] # Get the command object to test self.cmd = extension.ListExtension(self.app, None) def _test_extension_list_helper(self, arglist, verifylist, expected_data, long=False): parsed_args = self.check_parser(self.cmd, arglist, verifylist) # In base command class Lister in cliff, abstract method take_action() # returns a tuple containing the column names and an iterable # containing the data to be listed. columns, data = self.cmd.take_action(parsed_args) if long: self.assertEqual(self.long_columns, columns) else: self.assertEqual(self.columns, columns) self.assertEqual(expected_data, tuple(data)) def test_extension_list_no_options(self): arglist = [] verifylist = [] datalist = ( ( identity_fakes.extension_name, identity_fakes.extension_alias, identity_fakes.extension_description, ), ( compute_fakes.extension_name, compute_fakes.extension_alias, compute_fakes.extension_description, ), ( volume_fakes.extension_name, volume_fakes.extension_alias, volume_fakes.extension_description, ), ( network_fakes.extension_name, network_fakes.extension_alias, network_fakes.extension_description, ), ) self._test_extension_list_helper(arglist, verifylist, datalist) self.identity_extensions_mock.list.assert_called_with() self.compute_extensions_mock.show_all.assert_called_with() self.volume_extensions_mock.show_all.assert_called_with() self.network_extensions_mock.assert_called_with() def test_extension_list_long(self): arglist = [ '--long', ] verifylist = [ ('long', True), ] datalist = ( ( identity_fakes.extension_name, identity_fakes.extension_namespace, identity_fakes.extension_description, identity_fakes.extension_alias, identity_fakes.extension_updated, identity_fakes.extension_links, ), ( compute_fakes.extension_name, compute_fakes.extension_namespace, compute_fakes.extension_description, compute_fakes.extension_alias, compute_fakes.extension_updated, compute_fakes.extension_links, ), ( volume_fakes.extension_name, volume_fakes.extension_namespace, volume_fakes.extension_description, volume_fakes.extension_alias, volume_fakes.extension_updated, volume_fakes.extension_links, ), ( network_fakes.extension_name, network_fakes.extension_namespace, network_fakes.extension_description, network_fakes.extension_alias, network_fakes.extension_updated, network_fakes.extension_links, ), ) self._test_extension_list_helper(arglist, verifylist, datalist, True) self.identity_extensions_mock.list.assert_called_with() self.compute_extensions_mock.show_all.assert_called_with() self.volume_extensions_mock.show_all.assert_called_with() self.network_extensions_mock.assert_called_with() def test_extension_list_identity(self): arglist = [ '--identity', ] verifylist = [ ('identity', True), ] datalist = (( identity_fakes.extension_name, identity_fakes.extension_alias, identity_fakes.extension_description, ), ) self._test_extension_list_helper(arglist, verifylist, datalist) self.identity_extensions_mock.list.assert_called_with() def test_extension_list_network(self): arglist = [ '--network', ] verifylist = [ ('network', True), ] datalist = ( ( network_fakes.extension_name, network_fakes.extension_alias, network_fakes.extension_description, ), ) self._test_extension_list_helper(arglist, verifylist, datalist) self.network_extensions_mock.assert_called_with() def test_extension_list_compute(self): arglist = [ '--compute', ] verifylist = [ ('compute', True), ] datalist = (( compute_fakes.extension_name, compute_fakes.extension_alias, compute_fakes.extension_description, ), ) self._test_extension_list_helper(arglist, verifylist, datalist) self.compute_extensions_mock.show_all.assert_called_with() def test_extension_list_volume(self): arglist = [ '--volume', ] verifylist = [ ('volume', True), ] datalist = (( volume_fakes.extension_name, volume_fakes.extension_alias, volume_fakes.extension_description, ), ) self._test_extension_list_helper(arglist, verifylist, datalist) self.volume_extensions_mock.show_all.assert_called_with() <file_sep>====== flavor ====== Compute v2 flavor create ------------- Create new flavor .. program:: flavor create .. code:: bash os flavor create [--id <id>] [--ram <size-mb>] [--disk <size-gb>] [--ephemeral-disk <size-gb>] [--swap <size-mb>] [--vcpus <num-cpu>] [--rxtx-factor <factor>] [--public | --private] <flavor-name> .. option:: --id <id> Unique flavor ID; 'auto' creates a UUID (default: auto) .. option:: --ram <size-mb> Memory size in MB (default 256M) .. option:: --disk <size-gb> Disk size in GB (default 0G) .. option:: --ephemeral-disk <size-gb> Ephemeral disk size in GB (default 0G) .. option:: --swap <size-gb> Swap space size in GB (default 0G) .. option:: --vcpus <num-cpu> Number of vcpus (default 1) .. option:: --rxtx-factor <factor> RX/TX factor (default 1) .. option:: --public Flavor is available to other projects (default) .. option:: --private Flavor is not available to other projects .. _flavor_create-flavor-name: .. describe:: <flavor-name> New flavor name flavor delete ------------- Delete flavor .. program:: flavor delete .. code:: bash os flavor delete <flavor> .. _flavor_delete-flavor: .. describe:: <flavor> Flavor to delete (name or ID) flavor list ----------- List flavors .. program:: flavor list .. code:: bash os flavor list [--public | --private | --all] [--long] [--marker <marker>] [--limit <limit>] .. option:: --public List only public flavors (default) .. option:: --private List only private flavors .. option:: --all List all flavors, whether public or private .. option:: --long List additional fields in output .. option:: --marker <marker> The last flavor ID of the previous page .. option:: --limit <limit> Maximum number of flavors to display flavor show ----------- Display flavor details .. program:: flavor show .. code:: bash os flavor show <flavor> .. _flavor_show-flavor: .. describe:: <flavor> Flavor to display (name or ID) flavor set ---------- Set flavor properties .. program:: flavor set .. code:: bash os flavor set [--property <key=value> [...] ] <flavor> .. option:: --property <key=value> Property to add or modify for this flavor (repeat option to set multiple properties) .. describe:: <flavor> Flavor to modify (name or ID) flavor unset ------------ Unset flavor properties .. program:: flavor unset .. code:: bash os flavor unset [--property <key> [...] ] <flavor> .. option:: --property <key> Property to remove from flavor (repeat option to remove multiple properties) .. describe:: <flavor> Flavor to modify (name or ID) <file_sep>====== region ====== Identity v3 region create ------------- Create new region .. program:: region create .. code:: bash os region create [--parent-region <region-id>] [--description <description>] <region-id> .. option:: --parent-region <region-id> Parent region ID .. option:: --description <description> New region description .. _region_create-region-id: .. describe:: <region-id> New region ID region delete ------------- Delete region .. program:: region delete .. code:: bash os region delete <region-id> .. _region_delete-region-id: .. describe:: <region-id> Region ID to delete region list ----------- List regions .. program:: region list .. code:: bash os region list [--parent-region <region-id>] .. option:: --parent-region <region-id> Filter by parent region ID region set ---------- Set region properties .. program:: region set .. code:: bash os region set [--parent-region <region-id>] [--description <description>] <region-id> .. option:: --parent-region <region-id> New parent region ID .. option:: --description <description> New region description .. _region_set-region-id: .. describe:: <region-id> Region to modify region show ----------- Display region details .. program:: region show .. code:: bash os region show <region-id> .. _region_show-region-id: .. describe:: <region-id> Region to display <file_sep>==== user ==== Identity v2, v3 user create ----------- Create new user .. program:: user create .. code:: bash os user create [--domain <domain>] [--project <project> [--project-domain <project-domain>]] [--password <<PASSWORD>>] [--password-prompt] [--email <email-address>] [--description <description>] [--enable | --disable] [--or-show] <user-name> .. option:: --domain <domain> Default domain (name or ID) .. versionadded:: 3 .. option:: --project <project> Default project (name or ID) .. option:: --project-domain <project-domain> Domain the project belongs to (name or ID). This can be used in case collisions between project names exist. .. option:: --password <password> Set user password .. option:: --password-prompt Prompt interactively for password .. option:: --email <email-address> Set user email address .. option:: --description <description> User description .. versionadded:: 3 .. option:: --enable Enable user (default) .. option:: --disable Disable user .. option:: --or-show Return existing user If the username already exist return the existing user data and do not fail. .. describe:: <user-name> New user name user delete ----------- Delete user(s) .. program:: user delete .. code:: bash os user delete [--domain <domain>] <user> [<user> ...] .. option:: --domain <domain> Domain owning :ref:`\<user\> <user_delete-user>` (name or ID) .. versionadded:: 3 .. _user_delete-user: .. describe:: <user> User to delete (name or ID) user list --------- List users .. program:: user list .. code:: bash os user list [--project <project>] [--domain <domain>] [--group <group> | --project <project>] [--long] .. option:: --project <project> Filter users by `<project>` (name or ID) .. option:: --domain <domain> Filter users by `<domain>` (name or ID) *Identity version 3 only* .. option:: --group <group> Filter users by `<group>` membership (name or ID) *Identity version 3 only* .. option:: --long List additional fields in output user set -------- Set user properties .. program:: user set .. code:: bash os user set [--name <name>] [--project <project> [--project-domain <project-domain>]] [--password <<PASSWORD>>] [--email <email-address>] [--description <description>] [--enable|--disable] <user> .. option:: --name <name> Set user name .. option:: --project <project> Set default project (name or ID) .. option:: --project-domain <project-domain> Domain the project belongs to (name or ID). This can be used in case collisions between project names exist. .. option:: --password <<PASSWORD>> Set user password .. option:: --password-prompt Prompt interactively for password .. option:: --email <email-address> Set user email address .. option:: --description <description> Set user description .. versionadded:: 3 .. option:: --enable Enable user (default) .. option:: --disable Disable user .. describe:: <user> User to modify (name or ID) user show --------- Display user details .. program:: user show .. code:: bash os user show [--domain <domain>] <user> .. option:: --domain <domain> Domain owning :ref:`\<user\> <user_show-user>` (name or ID) .. versionadded:: 3 .. _user_show-user: .. describe:: <user> User to display (name or ID) <file_sep>============ access token ============ Identity v3 `Requires: OS-OAUTH1 extension` access token create ------------------- Create an access token .. program:: access token create .. code:: bash os access token create --consumer-key <consumer-key> --consumer-secret <consumer-secret> --request-key <request-key> --request-secret <request-secret> --verifier <verifier> .. option:: --consumer-key <consumer-key> Consumer key (required) .. option:: --consumer-secret <consumer-secret> Consumer secret (required) .. option:: --request-key <request-key> Request token to exchange for access token (required) .. option:: --request-secret <request-secret> Secret associated with <request-key> (required) .. option:: --verifier <verifier> Verifier associated with <request-key> (required) <file_sep># Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import json from openstackclient.identity.v3 import credential from openstackclient.tests.identity.v3 import fakes as identity_fakes from openstackclient.tests import utils class TestCredential(identity_fakes.TestIdentityv3): data = { "access": "abc123", "secret": "hidden-message", "trust_id": None } def __init__(self, *args): super(TestCredential, self).__init__(*args) self.json_data = json.dumps(self.data) def setUp(self): super(TestCredential, self).setUp() # Get a shortcut to the CredentialManager Mock self.credentials_mock = self.app.client_manager.identity.credentials self.credentials_mock.reset_mock() # Get a shortcut to the UserManager Mock self.users_mock = self.app.client_manager.identity.users self.users_mock.reset_mock() # Get a shortcut to the ProjectManager Mock self.projects_mock = self.app.client_manager.identity.projects self.projects_mock.reset_mock() class TestCredentialSet(TestCredential): def setUp(self): super(TestCredentialSet, self).setUp() self.cmd = credential.SetCredential(self.app, None) def test_credential_set_no_options(self): arglist = [ identity_fakes.credential_id, ] self.assertRaises(utils.ParserException, self.check_parser, self.cmd, arglist, []) def test_credential_set_missing_user(self): arglist = [ '--type', 'ec2', '--data', self.json_data, identity_fakes.credential_id, ] self.assertRaises(utils.ParserException, self.check_parser, self.cmd, arglist, []) def test_credential_set_missing_type(self): arglist = [ '--user', identity_fakes.user_name, '--data', self.json_data, identity_fakes.credential_id, ] self.assertRaises(utils.ParserException, self.check_parser, self.cmd, arglist, []) def test_credential_set_missing_data(self): arglist = [ '--user', identity_fakes.user_name, '--type', 'ec2', identity_fakes.credential_id, ] self.assertRaises(utils.ParserException, self.check_parser, self.cmd, arglist, []) def test_credential_set_valid(self): arglist = [ '--user', identity_fakes.user_name, '--type', 'ec2', '--data', self.json_data, identity_fakes.credential_id, ] parsed_args = self.check_parser(self.cmd, arglist, []) result = self.cmd.take_action(parsed_args) self.assertIsNone(result) def test_credential_set_valid_with_project(self): arglist = [ '--user', identity_fakes.user_name, '--type', 'ec2', '--data', self.json_data, '--project', identity_fakes.project_name, identity_fakes.credential_id, ] parsed_args = self.check_parser(self.cmd, arglist, []) result = self.cmd.take_action(parsed_args) self.assertIsNone(result) <file_sep>=================== security group rule =================== Compute v2, Network v2 security group rule create -------------------------- Create a new security group rule .. program:: security group rule create .. code:: bash os security group rule create [--proto <proto>] [--src-ip <ip-address> | --src-group <group>] [--dst-port <port-range>] <group> .. option:: --proto <proto> IP protocol (icmp, tcp, udp; default: tcp) .. option:: --src-ip <ip-address> Source IP address block (may use CIDR notation; default: 0.0.0.0/0) .. option:: --src-group <group> Source security group (ID only) .. option:: --dst-port <port-range> Destination port, may be a range: 137:139 (default: 0; only required for proto tcp and udp) .. describe:: <group> Create rule in this security group (name or ID) security group rule delete -------------------------- Delete a security group rule .. program:: security group rule delete .. code:: bash os security group rule delete <rule> .. describe:: <rule> Security group rule to delete (ID only) security group rule list ------------------------ List security group rules .. program:: security group rule list .. code:: bash os security group rule list [<group>] .. describe:: <group> List all rules in this security group (name or ID) security group rule show ------------------------ Display security group rule details .. program:: security group rule show .. code:: bash os security group rule show <rule> .. describe:: <rule> Security group rule to display (ID only) <file_sep>================ service provider ================ Identity v3 `Requires: OS-FEDERATION extension` service provider create ----------------------- Create new service provider .. program:: service provider create .. code:: bash os service provider create [--description <description>] [--enable | --disable] --auth-url <auth-url> --service-provider-url <sp-url> <name> .. option:: --auth-url Authentication URL of remote federated service provider (required) .. option:: --service-provider-url A service URL where SAML assertions are being sent (required) .. option:: --description New service provider description .. option:: --enable Enable the service provider (default) .. option:: --disable Disable the service provider .. describe:: <name> New service provider name (must be unique) service provider delete ----------------------- Delete service provider .. program:: service provider delete .. code:: bash os service provider delete <service-provider> .. describe:: <service-provider> Service provider to delete service provider list --------------------- List service providers .. program:: service provider list .. code:: bash os service provider list service provider set -------------------- Set service provider properties .. program:: service provider set .. code:: bash os service provider set [--enable | --disable] [--description <description>] [--auth-url <auth-url>] [--service-provider-url <sp-url>] <service-provider> .. option:: --service-provider-url New service provider URL, where SAML assertions are sent .. option:: --auth-url New Authentication URL of remote federated service provider .. option:: --description New service provider description .. option:: --enable Enable the service provider .. option:: --disable Disable the service provider .. describe:: <service-provider> Service provider to modify service provider show --------------------- Display service provider details .. program:: service provider show .. code:: bash os service provider show <service-provider> .. describe:: <service-provider> Service provider to display <file_sep>========== hypervisor ========== Compute v2 hypervisor list --------------- List hypervisors .. program:: hypervisor list .. code:: bash os hypervisor list [--matching <hostname>] .. option:: --matching <hostname> Filter hypervisors using <hostname> substring hypervisor show --------------- Display hypervisor details .. program:: hypervisor show .. code:: bash os hypervisor show <hypervisor> .. _hypervisor_show-flavor: .. describe:: <hypervisor> Hypervisor to display (name or ID) <file_sep># Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import time import uuid import testtools from functional.common import exceptions from functional.common import test class ServerTests(test.TestCase): """Functional tests for server. """ NAME = uuid.uuid4().hex OTHER_NAME = uuid.uuid4().hex HEADERS = ['"Name"'] FIELDS = ['name'] IP_POOL = 'public' @classmethod def get_flavor(cls): raw_output = cls.openstack('flavor list -f value -c ID') ray = raw_output.split('\n') idx = int(len(ray) / 2) return ray[idx] @classmethod def get_image(cls): raw_output = cls.openstack('image list -f value -c ID') ray = raw_output.split('\n') idx = int(len(ray) / 2) return ray[idx] @classmethod def get_network(cls): try: raw_output = cls.openstack('network list -f value -c ID') except exceptions.CommandFailed: return '' ray = raw_output.split('\n') idx = int(len(ray) / 2) return ' --nic net-id=' + ray[idx] @classmethod def setUpClass(cls): opts = cls.get_show_opts(cls.FIELDS) flavor = cls.get_flavor() image = cls.get_image() network = cls.get_network() raw_output = cls.openstack('server create --flavor ' + flavor + ' --image ' + image + network + ' ' + cls.NAME + opts) expected = cls.NAME + '\n' cls.assertOutput(expected, raw_output) @classmethod def tearDownClass(cls): # Rename test raw_output = cls.openstack('server set --name ' + cls.OTHER_NAME + ' ' + cls.NAME) cls.assertOutput("", raw_output) # Delete test raw_output = cls.openstack('server delete ' + cls.OTHER_NAME) cls.assertOutput('', raw_output) def test_server_list(self): opts = self.get_list_opts(self.HEADERS) raw_output = self.openstack('server list' + opts) self.assertIn(self.NAME, raw_output) def test_server_show(self): opts = self.get_show_opts(self.FIELDS) raw_output = self.openstack('server show ' + self.NAME + opts) self.assertEqual(self.NAME + "\n", raw_output) def wait_for(self, desired, wait=120, interval=5, failures=['ERROR']): # TODO(thowe): Add a server wait command to osc status = "notset" wait = 120 interval = 5 total_sleep = 0 opts = self.get_show_opts(['status']) while total_sleep < wait: status = self.openstack('server show ' + self.NAME + opts) status = status.rstrip() print('Waiting for {} current status: {}'.format(desired, status)) if status == desired: break self.assertNotIn(status, failures) time.sleep(interval) total_sleep += interval self.assertEqual(desired, status) @testtools.skip('skipping due to bug 1483422') def test_server_up_test(self): self.wait_for("ACTIVE") # give it a little bit more time time.sleep(5) # metadata raw_output = self.openstack( 'server set --property a=b --property c=d ' + self.NAME) opts = self.get_show_opts(["name", "properties"]) raw_output = self.openstack('server show ' + self.NAME + opts) self.assertEqual(self.NAME + "\na='b', c='d'\n", raw_output) # suspend raw_output = self.openstack('server suspend ' + self.NAME) self.assertEqual("", raw_output) self.wait_for("SUSPENDED") # resume raw_output = self.openstack('server resume ' + self.NAME) self.assertEqual("", raw_output) self.wait_for("ACTIVE") # lock raw_output = self.openstack('server lock ' + self.NAME) self.assertEqual("", raw_output) # unlock raw_output = self.openstack('server unlock ' + self.NAME) self.assertEqual("", raw_output) # pause raw_output = self.openstack('server pause ' + self.NAME) self.assertEqual("", raw_output) self.wait_for("PAUSED") # unpause raw_output = self.openstack('server unpause ' + self.NAME) self.assertEqual("", raw_output) self.wait_for("ACTIVE") # rescue opts = self.get_show_opts(["adminPass"]) raw_output = self.openstack('server rescue ' + self.NAME + opts) self.assertNotEqual("", raw_output) self.wait_for("RESCUE") # unrescue raw_output = self.openstack('server unrescue ' + self.NAME) self.assertEqual("", raw_output) self.wait_for("ACTIVE") # attach ip opts = self.get_show_opts(["id", "ip"]) raw_output = self.openstack('ip floating create ' + self.IP_POOL + opts) ipid, ip, rol = tuple(raw_output.split('\n')) self.assertNotEqual("", ipid) self.assertNotEqual("", ip) raw_output = self.openstack('ip floating add ' + ip + ' ' + self.NAME) self.assertEqual("", raw_output) raw_output = self.openstack('server show ' + self.NAME) self.assertIn(ip, raw_output) # detach ip raw_output = self.openstack('ip floating remove ' + ip + ' ' + self.NAME) self.assertEqual("", raw_output) raw_output = self.openstack('server show ' + self.NAME) self.assertNotIn(ip, raw_output) raw_output = self.openstack('ip floating delete ' + ipid) self.assertEqual("", raw_output) # reboot raw_output = self.openstack('server reboot ' + self.NAME) self.assertEqual("", raw_output) self.wait_for("ACTIVE") <file_sep>===== quota ===== Resource quotas appear in multiple APIs, OpenStackClient presents them as a single object with multiple properties. Compute v2, Block Storage v1 quota set --------- Set quotas for project .. program:: quota set .. code:: bash os quota set # Compute settings [--cores <num-cores>] [--fixed-ips <num-fixed-ips>] [--floating-ips <num-floating-ips>] [--injected-file-size <injected-file-bytes>] [--injected-files <num-injected-files>] [--instances <num-instances>] [--key-pairs <num-key-pairs>] [--properties <num-properties>] [--ram <ram-mb>] # Block Storage settings [--gigabytes <new-gigabytes>] [--snapshots <new-snapshots>] [--volumes <new-volumes>] [--volume-type <volume-type>] <project> Set quotas for class .. code:: bash os quota set --class # Compute settings [--cores <num-cores>] [--fixed-ips <num-fixed-ips>] [--floating-ips <num-floating-ips>] [--injected-file-size <injected-file-bytes>] [--injected-files <num-injected-files>] [--instances <num-instances>] [--key-pairs <num-key-pairs>] [--properties <num-properties>] [--ram <ram-mb>] # Block Storage settings [--gigabytes <new-gigabytes>] [--snapshots <new-snapshots>] [--volumes <new-volumes>] <class> .. option:: --class Set quotas for ``<class>`` .. option:: --properties <new-properties> New value for the properties quota .. option:: --ram <new-ram> New value for the ram quota .. option:: --secgroup-rules <new-secgroup-rules> New value for the secgroup-rules quota .. option:: --instances <new-instances> New value for the instances quota .. option:: --key-pairs <new-key-pairs> New value for the key-pairs quota .. option:: --fixed-ips <new-fixed-ips> New value for the fixed-ips quota .. option:: --secgroups <new-secgroups> New value for the secgroups quota .. option:: --injected-file-size <new-injected-file-size> New value for the injected-file-size quota .. option:: --floating-ips <new-floating-ips> New value for the floating-ips quota .. option:: --injected-files <new-injected-files> New value for the injected-files quota .. option:: --cores <new-cores> New value for the cores quota .. option:: --injected-path-size <new-injected-path-size> New value for the injected-path-size quota .. option:: --gigabytes <new-gigabytes> New value for the gigabytes quota .. option:: --volumes <new-volumes> New value for the volumes quota .. option:: --snapshots <new-snapshots> New value for the snapshots quota .. option:: --volume-type <volume-type> Set quotas for a specific <volume-type> quota show ---------- Show quotas for project .. program:: quota show .. code:: bash os quota show [--default] <project> .. option:: --default Show default quotas for :ref:`\<project\> <quota_show-project>` .. _quota_show-project: .. describe:: <project> Show quotas for class .. code:: bash os quota show --class <class> .. option:: --class Show quotas for :ref:`\<class\> <quota_show-class>` .. _quota_show-class: .. describe:: <class> Class to show <file_sep># Copyright 2016 IBM # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # import mock from openstackclient.compute.v2 import keypair from openstackclient.tests.compute.v2 import fakes as compute_fakes from openstackclient.tests import utils as tests_utils class TestKeypair(compute_fakes.TestComputev2): def setUp(self): super(TestKeypair, self).setUp() # Get a shortcut to the KeypairManager Mock self.keypairs_mock = self.app.client_manager.compute.keypairs self.keypairs_mock.reset_mock() class TestKeypairCreate(TestKeypair): keypair = compute_fakes.FakeKeypair.create_one_keypair() def setUp(self): super(TestKeypairCreate, self).setUp() self.columns = ( 'fingerprint', 'name', 'user_id' ) self.data = ( self.keypair.fingerprint, self.keypair.name, self.keypair.user_id ) # Get the command object to test self.cmd = keypair.CreateKeypair(self.app, None) self.keypairs_mock.create.return_value = self.keypair def test_key_pair_create_no_options(self): arglist = [ self.keypair.name, ] verifylist = [ ('name', self.keypair.name), ] parsed_args = self.check_parser(self.cmd, arglist, verifylist) columns, data = self.cmd.take_action(parsed_args) self.keypairs_mock.create.assert_called_with( self.keypair.name, public_key=None ) self.assertEqual({}, columns) self.assertEqual({}, data) def test_keypair_create_public_key(self): # overwrite the setup one because we want to omit private_key self.keypair = compute_fakes.FakeKeypair.create_one_keypair( no_pri=True) self.keypairs_mock.create.return_value = self.keypair self.data = ( self.keypair.fingerprint, self.keypair.name, self.keypair.user_id ) arglist = [ '--public-key', self.keypair.public_key, self.keypair.name, ] verifylist = [ ('public_key', self.keypair.public_key), ('name', self.keypair.name) ] parsed_args = self.check_parser(self.cmd, arglist, verifylist) with mock.patch('io.open') as mock_open: mock_open.return_value = mock.MagicMock() m_file = mock_open.return_value.__enter__.return_value m_file.read.return_value = 'dummy' columns, data = self.cmd.take_action(parsed_args) self.keypairs_mock.create.assert_called_with( self.keypair.name, public_key=self.keypair.public_key ) self.assertEqual(self.columns, columns) self.assertEqual(self.data, data) class TestKeypairDelete(TestKeypair): keypair = compute_fakes.FakeKeypair.create_one_keypair() def setUp(self): super(TestKeypairDelete, self).setUp() self.keypairs_mock.get.return_value = self.keypair self.keypairs_mock.delete.return_value = None self.cmd = keypair.DeleteKeypair(self.app, None) def test_keypair_delete(self): arglist = [ self.keypair.name ] verifylist = [ ('name', self.keypair.name), ] parsed_args = self.check_parser(self.cmd, arglist, verifylist) ret = self.cmd.take_action(parsed_args) self.assertIsNone(ret) self.keypairs_mock.delete.assert_called_with(self.keypair.name) class TestKeypairList(TestKeypair): # Return value of self.keypairs_mock.list(). keypairs = compute_fakes.FakeKeypair.create_keypairs(count=1) columns = ( "Name", "Fingerprint" ) data = (( keypairs[0].name, keypairs[0].fingerprint ), ) def setUp(self): super(TestKeypairList, self).setUp() self.keypairs_mock.list.return_value = self.keypairs # Get the command object to test self.cmd = keypair.ListKeypair(self.app, None) def test_keypair_list_no_options(self): arglist = [] verifylist = [ ] parsed_args = self.check_parser(self.cmd, arglist, verifylist) # In base command class Lister in cliff, abstract method take_action() # returns a tuple containing the column names and an iterable # containing the data to be listed. columns, data = self.cmd.take_action(parsed_args) # Set expected values self.keypairs_mock.list.assert_called_with() self.assertEqual(self.columns, columns) self.assertEqual(tuple(self.data), tuple(data)) class TestKeypairShow(TestKeypair): keypair = compute_fakes.FakeKeypair.create_one_keypair() def setUp(self): super(TestKeypairShow, self).setUp() self.keypairs_mock.get.return_value = self.keypair self.cmd = keypair.ShowKeypair(self.app, None) self.columns = ( "fingerprint", "name", "user_id" ) self.data = ( self.keypair.fingerprint, self.keypair.name, self.keypair.user_id ) def test_show_no_options(self): arglist = [] verifylist = [] # Missing required args should boil here self.assertRaises(tests_utils.ParserException, self.check_parser, self.cmd, arglist, verifylist) def test_keypair_show(self): # overwrite the setup one because we want to omit private_key self.keypair = compute_fakes.FakeKeypair.create_one_keypair( no_pri=True) self.keypairs_mock.get.return_value = self.keypair self.data = ( self.keypair.fingerprint, self.keypair.name, self.keypair.user_id ) arglist = [ self.keypair.name ] verifylist = [ ('name', self.keypair.name) ] parsed_args = self.check_parser(self.cmd, arglist, verifylist) columns, data = self.cmd.take_action(parsed_args) self.assertEqual(self.columns, columns) self.assertEqual(self.data, data) def test_keypair_show_public(self): arglist = [ '--public-key', self.keypair.name ] verifylist = [ ('public_key', True), ('name', self.keypair.name) ] parsed_args = self.check_parser(self.cmd, arglist, verifylist) columns, data = self.cmd.take_action(parsed_args) self.assertEqual({}, columns) self.assertEqual({}, data) <file_sep># Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # """Subnet action implementations""" from openstackclient.common import command from openstackclient.common import utils def _format_allocation_pools(data): pool_formatted = ['%s-%s' % (pool.get('start', ''), pool.get('end', '')) for pool in data] return ','.join(pool_formatted) _formatters = { 'allocation_pools': _format_allocation_pools, 'dns_nameservers': utils.format_list, 'host_routes': utils.format_list, } def _get_columns(item): columns = item.keys() if 'tenant_id' in columns: columns.remove('tenant_id') columns.append('project_id') return tuple(sorted(columns)) class DeleteSubnet(command.Command): """Delete subnet""" def get_parser(self, prog_name): parser = super(DeleteSubnet, self).get_parser(prog_name) parser.add_argument( 'subnet', metavar="<subnet>", help="Subnet to delete (name or ID)" ) return parser def take_action(self, parsed_args): client = self.app.client_manager.network client.delete_subnet( client.find_subnet(parsed_args.subnet)) class ListSubnet(command.Lister): """List subnets""" def get_parser(self, prog_name): parser = super(ListSubnet, self).get_parser(prog_name) parser.add_argument( '--long', action='store_true', default=False, help='List additional fields in output', ) return parser def take_action(self, parsed_args): data = self.app.client_manager.network.subnets() headers = ('ID', 'Name', 'Network', 'Subnet') columns = ('id', 'name', 'network_id', 'cidr') if parsed_args.long: headers += ('Project', 'DHCP', 'Name Servers', 'Allocation Pools', 'Host Routes', 'IP Version', 'Gateway') columns += ('tenant_id', 'enable_dhcp', 'dns_nameservers', 'allocation_pools', 'host_routes', 'ip_version', 'gateway_ip') return (headers, (utils.get_item_properties( s, columns, formatters=_formatters, ) for s in data)) class ShowSubnet(command.ShowOne): """Show subnet details""" def get_parser(self, prog_name): parser = super(ShowSubnet, self).get_parser(prog_name) parser.add_argument( 'subnet', metavar="<subnet>", help="Subnet to show (name or ID)" ) return parser def take_action(self, parsed_args): obj = self.app.client_manager.network.find_subnet(parsed_args.subnet, ignore_missing=False) columns = _get_columns(obj) data = utils.get_item_properties(obj, columns, formatters=_formatters) return (columns, data) <file_sep>============= request token ============= Identity v3 `Requires: OS-OAUTH1 extension` request token authorize ----------------------- Authorize a request token .. program:: request token authorize .. code:: bash os request token authorize --request-key <consumer-key> --role <role> .. option:: --request-key <request-key> Request token to authorize (ID only) (required) .. option:: --role <role> Roles to authorize (name or ID) (repeat to set multiple values) (required) request token create -------------------- Create a request token .. program:: request token create .. code:: bash os request token create --consumer-key <consumer-key> --consumer-secret <consumer-secret> --project <project> [--domain <domain>] .. option:: --consumer-key <consumer-key> Consumer key (required) .. option:: --description <description> Consumer secret (required) .. option:: --project <project> Project that consumer wants to access (name or ID) (required) .. option:: --domain <domain> Domain owning <project> (name or ID) <file_sep>========== volume qos ========== Block Storage v1, v2 volume qos associate -------------------- Associate a QoS specification to a volume type .. program:: volume qos associate .. code:: bash os volume qos associate <qos-spec> <volume-type> .. describe:: <qos-spec> QoS specification to modify (name or ID) .. describe:: <volume-type> Volume type to associate the QoS (name or ID) volume qos create ----------------- Create new QoS Specification .. program:: volume qos create .. code:: bash os volume qos create [--consumer <consumer>] [--property <key=value> [...] ] <name> .. option:: --consumer <consumer> Consumer of the QoS. Valid consumers: 'front-end', 'back-end', 'both' (defaults to 'both') .. option:: --property <key=value> Set a property on this QoS specification (repeat option to set multiple properties) .. describe:: <name> New QoS specification name volume qos delete ----------------- Delete QoS specification .. program:: volume qos delete .. code:: bash os volume qos delete <qos-spec> [<qos-spec> ...] .. describe:: <qos-spec> QoS specification(s) to delete (name or ID) volume qos disassociate ----------------------- Disassociate a QoS specification from a volume type .. program:: volume qos disassoiate .. code:: bash os volume qos disassociate --volume-type <volume-type> | --all <qos-spec> .. option:: --volume-type <volume-type> Volume type to disassociate the QoS from (name or ID) .. option:: --all Disassociate the QoS from every volume type .. describe:: <qos-spec> QoS specification to modify (name or ID) volume qos list --------------- List QoS specifications .. program:: volume qos list .. code:: bash os volume qos list volume qos set -------------- Set QoS specification properties .. program:: volume qos set .. code:: bash os volume qos set [--property <key=value> [...] ] <qos-spec> .. option:: --property <key=value> Property to add or modify for this QoS specification (repeat option to set multiple properties) .. describe:: <qos-spec> QoS specification to modify (name or ID) volume qos show --------------- Display QoS specification details .. program:: volume qos show .. code:: bash os volume qos show <qos-spec> .. describe:: <qos-spec> QoS specification to display (name or ID) volume qos unset ---------------- Unset QoS specification properties .. program:: volume qos unset .. code:: bash os volume qos unset [--property <key>] <qos-spec> .. option:: --property <key> Property to remove from QoS specification (repeat option to remove multiple properties) .. describe:: <qos-spec> QoS specification to modify (name or ID) <file_sep># Copyright 2016 EasyStack Corporation # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # from openstackclient.compute.v2 import hypervisor_stats from openstackclient.tests.compute.v2 import fakes as compute_fakes class TestHypervisorStats(compute_fakes.TestComputev2): def setUp(self): super(TestHypervisorStats, self).setUp() # Get a shortcut to the compute client hypervisors mock self.hypervisors_mock = self.app.client_manager.compute.hypervisors self.hypervisors_mock.reset_mock() class TestHypervisorStatsShow(TestHypervisorStats): def setUp(self): super(TestHypervisorStatsShow, self).setUp() self.hypervisor_stats = \ compute_fakes.FakehypervisorStats.create_one_hypervisor_stats() self.hypervisors_mock.statistics.return_value =\ self.hypervisor_stats self.cmd = hypervisor_stats.ShowHypervisorStats(self.app, None) self.columns = ( 'count', 'current_workload', 'disk_available_least', 'free_disk_gb', 'free_ram_mb', 'local_gb', 'local_gb_used', 'memory_mb', 'memory_mb_used', 'running_vms', 'vcpus', 'vcpus_used', ) self.data = ( 2, 0, 50, 100, 23000, 100, 0, 23800, 1400, 3, 8, 3, ) def test_hypervisor_show_stats(self): arglist = [] verifylist = [] parsed_args = self.check_parser(self.cmd, arglist, verifylist) columns, data = self.cmd.take_action(parsed_args) self.assertEqual(self.columns, columns) self.assertEqual(self.data, data) <file_sep># Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import hashlib from functional.common import test class ComputeAgentTests(test.TestCase): """Functional tests for compute agent. """ ID = None MD5HASH = hashlib.md5().hexdigest() URL = "http://localhost" VER = "v1" OS = "TEST_OS" ARCH = "x86_64" HYPER = "kvm" HEADERS = ['agent_id', 'md5hash'] FIELDS = ['agent_id', 'md5hash'] @classmethod def setUpClass(cls): opts = cls.get_show_opts(cls.HEADERS) raw_output = cls.openstack('compute agent create ' + cls.OS + ' ' + cls.ARCH + ' ' + cls.VER + ' ' + cls.URL + ' ' + cls.MD5HASH + ' ' + cls.HYPER + ' ' + opts) # Get agent id because agent can only be deleted by ID output_list = raw_output.split('\n', 1) cls.ID = output_list[0] cls.assertOutput(cls.MD5HASH + '\n', output_list[1]) @classmethod def tearDownClass(cls): raw_output = cls.openstack('compute agent delete ' + cls.ID) cls.assertOutput('', raw_output) def test_agent_list(self): raw_output = self.openstack('compute agent list') self.assertIn(self.ID, raw_output) self.assertIn(self.OS, raw_output) self.assertIn(self.ARCH, raw_output) self.assertIn(self.VER, raw_output) self.assertIn(self.URL, raw_output) self.assertIn(self.MD5HASH, raw_output) self.assertIn(self.HYPER, raw_output) def test_agent_set(self): ver = 'v2' url = "http://openstack" md5hash = hashlib.md5().hexdigest() raw_output = self.openstack('compute agent set ' + self.ID + ' ' + ver + ' ' + url + ' ' + md5hash) self.assertEqual('', raw_output) raw_output = self.openstack('compute agent list') self.assertIn(self.ID, raw_output) self.assertIn(ver, raw_output) self.assertIn(url, raw_output) self.assertIn(md5hash, raw_output) <file_sep># Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # import mock from openstackclient.network.v2 import floating_ip from openstackclient.tests.compute.v2 import fakes as compute_fakes from openstackclient.tests.network.v2 import fakes as network_fakes # Tests for Neutron network # class TestFloatingIPNetwork(network_fakes.TestNetworkV2): def setUp(self): super(TestFloatingIPNetwork, self).setUp() # Get a shortcut to the network client self.network = self.app.client_manager.network class TestDeleteFloatingIPNetwork(TestFloatingIPNetwork): # The floating ip to be deleted. floating_ip = network_fakes.FakeFloatingIP.create_one_floating_ip() def setUp(self): super(TestDeleteFloatingIPNetwork, self).setUp() self.network.delete_ip = mock.Mock(return_value=None) self.network.find_ip = mock.Mock(return_value=self.floating_ip) # Get the command object to test self.cmd = floating_ip.DeleteFloatingIP(self.app, self.namespace) def test_floating_ip_delete(self): arglist = [ self.floating_ip.id, ] verifylist = [ ('floating_ip', self.floating_ip.id), ] parsed_args = self.check_parser(self.cmd, arglist, verifylist) result = self.cmd.take_action(parsed_args) self.network.find_ip.assert_called_with(self.floating_ip.id) self.network.delete_ip.assert_called_with(self.floating_ip) self.assertIsNone(result) class TestListFloatingIPNetwork(TestFloatingIPNetwork): # The floating ips to list up floating_ips = network_fakes.FakeFloatingIP.create_floating_ips(count=3) columns = ( 'ID', 'Floating IP Address', 'Fixed IP Address', 'Port', ) data = [] for ip in floating_ips: data.append(( ip.id, ip.floating_ip_address, ip.fixed_ip_address, ip.port_id, )) def setUp(self): super(TestListFloatingIPNetwork, self).setUp() self.network.ips = mock.Mock(return_value=self.floating_ips) # Get the command object to test self.cmd = floating_ip.ListFloatingIP(self.app, self.namespace) def test_floating_ip_list(self): arglist = [] verifylist = [] parsed_args = self.check_parser(self.cmd, arglist, verifylist) columns, data = self.cmd.take_action(parsed_args) self.network.ips.assert_called_with(**{}) self.assertEqual(self.columns, columns) self.assertEqual(self.data, list(data)) class TestShowFloatingIPNetwork(TestFloatingIPNetwork): # The floating ip to display. floating_ip = network_fakes.FakeFloatingIP.create_one_floating_ip() columns = ( 'dns_domain', 'dns_name', 'fixed_ip_address', 'floating_ip_address', 'floating_network_id', 'id', 'port_id', 'project_id', 'router_id', 'status', ) data = ( floating_ip.dns_domain, floating_ip.dns_name, floating_ip.fixed_ip_address, floating_ip.floating_ip_address, floating_ip.floating_network_id, floating_ip.id, floating_ip.port_id, floating_ip.tenant_id, floating_ip.router_id, floating_ip.status, ) def setUp(self): super(TestShowFloatingIPNetwork, self).setUp() self.network.find_ip = mock.Mock(return_value=self.floating_ip) # Get the command object to test self.cmd = floating_ip.ShowFloatingIP(self.app, self.namespace) def test_floating_ip_show(self): arglist = [ self.floating_ip.id, ] verifylist = [ ('floating_ip', self.floating_ip.id), ] parsed_args = self.check_parser(self.cmd, arglist, verifylist) columns, data = self.cmd.take_action(parsed_args) self.network.find_ip.assert_called_with( self.floating_ip.id, ignore_missing=False ) self.assertEqual(self.columns, columns) self.assertEqual(self.data, data) # Tests for Nova network # class TestFloatingIPCompute(compute_fakes.TestComputev2): def setUp(self): super(TestFloatingIPCompute, self).setUp() # Get a shortcut to the compute client self.compute = self.app.client_manager.compute class TestDeleteFloatingIPCompute(TestFloatingIPCompute): # The floating ip to be deleted. floating_ip = compute_fakes.FakeFloatingIP.create_one_floating_ip() def setUp(self): super(TestDeleteFloatingIPCompute, self).setUp() self.app.client_manager.network_endpoint_enabled = False self.compute.floating_ips.delete.return_value = None # Return value of utils.find_resource() self.compute.floating_ips.get.return_value = self.floating_ip # Get the command object to test self.cmd = floating_ip.DeleteFloatingIP(self.app, None) def test_floating_ip_delete(self): arglist = [ self.floating_ip.id, ] verifylist = [ ('floating_ip', self.floating_ip.id), ] parsed_args = self.check_parser(self.cmd, arglist, verifylist) result = self.cmd.take_action(parsed_args) self.compute.floating_ips.delete.assert_called_with( self.floating_ip.id ) self.assertIsNone(result) class TestListFloatingIPCompute(TestFloatingIPCompute): # The floating ips to be list up floating_ips = compute_fakes.FakeFloatingIP.create_floating_ips(count=3) columns = ( 'ID', 'Floating IP Address', 'Fixed IP Address', 'Server', 'Pool', ) data = [] for ip in floating_ips: data.append(( ip.id, ip.ip, ip.fixed_ip, ip.instance_id, ip.pool, )) def setUp(self): super(TestListFloatingIPCompute, self).setUp() self.app.client_manager.network_endpoint_enabled = False self.compute.floating_ips.list.return_value = self.floating_ips # Get the command object to test self.cmd = floating_ip.ListFloatingIP(self.app, None) def test_floating_ip_list(self): arglist = [] verifylist = [] parsed_args = self.check_parser(self.cmd, arglist, verifylist) columns, data = self.cmd.take_action(parsed_args) self.compute.floating_ips.list.assert_called_with() self.assertEqual(self.columns, columns) self.assertEqual(self.data, list(data)) class TestShowFloatingIPCompute(TestFloatingIPCompute): # The floating ip to display. floating_ip = compute_fakes.FakeFloatingIP.create_one_floating_ip() columns = ( 'fixed_ip', 'id', 'instance_id', 'ip', 'pool', ) data = ( floating_ip.fixed_ip, floating_ip.id, floating_ip.instance_id, floating_ip.ip, floating_ip.pool, ) def setUp(self): super(TestShowFloatingIPCompute, self).setUp() self.app.client_manager.network_endpoint_enabled = False # Return value of utils.find_resource() self.compute.floating_ips.get.return_value = self.floating_ip # Get the command object to test self.cmd = floating_ip.ShowFloatingIP(self.app, None) def test_floating_ip_show(self): arglist = [ self.floating_ip.id, ] verifylist = [ ('floating_ip', self.floating_ip.id), ] parsed_args = self.check_parser(self.cmd, arglist, verifylist) columns, data = self.cmd.take_action(parsed_args) self.assertEqual(self.columns, columns) self.assertEqual(self.data, data) <file_sep>===================== Human Interface Guide ===================== *Note: This page covers the OpenStackClient CLI only but looks familiar because it was derived from the Horizon HIG.* Overview ======== What is a HIG? The Human Interface Guidelines document was created for OpenStack developers in order to direct the creation of new OpenStackClient command interfaces. Personas ======== Personas are archetypal users of the system. Keep these types of users in mind when designing the interface. Alice the admin --------------- Alice is an administrator who is responsible for maintaining the OpenStack cloud installation. She has many years of experience with Linux systems administration. Darren the deployer ------------------- Darren is responsible for doing the initial OpenStack deployment on the host machines. Emile the end-user ------------------ Emile uses the cloud to do software development inside of the virtual machines. She uses the command-line tools because she finds it quicker than using the dashboard. Principles ========== The principles established in this section define the high-level priorities to be used when designing and evaluating interactions for the OpenStack command line interface. Principles are broad in scope and can be considered the philosophical foundation for the OpenStack experience; while they may not describe the tactical implementation of design, they should be used when deciding between multiple courses of design. A significant theme for designing for the OpenStack experience concerns focusing on common uses of the system rather than adding complexity to support functionality that is rarely used. Consistency ----------- Consistency between OpenStack experiences will ensure that the command line interface feels like a single experience instead of a jumble of disparate products. Fractured experiences only serve to undermine user expectations about how they should interact with the system, creating an unreliable user experience. To avoid this, each interaction and visual representation within the system must be used uniformly and predictably. The architecture and elements detailed in this document will provide a strong foundation for establishing a consistent experience. Example Review Criteria ~~~~~~~~~~~~~~~~~~~~~~~ * Do the command actions adhere to a consistent application of actions? * Has a new type of command subject or output been introduced? * Does the design use command elements (options and arguments) as defined? (See Core Elements.) * Can any newly proposed command elements (actions or subjects) be accomplished with existing elements? * Does the design adhere to the structural model of the core experience? (See Core Architecture.) * Are any data objects displayed or manipulated in a way contradictory to how they are handled elsewhere in the core experience? Simplicity ---------- To best support new users and create straight forward interactions, designs should be as simple as possible. When crafting new commands, designs should minimize the amount of noise present in output: large amounts of nonessential data, overabundance of possible actions, etc. Designs should focus on the intent of the command, requiring only the necessary components and either removing superfluous elements or making them accessible through optional arguments. An example of this principle occurs in OpenStack's use of tables: only the most often used columns are shown by default. Further data may be accessed through the output control options, allowing users to specify the types of data that they find useful in their day-to-day work. Example Review Criteria ~~~~~~~~~~~~~~~~~~~~~~~ * Can options be used to combine otherwise similar commands? * How many of the displayed elements are relevant to the majority of users? * If multiple actions are required for the user to complete a task, is each step required or can the process be more efficient? User-Centered Design -------------------- Commands should be design based on how a user will interact with the system and not how the system's backend is organized. While database structures and APIs may define what is possible, they often do not define good user experience; consider user goals and the way in which users will want to interact with their data, then design for these work flows and mold the interface to the user, not the user to the interface. Commands should be discoverable via the interface itself. To determine a list of available commands, use the :code:`-h` or :code:`--help` options: .. code-block:: bash $ openstack --help For help with an individual command, use the :code:`help` command: .. code-block:: bash $ openstack help server create Example Review Criteria ~~~~~~~~~~~~~~~~~~~~~~~ * How quickly can a user figure out how to accomplish a given task? * Has content been grouped and ordered according to usage relationships? * Do work flows support user goals or add complexity? Transparency ------------ Make sure users understand the current state of their infrastructure and interactions. For example, users should be able to access information about the state of each machine/virtual machine easily, without having to actively seek out this information. Whenever the user initiates an action, make sure a confirmation is displayed[1] to show that an input has been received. Upon completion of a process, make sure the user is informed. Ensure that the user never questions the state of their environment. [1] This goes against the common UNIX philosophy of only reporting error conditions and output that is specifically requested. Example Review Criteria ~~~~~~~~~~~~~~~~~~~~~~~ * Does the user receive feedback when initiating a process? * When a process is completed? * Does the user have quick access to the state of their infrastructure? Architecture ============ Command Structure ----------------- OpenStackClient has a consistent and predictable format for all of its commands. * The top level command name is :code:`openstack` * Sub-commands take the form: .. code-block:: bash openstack [<global-options>] <object-1> <action> [<object-2>] [<command-arguments>] Subcommands shall have three distinct parts to its commands (in order that they appear): * global options * command object(s) and action * command options and arguments Output formats: * user-friendly tables with headers, etc * machine-parsable delimited Notes: * All long options names shall begin with two dashes ('--') and use a single dash ('-') internally between words (:code:`--like-this`). Underscores ('_') shall not be used in option names. * Authentication options conform to the common CLI authentication guidelines in :doc:`authentication`. Global Options ~~~~~~~~~~~~~~ Global options are global in the sense that they apply to every command invocation regardless of action to be performed. They include authentication credentials and API version selection. Most global options have a corresponding environment variable that may also be used to set the value. If both are present, the command-line option takes priority. The environment variable names are derived from the option name by dropping the leading dashes ('--'), converting each embedded dash ('-') to an underscore ('_'), and converting to upper case. For example, :code:`--os-username` can be set from the environment via :code:`OS_USERNAME`. --help ++++++ The standard :code:`--help` global option displays the documentation for invoking the program and a list of the available commands on standard output. All other options and commands are ignored when this is present. The traditional short form help option (:code:`-h`) is also available. --version +++++++++ The standard :code:`--version` option displays the name and version on standard output. All other options and commands are ignored when this is present. Command Object(s) and Action ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Commands consist of an object described by one or more words followed by an action. Commands that require two objects have the primary object ahead of the action and the secondary object after the action. Any positional arguments identifying the objects shall appear in the same order as the objects. In badly formed English it is expressed as "(Take) object1 (and perform) action (using) object2 (to it)." <object-1> <action> [<object-2>] Examples: * :code:`group add user <group> <user>` * :code:`volume type list` # Note that :code:`volume type` is a two-word single object The :code:`help` command is unique as it appears in front of a normal command and displays the help text for that command rather than execute it. Object names are always specified in command in their singular form. This is contrary to natural language use. Command Arguments and Options ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Each command may have its own set of options distinct from the global options. They follow the same style as the global options and always appear between the command and any positional arguments the command requires. Option Forms ++++++++++++ * **boolean**: boolean options shall use a form of :code:`--<true>|--<false>` (preferred) or :code:`--<option>|--no-<option>`. For example, the :code:`enabled` state of a project is set with :code:`--enable|--disable`. Command Output -------------- The default command output is pretty-printed using the Python :code:`prettytable` module. Machine-parsable output format may be specified with the :code:`--format` option to :code:`list` and :code:`show` commands. :code:`list` commands have an option (:code:`--format csv`) for CSV output and :code:`show` commands have an option (:code:`--format shell`) for the shell variable assignment syntax of :code:`var="value"`. In both cases, all data fields are quoted with `"` Help Commands ------------- The help system is considered separately due to its special status among the commands. Rather than performing tasks against a system, it provides information about the commands available to perform those tasks. The format of the :code:`help` command therefore varies from the form for other commands in that the :code:`help` command appears in front of the first object in the command. The options :code:`--help` and :code:`-h` display the global options and a list of the supported commands. Note that the commands shown depend on the API versions that are in effect; i.e. if :code:`--os-identity-api-version=3` is present Identity API v3 commands are shown. Examples ======== The following examples depict common command and output formats expected to be produces by the OpenStack client. Authentication -------------- Using global options: .. code-block:: bash $ openstack --os-tenant-name ExampleCo --os-username demo --os-password <PASSWORD> --os-auth-url http://localhost:5000:/v2.0 server show appweb01 +------------------------+-----------------------------------------------------+ | Property | Value | +------------------------+-----------------------------------------------------+ | OS-DCF:diskConfig | MANUAL | | OS-EXT-STS:power_state | 1 | | flavor | m1.small | | id | dcbc2185-ba17-4f81-95a9-c3fae9b2b042 | | image | Ubuntu 12.04 (754c231e-ade2-458c-9f91-c8df107ff7ef) | | keyname | demo-key | | name | appweb01 | | private_address | 10.4.128.13 | | status | ACTIVE | | user | demo | +------------------------+-----------------------------------------------------+ Using environment variables: .. code-block:: bash $ export OS_TENANT_NAME=ExampleCo $ export OS_USERNAME=demo $ export OS_PASSWORD=<PASSWORD> $ export OS_AUTH_URL=http://localhost:5000:/v2.0 $ openstack server show appweb01 +------------------------+-----------------------------------------------------+ | Property | Value | +------------------------+-----------------------------------------------------+ | OS-DCF:diskConfig | MANUAL | | OS-EXT-STS:power_state | 1 | | flavor | m1.small | | id | dcbc2185-ba17-4f81-95a9-c3fae9b2b042 | | image | Ubuntu 12.04 (754c231e-ade2-458c-9f91-c8df107ff7ef) | | keyname | demo-key | | name | appweb01 | | private_address | 10.4.128.13 | | status | ACTIVE | | user | demo | +------------------------+-----------------------------------------------------+ Machine Output Format --------------------- Using the csv output format with a list command: .. code-block:: bash $ openstack server list --format csv "ID","Name","Status","Private_Address" "ead97d84-6988-47fc-9637-3564fc36bc4b","appweb01","ACTIVE","10.4.128.13" Using the show command options of shell output format and adding a prefix of :code:`my_` to avoid collisions with existing environment variables: .. code-block:: bash $ openstack server show --format shell --prefix my_ appweb01 my_OS-DCF:diskConfig="MANUAL" my_OS-EXT-STS:power_state="1" my_flavor="m1.small" my_id="dcbc2185-ba17-4f81-95a9-c3fae9b2b042" my_image="Ubuntu 12.04 (754c231e-ade2-458c-9f91-c8df107ff7ef)" my_keyname="demo-key" my_name="appweb01" my_private_address="10.4.128.13" my_status="ACTIVE" my_user="demo" <file_sep>======== consumer ======== Identity v3 `Requires: OS-OAUTH1 extension` consumer create --------------- Create new consumer .. program:: consumer create .. code:: bash os consumer create [--description <description>] .. option:: --description <description> New consumer description consumer delete --------------- Delete consumer .. program:: consumer delete .. code:: bash os consumer delete <consumer> .. describe:: <consumer> Consumer to delete consumer list ------------- List consumers .. program:: consumer list .. code:: bash os consumer list consumer set ------------ Set consumer properties .. program:: consumer set .. code:: bash os consumer set [--description <description>] <consumer> .. option:: --description <description> New consumer description .. describe:: <consumer> Consumer to modify consumer show ------------- Display consumer details .. program:: consumer show .. code:: bash os consumer show <consumer> .. _consumer_show-consumer: .. describe:: <consumer> Consumer to display <file_sep>====== router ====== Network v2 router create ------------- Create new router .. program:: router create .. code:: bash os router create [--project <project> [--project-domain <project-domain>]] [--enable | --disable] [--distributed] [--availability-zone-hint <availability-zone>] <name> .. option:: --project <project> Owner's project (name or ID) .. option:: --project-domain <project-domain> Domain the project belongs to (name or ID). This can be used in case collisions between project names exist. .. option:: --enable Enable router (default) .. option:: --disable Disable router .. option:: --distributed Create a distributed router .. option:: --availability-zone-hint <availability-zone> Availability Zone in which to create this router (requires the Router Availability Zone extension, this option can be repeated). .. _router_create-name: .. describe:: <name> New router name router delete ------------- Delete router(s) .. program:: router delete .. code:: bash os router delete <router> [<router> ...] .. _router_delete-router: .. describe:: <router> Router(s) to delete (name or ID) router list ----------- List routers .. program:: router list .. code:: bash os router list [--long] .. option:: --long List additional fields in output router set ---------- Set router properties .. program:: router set .. code:: bash os router set [--name <name>] [--enable | --disable] [--distributed | --centralized] [--route destination=<subnet>,gateway=<ip-address> | --clear-routes] <router> .. option:: --name <name> Set router name .. option:: --enable Enable router .. option:: --disable Disable router .. option:: --distributed Set router to distributed mode (disabled router only) .. option:: --centralized Set router to centralized mode (disabled router only) .. option:: --route destination=<subnet>,gateway=<ip-address> Routes associated with the router. Repeat this option to set multiple routes. destination: destination subnet (in CIDR notation). gateway: nexthop IP address. .. option:: --clear-routes Clear routes associated with the router .. _router_set-router: .. describe:: <router> Router to modify (name or ID) router show ----------- Display router details .. program:: router show .. code:: bash os router show <router> .. _router_show-router: .. describe:: <router> Router to display (name or ID) <file_sep>====== subnet ====== Network v2 subnet delete ------------- Delete a subnet .. program:: subnet delete .. code:: bash os subnet delete <subnet> .. _subnet_delete-subnet: .. describe:: <subnet> Subnet to delete (name or ID) subnet list ----------- List subnets .. program:: subnet list .. code:: bash os subnet list [--long] .. option:: --long List additional fields in output subnet show ----------- Show subnet details .. program:: subnet show .. code:: bash os subnet show <subnet> .. _subnet_show-subnet: .. describe:: <subnet> Subnet to show (name or ID) <file_sep>===== token ===== Identity v2, v3 token issue ----------- Issue new token .. program:: token issue .. code:: bash os token issue token revoke ------------ Revoke existing token .. program:: token revoke .. code:: bash os token revoke <token> .. describe:: <token> Token to be deleted <file_sep>================= availability zone ================= Block Storage v2, Compute v2, Network v2 availability zone list ---------------------- List availability zones and their status .. program availability zone list .. code:: bash os availability zone list [--compute] [--network] [--volume] [--long] .. option:: --compute List compute availability zones .. option:: --network List network availability zones .. option:: --volume List volume availability zones .. option:: --long List additional fields in output <file_sep>====== domain ====== Identity v3 domain create ------------- Create new domain .. program:: domain create .. code:: bash os domain create [--description <description>] [--enable | --disable] [--or-show] <domain-name> .. option:: --description <description> New domain description .. option:: --enable Enable domain (default) .. option:: --disable Disable domain .. option:: --or-show Return existing domain If the domain already exists, return the existing domain data and do not fail. .. describe:: <domain-name> New domain name domain delete ------------- Delete domain .. program:: domain delete .. code:: bash os domain delete <domain> .. describe:: <domain> Domain to delete (name or ID) domain list ----------- List domains .. program:: domain list .. code:: bash os domain list domain set ---------- Set domain properties .. program:: domain set .. code:: bash os domain set [--name <name>] [--description <description>] [--enable | --disable] <domain> .. option:: --name <name> New domain name .. option:: --description <description> New domain description .. option:: --enable Enable domain .. option:: --disable Disable domain .. describe:: <domain> Domain to modify (name or ID) domain show ----------- Display domain details .. program:: domain show .. code:: bash os domain show <domain> .. describe:: <domain> Domain to display (name or ID) <file_sep>================ hypervisor stats ================ Compute v2 hypervisor stats show --------------------- Display hypervisor stats details .. program:: hypervisor stats show .. code:: bash os hypervisor stats show <file_sep>========= extension ========= Many OpenStack server APIs include API extensions that enable additional functionality. extension list -------------- List API extensions .. program:: extension list .. code:: bash os extension list [--compute] [--identity] [--network] [--volume] [--long] .. option:: --compute List extensions for the Compute API .. option:: --identity List extensions for the Identity API .. option:: --network List extensions for the Network API .. option:: --volume List extensions for the Block Storage API .. option:: --long List additional fields in output <file_sep>=========== ip floating =========== Compute v2, Network v2 ip floating add --------------- Add floating IP address to server .. program:: ip floating add .. code:: bash os ip floating add <ip-address> <server> .. describe:: <ip-address> IP address to add to server (name only) .. describe:: <server> Server to receive the IP address (name or ID) ip floating create ------------------ Create new floating IP address .. program:: ip floating create .. code:: bash os ip floating create <pool> .. describe:: <pool> Pool to fetch IP address from (name or ID) ip floating delete ------------------ Delete floating IP .. program:: ip floating delete .. code:: bash os ip floating delete <floating-ip> .. describe:: <floating-ip> Floating IP to delete (IP address or ID) ip floating list ---------------- List floating IP addresses .. program:: ip floating list .. code:: bash os ip floating list ip floating remove ------------------ Remove floating IP address from server .. program:: ip floating remove .. code:: bash os ip floating remove <ip-address> <server> .. describe:: <ip-address> IP address to remove from server (name only) .. describe:: <server> Server to remove the IP address from (name or ID) ip floating show ---------------- Display floating IP details .. program:: ip floating show .. code:: bash os ip floating show <floating-ip> .. describe:: <floating-ip> Floating IP to display (IP address or ID) <file_sep>==================== object store account ==================== Object Storage v1 object store account set ------------------------ Set account properties .. program:: object store account set .. code:: bash os object store account set [--property <key=value> [...] ] .. option:: --property <key=value> Set a property on this account (repeat option to set multiple properties) object store account show ------------------------- Display account details .. program:: object store account show .. code:: bash os object store account show object store account unset -------------------------- Unset account properties .. program:: object store account unset .. code:: bash os object store account unset [--property <key>] .. option:: --property <key> Property to remove from account (repeat option to remove multiple properties) <file_sep>==== port ==== Network v2 port create ----------- Create new port .. program:: port create .. code:: bash os port create --network <network> [--fixed-ip subnet=<subnet>,ip-address=<ip-address>] [--device-id <device-id>] [--device-owner <device-owner>] [--vnic-type <vnic-type>] [--binding-profile <binding-profile>] [--host-id <host-id>] [--enable | --disable] [--mac-address <mac-address>] [--project <project> [--project-domain <project-domain>]] <name> .. option:: --network <network> Network this port belongs to (name or ID) .. option:: --fixed-ip subnet=<subnet>,ip-address=<ip-address> Desired IP and/or subnet (name or ID) for this port: subnet=<subnet>,ip-address=<ip-address> (this option can be repeated) .. option:: --device-id <device-id> Device ID of this port .. option:: --device-owner <device-owner> Device owner of this port .. option:: --vnic-type <vnic-type> VNIC type for this port (direct | direct-physical | macvtap | normal | baremetal). If unspecified during port creation, default value will be 'normal'. .. option:: --binding-profile <binding-profile> Custom data to be passed as binding:profile: <key>=<value> (this option can be repeated) .. option:: --host-id <host-id> The ID of the host where the port is allocated .. option:: --enable Enable port (default) .. option:: --disable Disable port .. option:: --mac-address <mac-address> MAC address of this port .. option:: --project <project> Owner's project (name or ID) .. option:: --project-domain <project-domain> Domain the project belongs to (name or ID). This can be used in case collisions between project names exist. .. _port_create-name: .. describe:: <name> Name of this port port delete ----------- Delete port(s) .. program:: port delete .. code:: bash os port delete <port> [<port> ...] .. _port_delete-port: .. describe:: <port> Port(s) to delete (name or ID) port list --------- List ports .. program:: port list .. code:: bash os port list port set -------- Set port properties .. program:: port set .. code:: bash os port set [--fixed-ip subnet=<subnet>,ip-address=<ip-address>] [--device-id <device-id>] [--device-owner <device-owner>] [--vnic-type <vnic-type>] [--binding-profile <binding-profile>] [--host-id <host-id>] [--enable | --disable] <port> .. option:: --fixed-ip subnet=<subnet>,ip-address=<ip-address> Desired IP and/or subnet for this port: subnet=<subnet>,ip-address=<ip-address> (you can repeat this option) .. option:: --device-id <device-id> Device ID of this port .. option:: --device-owner <device-owner> Device owner of this port .. option:: --vnic-type <vnic-type> VNIC type for this port (direct | direct-physical | macvtap | normal | baremetal). If unspecified during port creation, default value will be 'normal'. .. option:: --binding-profile <binding-profile> Custom data to be passed as binding:profile: <key>=<value> (this option can be repeated) .. option:: --host-id <host-id> The ID of the host where the port is allocated .. option:: --enable Enable port .. option:: --disable Disable port .. _port_set-port: .. describe:: <port> Port to modify (name or ID) port show --------- Display port details .. program:: port show .. code:: bash os port show <port> .. _port_show-port: .. describe:: <port> Port to display (name or ID) <file_sep>====== volume ====== Block Storage v1, v2 volume create ------------- Create new volume .. program:: volume create .. code:: bash os volume create --size <size> [--snapshot <snapshot>] [--description <description>] [--type <volume-type>] [--user <user>] [--project <project>] [--availability-zone <availability-zone>] [--image <image>] [--source <volume>] [--property <key=value> [...] ] <name> .. option:: --size <size> (required) New volume size in GB .. option:: --snapshot <snapshot> Use <snapshot> as source of new volume .. option:: --description <description> New volume description .. option:: --type <volume-type> Use <volume-type> as the new volume type .. option:: --user <user> Specify an alternate user (name or ID) .. option:: --project <project> Specify an alternate project (name or ID) .. option:: --availability-zone <availability-zone> Create new volume in <availability-zone> .. option:: --image <image> Use <image> as source of new volume (name or ID) .. option:: --source <source> Volume to clone (name or ID) .. option:: --property <key=value> Set a property on this volume (repeat option to set multiple properties) .. describe:: <name> New volume name The :option:`--project` and :option:`--user` options are typically only useful for admin users, but may be allowed for other users depending on the policy of the cloud and the roles granted to the user. volume delete ------------- Delete volume(s) .. program:: volume delete .. code:: bash os volume delete [--force] <volume> [<volume> ...] .. option:: --force Attempt forced removal of volume(s), regardless of state (defaults to False) .. describe:: <volume> Volume(s) to delete (name or ID) volume list ----------- List volumes .. program:: volume list .. code:: bash os volume list [--all-projects] [--project <project> [--project-domain <project-domain>]] [--user <user> [--user-domain <user-domain>]] [--name <name>] [--status <status>] [--long] .. option:: --project <project> Filter results by project (name or ID) (admin only) *Volume version 2 only* .. option:: --project-domain <project-domain> Domain the project belongs to (name or ID). This can be used in case collisions between project names exist. *Volume version 2 only* .. option:: --user <user> Filter results by user (name or ID) (admin only) *Volume version 2 only* .. option:: --user-domain <user-domain> Domain the user belongs to (name or ID). This can be used in case collisions between user names exist. *Volume version 2 only* .. option:: --name <name> Filter results by volume name .. option:: --status <status> Filter results by status .. option:: --all-projects Include all projects (admin only) .. option:: --long List additional fields in output volume set ---------- Set volume properties .. program:: volume set .. code:: bash os volume set [--name <name>] [--description <description>] [--size <size>] [--property <key=value> [...] ] <volume> .. option:: --name <name> New volume name .. option:: --description <description> New volume description .. option:: --size <size> Extend volume size in GB .. option:: --property <key=value> Property to add or modify for this volume (repeat option to set multiple properties) .. describe:: <volume> Volume to modify (name or ID) volume show ----------- Show volume details .. program:: volume show .. code:: bash os volume show <volume> .. describe:: <volume> Volume to display (name or ID) volume unset ------------ Unset volume properties .. program:: volume unset .. code:: bash os volume unset [--property <key>] <volume> .. option:: --property <key> Property to remove from volume (repeat option to remove multiple properties) .. describe:: <volume> Volume to modify (name or ID)
ea474c0a13ddedb9faee4c7ff8b214ca8d123d29
[ "reStructuredText", "Shell", "YAML", "Python" ]
87
reStructuredText
FUJITSU-K5/python-openstackclient
3737c5a842f727ad9d28fd10af67784efc6ab416
b835fe841756e3bed4390dfcddd13bb7a6dac7b8
refs/heads/master
<repo_name>VinayakaMalya/helloworld<file_sep>/README.md # helloworld My first repository Hi I am <NAME> I am from Thirthahalli
1a557f0859195f3b41fd365612593b0ec671f993
[ "Markdown" ]
1
Markdown
VinayakaMalya/helloworld
c71daeb61e947ebcff2c581e9f6cb65c6989f430
c976c1cfc658a4cc79bf2617e9dfd2da820db04f
refs/heads/master
<repo_name>kekeen/chongqingzhongdian<file_sep>/app/templates/global.json { "site": "ejs-demo", "styles": [ "../css/custom-bootstrap.css", "../libs/font-awesome-4.7.0/css/font-awesome.min.css", "../libs/icheck/flat/_all.css", "../libs/datetimepicker/jquery.datetimepicker.min.css", "../css/ui-paging-container.css", "../css/global.css", "../css/jquery.paging.css", "../css/time_data.css" ], "scripts": [ "../libs/jquery/jquery.min.js", "../libs/bootstrap/dist/js/bootstrap.min.js", "../libs/My97DatePicker/WdatePicker.js", "../libs/icheck/icheck.min.js", "../libs/nicescroll/jquery.nicescroll.js", "../libs/laydate/laydate.js", "../libs/datetimepicker/jquery.datetimepicker.full.min.js", "../libs/echarts/echarts.js", "../libs/echarts/echarts-wordcloud.min.js", "../libs/echarts/china.js", "../js/global.js", "../js/jquery.paging.js" ] }<file_sep>/app/templates/zddx-zdzd-left.ejs <div class="zddx_nav_box"> <div class="leftnavbar leftnavbar1 menu-box"> <div class="navtop"> <div class="menu"><i class="fa fa-navicon"></i></div> </div> <div class="nicescroll"> <ul class="menu-li"> <li class="<%= local.gxt?'active':'' %>"> <a href="../html/重庆重点对象-重点关系图.html"> <div><img src="../images/cqdnk/guanxi.png" alt=""></div> <em class="fz16">重点关系网</em> </a> </li> <li class="<%= local.zdr?'active':'' %>"> <a href="../html/重庆重点对象-重点人-事业人物.html"> <div><img src="../images/cqdnk/guanzhu.png" alt=""></div> <em class="fz16">重点人</em> </a> </li> <li class="<%= local.zdzdw?'active':'' %> zdzd-nav"> <a href="javascript:;"> <div><img src="../images/cqdnk/mudidi.png" alt=""></div> <em class="fz16">重点阵地</em> </a> <ul class="li-menu-li"> <li style="border-radius: 0 3px 0 0;"> <a href="../html/重庆重点对象-重点阵地-网站2.html"> <div><img src="../images/glm-wz.png" alt=""></div> <p class="fz12" style="display: inline-block;margin-left:8px;">网站</p> </a> </li> <li> <a href="../html/重庆重点对象-重点阵地-微博.html"> <div style="position: relative;left: -3px;"><img src="../images/zlm-wb.png" alt=""></div> <p class="fz12" style="display: inline-block">微博</p> </a> </li> <li style="border-radius: 0 0 3px 0;"> <a href="../html/重庆重点对象-重点阵地-微信.html"> <div><img src="../images/zlm-wx.png" alt=""></div> <p class="fz12" style="display: inline-block;margin-left:6px;">微信</p> </a> <div class="zm-triangle1" style="position:absolute;top:44px;left:-6px;"></div> </li> </ul> </li> <li class="<%= local.zdsj?'active':'' %>"> <a href="../html/重庆重点对象-重点事件.html"> <div><img src="../images/cqdnk/shijian.png" alt=""></div> <em class="fz16">重点事件</em> </a> </li> </ul> </div> </div> </div> <file_sep>/app/templates/zddx-zdsj-left.ejs <div class="zddx_nav_box"> <div class="zddx-left"> <div class="left-top"> <div class="top-search-box"> <input type="text" placeholder="搜索"/> <a href="javascript:;"><i class="fa fa-search"></i></a> </div> </div> <ul class="herf-btn clearfix"> <li><a href="../html/重庆重点对象-重点事件-分组管理.html"><i class="fa fa-users"></i>分组管理</a></li> <li><a href="../html/重庆重点对象-添加重点事件.html"><i class="fa fa-plus"></i>添加事件</a></li> </ul> <div class="list-box"> <ul class="plista_sj"> <li class="<%= local.Djk?'active':'' %>"> <a href="../html/重庆重点对象-重点事件.html" class="fz16">事件总汇</a> <div class="operate-boxa"> <em class="operate-morea pull-right"><i class="fa fa-ellipsis-v"></i></em> <ul class="operate-btns clearfix"> <li class="pull-left"><a href="../html/重庆重点对象-编辑重点事件.html"><i class="fa fa-pencil"></i>编辑</a></li> <li class="pull-left"><a href="###"><i class="fa fa-times"></i>删除</a></li> </ul> </div> </li> <li class="<%= local.zdsjbr?'active':'' %>"> <a href="../html/重庆重点对象-重点事件-暴乱事件.html" class="fz16">暴乱事件</a> <div class="operate-boxa"> <em class="operate-morea pull-right"><i class="fa fa-ellipsis-v"></i></em> <ul class="operate-btns clearfix"> <li class="pull-left"><a href="../html/重庆重点对象-编辑重点事件.html"><i class="fa fa-pencil"></i>编辑</a></li> <li class="pull-left"><a href="###"><i class="fa fa-times"></i>删除</a></li> </ul> </div> </li> <li > <a href="../html/重庆重点对象-重点事件-暴乱事件.html" class="fz16">暴乱事件</a> <div class="operate-boxa"> <em class="operate-morea pull-right"><i class="fa fa-ellipsis-v"></i></em> <ul class="operate-btns clearfix"> <li class="pull-left"><a href="../html/重庆重点对象-编辑重点事件.html"><i class="fa fa-pencil"></i>编辑</a></li> <li class="pull-left"><a href="###"><i class="fa fa-times"></i>删除</a></li> </ul> </div> </li> </ul> </div> </div> <div class="leftnavbar leftnavbar1 menu-box"> <div class="navtop"> <div class="menu"><i class="fa fa-navicon"></i></div> </div> <div class="nicescroll"> <ul class="menu-li"> <li class="<%= local.gxt?'active':'' %>"> <a href="../html/重庆重点对象-重点关系图.html"> <div><img src="../images/cqdnk/guanxi.png" alt=""></div> <em class="fz16">重点关系网</em> </a> </li> <li class="<%= local.zdr?'active':'' %>"> <a href="../html/重庆重点对象-重点人-事业人物.html"> <div><img src="../images/cqdnk/guanzhu.png" alt=""></div> <em class="fz16">重点人</em> </a> </li> <li class="<%= local.gqgz?'active':'' %> zdzd-nav"> <a href="重庆重点对象-重点阵地-网站2.html"> <div><img src="../images/cqdnk/mudidi.png" alt=""></div> <em class="fz16">重点阵地</em> </a> </li> <li class="<%= local.zdsj?'active':'' %>"> <a href="../html/重庆重点对象-重点事件.html"> <div><img src="../images/cqdnk/shijian.png" alt=""></div> <em class="fz16">重点事件</em> </a> </li> </ul> </div> </div> </div> <file_sep>/app/less/other/newqj.less /*涉华舆情 start*/ .newqj{ padding: 60px 0 0 0; .newqj-main{ padding: 16px 16px 20px 16px; height: 100%; } .shadow{ .box-shadow (0, 0, 10px, 0, rgba(0,0,0,0.1)); padding: 0; } .w50{ height: 420px; float: left; margin-top: 10px; .bgw{ width: 100%; height: 100%; padding: 20px; position: relative; } } .ch-box1{ padding-right: 5px; } .ch-box2{ padding-left: 5px; } .w100{ padding: 0; } .top10-chart{ height: auto; } } .shadow-blue{ &:hover{ .box-shadow (0, 0, 8px, 0, rgba(2,155,229,0.4)); border: 1px solid rgba(2,155,229,0.5); } } .newqj-left{ width: 100%; height: 100%; margin-right: -400px; padding-right: 416px; .newqj-title{ padding: 8px 10px 8px 20px; } } .newqj-title{ line-height: 30px; .newztfx-cont{ margin-left: 0; .title-tip span{ top: 0; } } h3{ display: inline-block; font-weight: bold; position: relative; padding-left: 12px; &:before { content: ""; width: 4px; height: 20px; background: @key-blue; position: absolute; left: 0; } } .cycle{ display: inline-block; } .time-range{ width: 280px!important; padding:0 10px; } } .btn-blue{ background: @hui; line-height: 24px; padding:0 8px; border-radius: 1px; display: inline-block; margin-right: 5px; &:hover,&.active{ background: @key-blue; color: #fff; } } .charts-title{ h4{ position: relative; padding-left: 13px; font-weight: bold; display: inline-block; &:before { content: ""; width: 8px; height: 8px; background: @key-blue; position: absolute; top: 4px; left: 0; } } } .ch-btn{ display: inline-block; width: 30px; height: 30px; } .ch-bar{ background: url('../images/ch-bar.png') no-repeat center center; } .ch-line-s{ background: url('../images/ch-line-s.png') no-repeat center center; } .ch-line{ background: url('../images/ch-line.png') no-repeat center center; } .ch-funnel{ background: url('../images/ch-funnel.png') no-repeat center center; } .ch-pie{ background: url('../images/ch-pie.png') no-repeat center center; } .ch-list{ background: url('../images/ch-list.png') no-repeat center center; } .charts-box{ width: 100%; height: 100%; } .change-box{ position: absolute; bottom: 10px; left: 0; text-align: center; width: 100%; a{ display: inline-block; width: 46px; height: 46px; line-height: 46px; background: #9ad7f5; text-align: center; color:#fff; border-radius: 50%; } .btn-front{ margin-right: 55px; } .btn-behind{ margin-left: 55px; } } .china-language{ width: 100%; margin-top: 10px; overflow: hidden; .w50{ margin: 0; padding: 0; } .shyy-box{ border-left: 1px solid @line-color; .language-title{ line-height: 40px; padding: 0 20px 0 10px; background: #f7f8fa; border-bottom: 1px solid @line-color; h5{ display: inline-block; font-weight: bold; } span{ font-size: 12px; } a{ margin-top: 5px; } } .charts-box{ padding: 20px; } .top10-chart{ padding-top: 30px; } } } .newqj-right{ width: 400px; height: 100%; .newqj-title{ padding:0 15px; line-height: 48px; } .screen-box{ .dropdown{ float: left; width: 33.3%; .dropdown-toggle{ width: 100%; border-left: none; } &:nth-child(3){ .dropdown-toggle{ border-right: none; } } } .dropdown-menu{ text-align: center; margin: 0; width: 100%; } } } .newqj-right-list-box{ .newqj-right-list{ >li{ padding: 10px 0 10px 15px; border-bottom: 1px solid @line-color; display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; position: relative; &:hover,&.active{ background: #e8edf3; .operate-box{ display: block; } } .operate-box{ position: absolute; right: 0px; top: 50%; -webkit-transform: translateY(-50%); -moz-transform: translateY(-50%); -ms-transform: translateY(-50%); -o-transform: translateY(-50%); transform: translateY(-50%); text-align: center; display: none; .operate-btn{ width: 30px; height: 30px; line-height: 30px; display: inline-block; font-size: 25px; color:@f-zise; } .operate-list{ position: absolute; top: 40px; right: 0px; background: @key-blue; padding: 0 5px; border-radius: 1px; display: none; &:before { content: ""; width: 0; height: 0; border-right: 10px solid transparent; border-bottom: 10px solid @key-blue; border-left: 10px solid transparent; position: absolute; top: -10px; right: 5px; } li{ float: left; } a{ color:#fff; display: block; margin: 5px; min-width: 25px; i{ font-size: 18px; } span{ display: block; font-size: 12px; } } } } } .newqj-right-list-left{ width: 30px; div{ top: 50%; -webkit-transform: translateY(-50%); -moz-transform: translateY(-50%); -ms-transform: translateY(-50%); -o-transform: translateY(-50%); transform: translateY(-50%); } } .newqj-right-list-right{ -webkit-box-flex: 1; -webkit-flex: 1; -ms-flex: 1; flex: 1; display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; position: relative; margin-right: 30px; cursor: pointer; .left-pic{ width: 60px; height: 60px; margin-right: 10px; img{ width: 100%; height: 100%; } } .right-msg{ -webkit-box-flex: 1; -webkit-flex: 1; -ms-flex: 1; flex: 1; position: relative; height: 60px; .vam-box{ position: absolute; top: 50%; -webkit-transform: translateY(-50%); -moz-transform: translateY(-50%); -ms-transform: translateY(-50%); -o-transform: translateY(-50%); transform: translateY(-50%); } h5{ margin-bottom: 10px; } span{ color:@f-zise; } } } } } .w117{ width: 117px; } .icon-analysis{ display: inline-block; width: 16px; height: 16px; background: url('../images/icon-fx.png') no-repeat center center; } .newqj-foot{ padding: 15px; border-top: 1px solid @line-color; .pull-left{ line-height: 30px; } .export-btn{ color:@f-zise; font-size: 22px; display: inline-block; vertical-align: middle; margin-left: 10px; } } .float-menu{ position: absolute; top: 170px; left: -35px; a{ width: 70px; height: 70px; display: inline-block; border-radius: 50%; text-align: center; } .on-btn{ border: 1px solid @line-color; font-size: 22px; line-height: 68px; color:@f-zise; .box-shadow (0, 10px, 20px, 0, rgba(68,194,255,0.4)); } .float-menu-list{ display: none; li{ margin-top: 20px; position: relative; a{ color:#fff; opacity: 0.8; line-height: 16px; &:hover{ color:#fff; opacity: 1; } i{ margin-top: 15px; width: 24px; height: 24px; } } span{ display: block; } .btn-now{ .box-shadow (0, 10px, 20px, 0, rgba(68,194,255,0.4)); background: #029be5; line-height: 85px; i{ background: url('../images/btn-now.png') no-repeat center center; display: inline-block; width: 28px; height: 28px; } } } } .btn-sh{ .box-shadow (0, 10px, 20px, 0, rgba(68,194,255,0.4)); background: #029be5; i{ background: url('../images/btn-sh.png') no-repeat center center; display: inline-block; } } .btn-gn{ .box-shadow (0, 10px, 20px, 0, rgba(255,181,96,0.4)); background: #ffbe73; i{ background: url('../images/btn-gn.png') no-repeat center center; display: inline-block; } } .btn-bd{ .box-shadow (0, 10px, 20px, 0, rgba(163,121,255,0.4)); background: #a982ff; i{ background: url('../images/btn-bd.png') no-repeat center center; display: inline-block; } } } .now-data{ display: none; position: absolute; left: 90px; top: 0; padding: 15px 20px 20px 20px; border-radius: 3px; border: 1px solid @line-color; .box-shadow (0, 0, 20px, 0, rgba(0,0,0,0.2)); &:before { content: ""; width: 0; height: 0; border-top: 10px solid transparent; border-right: 10px solid #fff; border-bottom: 10px solid transparent; position: absolute; top: 20px; left: -10px; } .tables{ margin-top: 10px; th{ background: #f8f8f8; } td{ font-weight: bold; } } } .table-con{ height: 100%; margin: 0 20px 15px 20px; border: 1px solid @line-color; .zt-box{ padding: 10px 15px 0 15px; .layut-input a{ top: 5px; } .btn{ i{ color:@f-zise; margin-right: 7px; font-size: 16px; vertical-align: middle; } } } .table-box{ max-height:470px; } .tables-hover{ border: none; .tables-bt{ color:#333; } } .zt-ft{ padding: 10px; border-top: 1px solid @line-color; } } #similarity{ .modal-dialog{ width: 71%; max-width: 1250px; margin-top: 6%; } .modal-body{ max-height: 590px; } .dropdown-menu{ min-width: 120px; img{ display: inline-block; } } } .zdy-box{ display: none; } /*涉华舆情 end*/ /*国内舆情 start*/ .newqj-left{ .big-box{ width: 100%; height: 610px; padding: 20px; margin-top: 10px; } } .chart-btn{ width: 22px; height: 22px; display: inline-block; cursor: pointer; vertical-align: middle; position: relative; a{ width: 100%; height: 100%; position: absolute; top: 0; left: 0; z-index: 1; } &:hover{ .chart-popup{ display: block; } } .chart-popup{ position: absolute; top: 35px; right: -10px; z-index: 1; border-radius: 3px; width: 120px; padding: 7px 13px; display: none; &:after { content: ""; width: 0; height: 0; border-left: 10px solid transparent; border-right: 10px solid transparent; border-bottom: 10px solid #fff; position: absolute; top: -10px; right: 10px; } &:before { content: ""; width: 0; height: 0; border-left: 10px solid transparent; border-right: 10px solid transparent; border-bottom: 10px solid @line-color; position: absolute; top: -11px; right: 10px; } li{ line-height: 22px; } } #gnyq-zfm{ width: 100%; height: 100%; } } .w60{ width: 60%; height: 100%; position: relative; } .w40{ width: 40%; height: 100%; position: relative; .top10-chart{ padding-top: 40px; li{ height: 41px; line-height: 41px; } label{ width: 45px; line-height: 41px; } .list-bar{ padding-left: 50px; } .color-box{ .color-bar{ padding: 9px 50px 9px 0; } } } .change-box{ bottom: 40px; } } /*国内舆情 end*/ /*本地舆情 start*/ .bent{ background: url('../images/bent.png') no-repeat center center; width: 72px; height: 47px; display: inline-block; position: absolute; bottom: 190px; right: 35px; } /*本地舆情 end*/ @media screen and (max-width:1300px){ // .newqj-left .newqj-title .time-range{ // width: 235px!important; // padding: 0 5px; // } .newqj-left{ margin-right: -350px; padding-right: 366px; } .newqj-right{ width: 350px; } .newqj-right-list-box .newqj-right-list > li{ padding: 8px 0 8px 8px; } .newqj-right-list-box .newqj-right-list .newqj-right-list-right{ margin-right: 25px; } } @media screen and (max-width:1150px){ .newqj-left { margin-right: -300px; padding-right: 310px; } .newqj-right { width: 300px; } .change-box .btn-front{ margin-right: 45px; } .change-box .btn-behind { margin-left: 45px; } }<file_sep>/app/templates/data_times.ejs <div class="data-times"> <div class="timebox"> <input type="text" class="allData" placeholder="近七天"> </div> <div class="dataList"> <ul> <% var data = ['近七天','近一个月']; for(var i in data){ %> <li><a href="javascript:void(0)"><%= data[i] %></a></li> <% } %> </ul> <div class="timeCustom"> <p class="custom-title">自定义</p> <div class="custom-data">从<input type="text" class="ts-range"></div> <div class="custom-data">至<input type="text" class="ts-range2"></div> <div class="custom-btn"> <a href="javascript:void(0)">重置</a> <a href="javascript:void(0)" class="sure">确认</a> </div> </div> </div> </div><file_sep>/app/less/time_data.less /*@import "./base/conn.less";*/ @color:#4f5f6f; .input-pla(@color:#6c849c){ &::-webkit-input-placeholder { color: @color; } &:-moz-placeholder { color: @color; opacity: 1; } &::-moz-placeholder { color: @color; opacity: 1; } &:-ms-input-placeholder { color: @color; } } .linear-gradient(@color1:#fff,@color2:#f8f8f8){ background: linear-gradient(@color1, @color2); } .border(){ border: 1px solid #DEDBE3; } .btns(){ height: 28px; line-height: 28px; padding: 0 15px; font-size: 14px; letter-spacing: 1px; color: #666; .linear-gradient; .border; border-radius: 2px; } .data-times{ position: relative; display: inline-block; .allData{ background: #fff; height: 30px; line-height: 28px; padding: 0 10px; width: 295px !important; border-radius: 2px; border: 1px solid rgb(211, 219, 227); color: rgb(117, 117, 117); outline: none; &:focus{ border: 1px solid rgb(2, 155, 229); outline: none; } } .dataList{ display: none; position: absolute; top: 30px; margin-top: 10px; width: 209px; background-color: #fff; border: 1px solid #e6e6e6; padding: 14px 10px; z-index: 999; left: 50%; transform: translateX(-50%); >ul{ position: relative; border-bottom: 1px solid #e6e6e6; padding-bottom: 10px; &:before { content: ""; width: 0; height: 0; border-left: 8px solid transparent; border-right: 8px solid transparent; border-bottom: 10px solid #e2e2e2; position: absolute; top: -24px; left: 50%; transform: translateX(-50%); z-index: 1001; } &:after { content: ""; width: 0; height: 0; border-left: 8px solid transparent; border-right: 8px solid transparent; border-bottom: 10px solid #fff; position: absolute; top: -23px; left: 50%; transform: translateX(-50%); z-index: 1001; } li{ width: 100%; text-align: center; height: 30px; line-height: 30px; border-radius: 2px; a{ display: inline-block; width: 100%; height: 100%; color: #4c4c4c; &:hover{ color: #fff; background-color: #029be5; } } } } .timeCustom{ .custom-title{ height: 33px; line-height: 33px; font-weight: bold; font-size: 14px; color: #029be5; text-align: center; } input{ width: 168px; height: 34px; margin-left: 5px; .border; } .custom-data{ margin-bottom: 9px; input{ background: url(../images/date.png) no-repeat 97% center; background-color: white; outline: none; &:focus{ outline: none; border: 1px solid rgb(2, 155, 229); } } } .custom-btn{ display: flex; justify-content: space-between; padding-left: 17px; padding-top: 6px; >a{ .btns; } } } } }<file_sep>/app/less/temple.less @import "./base/base.less"; @bule:#029be5; @blue:#029be5; @red:#f54545; @hui:#d3dbe3; @pink:#ff8761; @tit:#333333; @green:#5ec45e; @yellow:#ffab0a; @border:#d3dbe3; @blue2:#169bd5; @zi:#8ea5c3; @line-color:#d3dbe3; @f-blue:#06bdf2; ::-webkit-scrollbar{ display:none; } .break(){ //word-wrap: break-word; //智能断句 word-break:break-all; //强制断句 } .box-shadow (@x: 0, @y: 0, @blur, @spread, @color) { -webkit-box-shadow: @arguments; -moz-box-shadow: @arguments; -o-kit-box-shadow: @arguments; -ms-box-shadow: @arguments; box-shadow: @arguments; } //单行文字省略 .txt() { overflow: hidden; white-space: nowrap; text-overflow: ellipsis; } .txtmore(@number){ overflow: hidden; display: -webkit-box; -webkit-line-clamp:@number; -webkit-box-orient: vertical; text-overflow: ellipsis; } .warn-right textarea::-webkit-input-placeholder{ color:#999; } /*boostrap*/ .tleft{ text-align:left !important; } .tcenter{ text-align:center !important; } .tright{ text-align:right !important; } .fz12{ font-size:12px; } .input{ outline:none; } .omit() { overflow: hidden; white-space: nowrap; text-overflow: ellipsis; } .martop15{ margin-top:15px; } .martop20{ margin-top:20px; } .omit-more(@number){ overflow: hidden; display: -webkit-box; -webkit-line-clamp:@number; -webkit-box-orient: vertical; } .btn { padding: 0 10px; background: #fff; border: 1px solid #d3dbe3; height: 29px; line-height: 28px; margin:0 5px; } .fullscreen{ color:@bule; float:right; font-weight:bold; margin:20px 40px 0 0; } .a-btn{ height: 28px; line-height: 28px; color:@tit; background:@hui; padding: 0 10px; border-radius:3px; margin-right:10px; display:inline-block; &.active,&:hover{ background:@green; color:#fff; } } label{ font-weight:normal; margin:0 3px; line-height:28px; display:inline-block; } .w49{ width:49%; } .w38{ width:38%; } .w50{ width:50% !important; } .w60{ width:60%; } .w100{ width:100% !important; } .fz22{ font-size:22px; } .yellow{ color:@yellow; } .pads{ padding-left:0; } .bgw{ background: #fff; } .m-n{ margin: 0 !important; } .ml10{ margin-left: 10px; } .mt5{ margin-top: 5px; } .ml0{ margin-left: 0; } .mb10{ margin-bottom: 10px; } .modal-bd-b{ border-bottom:1px solid #e5e5e5 !important; } .tables > tbody{ .tables-bt{ float:left; } .rz-img{ display:inline; } >tr{ .caozuo{ a{ display:none; padding:2px 10px; background:#fff; border-radius:3px; i{ margin-right:5px; } } } } } .XCtable{ >tbody{ >tr{ &:hover{ background:#029be5; td{ color:#fff; } .tables-bt{ color:#fff; } .green{ color:#fff !important; } .caozuo{ a{ display:inline-block; } .green{ color:@green !important; } } } } } } .xqbg{ background:#fff !important; padding:60px 300px 20px 0; } .tool{ .layout-data { border: 1px solid #d3dbe3; height: 30px; line-height: 30px; border-radius: 3px; background:#fff; display:inline-block; input { padding: 0; height: 26px; line-height: 26px; width: 90px; border: none; text-align: center; border-radius: 3px; color: #06bdf2; } } } .modal-footer{ .btn{ &:hover{ border:none; } } .yes{ &:hover{ color:#fff; } } } .fl-btn{ border: 1px solid @border; background: #FFF; color: #333; display: inline-block; min-width: 80px; text-align: center; height: 28px; line-height: 26px; padding: 0 10px; border-radius: 2px; i{ color: #8EA5C3; margin-right: 5px; } } @media screen and (max-width: 1300px) { .fz12{ font-size:10px; } .fz22{ font-size:20px; } h2{ font-size:26px; } } /* off-on按钮 start */ .rectangle { position: relative; width: 50px; height: 20px; line-height: 20px; background: #779bb5; border-radius: 24px; cursor: pointer; display: inline-block; vertical-align: middle; margin-top: -2px; em, i { font-style: normal; } i { position: absolute; left: 2px; top: 2px; width: 16px; height: 16px; background: #fff; border-radius: 50%; } span{ color: #fff; margin-left: 21px; line-height: 20px; font-size: 12px; } } .change-i { background: @green; i { left: 32px; } span{ margin-left: 7px; } } /* off-on按钮 end */ /* 切换按钮 */ .switch-show{ display: none; &.first{ display: block; } &.first-table{ display: table; } } /* 媒体分析 start */ .media-left-chart{ float: left; width: 50%; padding: 10px; } .media-right-chart{ float: left; width: 50%; padding: 10px; h5{ line-height: 40px; padding-left: 20px; } strong{ color:#169bd5; font-weight: bold; } } .tables .text-left{ text-align: left; } /* 媒体分析 end */ /* 境外社交 start */ .overseas-line{ margin-bottom: 30px; } .overseas-list.theory-con{ float: none; width: auto; .tit { height: 40px; line-height: 40px; border-bottom: 1px solid #d3dbe3; } .theory-con .ft-con{ margin-left: 60px; } .theory-img{ width: 48px; height: 48px; display: block; margin-left: 12px; } .ft-con p{ margin-bottom: 0; } .tit span{ height: 40px; line-height: 40px; img{ float: left; margin-right: 10px; margin-top:5px; } } } /* 境外社交 end */ /* 视频管理 start */ #videomManage{ .modal-dialog{ width: 70%; } .modal-body{ height: auto; max-height:none; } .tables td{ max-width: 0; } .txt-list{ overflow: hidden; white-space: nowrap; text-overflow: ellipsis; } } .video-bt{ padding:5px 10px; } .video-bt-page{ .page-total{ height: 29px; line-height: 29px; display: inline-block; vertical-align: middle; margin: 0 0 -1px 0; } a{ margin:0; } } /* 视频管理 end */ /* 编辑视频 start */ .video-wrap{ >.anli{ max-width: 1280px; margin: 0 auto; padding:20px 20px 50px; } } .video-title{ height: 40px; border-bottom: 1px solid @line-color; padding:0 12px; h3{ color:#333; line-height: 40px; } .pull-right{ padding-top: 5px; } } .video-l{ float: left; width: 70%; height: 600px; background: #ccc; } .video-r{ float: right; width: 30%; height: 600px; } .video-list{ padding: 8px 15px; height:100%; overflow: hidden; li{ height: 70px; margin-bottom: 12px; .video-img{ position: relative; float: left; overflow: hidden; width: 100px; height: 100%; display: block; img{ position: absolute; left:50%; top:50%; margin-left: -50%; -webkit-transform: translateY(-50%); -moz-transform: translateY(-50%); -ms-transform: translateY(-50%); -o-transform: translateY(-50%); transform: translateY(-50%); } } .video-art{ margin-left: 110px; .video-tit{ line-height: 20px; height: 40px; overflow: hidden; .txtmore(2); } .video-close{ display: none; padding:0 3px; border:1px solid @line-color; color:#ffab0a; font-size: 12px; margin:8px 0 0 0; &:hover{ color:@f-blue; } } } } } .video-ft{ padding: 6px 15px 10px; color:#333; } .vf-title{ font-size: 22px; height: 38px; } .vf-time{ line-height: 20px; i{ width: 20px; height: 20px; border-radius:50%; border: 1px solid #eef1f7; display: inline-block; vertical-align: middle; margin-right: 8px;margin-top: -2px; } span{ height: 20px; line-height: 20px; display: inline-block; vertical-align: middle; margin-right: 8px; } } .modal-cl-video{ line-height: 25px; padding: 20px 30px; font-size: 16px; color:#006daf; text-align: center; i{ margin-right: 5px; } } .modal-footer .btn.yl-btn{ padding: 0 10px; background:#ffab0a; color:#fff; &:hover{ opacity:0.8; } } #editVideoModal,#closeVideoModal{ .modal-dialog { margin: 15% auto 0 auto; } } .u-file{ position: relative; width: 84px; height: 30px; display: block; overflow: hidden; input{ z-index:2; position: absolute; left:0; top:0; width: 84px; height: 30px; opacity:0; font-size: 0; cursor:pointer; } } /* 编辑视频 end */ /* 站点标签 start */ .toolbar { padding: 20px; text-align: right; background: rgba(255,255,255,.8); } .toolbar .viciao a { border: 1px solid #E6E6E6; background: #FFF; padding: 3px 10px; color: #283e4c; margin: 0 0; } .toolbar .viciao a.active, .toolbar .viciao a:hover { background: @green; color: #FFFFFF; } .label-site{ .tables{ .fa-check{ color: @green; } .fa-close{ color: @red; } } } .tool-r { .layut-input.list{ padding-bottom: 0; } } .zdbq{ min-height: 300px; margin-bottom: 20px; border: 1px solid @line-color; } /* 站点标签 end*/ /* 站点标签-修改标签 start*/ .tags-wrap{ width: 1000px; margin: 0 auto; height:100%; } .tags-edit{ min-height:100%; background: #fff; padding: 20px 30px; h3{ font-size: 16px; color:@f-blue; font-weight: bold; } } .tags-list{ height: 400px; border: 1px solid @line-color; padding: 10px; } .tag-dib{ display: inline-block; .fa{ color:@yellow; } } .label-list{ li{ margin-bottom: 10px; label{ margin-bottom: 0; } .layut-input{ width: 180px; } &:last-child{ margin-bottom: 0; } } } .inline-button{ a{ color:#fff; background: #1389d0; &:hover{ opacity:0.8; } } } /* 站点标签-修改标签 end*/ /*创建专题*/ .warpper{ width:100%; height:100%; } .cjzt .modal-title{ float: left; } .cjzt .modal-body{ max-height: none; } .page-title{ margin-bottom: 15px; h4{ line-height: 30px; font-size: 18px; color: #1389d0; font-weight: bold; } } /*精简按钮*/ .checkout{ display:inline-block; width:120px; height:30px; line-height:30px; text-align:center; border:1px solid #369bd7; color:#369bd7; border-radius:10px; font-size: 14px; } .auto-push{ .checkout; } /*高级选项*/ .gjxx{ display:none; background:#f7f8fa; padding: 10px 15px 60px; margin-bottom: 40px; .sen-opt{ font-weight: bold; font-size: 16px; color:#96abc7; border-radius:3px; text-align: left; } } .cjzt{ width:1000px; height: auto; min-height:100%; padding:90px 20px 50px; margin:0 auto; background:#fff; } /*选择地域的样式*/ .all-country{ display:inline-block; width:355px; height:28px; line-height:28px; margin-right:50px; background:#fff; text-align:center; border-radius:2px; border:1px solid #d3dbe3; } .areaWords{ margin-left:9px; color:#97acc7; } .leader{ display:inline-block; min-width:100px; height:28px; line-height:26px; background:#fff; text-align:center; border-radius:2px; border:1px solid #d3dbe3; padding: 0 8px; } .yuzhi{ display:inline; width:121px!important; margin:0 20px; } /*底部的几个按钮*/ .inline-button{ text-align:center; padding-right:100px; >a{ display:inline-block; width:100px; height:28px; line-height:28px; background:#d3dbe3; border-radius:3px; } .active,>a:hover{ background:#1389d0; color:#fff; } } /*共享用户列表*/ .share{ width:455px; max-height:127px; padding-top:12px; padding-left:20px; border:1px solid #d3dbe3; } .words{ font-weight: bold; color:#029be5; text-align:center; display:inline; margin-right:5px; } /*省份*/ .province-menu{ width:450px; } .rect{ display:inline-block; background:#dedede; width:12px; height:12px; margin-right:3px; } .user-group{ margin-left:20px; margin-top:7px; >li>ul{ margin-left:20px; margin-top:7px; } } .dropdown-menu{ >li{ >.subProvince{ padding:3px 5px; display:inline-block; } } } .leader .plus-add{ display: inline-block; background: #1389d0; color: #fff; font-size: 16px; width: 18px; height: 18px; line-height: 16px; border-radius: 3px; margin-right: 4px; font-weight: bold; float: left; margin-top: 4px; margin-left: 0; } .checked{ span{ a{ text-align: center; min-width: 85px; padding: 3px 10px; border-radius: 3px; display: inline-block; margin-right: 5px; margin-bottom: 5px; color:#fff; } } .check-blue{ a{ background: #1389d0; } } .check-red{ a{ background: #f54545; } } .check-green{ a{ background: @green; } } .check-norm{ a{ background: #fff; border: 1px solid #d6e1e5; color:#1389d0; } } } /*向上的三角形*/ .upcaret{ display:inline-block; width:0; height:0; vertical-align:middle; margin-left:2px; border-left:6px solid transparent; border-right:6px solid transparent; border-bottom:6px dashed; } .cjzt{ .tc-table{ .unPi{ cursor:pointer; >img{ margin-left:10px; display:inline; } } } } .checkbtn{ display: none; } .circle-answer{ display:inline-block; margin-left:18px; width:20px; height:20px; border-radius:10px; background:#ffd584; color:#9f7422; font-weight:bold; text-align:center; line-height:20px; } .circle-answer-o{ background: #ffd584; color:#9f7422; } /*跟踪关键词*/ .tishi{ position: absolute; left: 40px; top: -4px; background:#eaf0f2; font-size:12px; padding:3px; min-width: 260px; border-radius: 2px; display: none; &:before{ content: ''; width: 0; height: 0; border-top: 5px solid transparent; border-right: 6px solid #eaf0f2; border-bottom: 5px solid transparent; position: absolute; left: -6px; top: 5px; } } .relbtn{ position: relative; .tishi{ left: 90px; top: -3px; min-width:215px; padding:5px 10px; } } .norSpan{ position: relative; } .relSpan{ position:relative; vertical-align: top; .circle-answer{ position:absolute; top:0px; left:5px; } .tishi{ position: absolute; top: 0px; left: 48px; padding: 2px 10px 5px; line-height: 27px; .symbol{ >span{ background:#fff; color:#000; } } } } /*时间控件的处理*/ .MyDateP{ display:none; } /*空白*/ .white-block{ height:50px; } /*三级联动的样式*/ .region{ >li{ position:relative; text-align:center; line-height:26px; >span{ overflow: hidden; position: relative; height: 30px; margin: 3px 20px; margin-right: 20px; margin-bottom: 3px; padding: 0 10px; font-size: 14px; color: #779bb5; line-height: 28px; text-align: left; border: 1px solid #dfe5e7; border-radius: 2px; display: block; cursor: pointer; >em{ float: left; width: 105px; padding-right: 15px; height: 100%; display: block; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; } } } } .tc-table .dropdown-box { display: none; position: absolute; right: -428px; top: 3px; width: 426px; height: auto!important; margin-right: 0!important; overflow-y: auto; border: 1px solid #000; background: #fff; padding: 5px 18px 10px; border-radius: 4px; border: 1px solid rgba(0, 0, 0, 0.15); box-shadow: 0 6px 12px rgba(0, 0, 0, 0.175); >dl dt{ float: left; width: 10%; font-size: 16px; line-height: 30px; text-align: center; color: #029be5; } >dl dd.unlimited{ width: 100%; padding-left: 40px; } >dl dd{ float: left; width: 90%; line-height: 30px; text-align:left; >a{ color: #779bb5; margin: 0 1px; margin-right: 1px; display: inline-block; margin-right: 20px; } } } /*表格内部的距离*/ .contents #j-monitor{ margin-bottom:10px; margin-left:-5px; } .single-mulu{ .dropdown{ .u-btn{ color:#029be5; height:31px; line-height:31px; width:101px; text-align:left; .caret{ color:#8ea5c3; margin-left:26px; } } .dropdown-menu{ min-width:101px; } } } #period{ height: 50px; vertical-align: top; .days{ min-width: auto; line-height: 30px; margin: 0; margin-right: 10px; height: 30px; vertical-align: top; .layout-data{ margin-left: 10px; } } .custom{ display: none; .MyDateP{ display: inline-block; } } } .tc-table{ .objWords{ margin-bottom:10px; } } .cjzt .tc-table label { margin-bottom: 5px; } .cjzt .tc-table label.min-width{ min-width: auto; } .table-ls{ >label{ margin: 0; min-width:135px; } >span{ min-width:135px; display: inline-block; label{ margin: 0; min-width:0; } span{ width: 25px; display: inline-block; img{ cursor: pointer; display: none; margin-left: 10px; } } } } .ac-top{ margin-bottom: 15px; a{ padding: 3px 10px; border: 1px solid @line-color; border-radius:3px; display: inline-block; background: #fff; &:hover,&.active{ color:#fff; border-color:@green; background: @green; } } } .ac-box{ color:#333; height:300px; overflow-y: auto; border: 1px solid @line-color; >div{ display: none; &.active{ display: block; } } } .ac-normal{ padding: 15px 10px; >div{ >a{ float: left; min-width: 85px; padding: 3px 10px; border-radius: 3px; display: inline-block; margin: 0 12px 10px; background: @line-color; text-align: center; &:hover,&.active { color:#fff; background: @green; } } } } .ac-personality{ padding: 10px 0 10px 15px; .layut-input{ width: 50%; } .subs-list{ dl{ margin-bottom: 10px; i{ float: left; width: 20px; font-size: 18px; height: 20px; } .title { float: left; font-size: 12px; height: 20px; line-height: 20px; display: inline-block; position: relative; margin-left: 7px; } &.subs-list-blue{ .fa-edge{ color:#1389d0; } dd>a.on{ color:#fff; background: #1389d0; } } &.subs-list-red{ .fa-weibo{ color:#f54545; } dd>a.on{ color:#fff; background: #f54545; } } &.subs-list-green,.fa-weixin{ .fa-weixin{ color: @green; } dd>a.on{ color:#fff; background: @green; } } &.subs-list-purple{ i{ background: url(../images/s-a-2.png) no-repeat; } .fa-weibo{ color:#7085F2; } dd>a.on{ color:#fff; background: #7085F2; } } &.subs-list-orange{ i{ background: url(../images/s-a-1.png) no-repeat; } .fa-weibo{ color:#FB3E05; } dd>a.on{ color:#fff; background: #FB3E05; } } } dt{ padding: 8px 0; font-weight: bold; border-bottom: 1px dashed @line-color; .fa-edge{ color:#1389d0; } } dd{ a{ text-align: center; min-width: 85px; padding: 3px 10px; border-radius: 3px; display: inline-block; margin: 10px 10px 0; background: @line-color; } } } } .ac-num{ line-height: 30px; } /* 创建专题 end */ /* 专题分析 start */ .fxpz{ padding-top: 10px; text-align: center; .a-btn{ } } .bg_gray{ background: #f3f3f3; } .gj-tit{ font-weight: bold; color:#8ea5c3; margin-bottom: 15px; } /* 专题分析 end */ /*左侧边栏 start*/ .leftnvvbar2{ left: 0; } .time-list{ .er-list{ li{ position: relative; a{ padding-right: 35px; } &:hover{ a{ background: #1389d0; color: #fff; font-weight: bold; } .load-circle{ display: block; } .operation{ a{ background: none; font-weight: normal; } } } } .add-list{ padding-left:20px; line-height: 35px; color: #029be5; font-size: 30px; a{ padding-left: 0; display: inline-block; &:hover{ background:transparent; color:#029be5; font-weight: normal; } } } } .operationb{ width: 100%; height: 100%; .operation{ background: rgba(255,255,255,.1); color: #fff; padding:5px 10px; border-radius: 3px; label,a{ cursor: pointer; border: 1px solid #fff; border-radius:2px; padding:0 5px; line-height: 25px; i{ margin-right: 5px; } } a{ display: inline-block; color:#fff; margin-right: 10px; } } } } #time{ .modal-body{ padding: 40px; text-align: center; input{ padding: 15px 13px; width: 115px; margin: 0 10px; border-color: #d6e1e5; border-radius: 2px; } } } #del,#delMore{ .modal-body{ padding: 40px; text-align: center; } } .load-circle{ display: none; position: absolute; right: 5px; top: 0; width: 30px; height: 35px; line-height: 35px; text-align: center; cursor: pointer; i{ color:#fff; font-size: 14px; } } .circle{ position: absolute; right: 2px; top: 5px; width: 25px; height: 25px; } .renew{ display: none; position: absolute; right: 6px; top: 10px; width: 16px; height: 16px; background: url(../images/renew.png) no-repeat; -webkit-transform: rotate(360deg); animation: c-ani 10s linear infinite; -moz-animation: c-ani 10s linear infinite; -webkit-animation: c-ani 10s linear infinite; -o-animation: c-ani 10s linear infinite; } @-webkit-keyframes c-ani{ from {-webkit-transform: rotate(0deg);} to {-webkit-transform: rotate(360deg);} } @keyframes c-ani{ from {-webkit-transform: rotate(0deg);} to {-webkit-transform: rotate(360deg);} } @-moz-keyframes c-ani{ from {-webkit-transform: rotate(0deg);} to {-webkit-transform: rotate(360deg);} } @-o-keyframes c-ani{ from {-webkit-transform: rotate(0deg);} to {-webkit-transform: rotate(360deg);} } /*左侧边栏 end*/ /*案例概况 start*/ .anli{ .title-big{ margin:8px 0 30px; position: relative; h3{ color:#029be5; font-weight: bold; padding-left: 18px; display: inline-block; &:before{ content:''; width: 4px; height: 30px; background:#169bd5; position: absolute; top: 14px; left: 15px; } } span{ vertical-align: text-bottom; margin-left: 40px; } button{ color:@green; border: 1px solid @line-color; background: #fff; border-radius: 1px; padding: 3px 8px; } } .time-change1{ text-align: left; margin-bottom: 40px; .tm-tab{ padding: 3px 13px; background: #d3dbe3; } } .chart{ width: 100%; /*overflow: hidden;*/ .chart-left{ width: 70%; margin-right: 2%; } .chart-right{ width: 28%; } } } /*列表样式--start*/ .ul-list > li { margin-bottom: 10px; padding: 20px; border: 1px solid #e9edf1; width: 100%; background: #f6f8fb; } .ul-list > li .bg-span { display: inline-block; } .ul-list > li .li-left { margin-left: 10px; } .ul-list > li .li-right { margin-left: 10px; } .ul-list > li .li-right > p > span { margin: 0 5px; } /*列表样式--end*/ /*案例概况 end*/ @import "./other/newweibo.less"; /*新版检索 start*/ /*左侧栏 start*/ .xbjs-left{ padding-top: 70px; height: 100%; float: left; position: relative; .btn-blue{ position: absolute; left: 100%; top: 50%; transform: translateY(-50%); background: @blue; color:#fff; padding: 10px 5px; line-height: 18px; border-top-right-radius: 3px; border-bottom-right-radius: 3px; z-index: 10; } .btn-trapezoid { position: absolute; z-index: 5; left: 100%; top: 50%; -webkit-transform: translateY(-50%); transform: translateY(-50%); height: 120px; width: 0; border-left: 12px solid #029be5; border-top: 20px solid transparent; border-bottom: 20px solid transparent; cursor: pointer; i { position: absolute; left: -10px; top: 50%; color: #fff; transform: translateY(-50%); } } } .xinyuan{ display: inline-block; button{ width: 90px; height: 24px; border: 0 none; border-radius: 2px; background-color: #d3dbe3; font-size: 14px; color: #333333; line-height: 0; &:first-child{ border-radius: 2px 0 0 2px; } &:last-child{ border-radius: 0 2px 2px 0; } &.active{ background-color: #35afea; color: #ffffff; font-weight: bold; } } } .js-box{ width: 350px; height: 100%; } .js-type-list{ li{ margin-right: 7px; float: left; a{ background: @hui; border-top-left-radius: 3px; border-top-right-radius: 3px; display: inline-block; width: 112px; height: 40px; line-height: 40px; text-align: center; &.active{ background: #fff; font-weight: bold; } } &:last-child{ margin-right: 0; } } } .js-con-box{ position: relative; height: 100%; >ul{ height: 100%; padding:10px 15px 40px; border-right: 1px solid @line-color; >li{ padding: 10px 0; label{ font-size: 12px; span{ color:#8ea5c3; } } } } .left-lock{ position: absolute; bottom: 10px; right: 15px; background: #eef1f7; border: 1px solid @line-color; border-radius: 50%; color: #8ea5c3; width: 30px; height: 30px; text-align: center; line-height: 28px; font-size: 18px; } .js-search-box{ border: 1px solid @line-color; position: relative; border-radius: 2px; input{ width: 100%; border: none; padding: 4px 50px 4px 10px; height: 30px; outline:none!important; &:focus{ outline:none!important; } } .btn{ margin: 0; background: @blue; color: #fff; border-color: @blue; position: absolute; top: 0px; right: -1px; height: 30px; } } .rem-keyword{ input{ width: 100%; border: 1px solid @line-color; border-radius: 2px; padding: 4px 10px; } } .js-time-range{ input{ width: 100% !important; height: 30px; padding: 4px 10px; line-height: 30px; border-radius: 3px; border: 1px solid #d3dbe3; background: #fff; } } .infmt-source{ .infmt-sour-tab{ ul{ display: inline-block; li{ display: inline-block; margin-bottom: 10px; } } } } .senior-opt{ background: #eef1f7; border: 1px solid @line-color; padding: 0px 10px; } .opt-con{ display: none; label{ margin-top: 15px; a{ color:@yellow; margin-left: 5px; } } .dropdown{ display: block; width: 100%; button{ width: 100%; text-align: left; .caret{ float: right; margin-top: 12px; } } ul{ width: 100%; } } .multi{ button{ padding-right: 20px; position: relative; .txt; .caret{ position: absolute; top: 0px; right: 10px; } } .dropdown-menu{ max-height: 200px; padding: 0 5px; li{ display: inline-block; width: 33%; float: left; line-height: 30px; } label{ margin-top:0; width: 100%; position: relative; div{ position: absolute; top: 8px; left: 0; } span{ width: 100%; padding-left: 22px; display: inline-block; vertical-align: bottom; .txt; } } } } .realm-name{ border: 1px solid @line-color; input{ border: none; width: 100%; float: left; margin-right: -80px; padding: 4px 90px 4px 10px; } .fl-btn{ float: right; height: 30px; border-color:#fff; border-left-color: @line-color; } } .realm-name-list{ li{ a{ padding:0px 30px 0px 10px; display: block; float: left; width: 100%; margin-right: -30px; border-bottom: 1px solid @line-color; line-height: 29px; .txt; } i{ color:@red; font-size: 15px; float: right; width: 15px; text-align: center; margin-top: 6px; margin-right: 10px; display: none; cursor: pointer; } &:hover{ i{ display: inline-block; } } &:last-child{ a{ border: none; } } } } .check-weibo{ margin-left: 10px; span{ color:@red; } } } .opt-btn{ display: block; text-align: center; line-height: 40px; margin-top: 5px; i{ margin-left: 5px; } } } /*左侧栏 end*/ /*搜索前 start*/ .js-con-pd{ padding: 15px 15px 0; } .xbjs-right-box{ padding: 60px 0px 0 350px; height: 100%; .bgw{ height: 100%; position: relative; } } .biglist-box{ position: absolute; top: 50%; left: 50%; transform: translate(-50%,-50%); width: 85%; .list-box{ border: 1px solid @line-color; float: left; width: 30%; margin-right: 5%; h4{ padding: 10px; font-weight: bold; background: #eef1f7; color: #fff; i{ color:#fff; font-size: 14px; margin-right: 5px; } } .bg1{ background: #40C6BD; } .bg2{ background: #6AA9E4; } .bg3{ background: #FC7E72; } } .sec-box{ margin-right: 0!important; } .list-table{ width: 100%; max-height: 590px; table{ width: 100%; } thead{ background: #f6f8fb; th{ padding:5px 10px; } } tr{ border-top: 1px solid @line-color; a{ padding: 7px; display: block; i{ float: right; color:@blue; display: none; line-height: 19px; } &:hover{ i{ display: inline-block; } } } .tright{ padding: 7px 10px; } } .list-num{ width: 16px; height: 16px; display: inline-block; background: @hui; text-align: center; line-height: 16px; } .top3{ background: @red; color:#fff; } } } /*搜索前 end*/ /*搜索结果 start*/ .xbjs-right-box{ .mr10{ margin-right: 15px; } .star{ border:none; background:#fff; } .record-top{ height: 30px; line-height: 30px; border-bottom: 1px solid #d3dbe3; overflow: hidden; .text{ width: 100%; height: 30px; padding-left: 13px; float: left; margin-right: -110px; padding-right: 110px; } .pull-right{ margin: 0; height: 30px; line-height: 30px; } .hd{ position: relative; display: inline-block; height: 30px; max-width:200px; min-width:79px; padding: 0 17px; margin-left: -13px; overflow: hidden; b{ display: block; position: absolute; &.bg-lf{ left: 1px; width: 0; height: 0; border-bottom: 30px solid #d3dbe3; border-left: 17px solid transparent; &:before{ content: ""; position: absolute; width: 1px; height: 32px; display: block; background-color: #a8b8d0; left: -9.2px; -webkit-transform: rotate(32deg); transform: rotate(32deg); } } &.bg-rf{ z-index: 3; right: 1px; width: 0; height: 0; border-bottom: 30px solid #d3dbe3; border-right: 17px solid transparent; &:before{ content: ""; position: absolute; width: 1px; height: 32px; display: block; background-color: #a8b8d0; left: 6.8px; -webkit-transform: rotate(-29deg); transform: rotate(-29deg); } } } .text{ display: inline-block; position: relative; width: 100%; margin:0; text-align: center; overflow: hidden; height: 30px; padding: 0 5px; z-index: 2; background: #d3dbe3; border-top: 1px solid #a8b8d0; border-radius: 6px 6px 0 0; } .btn-i{ position: absolute; right: 16px; top: 50%; height: 19px; margin-top: -8px; z-index: 2; margin-left: 0; width: 22px; text-align: center; background: #d3dbe3; display: none; i{ z-index: 2; margin: 0; height: 18px; width: 20px; background: #d3dbe3; background: url(../images/bg_a_2x.png) no-repeat; } } &:hover{ .btn-i{ display: block; } } &.on{ color: #fff; z-index: 5; .text,.btn-i{ background:@blue; } i{ background: url(../images/bg_a_1x.png) no-repeat; } b{ top: 2px; &.bg-lf{ border-bottom: 30px solid @blue; &:before{ display: none; } } &.bg-rf{ border-bottom: 30px solid @blue; &:before{ display: none; } } } } } i{ float: right; margin-left: 5px; height: 29px; line-height: 30px; } } } .xbjs-right-middle{ position: relative; top: -1px; background: #fff; overflow: scroll; border: 1px solid #d3dbe3; border-top: 2px solid #2d9be5; border-bottom: none; .a2{ color: #5CCA79; } .bt-line{ position:relative; padding: 13px; padding-bottom: 0; margin-bottom: 0; .down-box { position: absolute; right: 13px; justify-content: center; align-items: center; } .a-btn-down { display: inline-block; width: 30px; height: 30px; font-size: 20px; color: #8ea5c3; line-height: 30px; text-align: center; border-radius: 3px; border:1px solid #d3dbe3; cursor: pointer; } } .date-wrapper{ padding: 13px 0px 9px 0; } .li-bottom{ // position: relative; // top: 0px; .bg-p{ height: 116px; } } .input-mt{ position: relative; top: -1px; } .topNav{ position: relative; width: 100%; background: #fff; z-index: 1; .tab-item{ a{ margin-right: 5px; border-radius: 3px; border-right:none; } } &.on{ display:none; } } .a-target{ display: inline-block; padding: 0 10px; margin: 0 5px; min-width: 40px; height: 30px; border: 1px solid #d3dbe3; line-height: 28px; color: #029be5; border-radius: 0; background: #fff; img{ margin-top: 3px; } } .btn-show{ display: none; position: relative; top: -1px; width: 85px; height: 35px; margin: 0 auto; padding: 5px; border: 1px solid #d3dbe3; text-align: center; .btn-down{ display: inline-block; width: 70px; height: 22px; background: url(../images/btn-down.png) no-repeat; background-position: center; text-align: center; background-size: 50%; } } .js-tab-list{ // position: absolute; // top: 110px; width: 100%; // padding-top: 110px; .ck-checked{ position: relative; top: -5px; left: -3px; } .hd-title{ float: left; width: 93%; margin-right: -222px; padding-right: 230px; em{ font-weight: normal; } h3{ height: 20px; font-weight: 700; display: block; max-width: 100%; margin-right: -55px; padding-right: 58px; a{ display: block; width: 100%; .txt() } } } > li{ position: relative; height: 120px; padding: 13px; background: #fff; border-bottom:1px solid #d3dbe3; &:last-child{ border-bottom:none; } .u-icon{ display: none } &:hover{ background: #EEF1F7; .u-icon{ display: block; } } &.mode{ .news-rf{ margin-left: 0; } } } dt{ width: 100%; height: 20px; line-height: 20px; } dl{ margin-left: 35px; } } .original{ margin-top: 8px; .img-lf{ float: left; width: 90px; height: 60px; overflow: hidden; } img{ width: 100%; } .news-rf{ margin-left:103px; p{ height: 40px; line-height: 20px; overflow: hidden; text-overflow: ellipsis; display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 2; } } .article-more{ margin-top: 8px; a{ float: right; color:@blue; } } } } .xbjs-right-bottom{ background:#fff; border: 1px solid #d3dbe3; border-top: none; .check-pd{ padding-left: 3px; padding-right: 4px; } .zt-ft{ height: 51px; } } .xbjs-fixed-box{ position: fixed; z-index: 999; top: 0; right: -300px; min-width: 300px; height: 100%; background: #fff; box-shadow: -1px 0 15px 0px rgba(0, 0, 0, 0.17); .hd-nav{ height: 30px; padding: 8px 15px; border-bottom: 1px solid #d3dbe3; box-sizing: content-box; a{ position:relative; display: inline-block; float: left; padding: 0 10px; width: 50%; height: 30px; line-height: 30px; color: #333333; text-align: center; font-size: 14px; background: #d3dbe3; border-radius: 3px 0 0px 3px; &:last-child{ border-radius: 0 3px 3px 0; } &.on{ color: #fff; background: #2d9be5; &:before{ content: ""; display: block; position: absolute; left: 50%; bottom: -8px; width: 0px; height: 0px; margin-left: -4px; border-right: 4px solid transparent; border-left: 4px solid transparent; border-top: 8px solid #2d9be5; } } } } .bd-box{ &.box-hide{ display: none; } .article:last-child{ display: none; } .text{ display: block; width: 100%; line-height: 16px; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; } .ul{ max-height: 400px; overflow: hidden; } li{ position: relative; border-bottom: 1px solid #d3dbe3; &:hover{ .del{ display: block; } } a{ padding: 12px 15px; } } .del{ display: none; position: absolute; right: 15px; top: 50%; margin-top: -7px; } em{ display: inline-block; width: 18px; height: 15px; margin-right: 22px; line-height: 15px; text-align: center; background: #cfd5de; &.hot{ color: #fff; background: red; } } .switch-page{ margin: 0 auto; margin-top: 10px; text-align: center; } } .record{ margin-top: 30px; .title{ padding: 0px 15px 8px 15px; border-bottom: 1px solid #d3dbe3; i{ position: relative; top: 1px; color: #9AAFC7; font-size: 14px; } span{ margin-left: 5px; color: #000; font-size: 16px; font-weight: 700; } a{ float: right; text-decoration: underline; } } .article{ max-height: 200px; } li{ &:hover{ background:#eef1f7; } a{ display: block; width: 100%; line-height: 16px; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; padding: 12px 15px; border-bottom: 1px solid @line-color; position: relative; .del{ display: none; position: absolute; right: 15px; top: 50%; margin-top: -7px; } &:hover{ .del{ display: block; } } } } } .rightbar-go{ display: block; position: absolute; top: 50%; left: -32px; width: 33px; height: 90px; margin-top: -45px; background: url(../images/icon_l_btn.png) center center no-repeat; } } #see-Show,#Reported{ .modal-body{ padding: 0; max-height:550px; } .modal-footer{ border-top: 1px solid #e5e5e5; } .modal-header{ border-bottom: 1px solid #e5e5e5; } .btns{ margin: 0 5px; padding: 0 10px; height: 29px; line-height: 28px; border: 1px solid #d3dbe3; border-radius: 3px; background: #fff; &:hover{ color: #06bdf2; } } .a2{ color: #5CCA79; } .js-tab-list{ width: 100%; .ck-checked{ position: relative; top: -5px; left: -3px; } .hd-title{ float: left; width: 100%; margin-right: -222px; padding-right: 230px; em{ font-weight: normal; } h3{ height: 20px; font-weight: 700; display: block; max-width: 100%; margin-right: -55px; padding-right: 58px; a{ display: block; width: 100%; .txt() } } } li{ height: 120px; padding: 13px; background: #fff; border-bottom:1px solid #d3dbe3; &:last-child{ border-bottom:none; } .u-icon{ display: none } &:hover{ background: #EEF1F7; .u-icon{ display: block; } } &.mode{ .news-rf{ margin-left: 0; } } } dt{ width: 100%; height: 20px; line-height: 20px; } } .original{ margin-top: 8px; .img-lf{ float: left; width: 90px; height: 60px; overflow: hidden; } img{ width: 100%; } .news-rf{ margin-left:103px; p{ height: 40px; line-height: 20px; overflow: hidden; text-overflow: ellipsis; display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 2; } } .article-more{ margin-top: 8px; a{ float: right; color:@blue; } } } } .modal-text{ text-align: center; padding: 80px; } /*搜索结果 end*/ /*检索微博 start*/ .weibo-sign{ color:#fff; text-align: center; position: absolute; top: 0; left: 0; span{ position: absolute; z-index: 2; left: 3px; } &:after { content: ""; display: inline-block; width: 0; height: 0; border-width: 0 0 35px 35px; border-style:solid; border-color:transparent @blue; position: absolute; top: 0; left: 0; } } .reprint-sign{ &:after { content: ""; border-color:transparent @green; } } .reprint-relay{ &:after { content: ""; border-color:transparent #72c7c8; } } .xbjs-right-middle{ .wb-list{ li{ padding: 15px 13px 20px 13px; margin-bottom: 0; position: relative; &:hover{ background: #eef1f7; .u-icon{ display: block; } .news-details{ background: #d5deef; } } } img{ display: inline-block; } .list-l{ div{ top: 3px; vertical-align: top; } span{ vertical-align: top; line-height: 17px; } .user{ display: inline-block; } } .list-r{ margin-left: 110px; } .weibo-tit{ padding-top: 3px; } .u-icon{ display: none; } .gril{ float: left; padding-right: 222px; margin-right: -222px; } .pic{ span{ width: 80px; } } .ft-forward { span{ color:#333; img{ margin-right: 5px; } } div.pull-left{ margin-left: 20px; } } } } /*检索微博 end*/ /*以图搜图 start*/ .no-bor{ border:0!important; } .js-search-box{ i{ color:#5ec45e; position: absolute; top: 8px; left: 5px; font-size: 18px; } } .js-con-box{ .search-pic{ input{ padding-left: 30px; } } .type-box{ li{ display: inline-block; &+li{ margin-left: 25px; } } } .pic-box{ position: relative; padding: 0; a{ position: absolute; right: -8px; top: -8px; i{ font-size: 18px; color:#9cb0c9; } } } } .type-box.type-box-poa{ label{ float: left; } ul{ margin-left: 50px; } } .bdtn{ border-top: none; .js-tab-list dl{ margin-left: 10px; } } .js-con-pd{ position: relative; } .view-more{ position: absolute; bottom: 5%; left: 50%; transform:translateX(-50%); background: #029be5; color:#fff; border: none; line-height: 40px; height: 40px; padding:0 20px; z-index: 10; &:hover{ color:#fff!important; } } .li-bottom{ .pic-list,.video-list{ padding: 7px; li{ float: left; width: 24%; height: 280px; .box-shadow (0,0,8px,0,rgba(0, 0, 0, 0.2)); margin: 0.5%; margin-top: 0; text-align: center; overflow: hidden; img{ display: inline-block; width: 100%; height: 100%; } } } } .li-bottom .video-list{ li{ height: 210px; } } /*以图搜图 end*/ @media screen and (max-width: 1500px){ .xbjs-right-box .bt-line{ padding: 11px; } .xbjs-right-box .bt-line .tab-item{ margin-bottom:0; } .xbjs-right-box .bt-line .tab-item a{ padding: 0 15px; } .biglist-box .list-table{ max-height: 500px; } .li-bottom .pic-list li{ height: 250px; } .li-bottom .video-list li{ width: 32%; height: 180px; } } @media screen and (max-width: 1380px){ .xbjs-right-box .bt-line{ padding: 9px; } .xbjs-right-box .bt-line .tab-item{ margin-bottom:0; } .xbjs-right-box .bt-line .tab-item a{ padding: 0 8px; } .biglist-box{ width: 95%; } .li-bottom .pic-list li{ width: 32%; } } @media screen and (max-width:1300px){ .js-box{ width: 300px; } .js-type-list li a{ width: 95px; } .xbjs-right-box{ padding-left: 300px; } .biglist-box .list-box{ width: 32%; margin-right: 2%; } .biglist-box .list-table{ max-height: 400px; } .js-con-box .js-time-range input{ padding: 4px 8px; } } @media screen and (max-width: 1200px){ .xbjs-right-box .bt-line{ padding: 9px; } .xbjs-right-box .bt-line .tab-item{ width: 420px; margin-bottom:0; } .xbjs-right-box .bt-line .tab-item a{ padding: 0 5px; } .xbjs-right-box .sort-item .dropdown-toggle{ padding: 0 5px; } .u-icon a { margin: 0 1px !important; } .xbjs-right-middle .js-tab-list .hd-title{ padding-right: 155px; } .li-bottom .pic-list li{ height: 200px; } .li-bottom .video-list li{ width: 49%; } } @media screen and (max-height: 800px){ #see-Show .modal-body{ max-height:480px; } } @media screen and (max-height: 768px){ .xbjs-fixed-box .bd-box li a{ padding: 10px 15px; } } @media screen and (max-height: 710px){ .xbjs-fixed-box .bd-box li a,.xbjs-fixed-box .record li a{ padding: 8px 15px; } #see-Show .modal-body{ max-height:400px; } } /*新版检索 end*/ /* 4.1检索-境内开始 */ .tu_con{ display: inline-block; width: 12px; height: 12px; background: url('../images/js/tu_tengxun.png') no-repeat center center; vertical-align: middle; margin-right: 2px; } .tu_twitter{ background: url('../images/js/tu_twitter.png') no-repeat center center; } .tu_Facebook{ background: url('../images/js/tu_Facebook.png') no-repeat center center; } .tu_weixin{ background: url('../images/js/tu_weixin.png') no-repeat center center; } .tu_app{ background: url('../images/js/tu_app.png') no-repeat center center; } .tu_tianya{ background: url('../images/js/tu_tianya.png') no-repeat center center; } .tu_shipin{ background: url('../images/js/tu_shipin.png') no-repeat center center; } .tu_baidu{ background: url('../images/js/tu_baidu.png') no-repeat center center; } .tu_guosou{ background: url('../images/js/tu_guosou.png') no-repeat center center; } .tu_qq{ background: url('../images/js/tu_qq.png') no-repeat center center; } .tu_pengyoujuan{ background: url('../images/js/tu_pengyoujuan.png') no-repeat center center; } .tu_douyin{ background: url('../images/js/tu_douyin.png') no-repeat center center; } .tu_tengwei{ background: url('../images/js/tu_tengwei.png') no-repeat center center; } .icon-zf{ display: inline-block; background: url('../images/wb-zf.png') no-repeat center center; width: 14px; height: 12px; } .icon-pl{ display: inline-block; background: url('../images/wb-pl.png') no-repeat center center; width: 14px; height: 12px; } .icon-dz{ display: inline-block; background: url('../images/wb-dz.png') no-repeat center center; width: 14px; height: 12px; } a{ &:hover{ color: @blue; .icon-zf{ background: url('../images/wb-zf-b.png') no-repeat center center; } .icon-pl{ background: url('../images/wb-pl-b.png') no-repeat center center; } .icon-dz{ background: url('../images/wb-dz-b.png') no-repeat center center; } } } .wb-pl{ display: inline-block; vertical-align: middle; margin: -2px 2px 0 2px; padding: 2px; border: 1px solid #5ec45e; font-size: 12px; color: #5ec45e; } .wb-yc{ border: 1px solid #ffa640; color: #ffa640; } .wb-zf{ border: 1px solid #029be5; color: #029be5; } .wb-cwb{ border: 1px solid #f65757; color: #f65757; } .navList{ float: left; position: relative; width: 100%; border: 1px solid #d3dbe3; background: #ffffff; padding: 10px 20px 4px 20px; border-bottom: none; .nLeft{ width: 75%; } >ul>li{ float: left; line-height: 30px; margin-right: 6px; margin-bottom: 6px; >a{ display: inline-block; background: #d3dbe3; padding: 0 15px; border-radius: 3px; font-size: 14px; color: #333333; &:hover{ color: #029be5; } } &.question a{ width: 18px; height: 18px; margin-left: 5px; line-height: 18px; padding: 0; border-radius: 50%; text-align: center; background: #ffd584; color: #9f7422; font-size: 12px; } &.nActive a{ background: #5ec45e; color: white; } &.nActive .sanjiao{ color: white !important; } &.news .sanjiao{ margin-left: 5px; vertical-align: top; font-size: 20px; color: #8ea5c3; } &.news{ position: relative; } .select{ display: none; position: absolute; z-index: 3; left: -84px; top: 33px; width: 420px; background: #ffffff; border: 1px solid #d3dbe3; .baijiao{ position: absolute; left: 110px; top: -8px; display: block; width: 18px; height: 8px; background: url(../images/js/js_sanjiao.png) no-repeat; } a{ display: inline-block; margin-left: 28px; padding: 10px 0; font-size: 14px; color: #333333; &:hover{ color: #029be5; } } } &.question{ position: relative; span{ position: absolute; top: 0px; left: 23px; background: #f7f1e5; display: inline-block; border-radius: 3px; margin-left: 10px; font-weight: normal; line-height: 24px; padding: 5px 10px; z-index: 3; width: 310px; display: none; &:after { content: ''; width: 0; height: 0; border-top: 5px solid transparent; border-right: 10px solid #f7f1e5; border-bottom: 5px solid transparent; position: absolute; left: -7px; top: 11px; display: block; } } } } .nRight{ position: absolute; right: 10px; top: 10px; >li{ margin-left: 4px; >a{ background: white; border: 1px solid #d3dbe3; .jian{ margin-left: 3px; } .sanjiao{ margin-left: 10px; vertical-align: top; font-size: 20px; color: #8ea5c3; } } } .translate{ a{ background: #f6f8fa; } } .inside{ .dropdown-toggle{ border-radius: 3px; color: #333333; } .caret{ margin-right: 10px; color: #8ea5c3; } } .nUp{ a{ color: #029be5; border: 1px solid #029be5; } } } } .chooseList{ display: none; float: left; background: white; width: 100%; padding-left: 20px; li{ line-height: 50px; border-bottom: 1px dashed #d3dbe3; .cLable{ float: left; width: 75px; text-align: right; color: #767676; } .cChoose{ float: left; margin-left: 5px; a{ margin-right: 12px; font-size: 14px; color: #333333; } .aActive{ color: #029be5; } a:hover{ color: #029be5; } } &:last-child{ border-bottom: none; } .cTime{ display: inline-block; width: 190px; height: 24px; .time-range{ width: 190px; height: 24px; line-height: 24px; } } } } .chooseResult{ float: left; position: relative; width: 100%; padding: 10px 20px 4px 20px; border: 1px solid #d3dbe3; background: #ffffff; font-size: 14px; color: #333333; .condLeft{ width: 75px; line-height: 32px; } .condRight{ .l_flex(); li{ float: left; margin-right: 6px; margin-bottom: 6px; line-height: 30px; border-radius: 3px; border: 1px solid #d3dbe3; padding: 0 10px; font-size: 14px; cursor: pointer; .delete{ display: inline-block; width: 16px; height: 16px; line-height: 16px; background: #e5e9ee; border-radius: 50%; vertical-align: middle; text-align: center; margin: -2px 0 0 5px; cursor: pointer; font-size: 12px; color: #95aac6; } &:hover{ .delete{ background: #86cff2; color: white; } } &.empty{ border: none; background: #029be5; color: white; } &.default{ background: #f6f8fa; &:hover{ color: #029be5; } } &.number{ border: none; cursor: default; color: #8ea5c3; } } } .summary{ position: absolute; top: 10px; right: 20px; a{ background: #f6f8fa; border: 1px solid #d3dbe3; display: inline-block; line-height: 30px; padding: 0 15px; border-radius: 3px; font-size: 14px; color: #333333; &:hover{ color: #029be5; } } } } .resultBox{ border-top: 1px solid #d3dbe3; } .resultList,.modal{ .floatNone{ float: none !important; } .dian{ display: inline-block; vertical-align: top; margin: 0 2px; } .s10{ margin: 0 15px 0 17px; } li{ height: auto !important; } .detail{ color: #767676 ; } .twoLine{ .txtmore(2); } .article1{ margin-top: 2px !important; } .sTime{ color: #8ea5c3; font-size: 12px; s{ text-decoration: none; color: #029be5; } } .aLabel{ display: inline-block; vertical-align: middle; margin-left: 15px; i{ display: inline-block; border: 1px solid #ffa640; font-size: 12px !important; border-radius: 20px; padding: 0 8px; background: #fff6ec; color: #ffa640; } } .articleShow{ display: none; margin-left: 35px; margin-top: 10px; } .weoboLogo{ color: #f65757; } .headPic{ display: inline-block; vertical-align: middle; width: 25px; height: 25px; border-radius: 50%; overflow: hidden; img{ width: 100%; } } .wb-word{ .article1{ margin-top: 7px !important; } } .control{ display: inline-block; vertical-align: middle; li{ float: left; border-right: 1px solid #8ea5c3; &:last-child{ border-right: none; padding-right: 0; } } a{ margin-right: 10px; padding: 0 10px; color: #333333 !important; font-size: 12px !important; &:first-child{ border-right: none; padding: 0 0 0 10px; } &:hover{ color: #029be5 !important; } i{ margin-right: 5px; vertical-align: middle; margin-top: -2px; } } } /* 微博图片 */ .imgBox{ li{ float: left; margin-right: 10px; margin-top: 10px; width: 60px; height: 60px; overflow: hidden; img{ width: 100%; } } } /* 微博转发 */ .relayContent{ background: #eef1f7; margin-top: 8px; padding: 5px 0; font-size: 12px; color: #767676; p{ height: auto !important; } .relayWho{ padding:0 10px; font-size: 14px; height: auto !important; color: #029be5; } .detail{ padding: 0 10px; } .imgBox{ margin-top: -3px; padding: 0 10px !important; } .article1{ padding: 0 10px !important; } } /* 微博长图 */ .longImg{ margin-top: 8px; li{ float: left; position: relative; margin-right: 10px; width: 130px; height: 150px; overflow: hidden; img{ width: 100%; } .changtu{ position: absolute; right: 0; bottom: 0; display: block; width: 30px; height: 16px; line-height: 16px; text-align: center; background: #fb8d0a; color: white; font-size: 12px; } } } /* 微博长文 */ .longWen{ margin-top: 8px; padding: 5px 10px; background: #d4d8de; font-size: 12px; color: #333333; .big{ font-size: 14px; font-weight: 700; } } .pull-left a:active{ color: #767676; } } /* 展开点赞,评论,转发 */ .showControl{ display: none; position: relative; width: 100%; margin-top: 20px; background: #f6f8fb; border-top: 1px solid #d3dbe3; font-size: 12px; color: #333333; .huijiao{ position: absolute; left: 225px; /* left: 290px; left: 352px; */ top: -11px; display: block; width: 22px; height: 11px; background: url('../images/js/huijiao.png') no-repeat; } li{ padding: 20px 5px; border-bottom: 1px solid #d3dbe3; &.loadMore{ height: 30px; padding: 0; line-height: 30px; text-align: center; a{ color: #13a2e7; } } } .sLeft{ display: inline-block; vertical-align: top; width: 34px; height: 34px; overflow: hidden; img{ width: 100%; } } .sRight{ margin-left: 15px; display: inline-block; vertical-align: top; .rName{ margin-top: -2px; } .rDetail{ margin-top: 3px; } .blue{ margin-right: 5px; } .time{ font-size: 12px; color: #767676; } .control{ margin-left: 30px; } .sImg{ li{ float: left; width: 60px; height: 60px; overflow: hidden; border-bottom: none; padding: 0; margin: 6px 10px 6px 0; img{ width: 100%; } } } } .show-zf{ display: none; } } .newRetrMain{ /* .tcenter{ font-weight: 100; } .u-words{ font-weight: 100; } */ thead{ background: #f6f8fb; } } @media screen and (max-width:1400px){ .navList .nLeft{ width: 72%; } .chooseResult .condRight{ width: 80%; } } @media screen and (max-width:1200px){ .navList .nLeft{ width: 66%; } } /* 4.1检索-境内结束 */ <file_sep>/app/less/other/rot.less @charset "utf-8"; /* 词云 start */ .rot-ciyun-left{ width: 100%; height: 100%; margin-right: -700px; padding-right: 720px; } .ciyun-top{ position: relative; border: 1px solid #d3dbe3; padding: 10px 20px; height: 50px; overflow: hidden; >ul{ width: 96%; } li{ float: left; margin-right: 6px; margin-bottom: 10px; a{ display: inline-block; min-width: 80px; height: 30px; line-height: 30px; text-align: center; border-radius: 1px; padding: 0 8px; background: #d3dbe3; &.active,&:hover{ background: #5ec45e; color: #fff; font-weight: bold; } } } .ciyun-top-more{ position: absolute; top: 10px; right:20px; color: #8ea5c3; } } .ciyun-box{ width: 100%; height:818px; margin-top: 11px; padding: 10px 20px 20px; border: 1px solid #d3dbe3; overflow: hidden; } .ciyun-box-top{ margin-bottom: 20px; .time-cycle{ display: inline-block; margin-right: 40px; } .export-btn{ color: #8ea5c3; } } .ciyun-chart{ position: relative; height: 94%; width: 100%; } .rot-ciyun-right{ width: 700px; height: 100%; border: 1px solid #d3dbe3; position: relative; .newqj-title{ line-height: 48px; padding: 0 15px; border-bottom: 1px solid #d3dbe3; } .rotNews-weixin,.rotNews-weibo{ display: none; } .dropdown-toggle{ color: #333; .caret{ color: #8ea5c3; } } .g-zlm-rotNews{ overflow: hidden; } /* .newweibo-box { .wb-list{ li{ padding: 10px 15px !important; .new-weibo{ padding: 0; } .weibo-handle-box{ margin-op: 24px; li{ border: none; .handle-icon{ display: block; margin-left: -2px; } } } } } } */ } .ciyun-right-middle{ border: none; top: 0; .list-l{ span{ vertical-align: top; } } .list-r{ -webkit-box-flex: 1; -ms-flex: 1; flex: 1; display: -webkit-box; display: -ms-flexbox; display: flex; position: relative; cursor: pointer; margin-left: 70px !important; margin-right: 290px !important; } .user{ width: 60px; height: 60px; display: inline-block; overflow: hidden; margin-right: 10px; } .right-box{ -ms-flex: 1; flex: 1; position: relative; height: 60px; .right-news{ color: #029be5; } .exceed-p{ margin-bottom: 5px !important; overflow:hidden; text-overflow:ellipsis; display:-webkit-box; -webkit-box-orient:vertical; -webkit-line-clamp:2; } } } /* 右侧新闻模块 */ .g-zlm-rotNews{ .ul-big{ .li-big{ position:relative; padding:8px 0 8px 15px; border-bottom: 1px solid #D3DBE3; .g-zlm-hoverBox{ position:absolute; left: 145px; top: 90px; background: #fff; z-index: 1; min-height: 248px; display: none; } .new-lt{ width: 55.5%; >div{ float: left; } .check{ margin: 22px 16px 0 0; } .new-img{ margin-right: 12px; } .new-ct{ width: 66%; span{ font-size: 13px; color: #8EA5C3; a{ color: #8EA5C3; } } >a{ font-size: 13px; color: #363636; font-weight: 600; min-height: 44px; padding-top: 7px; line-height: 18px; display: inline-block; } } } } } .g-zlm-btnList{ right: 0; top: 0px; } } .g-zlm-btnList{ position: absolute; padding: 9px 12px 16px 20px; .sm-ul{ padding-top: 12px; li{ float: left; margin-right: 13px; &:hover{ i{ -ms-background-position-y: -197px; background-position-y: -197px; } .i6{ background-position: -190px -194px; } .i8,.i9,.i10,.i11{ background-position-y: -196px; } .i7{ background-position-y:-195px; } } i{ background: url(../images/xuan/pubuliu-icon.png); width: 20px; height: 20px; display: inline-block; position: relative; top: 6px; } .i1{ background-position: -10px -156px; left: 9px; } .i2{ background-position: -45px -156px; left: 14px; } .i3{ background-position: -84px -156px; left: 4px; } .i4{ background-position: -118px -156px; left: 2px; } .i5{ background-position: -152px -156px; left: 2px; } .i6{ background-position: -190px -153px; left: 6px; top:5px; } .i7{ background-position: -228px -154px; left: 5px; } .i8{ background-position: -265px -155px; left: 2px; } .i9{ background-position: -302px -155px; left: 3px; } .i10{ background-position: -335px -155px; left: 2px; } .i11{ background-position: -368px -155px; left: 4px; } div{ font-size: 12px; color: #8EA5C3; } a{ display: block; } } .hides{ display: none; } } .moreList{ cursor: pointer; padding: 0 6px; margin-top: 23px; &:hover{ div{ background: #FFA643; } } >div{ width: 5px; height: 5px; background: #8EA5C3; border-radius:50%; margin-bottom: 5px; } } .g-zlm-page{ padding: 35px 0 0 15px; } } /* 列表下面的页码样式 */ .g-zlm-page{ padding: 15px 0 12px 15px; width: 100%; >div{ float: left; span{ color: #363636; font-size: 12px; } a{ display: inline-block; color: #363636; font-size: 12px; padding: 4px 12px; background:#FCFDFD; border: 1px solid #D3DBE3; &:hover{ background:#E6E7EA; border: 1px solid #8EA5C3; } } } .allopr{ font-size: 15px; color: #363636; padding: 2px 15px; background: #FBFCFD; border:1px solid #D3DBE3; border-radius: 3px; margin-right: 305px; } .chec{ margin: 5px 10px 0 0; } .bt{ margin-left: 8px; } .num{ padding-top: 4px; } } .rot-ciyun-right{ .rotNews-weixin{ .new-ct{ span{ a{ color: #14A2E7!important; } } } } .rotNews-weibo{ overflow: hidden; height: 825px; .wb-list > ul > li { margin-bottom: 0; } } } .g-zlm-hoverBox{ width: 408px; .function-intro{ padding: 16px; border:1px solid #D3DBE3; border-radius: 4px 4px 0 0; .top{ .top-content{ margin: 12px 0 0 12px; } .title{ font-size: 18px; color: #363636; font-weight: 600; } .count{ font-size: 13px; color: #363636; span{ color: #8EA5C3; } } .analysis{ font-size: 13px; color: #363636; background: #F6F7FA; padding: 3px 6px; border:1px solid #D3DBE3; border-radius: 3px; margin-top: 13px; display: inline-block; } } p{ padding-top: 8px; font-size:13px; color: #363636; em{ color:#8EA5C3; } } } .biaoqian{ padding: 12px 0 0 18px; border:1px solid #D3DBE3; border-top: none; font-size: 14px; color: #363636; li{ margin:0 10px 10px 0; float: left; a{ display: inline-block; background: #D3DBE3; padding: 1px 6px; border-radius:2px; } } .lable-rt{ width: 83%; } } } .rot-ciyun-right .newweibo-box .weibo-handle-box { position: relative; top: 0; right: 0; margin-top: 0; >li{ padding: 0 28px; } >li:last-child{ padding-right: 0; } .more-btn{ top: 2px; } } .rotNews-weibo .Functional-options{ padding-left: 32px; height: 38px; padding-top: 7px; border-top: 1px solid #EFF2F7; .icon-heart{ background: url(../images/xuan/pubuliu-icon.png); background-position: -10px -156px; width: 20px; height: 20px; display: inline-block; position: relative; top:4px ; } .icon-search{ background: url(../images/xuan/pubuliu-icon.png); background-position: -84px -156px; width: 20px; height: 20px; display: inline-block; position: relative; top: 3px; } .icon-add{ background: url(../images/xuan/pubuliu-icon.png); background-position: -152px -156px; width: 20px; height: 20px; display: inline-block; position: relative; top: 3px; } .icon-unfun { height: 20px; position: relative; top: 2px; } .icon-yujing { height: 20px; position: relative; top: 1px; } } /* 词云 end */ <file_sep>/app/less/cq_zddx.less @import "./base/base.less"; .redStar{ display: inline-block; vertical-align: middle; line-height: normal; margin-right: 2px; color: #f54545; } /*重庆重点对象*/ .cqzdr{ padding-left: 50px; } .zddx_nav_box{ height: 100%; float: left; /* 左边导航 start */ .leftnavbar { z-index: 9; position: fixed; left: 0; top: 0; padding-top: 60px; height: 100%; background: #06548F; font-size: 14px; } .system-settings { height: 50px; padding: 10px 20px; a { width: 100%; height: 30px; background: #06548F; border-radius: 5px; text-align: center; line-height: 30px; color: #fff; display: inline-block; &:hover, &.active { background: @hover-blue; color: #fff; } } } .nav-list { width: 200px; overflow-y: auto; li { height: 46px; background: #06548F !important; margin-bottom: 1px; a { line-height: 46px; padding: 0 15px; color: @key-blue; display: block; i { margin-right: 5px; width: 15px; } } &:hover, &.active { background: #06548F !important; } &:hover a, &.active a { color: #fff; } } } .navtop { text-align: center; width: 50px; .menu { height: 51px; line-height: 50px; font-size: 24px; color: #fff; } a { color: #fff; display: block; &:hover { color: @bule; } } .menu-list { a { position: relative; font-size: 16px; width: 30px; height: 30px; line-height: 30px; display: inline-block; border-radius: 50%; background: #006daf; margin-bottom: 15px; &:hover,&.active { color: #fff; background: @bule; } } } } .menu-li { background: #06548F; li { height: 51px; background: #06548F; margin-bottom: 0px; &:hover{ background: #1389D2; } &.active{ background:#1389d0; border-bottom:1px solid #06548f; border-top:1px solid #06548f; } &.zdzd-nav{ position: relative; /* &:hover{ .li-menu-li{ display: block; } } */ .li-menu-li{ display: none; box-shadow: -1px 0px 7px #06548f; position: fixed; left: 139px; top: 186px; >li{ height: 35px; width: 75px; background:#509BDD; &:hover{ background:#4290D4; } a{ p{ display: inline-block; vertical-align: top; color: #fff; } } } } } } a { width: 100%; height: 100%; display: block; padding: 10px; >div{ display: inline-block; } em { display: none; color: #fff; margin-left: 5px; vertical-align: super; } } } /* 左边导航 end */ .zddx-left{ display: inline-block; width: 300px; height: 100%; float: left; background: -webkit-radial-gradient(circle,#0e4f80, #043553); /* Safari 5.1 - 6.0 */ background: -o-radial-gradient(circle,#0e4f80, #043553); /* Opera 11.6 - 12.0 */ background: -moz-radial-gradient(circle,#0e4f80, #043553); /* Firefox 3.6 - 15 */ background: radial-gradient(circle,#0e4f80, #043553); /* 标准的语法 */ a{ color:#fff; &:hover{ color:#fff; } } .left-top{ padding: 20px; .top-search-box{ width: 100%; height: 100%; background: #011e2f; position: relative; input{ width: 100%; height: 100%; background: none; border: none; padding: 7px 25px 7px 7px; margin-right: -25px; color: #fff; } a{ position: absolute; cursor: pointer; height: 30px; line-height: 30px; width: 30px; i{ color: #808F97; } } } } .herf-btn{ li{ float: left; width: 50%; border: 1px solid #011e2f; border-left: none; &:last-child{ border-right: none; } a{ display: block; text-align: center; line-height: 38px; i{ margin-right: 5px; } } } } .plista{ >li{ position: relative; border-bottom:1px solid #063657; >a{ display: block; padding: 15px 20px; i{ margin-right: 18px; margin-top: 5px; color:#8ea5c3; font-size: 18px; } } &:hover,&.active{ background: #1389d0; >a{ i{ color:#fff; } } } &.active{ .clist{ display: block; } } .operate-sj-box{ position: absolute; right: 15px; top: 15px; width: 20px; height: 40px; text-align: center; color:#fff; font-size: 18px; &:hover{ .operate-btna{ display: block; } } .operate-btna{ position: absolute; background: #fff; font-size: 12px; top: 35px; right: -5px; border-radius: 1px; padding: 7px 6px 0px; width: 84px; z-index: 2; display: none; &:before { content: ""; width: 0; height: 0; border-left: 10px solid transparent; border-right: 10px solid transparent; border-bottom: 10px solid #fff; position: absolute; top: -10px; right: 8px; } li{ float: left; a{ display: inline-block; width: 36px; height: 44px; text-align: center; color: #000; i{ font-size: 18px; width: 100%; } } } } } } .clist{ display: none; >li{ position: relative; height: 52px; background: #063657; &:hover{ background: #011e2f; } >a{ display: inline-block; padding: 15px 10px 15px 20px; margin-right: -40px; width: 100%; i{ margin-right: 10px; margin-top: 4px; float: left; } span{ display: inline-block; float: left; width: 100%; margin-right: -60px; padding-right: 45px; .txt; } } .operate-box{ position: absolute; top: 15px; right: 13px; .operate-morea{ display: inline-block; width: 25px; text-align: center; color:#8ea5c3; cursor: pointer; font-size: 18px; } .operate-btn{ position: absolute; background: #fff; font-size: 12px; top: 35px; right: -5px; border-radius: 1px; padding: 7px 6px 0px; width: 84px; z-index: 2; display: none; &:before { content: ""; width: 0; height: 0; border-left: 10px solid transparent; border-right: 10px solid transparent; border-bottom: 10px solid #fff; position: absolute; top: -10px; right: 8px; } li{ float: left; a{ display: inline-block; width: 36px; height: 44px; text-align: center; color: #000; i{ font-size: 18px; width: 100%; } } } } } } } } .plista_sj{ >li{ position: relative; border-bottom: 1px solid #063657; >a{ display: block; padding: 15px 20px; } &:hover,&.active{ background: #1389d0; } .operate-boxa{ position: absolute; top: 15px; right: 13px; .operate-morea{ display: inline-block; width: 25px; text-align: center; color:#8ea5c3; cursor: pointer; font-size: 18px; } &:hover{ .operate-btns{ display: block; } } .operate-btns{ position: absolute; background: #fff; font-size: 12px; top: 35px; right: -5px; border-radius: 1px; padding: 7px 6px 0px; width: 84px; z-index: 2; display: none; &:before { content: ""; width: 0; height: 0; border-left: 10px solid transparent; border-right: 10px solid transparent; border-bottom: 10px solid #fff; position: absolute; top: -10px; right: 8px; } >li{ a{ display: inline-block; width: 36px; height: 44px; text-align: center; color: #000; i{ font-size: 18px; width: 100%; } } } } } } } } } .zddx-right{ padding: 0 20px; width: auto; margin-left: 300px; } .zddx-right-box{ padding: 12px 0; } .zddx-right-title{ background: #fff; height: 50px; border: 1px solid #d3dbe3; padding: 0 20px; .title-aleft{ float: left; h3{ line-height: 48px; font-weight: bold; color: #029be5; display: inline-block; } } } .cqzdr{ .title-aright{ line-height:48px; .btn{ background: linear-gradient(#fff, #f3f5f8); &.active,&:hover{ color: white; background: #029be5; border: 1px solid #029be5; box-shadow: inset 0 3px 5px rgba(0, 0, 0, 0); } } } } /*重庆重点对象 end*/ /*重点人编辑 start*/ .zdr-bj-box{ .zdr-bj-con{ background: #fff; height: 795px; padding-top: 20px; .g-zlm-phone{ .lxfs:last-child{ .i1{ display: block; } } .lxfs{ .btnbox{ position: relative;left: 20px;top: 8px;margin-left: -17px; i{ display: inline-block; width: 18px; height: 18px; cursor: pointer; } .i1{ background: url(../images/zlm732_03.png); background-repeat: no-repeat; display: none; } .i2{ background: url(../images/icon_del.png); background-repeat: no-repeat; // display: none; } } } } >ul{ padding: 0 16% 0 15%; >li.fjsc{ position: relative; height: 100px; .xs{ i{ display: inline-block; width: 14px; height:14px; background: url(../images/zlm732_07.png); cursor: pointer; position:relative; top: 3px; margin-left: 20px; } } .xs1{ position:absolute; top: 53px; left: 127px; } .xs2{ position:absolute; top: 83px; left: 127px; } } >li{ margin-bottom: 20px; display: flex; width: 100%; >div{ } // .w10{ // width: 10%; // } // .w20{ // width: 20%; // } &.ww50{ width: 50%; } .bj-left{ width: 120px; margin-right:10px; line-height: 30px; text-align: right; } .bj-right{ .l_flex; .u-ipt{ display: inline-block; width: 100%; height: 30px; line-height: 30px; padding-left: 10px; } img{ display: inline-block; vertical-align: unset; } .touxiang-em{ margin-left: 10px; color: #C1CDDE; font-size: 12px; i{ display: inline-block; width: 15px; height: 15px; text-align: center; line-height: 15px; border-radius: 50%; border: 1px solid #C1CDDE; } } .Prompt{ display: inline-block; position: relative; width: 20px; height: 20px; background-color: #FFD584; color: #9F7422; line-height: 20px; text-align: center; border-radius: 50%; margin-left: 10px; margin-top: 5px; &:hover{ span{ display: block; } } span{ display: none; position: absolute; padding: 5px 8px; background-color: #F7F1E5; text-align: left; &.Prompt-top{ width: 234px; bottom: 30px; transform: translateX(-47%); } &.Prompt-right{ width: 495px; left: 30px; bottom: -67%; } &.Prompt-left{ width: 180px; left: -190px; bottom: -210%; } } } .option-ul{ display: inline-block; margin-left: 15px; li{ position: relative; margin-right: 10px; padding: 4px 10px; border: 1px solid #d3dbe3; border-radius: 2px; color: #333; min-width: 60px; text-align: center; display: inline-block; background: #fff; i{ position: absolute; right: -5px; top: -5px; width: 14px; height: 14px; line-height: 14px; text-align: center; color: #fff; border-radius: 50%; background: #f56969; display: inline-block; cursor: pointer; } } } .bj_add{ width: 60px; height: 30px; background-color: #1389D0; background-image: url(../images/cqdnk/icon_bjadd.png); background-repeat: no-repeat; // background-size: contain; background-position: center center; } .site_detection{ >li{ margin-bottom: 10px; >div,>label{ margin-right: 10px; } >label{ input{ padding-left: 10px; } .w190{ width: 180px; } .w350{ width: 350px; } } .del-input{ position: relative; i{ position: absolute; right: -5px; top: -5px; width: 14px; height: 14px; line-height: 14px; text-align: center; color: #fff; border-radius: 50%; background: #f56969; display: inline-block; cursor: pointer; } } } } } } } input{ border: 1px solid #D6E1E5; border-radius: 2px; } } } /*重点人编辑 end*/ /*重点人基本信息 start*/ .zddx-basic{ .title-aright{ .btn{ background: linear-gradient(#fff, #f3f5f8); &.active,&:hover{ color: white; background: #029be5; border: 1px solid #029be5; box-shadow: inset 0 3px 5px rgba(0, 0, 0, 0); } } } .zddx-basic-cont{ background-color: white; padding-top: 20px; height: 795px; .cont-pic{ width: 30%; max-width: 250px; margin-right: 45px; float: left; img{ float: right; } } .cont-bs{ width: 60%; /*max-width: 800px;*/ float: left; color: #333; ul{ font-size: 14px; li.zlm-download{ span{ margin-right: 40px; } i{ display: inline-block; width: 19px; height:14px; background: url(../images/zlm730_06.png); position: relative; top: 3px; left: 10px; cursor: pointer; &:hover{ background: url(../images/zlm730_03.png); } } } li{ float: left; width: 50%; margin-bottom: 10px; position: relative; .s-tit{ display: inline-block; width: 70px; position: absolute; top: 5px; } &.s-line{ clear: both; width: 100%; } .s-label{ display: inline-block; height: 29px; line-height: 29px; padding: 0 6px; margin-right: 15px; border: 1px solid #d3dbe3; background: linear-gradient(#feffff, #f9f9fd); } >div{ display: inline-block; height: 30px; line-height: 30px; border: 1px solid #d6e1e5; padding:0 10px; width: 60px; margin-right: 12px; &.co-s1{ margin-left: 71px; } &.co-s2{ max-width: 192px; width: 25%; } &.co-s3{ max-width: 440px; width: 50%; margin-right: 0; color: #8ea5c3; } } .web-name,.web-num,.web-address{ width: 100%; height: 100%; display: inline-block; overflow: hidden; } } } } } } @media screen and (max-width: 1450px){ .zddx-basic{ .zddx-basic-cont{ .cont-pic{ width: 20%; } .cont-bs{ width: 70%; } } } } /*重点人基本信息 end*/ /*重点人分组管理 start*/ .zddx-group{ .zddx-right-box{ .zddx-right-title{ .title-aright{ label{ width: 200px; height: 29px; line-height: 29px; position: relative; input{ width: 100%; height: inherit; padding-left: 5px; border: 1px solid #D6E1E5; border-radius: 2px; } >a{ position: absolute; background-image:url(../images/cqdnk/u_js.png); background-position: center center; background-repeat: no-repeat; right: 1px; margin: 0; border: none; height: 27px; bottom: 1px; width: 30px; } } } } .zddx-group-cont{ padding: 22px 15%; background-color: #fff; .group-tab{ border-radius: 5px; border: 1px solid #CFD5DE; table{ width: 100%; text-align: center; thead{ background-color: #CFD5DE; } tr{ height: 42px; line-height: 42px; } tbody{ tr{ &:nth-child(odd) { background-color: #EEF1F7; } cursor: pointer; border-bottom: 1px solid #CFD5DE; &:hover{ background-color: #93CFF3; } td{ i{ display: inline-block; width: 20px; height: 20px; vertical-align: text-top; } .icon-aright-edit{ background-image: url(../images/cqdnk/aright-edit.png); background-repeat: no-repeat; background-position: center center; margin-right: 10px; } .icon-aright-del{ background-image: url(../images/cqdnk/aright-del.png); background-repeat: no-repeat; background-position: center center; } .icon-aright-eye{ background-image: url(../images/u-q3.png); background-repeat: no-repeat; background-position: center center; margin-right: 10px; } } } } } .foot-paging{ height: 40px; line-height: 40px; } } } } } /*重点人分组管理 end*/ /*重点人-事业人物 start*/ .zddx-undertakings{ .zddx-undertakings-cont{ background: #fff; .undertakings-title{ >ul{ height: 50px; padding-top: 10px; padding-left: 10px; >li{ float: left; &.input_li{ .layut-input{ width: 250px; } } margin-right: 20px; } } } .undertakings-tab{ .tables{ .u-icon{ .u-b2 { background: url(../images/u_b2.png) no-repeat center center; &:hover { background: url(../images/u_2.png) no-repeat center center; } } .u-q1{ background: url(../images/u_b12.png) no-repeat center center; &:hover { background: url(../images/u_12.png) no-repeat center center; } } .u-q2{ background: url(../images/u_b11.png) no-repeat center center; &:hover { background: url(../images/u_11.png) no-repeat center center; } } .u-q3{ background: url(../images/u-q3.png) no-repeat center center; &:hover { background: url(../images/u-q33.png) no-repeat center center; } } } .td200{ position: relative; cursor: pointer; >span{ max-width: 200px; display: inline-block; overflow: hidden; text-overflow:ellipsis; white-space: nowrap; position: relative; } &:hover{ .ta-tltle{ display: block; } } .ta-tltle{ display: none; position: absolute; padding: 5px; max-width: 300px; background-color: #CFD5DE; left: 30px; z-index: 2; &::after{ content: ''; width: 0; height: 0; border-top: 5px solid transparent; border-right: 6px solid #CFD5DE; border-bottom: 5px solid transparent; position: absolute; left: 45%; top: -8px; transform: rotate(446deg); } } } .tooltip.right .tooltip-arrow{ border-right-color: #ccc !important; } .tooltip-inner{ color: #000 !important; background-color: #ccc !important; } } .zt-ft{ height: 50px; } } } } /*重点人-事业人物 end*/ /*重点事件 start*/ .undertakings-titless{ >ul{ height: 50px; // padding-top: 10px; padding-left: 10px; >li{ float: left; &.input_li{ .layut-input{ width: 250px; } } margin-right: 10px; } } } /*重点事件 end*/ /*重点人添加重点事件 start*/ .zdr-oths { .zdr-bj-con { > ul { > li { position: relative; width: 50%; .u-ipt { width: 100% !important; color: #8ea5c3; } input::-webkit-input-placeholder { color: #8ea5c3; } input:-moz-placeholder { color: #8ea5c3; } input::-moz-placeholder { color: #8ea5c3; } input:-ms-input-placeholder { color: #8ea5c3; } .oths-establish { color: #8ea5c3; height: 100%; display: flex; align-items: center; } .time-range { background: url("../images/cqdnk/date.png") no-repeat 96% center; } .dropdown { width: 100%; .dropdown-toggle { width: 100%; color: #8ea5c3 !important; text-align: left; .caret { color: #8ea5c3; float: right; margin-top: 11px; } } } .n-hd-tip { z-index: 3; position: absolute; display: inline-block; right: -27px; top: 7px; width: 38px; height: 20px; &:hover { .n-tip-txt { display: block; } } .n-circle { display: inline-block; margin-left: 18px; width: 20px; height: 20px; border-radius: 20px; background: #ffd584; color: #9f7422; font-weight: bold; text-align: center; line-height: 20px; cursor: pointer; } .n-tip-txt { display: none; position: absolute; left: 50px; top: 0; font-size: 12px; padding: 10px; width: 374px; border-radius: 5px; background: #f7f1e5; &:after { content: ''; width: 0; height: 0; border-top: 5px solid transparent; border-right: 6px solid #f7f1e5; border-bottom: 5px solid transparent; position: absolute; left: -6px; top: 5px; } } &.n-s-tip, &.n-s-tip2 { left: -8px; top: 0; .n-tip-txt { position: absolute; left: 16px; top: 31px; font-size: 12px; padding: 10px; width: 102px; border-radius: 5px; background: #f7f1e5; &:after { content: ''; width: 0; height: 0; border-top: 5px solid transparent; border-right: 6px solid #f7f1e5; border-bottom: 5px solid transparent; position: absolute; left: 11px; top: -8px; transform: rotate(446deg); } } } &.n-s-tip2 { left: -20px; top: 1px; .n-tip-txt { line-height: 17px; text-align: left; width: 122px; } } } .day-show { display: none; position: absolute; z-index: 9999; top: 30px; padding: 15px; width: 425px; border: 1px solid #d6e1e5; box-shadow: 0 6px 12px rgba(0, 0, 0, 0.175); border-radius: 4px; overflow-y: auto; background: #fff; .choose { position: relative; display: block; float: left; margin-right: 10px; margin-bottom: 3px; padding: 0 10px; height: 30px; font-size: 14px; color: #779bb5; line-height: 28px; text-align: left; border: 1px solid #dfe5e7; border-radius: 2px; overflow: hidden; cursor: pointer; &:last-child { margin-right: 0; } &.active { border: 1px solid #85C1EB; } em { float: left; display: block; width: 68px; height: 100%; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; } } input.ichoose { position: relative; float: left; padding: 0 10px; height: 30px; font-size: 14px; color: #779bb5; line-height: 28px; text-align: left; border: 1px solid #dfe5e7; border-radius: 2px; overflow: hidden; // cursor: pointer; width: 23%; margin-right: 8px; &:last-child { margin-right: 0; } &.active { border: 1px solid #85C1EB; } } } .bd { display: none; padding: 10px 0; &.first { display: block; } } .hd { padding-bottom: 15px; border-bottom: 1px solid #d6e1e5; } .li1 { padding-left: 50px; margin-bottom: 5px; } .lf-letter { float: left; width: 10%; font-size: 16px; line-height: 30px; text-align: center; color: #029be5; } .rf-text { float: left; padding-left: 10px; width: 90%; line-height: 30px; text-align: left; span { display: inline-block; margin-right: 20px; margin: 0 1px; margin-right: 1px; color: #779bb5; cursor: pointer; } } &.w100 { width: 100%; } .us { width: 100%; color: #8ea5c3; padding: 8px 10px; height: 78px; border: 1px solid #D6E1E5; } .us::-webkit-input-placeholder { color: #8ea5c3; } .us:-moz-placeholder { color: #8ea5c3; } .us::-moz-placeholder { color: #8ea5c3; } .us:-ms-input-placeholder { color: #8ea5c3; } .invo-all, .key-websit { margin-top: 7px; border: 1px solid #d3dbe3; background-color: #f6f8fb; width: 100%; max-width: 310px; .invo-search { margin-bottom: 14px; input { height: 29px; border: 0; padding-left: 7px; width: 100%; line-height: 29px; border-bottom: 1px solid #d6e6e5; background: url("../images/icon_sea.png") no-repeat 95% center; } } .u-pd { padding-left: 12px; padding-bottom: 15px; height: 273px; } } &.involve-person { label { position: relative; } } &.involve-key { position: relative; justify-content: flex-end; label { position: relative; } .key-websit { border: 1px solid #d3dbe3; background-color: #f6f8fb; margin-top: 7px; width: 100%; max-width: 310px; .hd { border: 0; padding-bottom: 0; border-bottom: 1px solid #d6e1e5; a { width: 33.36%; height: 30px; line-height: 30px; text-align: center; display: inline-block; border-right: 1px solid #d3dbe3; &:nth-of-type(2) { margin-left: -4px; } &:last-child { border-right: 0; margin-left: -4px; } &.active, &:hover { text-align: center; color: white; background-color: #1389d0; } } } .u-pd { height: 244px; } } } } } } .inline-button { text-align: center; margin-top: 32px; padding-right: 0; a { margin-right: 10px; } } .u-zd { position: relative; width: 100%; min-height: 30px; span { position: relative; padding: 4px 10px; margin: 0 0 10px 10px; border: 1px solid #d3dbe3; border-radius: 2px; color: #333; min-width: 60px; text-align: center; display: inline-block; background: #fff; i { position: absolute; right: -5px; top: -5px; width: 14px; height: 14px; line-height: 14px; text-align: center; color: #fff; border-radius: 50%; background: #f56969; display: inline-block; cursor: pointer; } } .input-blue{ width: 100%; background: #fff; border: 1px solid #d3dbe3; height: 28px; line-height: 28px; padding: 0 10px; min-width: 40px; color: #029be5; } .triangle-ds{ display: inline-block; position: absolute; border-top: 6px dashed; border-top: 6px solid #8ea5c3; border-right: 6px solid transparent; border-left: 6px solid transparent; right: 9px; top: 13px; } } .dropdown-menu { min-width: 100%; } } /*重点人添加重点事件 end*/ /*重点事件详情 start*/ .zddx-eventDetails{ .zddx-eventDetails-cont{ background-color: #fff; padding: 0 40px 30px 40px; >ul{ overflow: hidden; padding-top: 10px; margin-bottom: 30px; li{ float: left; width: 50%; height: 32px; line-height: 32px; >span{ display: inline-block; width: 99px; } &.wlist100{ width: 100%; } } li.zlm-download{ div{ margin-right: 40px; } i{ display: inline-block; width: 19px; height:14px; background: url(../images/zlm730_06.png); position: relative; top: 3px; left: 10px; cursor: pointer; &:hover{ background: url(../images/zlm730_03.png); } } } } .relationship-box{ border: 1px solid #D3DBE3; .relationship-title{ height: 50px; line-height: 50px; padding: 0 20px; >h4{ position: relative; line-height: inherit; margin-left: 20px; display: inline-block; &::before{ position: absolute; content: ""; width: 8px; height: 8px; background-color: #029BE5; left: -14px; top: 20px; } } >a{ width: 50px; margin-top: 10px; background-image: url(../images/cqdnk/icon_quanping.png); background-repeat: no-repeat; background-position: center center; } } .relationship-con{ height: 460px; } } } } /*重点事件详情 end*/ /*重点关系图 start*/ .Relation_diagram{ .zddx_nav_box{ .zddx-left{ display: none; } } .Relation_diagram_box{ margin: 15px; background: #fff; .diagram_box_title{ background: #fff; height: 50px; border-bottom: 1px solid #d3dbe3; line-height: 50px; padding: 0 20px; .title-aleft{ display: inline-block; h3{ line-height: 50px; font-weight: bold; color: #029be5; display: inline-block; } } .title-aright{ >a{ .Full_screen{ display: inline-block; width: 20px; height: 20px; background-image: url(../images/cqdnk/icon_quanping.png); background-position: center center; background-repeat: no-repeat; vertical-align: inherit; } } } } .diagram_box_con{ height: 800px; } } } /*重点关系图全屏*/ .Relation_diagram_quan{ padding-left: 20px; padding-right: 20px; .Relation_diagram_quan_box{ background: #fff; position: relative; height: 845px; margin-top: 20px; >a{ position: absolute; right: 30px; top: 30px; background-image: url(../images/cqdnk/shanchu.png); background-position: center center; background-repeat: no-repeat; width: 30px; height: 30px; border: none; z-index: 2; } } } /*重点关系图 end*/ @media screen and (max-width: 1700px){ .zdr-bj-box .zdr-bj-con > ul > li .bj-right .site_detection > li > label input.w350{ width: 365px; margin-left: 40px; margin-top: 10px; } .zddx-group{ .zddx-right-box{ .zddx-group-cont{ padding: 22px 8%; } } } } @media screen and (max-width: 1680px){ .zddx-undertakings .zddx-undertakings-cont .undertakings-tab .tables .td200 > span{ max-width: 180px; } /*.zdr-oths{ .zdr-bj-con > ul { padding: 0 12% 0 10% !important; } }*/ } @media screen and (max-width: 1600px){ .zddx-undertakings .zddx-undertakings-cont .undertakings-tab .tables .td200 > span{ max-width: 140px; } .zddx-left{ width: 220px !important; } .zddx-right{ margin-left: 220px; } .undertakings-tab{ .tables{ .td200{ max-width: 100px; } } } } /*@media screen and (max-width: 1530px){ .zdr-oths{ .zdr-bj-con > ul { padding: 0 4% 0 3%!important; } } }*/ @media screen and (max-width: 1450px){ .zddx-group{ .zddx-right-box{ .zddx-group-cont{ padding: 22px 5%; } } } /*.zdr-bj-box{ .zdr-bj-con{ >ul{ padding: 0 2% 0 2% !important; .ww50{ width: 100% !important; } } } }*/ } @media screen and (max-width: 1300px){ .zddx-left{ width: 200px !important; } .zddx-right{ margin-left: 200px; .input_li{ .layut-input{ width: 110px !important; } } } } @media screen and (max-width: 1320px){ .zddx-undertakings .zddx-undertakings-cont .undertakings-tab .tables .td200 > span{ max-width: 120px; } /*.zdr-oths{ .zdr-bj-con > ul { padding: 0 2% 0 1%!important; } }*/ } /*@media screen and (max-width: 1173px){ .zdr-oths{ .zdr-bj-con > ul { padding: 0 1% 0 0%!important; } } }*/ .zm-triangle1{ width: 0; height: 0; border-top: 9px solid transparent; border-right: 6px solid #4290D4; border-bottom: 9px solid transparent; } .g-zlm-zdzdwb{ .u-b2{ display: inline-block; width: 20px; height:20px; } .u-b2:hover { background: url(../images/u_b2.png) no-repeat center center; } .newweibo-box .new-weibo .list-r { margin-left: 116px; } .new-weibo{ .list-l{ .num{ position: relative; top: -21px; } } } .newweibo-box .weibo-handle-box { right: 6px; } } .g-zlm-zdrfzgg{ .modal-body{ ul{ li{ margin-bottom: 12px; textarea{ vertical-align:top; width: 494px; } span{ display: inline-block; width:284px; text-overflow: ellipsis; overflow: hidden; white-space: nowrap; vertical-align: top; } } } } } /* 上传按钮美化 */ .g-upload-wrap{ position:relative; width:98px; height:30px; .upload-pic{ position: absolute; font-size: 0; width: 100%; height: 100%; outline: 0; opacity: 0; filter: alpha(opacity=0); z-index: 1; cursor: pointer; } .upload-icon{ display: inline-block; width: 98px; height:30px; background: url(../images/zlm731_03.png); } } /*上传头像按钮美化*/ .upload-headPic{ display: inline-block; position:relative; .upload-pic{ position: absolute; font-size: 0; width: 100%; height: 100%; outline: 0; opacity: 0; filter: alpha(opacity=0); z-index: 1; cursor: pointer; } .upload-icon{ display: inline-block; padding: 0 10px; height: 30px; line-height: 30px; background: linear-gradient(to bottom,white 0,#f2f4f8 100%); border: 1px solid #c6d0db; border-radius: 2px; } } /*v3.0版*/ /*公共部分开始*/ .u-b9{ background: url(../images/u_b9.png) no-repeat center center; &:hover{ background: url(../images/u_9.png) no-repeat center center; } } .u-b10{ background: url(../images/u_b10.png) no-repeat center center; &:hover{ background: url(../images/u_10.png) no-repeat center center; } } .zdr-jiankong{ display: inline-block; vertical-align: middle; width: 14px; height: 17px; background: url("../images/v3.0-cqzddx/zdr-jiankong1.png") no-repeat center center; margin-top: -3px; } .zdr-xinxi{ display: inline-block; vertical-align: middle; width: 14px; height: 18px; background: url("../images/v3.0-cqzddx/zdr-xinxi1.png") no-repeat center center; margin-top: -3px; } .zdr-guanzhu{ display: inline-block; vertical-align: middle; width: 16px; height: 18px; background: url("../images/v3.0-cqzddx/zdr-guanzhu1.png") no-repeat center center; margin-top: -3px; } .gzqk-chakan{ display: inline-block; vertical-align: middle; width: 18px !important; height: 19px !important; line-height: normal !important; background: url("../images/v3.0-cqzddx/gzqk-chakan.png") no-repeat center center; margin-top: -10px !important; } .blue-title{ position: relative; padding-left: 10px; font-size: 16px; color: #333333; &::before{ width: 4px; height: 16px; background: #029be5; content: ''; position: absolute; left: 0; top: 4px; } } .blueLetter-title{ position: relative; padding-left: 10px; font-size: 18px; color: #1389d0; font-weight: bold; &::before{ width: 4px; height: 18px; background: #029be5; content: ''; position: absolute; left: 0; top: 4px; } } .mt10{ margin-top: 10px; } .mt15{ margin-top: 15px; } /*问好提示开始*/ .Prompt{ display: inline-block; position: relative; width: 20px; height: 20px; background-color: #FFD584; color: #333333; line-height: 20px; text-align: center; border-radius: 50%; margin-left: 10px; margin-top: 5px; &:hover{ span{ display: block; } } span{ display: none; position: absolute; padding: 5px 8px; background-color: #F7F1E5; text-align: left; z-index: 3; &.Prompt-top{ width: 234px; bottom: 30px; transform: translateX(-47%); &.width380{ width: 380px; } &::after{ content: ''; position: absolute; left: 50%; top: 100%; width: 0; height: 0; border-top: 6px solid #F7F1E5; border-right: 5px solid transparent; border-left: 5px solid transparent; margin-top: -1px; margin-left: -9px; } } &.Prompt-right{ width: 495px; left: 30px; bottom: -67%; &.oneline{ bottom: -20%; } &::after{ content: ''; position: absolute; left: -6px; top: 50%; width: 0; height: 0; border-right: 6px solid #F7F1E5; border-top: 5px solid transparent; border-bottom: 5px solid transparent; margin-top: -3px; } } &.Prompt-left{ width: 180px; left: -190px; bottom: -210%; } } } /*问好提示结束*/ .rollHeight{ overflow: auto; } .rollHeight1{ overflow: auto; } .rollHeight2{ overflow: auto; } .rollHeight3{ overflow: auto; } .rollHeight4{ overflow: auto; } .rollHeight5{ overflow: auto; } .rollHeight6{ overflow: auto; } .rollHeight7{ overflow: auto; } /*文件列表开始*/ .b-fileList{ padding-left: 20px; .down{ display: inline-block; vertical-align: middle; width: 19px; height: 14px; background: url("../images/zlm730_06.png") no-repeat center center; margin-left: 5px; &:hover{ background: url("../images/zlm730_03.png") no-repeat center center; } } } /*文件列表结束*/ .u-changgui{ display: inline-block; vertical-align: middle; width: 19px !important; height: 16px !important; background: url("../images/icon_submit_b.png") no-repeat center center; margin: -9px 5px 0 !important; &:hover{ background: url("../images/icon_submit_y.png") no-repeat center center; } } .u-changgui2{ display: inline-block; vertical-align: middle; width: 19px !important; height: 16px !important; background: url("../images/icon_submit_b.png") no-repeat center center; margin: -9px 5px 0 !important; } .icon-cata{ display: inline-block; vertical-align: middle; width: 15px; height: 13px; background: url("../images/v3.0-cqzddx/icon-cata.png") no-repeat center center; margin-top: -3px; } .icon-pencil{ font-size: 17px; display: inline-block; vertical-align: middle; margin-top: -12px; color: #1389d0; &:hover{ color: #ffa640; } } .gray-btn{ display: inline-block; vertical-align: middle; padding: 0 8px; height: 30px; line-height: 30px; background: -webkit-linear-gradient(top, white 0, #f7f9fc 100%); background: linear-gradient(to bottom, white 0, #f7f9fc 100%); border: 1px solid #d3dbe3; border-radius: 2px; } .u-q2{ width: 18px; height: 18px; line-height: 20px; display: inline-block; color: #029be5; background: url("../images/u_b11.png") no-repeat center center; &:hover{ background: url("../images/u_11.png") no-repeat center center; } } .u-q3{ width: 18px; height: 18px; line-height: 20px; display: inline-block; color: #029be5; background: url(../images/u-q3.png) no-repeat center center; &:hover { background: url(../images/u-q33.png) no-repeat center center; } } .tables-hover tr:hover { background: #93CFF3!important; } .timeControl{ display: inline-block; vertical-align: middle; a{ display: block; width: 15px; height: 15px; } .fa{ display: block; height: 5px; color: #818488; &.active{ color: #019be5; } } .down{ margin-top: -5px; } } /*下拉框*/ .dropdown-toggle{ min-width: 120px; } .dropdown-menu{ min-width: 120px; } /*公共部分结束*/ /*重庆重点对象-重点人-事业人物开始*/ .breadCrumb{ height: 26px; color: #767676; a{ color: #767676; } } .control-nav{ width: 100%; background: white; border: 1px solid #d3dbe3; padding: 30px 20px 0; .con-top{ position: relative; margin-bottom: 30px; min-height: 38px; .name{ position: absolute; left: 0; top: 5px; font-size: 18px; color: #1389d0; font-weight: bold; } } } .co-searchBox{ display: flex; width: 635px; height: 38px; margin: 0 auto; border: 1px solid #029be5; border-radius: 3px; overflow: hidden; .int{ flex: 1; height: 100%; padding: 0 10px; background: #f6f8fb; outline: none; border: none; font-size: 16px; &::placeholder{ color: #7b8fa8; } } .aBtn{ width: 100px; height: 100%; line-height: 36px; text-align: center; background: #029be5; color: white; font-size: 16px; } } .con-navBox{ >ul{ font-size: 0; >li{ display: inline-block; margin-right: 50px; a{ display: block; height: 40px; line-height: 40px; font-size: 16px; color: #8da4c4; padding: 0 2px; } &.active{ a{ color: #1389d0; border-bottom: 2px solid #1389d0; } .zdr-jiankong{ background: url("../images/v3.0-cqzddx/zdr-jiankong2.png") no-repeat center center; } .zdr-xinxi{ background: url("../images/v3.0-cqzddx/zdr-xinxi2.png") no-repeat center center; } .zdr-guanzhu{ background: url("../images/v3.0-cqzddx/zdr-guanzhu2.png") no-repeat center center; } } } } } .control-content{ margin-top: 7px; overflow: auto; border: 1px solid #d3dbe3; } .zddx-right{ height: 100%; } /*重庆重点对象-重点人-事业人物结束*/ /*重庆重点对象-重点人-基本信息开始*/ .basic-content{ width: 100%; margin-top: 7px; background: white; border: 1px solid #d3dbe3; padding: 20px 20px 50px; overflow: auto; .bas-xinxi{ font-size: 0; &>div{ display: inline-block; vertical-align: bottom; margin-right: 20px; } .img{ width: 80px; height: 106px; overflow: hidden; img{ width: 100%; height: 100%; } } .mes{ font-size: 14px; >p{ margin-bottom: 7px; &:last-child{ margin-bottom: 0; } } } } .bas-zuzhi{ .lab{ display: inline-block; vertical-align: middle; } .sp{ margin-right: 10px; display: inline-block; vertical-align: middle; padding: 0 8px; height: 28px; line-height: 28px; background: linear-gradient(to bottom,white 0,#f7f9fc 100%); border: 1px solid #d3dbe3; border-radius: 2px; } } .geren{ color: #767676; } .b-fileList{ padding-left: 20px; .down{ display: inline-block; vertical-align: middle; width: 19px; height: 14px; background: url("../images/zlm730_06.png") no-repeat center center; margin-left: 5px; &:hover{ background: url("../images/zlm730_03.png") no-repeat center center; } } } .wangzhan-table{ text-align: center; th{ text-align: center; font-weight: normal; font-size: 14px; color: #333333; } td{ padding: 5px; .gray-sp{ padding: 3px 8px; display: block; width: 100%; height: 100%; background: #eef1f7; border: 1px solid #d3dbe3; color: #767676; } } .paddingLeft{ padding-left: 35px; } } .bas-qq{ .smallTit{ font-size: 14px; color: #029be5; } .detUl{ margin-top: 5px; font-size: 0; li{ display: inline-block; vertical-align: middle; margin-right: 15px; label{ display: inline-block; vertical-align: middle; font-size: 14px; color: #333333; } span{ display: inline-block; vertical-align: middle; padding: 0 8px; height: 28px; line-height: 28px; min-width: 130px; background: #eef1f7; border: 1px solid #d3dbe3; font-size: 14px; color: #767676; } } } .detail{ margin-top: 5px; span{ color: #767676; } } } } /*重庆重点对象-重点人-基本信息结束*/ /*重庆重点对象-重点人-关注情况开始*/ /*重庆重点对象-重点人-关注情况结束*/ /*重庆重点对象-重点事件详情开始*/ .sj-xiangqing{ display: inline-block; vertical-align: middle; width: 13px; height: 16px; background: url("../images/v3.0-cqzddx/sj-xiangqing1.png") no-repeat center center; margin-top: -3px; } .sj-xinxi{ display: inline-block; vertical-align: middle; width: 15px; height: 15px; background: url("../images/v3.0-cqzddx/sj-xinxi1.png") no-repeat center center; margin-top: -2px; } .detail-navBox{ >ul{ font-size: 0; >li{ display: inline-block; margin-right: 50px; a{ display: block; height: 48px; line-height: 48px; font-size: 16px; color: #8da4c4; padding: 0 2px; } &.active{ a{ color: #1389d0; border-bottom: 2px solid #1389d0; } .sj-xiangqing{ background: url("../images/v3.0-cqzddx/sj-xiangqing2.png") no-repeat center center; } .sj-xinxi{ background: url("../images/v3.0-cqzddx/sj-xinxi2.png") no-repeat center center; } } } } } .detail-rightTit{ .title-aright{ line-height: 48px; .btn{ margin: 0; } } } .bottom-detailCont{ margin-top: 7px; background: white; padding: 20px; border: 1px solid #d3dbe3; } .detail-table{ width: 80%; border: 1px solid #d3dbe3; tr{ td{ padding: 15px 12px; border-bottom: 1px solid #d3dbe3; .p2{ margin-top: 3px; color: #767676; } } } .b-fileList{ margin-top: 3px; } } .middle-control{ >ul{ height: 50px; padding: 10px 20px 0; >li{ float: left; margin-right: 10px; &:last-child{ margin-right: 0; } &.input_li{ .layut-input{ width: 250px; } } } } } .bottom-mesCont{ margin-top: 7px; background: white; border: 1px solid #d3dbe3; .zt-ft{ height: 50px; padding: 10px 20px 30px; } } .message-table{ width: 100%; border-top: 1px solid #d3dbe3; border-bottom: 1px solid #d3dbe3; tr{ th{ background: #eef1f7; padding: 12px 15px; font-weight: normal; text-align: center; border-bottom: 1px solid #d3dbe3; } td{ padding: 12px 15px; text-align: center; border-bottom: 1px solid #d3dbe3; border-right: 1px solid #d3dbe3; &.text-left{ text-align: left; } } } } /*重庆重点对象-重点事件详情结束*/ /*重庆重点对象-重点人-编辑开始*/ .with235{ width: 235px !important; } .zdr-bj-box{ .new-editCont{ background: #fff; height: 795px; padding-top: 15px; border: 1px solid #d3dbe3; border-top: none; .tit{ padding: 0 20px; } .g-zlm-phone{ padding-top: 15px; .lxfs:last-child{ .i1{ display: block; } } .lxfs{ margin-bottom: 40px; .addNum{ position: absolute; left: 130px; top: 31px; font-size: 12px; color: #8ea5c3; } .btnbox{ position: absolute; right: 4px; top: 5px; width: 42px; i{ display: inline-block; width: 18px; height: 18px; cursor: pointer; } .i1{ background: url(../images/zlm732_03.png); background-repeat: no-repeat; display: none; } .i2{ background: url(../images/icon_del.png); background-repeat: no-repeat; // display: none; } } .bj-right{ display: flex; .num86{ width: 95px; font-size: 0; i{ display: inline-block; vertical-align: middle; color: #767676; font-size: 14px; } .shuzi { height: 30px; line-height: 28px; width: 80px; background: #eef1f7; text-align: center; border: 1px solid #D6E1E5; border-radius: 2px; } .heng{ width: 15px; text-align: center; } } .u-ipt{ flex: 1; } } } } >ul{ width: 80%; >li.fjsc{ position: relative; height: 100px; .xs{ i{ display: inline-block; width: 14px; height:14px; background: url(../images/zlm732_07.png); cursor: pointer; position:relative; top: 3px; margin-left: 20px; } } .xs1{ position:absolute; top: 53px; left: 127px; } .xs2{ position:absolute; top: 83px; left: 127px; } } >li{ margin-bottom: 28px; display: flex; width: 100%; padding-right: 50px; position: relative; .btn{ margin: 0; } &.mbottom12{ margin-bottom: 12px; } &.gkjb{ .bj-right{ label{ margin-right: 40px; cursor: pointer; &:last-child{ margin-right: 0; } } .iradio_flat-blue{ display: inline-block; vertical-align: middle; margin-top: -2px; } } } &.ww50{ width: 50%; } .bj-left{ width: 120px; margin-right:10px; line-height: 30px; text-align: right; } .bj-right{ .l_flex; .u-ipt{ display: inline-block; width: 100%; height: 30px; line-height: 30px; padding-left: 10px; } .imgBox{ display: inline-block; vertical-align: bottom; width: 80px; height: 80px; overflow: hidden; img{ display: inline-block; width: 100%; height: 100%; } } .uploadBox{ margin-left: 10px; display: inline-block; } .touxiang-p{ margin-top: 5px; color: #8ea5c3; font-size: 12px; } .Prompt{ display: inline-block; position: relative; width: 20px; height: 20px; background-color: #FFD584; color: #333333; line-height: 20px; text-align: center; border-radius: 50%; margin-left: 10px; margin-top: 5px; &:hover{ span{ display: block; } } span{ display: none; position: absolute; padding: 5px 8px; background-color: #F7F1E5; text-align: left; z-index: 3; &.Prompt-top{ width: 234px; bottom: 30px; transform: translateX(-47%); &.width380{ width: 380px; } &::after{ content: ''; position: absolute; left: -6px; top: 50%; width: 0; height: 0; border-top: 6px solid #F7F1E5; border-right: 5px solid transparent; border-left: 5px solid transparent; margin-top: -1px; margin-left: -9px; } } &.Prompt-right{ width: 495px; left: 30px; bottom: -67%; &.oneline{ bottom: -20%; } &::after{ content: ''; position: absolute; left: -6px; top: 50%; width: 0; height: 0; border-right: 6px solid #F7F1E5; border-top: 5px solid transparent; border-bottom: 5px solid transparent; margin-top: -3px; } } &.Prompt-left{ width: 180px; left: -190px; bottom: -210%; } } } .option-ul{ display: inline-block; margin-left: 15px; li{ position: relative; margin-right: 10px; padding: 4px 10px; border: 1px solid #d3dbe3; border-radius: 2px; color: #333; min-width: 60px; text-align: center; display: inline-block; background: #fff; i{ position: absolute; right: -5px; top: -5px; width: 14px; height: 14px; line-height: 14px; text-align: center; color: #fff; border-radius: 50%; background: #f56969; display: inline-block; cursor: pointer; } } } .bj_add{ width: 60px; height: 30px; background-color: #1389D0; background-image: url(../images/cqdnk/icon_bjadd.png); background-repeat: no-repeat; // background-size: contain; background-position: center center; } .site_detection{ >li{ margin-bottom: 10px; font-size: 0; &:last-child{ margin-bottom: 0; } >div,>label{ margin-right: 0px; display: inline-block; vertical-align: middle; font-size: 14px; } >label{ input{ padding-left: 10px; } .w190{ width: 180px; } .w440{ width: 440px; } .w310{ width: 310px; } } .del-input{ position: relative; i{ position: absolute; right: -5px; top: -5px; width: 14px; height: 14px; line-height: 14px; text-align: center; color: #fff; border-radius: 50%; background: #f56969; display: inline-block; cursor: pointer; } } .grayBg{ .dropdown-toggle{ background: #eef1f7; border-right: none !important; .caret{ color: #8ea5c3; } } } .wangzhan{ display: inline-block; vertical-align: middle; min-width: 80px; background: #eef1f7; height: 30px; line-height: 30px; border-top: 1px solid #D6E1E5; border-bottom: 1px solid #D6E1E5; padding: 0 10px; text-align: center; } } } } } } input{ border: 1px solid #D6E1E5; border-radius: 2px; &::placeholder{ color: #8ea5c3; } } .tArea{ color: #333333; &::placeholder{ color: #8ea5c3; } } } } @media screen and (max-width: 1650px){ .zdr-bj-box { .new-editCont { >ul{ width: 90%; } } } } @media screen and (max-width: 1350px){ .zdr-bj-box { .new-editCont { >ul{ width: 98%; } } } } /*重庆重点对象-重点人-编辑结束*/ /*重庆重点对象-关注情况编辑开始*/ .zdr-bj-box{ .attention-cont{ border: 1px solid #d3dbe3; border-top: none; padding-top: 0; .navWrap{ padding: 0 20px; .detail-navBox{ border-bottom: 1px dashed #d3dbe3; } } >ul{ width: 80%; padding: 25px 0 0; >li{ margin-bottom: 28px; padding-right: 50px; .invo-all{ background: white; max-width: 325px; .u-pd { overflow: auto !important; } } } } .g-upload-wrap{ .uploadFile-icon{ display: inline-block; width: 98px; height: 30px; background: url(../images/v3.0-cqzddx/icon-uploadFile.png) no-repeat -1px -1px; } } .gray-tip{ padding-top: 7px; font-size: 12px; color: #8ea5c3; } } } .uploadFile-icon{ display: inline-block; width: 98px; height: 30px; background: url(../images/v3.0-cqzddx/icon-uploadFile.png) no-repeat -1px -1px; } @media screen and (max-width: 1650px){ .zdr-bj-box { .attention-cont { >ul{ width: 90%; } } } } @media screen and (max-width: 1350px){ .zdr-bj-box { .attention-cont { >ul{ width: 98%; } } } } /*事件信息*/ .attention-edit2{ margin-top: 0; border-top: none; .navWrap{ padding: 0 20px; .detail-navBox{ border-bottom: 1px dashed #d3dbe3; } } .blueA{ color: #1389d0; } .att-dele{ margin-left: 10px; } .att-sure{ display: none; } } .borderBot{ border: none; border-bottom: 1px solid #d3dbe3; } /*重庆重点对象-关注情况编辑结束*/ /*重庆重点对象-重点人-监控情况-微博开始*/ /* 数据可视图文beta1.0 start*/ .tu_con{ display: inline-block; width: 12px; height: 12px; background: url('../images/js/tu_tengxun.png') no-repeat center center; vertical-align: middle; margin-right: 2px; } .data-list{ background-color: #fff; border-bottom: 1px solid #d3dbe3; border-top: 1px solid #d3dbe3; >li{ border-top: 1px solid #d3dbe3; padding: 18px 20px 22px; position: relative; &:hover{ .handle-box{ display: block; } } &:first-child{ border-top: none; } .data-list-right{ margin-left: 32px; } .data-list-right-top{ height: 24px; .flex(); } .data-list-right-top-l{ display: inline-block; } .data-list-right-top-md{ font-size: 16px; line-height: 22px; display: inline-block; font-weight: bold; .txt(); .l_flex(); &:hover{ color:#333; } } .data-list-right-con{ margin-top: 5px; .flex(); .data-list-img{ width: 100px; height: 60px; margin-right: 10px; } .data-list-main{ .l_flex(); } .data-list-main-cont{ display: inline-block; color:#767676; line-height: 16px; height: 32px; margin: 7px 0; .txtmore(2); } .data-list-main-foot{ color:#8ea5c3; font-size: 12px; .data-source{ color:#029be5; position: relative; i{ margin-right: 5px; &.fa-weibo{ color:#f65757; } &.fa-weixin{ color:#01b90d; } } &:hover{ .monitor-box{ display: inline-block; } } } .conform-btn,.before-link{ color:#8ea5c3; } .conform-btn{ margin-left: 10px; } } } } } .tag-label{ display: inline-block; border-radius:1px; line-height: 16px; font-size: 12px; padding:0 3px; vertical-align: text-bottom; margin-right: 5px; } .tag-red{ color:#f65757; border: 1px solid #f65757; } .tag-orange{ color:#ffa640; border: 1px solid #ffa640; } .handle-box{ display: none; .handle-list{ border: none; li{ float: left; padding: 0 5px; border: none; } } } .before-link{ text-decoration:underline; } .btn-blue{ display: inline-block; background-color: #fff; width: 65px; line-height: 22px; text-align: center; font-size: 12px; border: 1px solid #d6e1e5; border-radius:1px; &:hover,&.active{ color:#fff; background-color: #029be5; border-color: #029be5; } } .monitor-box{ display: none; position: absolute; top: -35px; left: 10px; padding-bottom: 6px; .monitor{ display: inline-block; color:#fff; background-color: rgba(0, 0, 0, 0.75); border-radius:3px; line-height: 28px; padding:0 10px; &:after{ content: ''; width: 0; height: 0; border-left: 6px solid transparent; border-right: 6px solid transparent; border-top: 6px solid rgba(0, 0, 0, 0.75); position: absolute; bottom: 0px; left: 50%; -webkit-transform: translateX(-50%); -moz-transform: translateX(-50%); -ms-transform: translateX(-50%); -o-transform: translateX(-50%); transform: translateX(-50%); } &.monitor-be{ width: 80px; } &.monitor-af{ width: 56px; } } } .keyword-list{ display: inline-block; vertical-align: middle; margin-left: 20px; li{ float: left; margin-left: 5px; &:first-child{ margin-left: 0; } a{ display: inline-block; color:#ffa640; border: 1px solid #ffa640; border-radius:15px; line-height: 14px; padding:0 5px; background-color: rgba(255,166,64,0.1); } } } /* 数据可视图文beta1.0 end*/ /*重庆重点对象-重点人-监控情况-微博结束*/ /*重庆重点对象-重点阵地-微博开始*/ .u-b2 { background: url(../images/u_b2.png) no-repeat center center; } /*重庆重点对象-重点阵地-微博结束*/ /*重庆重点对象-重点阵地-目录管理开始*/ .catalog-top{ .gray-btn{ position: absolute; right: 0; top: 4px; } } .addTeam{ width: 100%; height: 50px; line-height: 50px; background: #e5eef6; border: 1px solid #d3dbe3; border-top: none; text-align: center; } .addTeam-btn{ color: #029be5; font-weight: bold; .add{ margin-right: 8px; display: inline-block; vertical-align: middle; font-size: 28px; } } .g-zlm-zdrfzgg{ .modal-body{ ul{ li{ margin-bottom: 12px; textarea{ vertical-align:top; width: 494px; } span{ display: inline-block; width:284px; text-overflow: ellipsis; overflow: hidden; white-space: nowrap; vertical-align: top; } } } } } .addModal{ .modal-content{ width: 600px; } .addUl{ padding: 20px 20px 0; li{ display: flex; margin-bottom: 20px; .sp{ width: 85px; } .int{ flex: 1; display: inline-block; vertical-align: middle; height: 30px; line-height: 30px; border: 1px solid #d6e1e5; padding: 0 12px; &::placeholder{ color: #8ea5c3; } } .tArea{ flex: 1; height: 60px; border: 1px solid #d6e1e5; padding: 2px 12px; &::placeholder{ color: #8ea5c3; } } } } } /*重庆重点对象-重点阵地-目录管理结束*/ /*重庆重点对象-重点阵地-添加分组开始*/ .addTeam-nav{ .con-top{ margin-bottom: 15px; } } .s-int{ display: inline-block; vertical-align: middle; width: 395px; height: 30px; line-height: 30px; border: 1px solid #D6E1E5; border-radius: 2px; padding: 0 10px; &::placeholder{ color: #8ea5c3; } } .addTeam-ul{ li{ float: left; margin-right: 25px; &:last-child{ margin-right: 0; } } } .addTeam-content{ padding: 20px; .singleTree{ margin-top: 4px; } .g-nvolving-content{ flex: inherit; width: 400px; } } .blueColor-title{ font-size: 16px; color: #1389d0; } /*标签目录开始*/ .g-font-blue { color: #1389d0; } .modal-dialog.g-area{ width: 720px; margin: 10% auto 0 auto; } .g-source-dialog{ display: block; margin-top: 10px; } .g-nvolving-c{ width: 100%; display: flex; } .g-nvolving-content{ flex: 1; height: 300px; border-radius: 2px; border: 1px solid #d6e1e5; padding: 10px; overflow-y: scroll; &::-webkit-scrollbar { display: none; } } .mr10{ margin-right: 10px; } .mb10{ margin-bottom: 10px; } .g-involving-tag{ display: inline-block; border-radius: 2px; border: 1px solid #d3dbe3; margin-right: 12px; margin-bottom: 10px; position: relative; padding: 3px 18px; cursor: pointer; color: #333; .g-icon-del-tag{ display: inline-block; position: absolute; cursor: pointer; background: url(../images/icon-del-tag.png) no-repeat; width: 14px; height: 14px; right: -7px; top: -7px; } } .borderRight{ border-right: none; } .treeWrap{ margin-top: 5px; width: 80%; .jstree-default > .jstree-container-ul > .jstree-node{ padding: 0; } } /*标签目录结束*/ .ad-footBtn{ width: 80%; margin-top: 40px; text-align: center; font-size: 0; } .ad-blueBtn{ display: inline-block; vertical-align: middle; background: #1389d0; padding: 0 30px; color: #fff; height: 30px; line-height: 30px; margin: 0 5px; border-radius: 4px; font-size: 16px; &:hover{ color: white; } } /*重庆重点对象-重点阵地-添加分组结束*/ /*重庆重点对象-重点阵地-微信开始*/ .wx-grayTip{ position: relative; display: inline-block; vertical-align: middle; margin-left: 4px; margin-top: -2px; .icon-tip{ display: inline-block; width: 15px; height: 15px; text-align: center; line-height: 15px; border: 1px solid #353636; border-radius: 50%; color: #797b7f; font-size: 12px; cursor: pointer; } .tip-cont{ position: absolute; left: 50%; margin-left: -130px; top: -35px; width: 260px; padding: 5px 8px; background: #eaf0f2; font-weight: normal; color: #556482; font-size: 12px; display: none; &:before{ content: ''; position: absolute; left: 50%; margin-left: -5px; bottom: -5px; width: 0; height: 0; border-top: 6px solid #eaf0f2; border-left: 5px solid transparent; border-right: 5px solid transparent; } } &:hover{ .tip-cont{ display: block; } } } .relative-cont{ padding-top: 50px; .fixed-tit{ position: fixed; z-index: 2; top: 70px; background: white; } } /*重庆重点对象-重点阵地-微信结束*/ /*重庆重点对象-重点事件-分组管理开始*/ .zddx-group { .zddx-right-box{ .teamManage-cont{ padding: 0; .group-tab{ td{ padding: 0 10px; .icon-pencil{ vertical-align: middle; margin-top: -10px; } } .icon-wrap{ a{ margin: 0 5px; } } } } } } /*重庆重点对象-重点事件-分组管理结束*/ /*重庆重点对象-重点关系图-配置开始*/ .gxw-right{ width: 100%; height: 100%; padding: 12px 20px; } .big-blueTit{ height: 50px; border: 1px solid #d3dbe3; line-height: 50px; padding: 0 20px; background: #fff; span{ font-size: 18px; color: #1389d0; font-weight: bold; } } .peizhi-cont{ width: 100%; height: 100%; background: white; } .pz-cont{ margin-top: 7px; background: white; border: 1px solid #d3dbe3; padding: 20px; .contWrap{ display: inline-block; } } .co-chooseWrap{ padding-left: 10px; .singleTree{ margin-top: 20px; float: left; width: 400px; margin-right: 60px; .treeTit{ margin-bottom: 5px; font-size: 16px; color: #1389d0; font-weight: bold; } .g-nvolving-content{ height: 260px; } } } .inline-button{ a{ display: inline-block; width: 100px; height: 28px; line-height: 28px; background: #d3dbe3; border-radius: 3px; margin-right: 5px; } } /*重庆重点对象-重点关系图-配置结束*/ /*重庆重点对象-重点关系图开始*/ @greenColor:#73c8c9; @yellowColor:#f8ac59; @blueColor:#029be5; .seeBtn{ display: inline-block; height: 20px; padding: 0 8px; line-height: 20px; border: 1px solid #029be5; border-radius: 2px; color: #029be5; font-size: 12px; } .gxw-peizhi{ display: inline-block; vertical-align: middle; width: 17px; height: 16px; background: url("../images/v3.0-cqzddx/gxw-peizhi.png") no-repeat center center; } .gxw-tab{ position: relative; width: 100%; height: 120px; background: white; border: 1px solid #d3dbe3; padding: 0 55px 0 0; .tit{ position: absolute; left: 20px; top: 15px; font-size: 18px; color: #1389d0; font-weight: bold; } .peizhi-btn{ position: absolute; right: 15px; top: 15px; display: inline-block; height: 40px; line-height: 40px; padding: 0 20px; border-radius: 20px; background: white; border: 1px solid #d3dbe3; .gxw-peizhi{ margin: -2px 5px 0 0; } &:hover{ .gxw-peizhi{ background: url("../images/v3.0-cqzddx/gxw-peizhi-blue.png") no-repeat center center; } } } } .tab-zdr{ display: inline-block; vertical-align: middle; width: 30px; height: 30px; border-radius: 50%; background: rgba(0,0,0,.1) url("../images/v3.0-cqzddx/tab-zdr.png") no-repeat center -2px; } .tab-zdzd{ display: inline-block; vertical-align: middle; width: 30px; height: 30px; border-radius: 50%; background: rgba(0,0,0,.1) url("../images/v3.0-cqzddx/tab-zdzd.png") no-repeat center center; } .tab-zdsj{ display: inline-block; vertical-align: middle; width: 30px; height: 30px; border-radius: 50%; background: rgba(0,0,0,.1) url("../images/v3.0-cqzddx/tab-zdsj.png") no-repeat center center; } .ta-tabUl{ position: relative; width: 830px; height: 95px; margin: 0 auto; padding-top: 20px; text-align: center; font-size: 0; li{ position: absolute; left: 0; bottom: 0; &:last-child{ margin-right: 0; } a{ display: block; width: 260px; height: 60px; line-height: 60px; text-align: center; color: white; font-size: 18px; background: #029be5; border-radius: 30px; i{ margin-top: -2px; margin-right: 2px; } } &.zdzd-li{ a{ background: #f8ac59; } } &.zdsj-li{ a{ background: #73c8c9; } } &.active{ left: 280px; z-index: 10; transition: all 0.7s ease-in-out; animation: rotateBg 0.7s; a{ height: 75px; line-height: 75px; box-shadow: 0 0 25px rgba(0,0,0,.25); border-radius: 40px; transition: all 0.7s ease-in-out; } } &.left{ left: 0; } &.right{ left: 560px; } } } .gxw-cont{ width: 100%; border: 1px solid #d3dbe3; border-top: none; background: white; } .zdr-cont{ width: 100%; height: 100%; display: flex; } .people-left{ position: relative; width: 200px; height: 100%; border-right: 1px solid #d3dbe3; .list-wrap{ height: 100%; padding-bottom: 60px; } } .search-input { position: relative; margin: 20px; input { padding-right: 25px; background: #f5f7fb; } a { position: absolute; right: 5px; top: 0; font-size: 18px; color: @line-color; } } .peo-list{ ul{ li{ padding: 10px 5px 10px 20px; border-top: 1px solid #edf1f7; .txt(); &:hover{ background: #ccebfa; } .img{ margin-right: 3px; display: inline-block; vertical-align: middle; width: 40px; height: 40px; border-radius: 50%; overflow: hidden; img{ width: 100%; height: 100%; } } } } } .peo-page{ position: absolute; left: 0; bottom: 0; border-top: 1px solid #d3dbe3; width: 100%; height: 60px; background: white; padding-top: 20px; text-align: center; ul{ font-size: 0; li{ display: inline-block; vertical-align: middle; margin-right: 5px; width: 20px; height: 20px; border: 1px solid transparent; border-radius: 50%; line-height: 18px; text-align: center; font-size: 14px; color: #767676; cursor: pointer; &:last-child{ margin-right: 0; } &:hover,&.active{ color: #029be5; border: 1px solid #029be5; &.prev,&.next{ color: #029be5; border: 1px solid transparent; } } } } } .people-middle{ position: relative; flex: 1; height: 100%; padding-bottom: 30px; .nameWrap{ width: 540px; margin: 40px auto 0; text-align: center; .singleName{ display: inline-block; vertical-align: middle; height: 35px; line-height: 35px; min-width: 155px; padding: 0 15px; background: #029be5; border-radius: 20px; color: white; margin-right: 10px; margin-top: 14px; } } } /*动画开始*/ /*@keyframes mymove1 { 0% {transform: scale(0.5);} 20% {transform: scale(1);} 50% {transform: scale(1.3);} 100% {transform: scale(1);} } @keyframes mymove2 { 0% {transform: scale(0.5);} 10% {transform: scale(1);} 30% {transform: scale(1);} 70% {transform: scale(1.3);} 100% {transform: scale(1);} } @keyframes mymove3 { 0% {transform: scale(0.5);} 22% {transform: scale(1);} 44% {transform: scale(1);} 77% {transform: scale(1.3);} 100% {transform: scale(1);} }*/ @keyframes mymove1 { 0% {transform: scale(0.5);} 20% {transform: scale(1);} 50% {transform: scale(1.1);} 100% {transform: scale(0.8);} } @keyframes mymove2 { 0% {transform: scale(0.5);} 10% {transform: scale(1);} 30% {transform: scale(1);} 70% {transform: scale(1.1);} 100% {transform: scale(0.8);} } @keyframes mymove3 { 0% {transform: scale(0.5);} 22% {transform: scale(1);} 44% {transform: scale(1);} 77% {transform: scale(1.1);} 100% {transform: scale(0.8);} } @keyframes rotateBg { 0% {transform: rotate(0deg);} 100% {transform: rotate(360deg);} } /*动画结束*/ .flowerWrap{ position: relative; width: 321px; height: 321px; margin: 0 auto; .flower{ position: relative; width: 321px; height: 321px; line-height: 321px; margin: 15% auto 0; text-align: center; .big-flowerBg{ position: absolute; left: 0; top: 0; width: 321px; height: 321px; &.zdr-flower{ background: url("../images/v3.0-cqzddx/blue-oval.png") no-repeat center center; } &.zdzd-flower{ background: url("../images/v3.0-cqzddx/yellow-oval.png") no-repeat center center; } &.zdsj-flower{ background: url("../images/v3.0-cqzddx/green-oval.png") no-repeat center center; } &.rotateBg{ animation: rotateBg 2s; } } } .flower-bg{ position: absolute; z-index: 10; left: 77px; top: 83px; width: 169px; height: 161px; &.blue-flower{ background: url("../images/v3.0-cqzddx/blue-flower.png") no-repeat center center; } &.yellow-flower{ background: url("../images/v3.0-cqzddx/yellow-flower.png") no-repeat center center; } &.green-flower{ background: url("../images/v3.0-cqzddx/green-flower.png") no-repeat center center; } } .picWrap{ position: relative; width: 111px; height: 111px; border-radius: 50%; margin: 0 auto; margin-top: 23px; overflow: hidden; img{ width: 100%; } .name{ position: absolute; left: 0; bottom: 0; display: block; width: 100%; background: rgba(0,0,0,.55); padding: 5px 15px 6px; line-height: 15px; text-align: center; color: white; font-size: 12px; } } .water-circle1{ width: 205px; height: 205px; line-height: 205px; display: inline-block; vertical-align: middle; border-radius: 50%; margin: 0 auto; &.blue-circle{ background: rgba(130,206,242,.15); .water-circle2{ background: rgba(130,206,242,.25); } .water-circle3{ background: rgba(130,206,242,.35); } } &.yellow-circle{ background: rgba(251,214,173,.18); .water-circle2{ background: rgba(251,214,173,.28); } .water-circle3{ background: rgba(251,214,173,.38); } } &.green-circle{ background: rgba(185,228,228,.18); .water-circle2{ background: rgba(185,228,228,.28); } .water-circle3{ background: rgba(185,228,228,.38); } } &.animate{ animation: 3s mymove1 cubic-bezier(.25, .46, .45, .94) infinite; .water-circle2{ animation: 3.5s mymove2 cubic-bezier(.25, .46, .45, .94) infinite; } .water-circle3{ animation: 4s mymove3 cubic-bezier(.25, .46, .45, .94) infinite; } } } .water-circle2{ width: 185px; height: 185px; line-height: 185px; display: inline-block; vertical-align: middle; border-radius: 50%; margin: 0 auto; } .water-circle3{ width: 165px; height: 165px; display: inline-block; vertical-align: middle; border-radius: 50%; margin: 0 auto; } .flowerLeft{ position: absolute; left: -321px; top: -10px; .listUl{ li{ margin-top: 15px; &:first-child{ margin-top: 0; } &:nth-child(1){ padding-left: 52px; } &:nth-child(2){ padding-left: 18px; } &:nth-child(4){ padding-left: 18px; } &:nth-child(5){ padding-left: 52px; } .team{ width: 280px; height: 20px; font-size: 12px; padding: 0 12px; .txt(); } .circle{ margin: -13px 4px 0 0; position: relative; display: inline-block; vertical-align: middle; width: 15px; height: 15px; border-radius: 50%; background: white; border: 1px dashed #73c8c9; &:before{ position: absolute; left: 3px; top: 3px; width: 7px; height: 7px; background: #73c8c9; border-radius: 50%; content: ''; } } .con{ width: 280px; height: 32px; line-height: 32px; border-radius: 15px; padding: 0 12px; background: #73c8c9; color: white; .txt(); &.pad-left{ padding: 0 12px 0 3px; } } .seeMore{ color: #73c8c9; } &.seeLi{ padding-left: 40px; text-align: center; } } } &.greenStyle{ .listUl{ li{ .circle{ border: 1px dashed @greenColor; &:before{ background: @greenColor; } } .con{ background: @greenColor; } .seeMore{ color: @greenColor; } } } } &.yellowStyle{ .listUl{ li{ .circle{ border: 1px dashed @yellowColor; &:before{ background: @yellowColor; } } .con{ background: @yellowColor; } .seeMore{ color: @yellowColor; } } } } &.blueStyle{ .listUl{ li{ .circle{ border: 1px dashed @blueColor; &:before{ background: @blueColor; } } .con{ background: @blueColor; } .seeMore{ color: @blueColor; } } } } } .flowerRight{ position: absolute; right: -321px; top: -10px; .listUl{ li{ margin-top: 15px; padding-top: 16px; &:first-child{ margin-top: 0; } &:last-child{ padding-top: 0; } &:nth-child(2){ padding-left: 38px; } &:nth-child(3){ padding-left: 52px; } &:nth-child(4){ padding-left: 38px; } .team{ width: 280px; height: 20px; font-size: 12px; padding: 0 12px; .txt(); } .con{ width: 280px; height: 36px; line-height: 36px; border-radius: 18px; padding: 0 12px 0 4px; color: white; background: #73c8c9; .txt(); } .seeMore{ color: #73c8c9; } &.seeLi{ padding-right: 40px; text-align: center; } .opCircle{ display: inline-block; vertical-align: middle; width: 28px; height: 28px; border-radius: 50%; background: rgba(0,0,0,.1); text-align: center; line-height: 28px; color: white; margin: -2px 8px 0 0; } } } &.greenStyle{ .listUl{ li{ .con{ background: @greenColor; } .seeMore{ color: @greenColor; } } } } &.yellowStyle{ .listUl{ li{ .con{ background: @yellowColor; } .seeMore{ color: @yellowColor; } } } } &.blueStyle{ .listUl{ li{ .con{ background: @blueColor; } .seeMore{ color: @blueColor; } } } } } .zdzd-flowerRight{ position: absolute; right: -321px; top: -10px; .listUl{ li{ margin-top: 15px; &:first-child{ margin-top: 0; } &:nth-child(2){ padding-left: 38px; } &:nth-child(3){ padding-left: 52px; } &:nth-child(4){ padding-left: 38px; } .team{ width: 280px; height: 20px; font-size: 12px; padding: 0 12px; .txt(); } .circle{ margin: -13px 4px 0 0; position: relative; display: inline-block; vertical-align: middle; width: 15px; height: 15px; border-radius: 50%; background: white; border: 1px dashed #73c8c9; &:before{ position: absolute; left: 3px; top: 3px; width: 7px; height: 7px; background: #73c8c9; border-radius: 50%; content: ''; } } .con{ width: 280px; height: 32px; line-height: 32px; border-radius: 15px; padding: 0 12px 0 3px; background: #73c8c9; color: white; .txt() } .seeMore{ color: #73c8c9; } &.seeLi{ padding-right: 40px; text-align: center; } } } &.greenStyle{ .listUl{ li{ .circle{ border: 1px dashed @greenColor; &:before{ background: @greenColor; } } .con{ background: @greenColor; } .seeMore{ color: @greenColor; } } } } &.yellowStyle{ .listUl{ li{ .circle{ border: 1px dashed @yellowColor; &:before{ background: @yellowColor; } } .con{ background: @yellowColor; } .seeMore{ color: @yellowColor; } } } } &.blueStyle{ .listUl{ li{ .circle{ border: 1px dashed @blueColor; &:before{ background: @blueColor; } } .con{ background: @blueColor; } .seeMore{ color: @blueColor; } } } } } } .spreadBtn{ position: absolute; left: -15px; top: 50%; margin-top: -45px; display: inline-block; width: 15px; height: 90px; line-height: 90px; background: #029be5; border-radius: 10px 0 0 10px; text-align: center; color: white; .triangle{ display: inline-block; vertical-align: middle; font-weight: bold; font-size: 18px; } &:hover,&:focus{ color: white; } &.hideCont{ .triangle{ transform: rotate(180deg); } } } .people-right{ position: relative; width: 260px; height: 100%; border-left: 1px solid #d3dbe3; padding: 15px; background: white; .scrollWrap{ width: 100%; height: 100%; } .messageUl{ padding-bottom: 18px; border-bottom: 1px solid #d3dbe3; li{ margin-top: 6px; font-size: 0; &.headLi{ margin-bottom: 15px; } &:first-child{ margin-top: 0; } } .touxiang{ display: inline-block; vertical-align: bottom; width: 80px; height: 106px; overflow: hidden; img{ width: 100%; height: 100%; } } .xingming{ display: inline-block; vertical-align: bottom; margin-left: 15px; .name{ font-size: 18px; } .seeBtn{ display: block; margin-top: 4px; } } .span1{ width: 70px; display: inline-block; vertical-align: top; font-size: 14px; color: #333333; } .span2{ width: 155px; display: inline-block; vertical-align: top; font-size: 14px; color: #767676; &.span-block{ display: block; width: 100%; } } } .describe{ padding-top: 10px; color: #767676; } } .colorNum{ color: @greenColor; } .team-wrap{ padding: 0 10px; .pop-span{ display: inline-block; vertical-align: middle; height: 35px; line-height: 35px; padding: 0 10px; min-width: 100px; border-radius: 20px; text-align: center; color: white; background: @greenColor; margin: 10px 0 0 5px; } } .pagBtn{ margin-top: 20px; text-align: center; padding-bottom: 30px; a{ margin-right: 5px; &:last-child{ margin-right: 0; } } } .greenPop{ .colorNum{ color: @greenColor; } .team-wrap{ .pop-span{ background: @greenColor; } } } .yellowPop{ .colorNum{ color: @yellowColor; } .team-wrap{ .pop-span{ background: @yellowColor; } } } .bluePop{ .colorNum{ color: @blueColor; } .team-wrap{ .pop-span{ background: @blueColor; } } } .seeP{ text-align: right; } .grayTable{ margin-top: 15px; width: 100%; border: 1px solid #d3dbe3; tr{ border-bottom: 1px solid #d3dbe3; &:last-child{ border-bottom: none; } td{ padding: 8px; background: #eef1f7; border-right: 1px solid #d3dbe3; &:last-child{ border-right: 0; } } } } .xiaotou{ display: inline-block; vertical-align: middle; width: 28px; height: 28px; border-radius: 50%; overflow: hidden; margin-top: -3px; img{ width: 100%; } } #zdzd-possy{ .team-wrap{ .pop-span{ padding: 0 10px 0 4px; } .xiaotou{ margin-top: -2px; } } } /*媒体查询开始*/ @media screen and (max-width: 1920px) { .flowerWrap{ .flower{ margin: 19% auto 0; } .flowerLeft{ position: absolute; left: -370px; top: -20px; .listUl{ li{ .team{ width: 325px; height: 20px; } .con{ width: 325px; height: 40px; line-height: 40px; border-radius: 20px; } } } } .flowerRight{ position: absolute; right: -370px; top: -20px; .listUl{ li{ .con{ width: 325px; height: 44px; line-height: 44px; border-radius: 22px; } .opCircle{ width: 34px; height: 34px; line-height: 34px; } } } } .zdzd-flowerRight{ position: absolute; right: -370px; top: -20px; .listUl{ li{ .team{ width: 325px; height: 20px; } .con{ width: 325px; height: 40px; line-height: 40px; border-radius: 20px; .xiaotou { width: 32px; height: 32px; border-radius: 50%; overflow: hidden; margin-top: -3px; } } } } } } .people-middle{ .nameWrap { width: 540px; margin: 70px auto 0; text-align: center; } } } /*@media screen and (max-width: 1670px) { .flowerWrap{ .flower{ margin: 19% auto 0; } .flowerLeft{ position: absolute; left: -325px; top: -20px; .listUl{ li{ .team{ width: 280px; height: 20px; } .con{ width: 280px; height: 40px; line-height: 40px; border-radius: 20px; } } } } .flowerRight{ position: absolute; right: -325px; top: -20px; .listUl{ li{ .con{ width: 280px; height: 44px; line-height: 44px; border-radius: 22px; } .opCircle{ width: 34px; height: 34px; line-height: 34px; } } } } .zdzd-flowerRight{ position: absolute; right: -325px; top: -20px; .listUl{ li{ .team{ width: 280px; height: 20px; } .con{ width: 280px; height: 40px; line-height: 40px; border-radius: 20px; .xiaotou { width: 32px; height: 32px; border-radius: 50%; overflow: hidden; margin-top: -3px; } } } } } } .people-middle{ .nameWrap { width: 540px; margin: 70px auto 0; text-align: center; } } }*/ @media screen and (max-width: 1670px) { .flowerWrap{ .flower{ margin: 15% auto 0; } .flowerLeft{ position: absolute; left: -321px; top: -10px; .listUl{ li{ .team{ width: 280px; height: 20px; } .con{ width: 280px; height: 32px; line-height: 32px; border-radius: 15px; } } } } .flowerRight{ position: absolute; right: -321px; top: -10px; .listUl{ li{ .con{ width: 280px; height: 36px; line-height: 36px; border-radius: 18px; } .opCircle{ width: 28px; height: 28px; line-height: 28px; } } } } .zdzd-flowerRight{ position: absolute; right: -321px; top: -10px; .listUl{ li{ .team{ width: 280px; height: 20px; } .con{ width: 280px; height: 32px; line-height: 32px; border-radius: 15px; .xiaotou { width: 28px; height: 28px; border-radius: 50%; overflow: hidden; margin-top: -3px; } } } } } } .people-middle{ .nameWrap { width: 540px; margin: 40px auto 0; text-align: center; } } } /*媒体查询结束*/ /*重庆重点对象-重点关系图结束*/ <file_sep>/app/less/base/base.less //初始化 @import "./conn.less"; body{ //font-family:"Microsoft YaHei",Arial,SimSun, Tahoma, Helvetica; font-size: 14px;line-height: 1.6; color:#333;background:@bg-color url(../images/bg.png) no-repeat center center; background-size: cover;} html, body, div, table, ul, li,ol, dl, dd, dt, a, img ,label,p,h1,h2,h3,h4,h5,h6,span{ margin:0; padding:0;box-sizing:border-box; -moz-box-sizing:border-box;} body{ position: relative; } input{ margin:0; padding:0; } ul,ol{ list-style: none; } strong{ font-weight: normal; } em,i{ font-style: normal; } img{ max-width: 100%; display: block; } textarea{ resize:none; } form{ margin:0; } button{ outline:none!important; &:focus{ outline:none!important; } } a { color:@color; text-decoration:none; outline:none; cursor:pointer; } a:hover{ color:@f-blue; text-decoration:none; outline:none; } a:focus{ outline:none; text-decoration:none; } .wrap{ width: 100%; margin:0 auto; } .btn{ &:hover{ color:@bg-blue; border-color:@bg-blue; } } h3{ font-size: 18px; } h4{ font-size: 14px; } h5{ font-size: 14px; } .fz24{ font-size: 24px; } .fz20{ font-size: 20px; } .fz18{ font-size: 18px; } .fz16{ font-size: 16px; } .fz14{ font-size: 14px; } @media screen and (max-width: 1300px) { body{ font-size: 12px; } h3{ font-size: 16px; } h4{ font-size: 12px; } h5{ font-size: 12px; } .fz24{ font-size: 20px; } .fz20{ font-size: 18px; } .fz18{ font-size: 16px; } .fz16{ font-size: 14px; } .fz14{ font-size: 12px; } .btn{ font-size: 12px!important; } .form-control{ font-size: 12px!important; } }<file_sep>/app/less/ui-paging-container.less /* .ui-paging-container{ color: #333; ul{ overflow: hidden; text-align: center; list-style: none; } li{ list-style: none; display: inline-block; vertical-align: middle; padding: 3px 6px; margin-left: 5px; color: #666; &.ui-pager{ border: 1px solid #d3dbe3; border-radius: 1px; font-size: 12px; color: #333; cursor: pointer; padding: 5px 10px; &:hover{ background: #35afea; border: 1px solid #35afea; border-radius: 1px; color:#fff; } } &.ui-pager-disabled{ background-color: #f5f5f5; cursor: default; color: #999; &:hover{ background-color: #f5f5f5; cursor: default; border: 1px solid #d3dbe3; color: #999; } } &.focus{ background: #35afea; border: 1px solid #35afea; border-radius: 1px; color:#fff; } } }*/ <file_sep>/app/less/other/newweibo.less .newweibo-box,.modules-weibo4-list{ .wb-list{ >ul{ >li{ position: relative; padding: 0!important; &:hover{ background: inherit!important; .news-details{ background: #eef1f7!important; } } .news-details{ margin-left: 0; margin-top: 5px; padding: 5px 15px 0 10px; } } } } .weibo-handle-box{ position: absolute; top: 0; right: 0; margin-top: 12px; .a-interest.on { i { color: #ffa640; } } >li{ float: left; border-left: 1px solid @line-color; padding:0 15px; line-height: 20px; &:hover{ background: inherit!important; } >a{ color: #8ea5c3; font-size: 12px; &:hover{ color: @blue; } } i{ color: @blue; font-size: 20px; vertical-align: sub; margin-right: 5px; } } .more-btn{ position: relative; font-size: 14px; i{ padding-left: 5px; } } .more-box{ position: absolute; top: 35px; right: 0; min-width: 100px; border: 1px solid @line-color; color: #333; text-align: center; padding: 6px 0; z-index: 1; height: auto; display: none; &:before { content: ""; width: 0; height: 0; border-left: 9px solid transparent; border-right: 9px solid transparent; border-bottom: 10px solid @line-color; position: absolute; top: -11px; left: 50%; transform: translateX(-50%); } &:after { content: ""; width: 0; height: 0; border-left: 8px solid transparent; border-right: 8px solid transparent; border-bottom: 10px solid #fff; position: absolute; top: -10px; left: 50%; transform: translateX(-50%); } li{ line-height: 31px; padding: 0; a{ display: block; &:hover{ background: #eef1f7; color: @blue; } } } } } .new-weibo{ padding: 20px 15px 0px 12px; .weibo-tit .gril { padding-right: 500px; a{ color: #333; } } .weibo-p{ line-height: 18px; display: inline-block; span{ i{ margin-right: 5px; } } } .list-l{ div{ top: -20px; } .user{ display: inline-block; } } .list-r{ margin-left: 90px; p{ line-height: 18px; margin-bottom: 10px; .weibo-p{ display: inline; } .long-essay-title{ margin-left: 5px; i{ margin-right: 5px; } &:hover{ color: #fb8d0a; } } } } } .news-details{ position: relative; .weibo-tit{ line-height: 20px; font-weight: bold; a{ color: @blue; } } .weibo-p{ font-size: 12px; } .long-essay-title{ font-size: 12px; } } .long-essay-box{ background: #d4d8de; padding:5px 15px 5px 10px; font-size: 12px; .weibo-tit{ padding-top: 0px; font-weight: bold; line-height: 20px; a{ color: #333; } } .weibo-p{ max-height:54px; display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 3; overflow: hidden; } } .pic{ li{ float: left; width: 60px; height: 60px; padding: 0; &+li{ margin-left: 10px; } &:hover{ background: inherit!important; } img{ width: 100%; height: 100%; } } } .fens{ margin-top: 5px; font-size: 12px; padding-bottom: 10px; color: #333!important; span{ line-height: 22px; margin-right: 15px; } ul{ display: inline-block; li{ float: left; line-height: 12px; padding: 0; &+li{ border-left: 1px solid @line-color; } &:hover{ background: inherit!important; } a{ display: block; padding:0 15px; i{ vertical-align: top; margin-right: 5px; } &:hover,&.active{ color: @blue; .icon-zf{ background: url('../images/wb-zf-b.png') no-repeat center center; } .icon-pl{ background: url('../images/wb-pl-b.png') no-repeat center center; } .icon-dz{ background: url('../images/wb-dz-b.png') no-repeat center center; } } } } } } .zt-ft{ border-top: 1px solid @line-color; } } .total-num{ color: #8ea5c3; vertical-align: sub; } .detailed-list{ background: #f6f8fb; border-top: 1px solid @line-color; font-size: 12px; position: relative; display: none; .arrow-before{ content: ""; width: 0; height: 0; border-left: 8px solid transparent; border-right: 8px solid transparent; border-bottom: 10px solid #f6f8fb; position: absolute; top: -10px; left: 230px; } .arrow-after{ content: ""; width: 0; height: 0; border-left: 9px solid transparent; border-right: 9px solid transparent; border-bottom: 10px solid @line-color; position: absolute; top: -11px; left: 229px; } .list-box{ padding-left: 43px; >li{ padding: 20px 15px 0px; &+li{ border-top: 1px solid @line-color; } &:hover{ background: inherit!important; } } .detailed-list-left{ width: 35px; height: 35px; float: left; } .detailed-list-right{ padding-left: 50px; p{ line-height: 14px; } .pic{ margin-top: 8px; } } } .loading-more{ display: block; text-align: center; color: @blue; border-top: 1px solid @line-color; line-height: 28px; } } .dz-list{ ul{ padding: 7px 37px; li{ background: #fff; border: 1px solid #eef1f7; border-radius: 1px; float: left; width: 130px; margin: 7px!important; padding: 0!important; &:hover{ background: #fff!important; } a{ padding: 6px 5px; display: -webkit-box; /* 老版本语法: Safari, iOS, Android browser, older WebKit browsers. */ display: -moz-box; /* 老版本语法: Firefox (buggy) */ display: -ms-flexbox; /* 混合版本语法: IE 10 */ display: -webkit-flex; /* 新版本语法: Chrome 21+ */ display: flex; } i{ display: inline-block; width: 34px; height: 34px; border-radius:50%; img{ border-radius:50%; } } span{ -webkit-box-flex: 1; /* OLD - iOS 6-, Safari 3.1-6 */ -moz-box-flex: 1; /* OLD - Firefox 19- */ -webkit-flex: 1; /* Chrome */ -ms-flex: 1; /* IE 10 */ flex: 1; display: inline-block; padding-left: 10px; line-height: 34px; .txt; } } } } .xbjs-right-middle .wb-list .list-l div{ top: 20px; } .newztfx .date-wrapper .time-ser > div{ margin-top: 1px; margin-bottom: 1px; } .newztfx .date-wrapper .time-ser .dropdown .u-btn{ float: left; } @media screen and (max-width: 1400px) { .newweibo .weibo-handle-box .more-btn{ font-size: 12px; } .newztfx .date-wrapper{ padding:10px; } .date-wrapper .time-ser .layout-data{ margin-right: 0!important; } } @media screen and (max-width: 1300px) { .time-range1{ width: 150px!important; padding: 0 4px!important; } } @media screen and (max-width: 1200px) { .zddx { .tab-item{ margin-bottom: 0; } .layut-input{ padding: 0; } .sort-item{ .dropdown,.u-btn,.dropdown-menu{ float: left; } } } .total-num{ margin-left: 2px; } } .orange{ color: #fb8d0a; } .icon-unfun{ display: inline-block; background: url('../images/icon-unfun.png') no-repeat center center; width: 19px; height: 18px; } .icon-yujing{ display: inline-block; background: url('../images/icon_yujing.png') no-repeat center center; width: 18px; height: 17px; } .icon-blue-arr{ display: inline-block; background: url('../images/icon_blue_arr.png') no-repeat center center; width: 18px; height: 17px; } .icon-zlm717_05{ display: inline-block; background: url('../images/zlm717_05.png') no-repeat center center; width: 18px; height: 17px; } .icon-sb{ display: inline-block; background: url('../images/u_b9.png') no-repeat center center; width: 18px; height: 18px; } .icon-xf{ display: inline-block; background: url('../images/u_b10.png') no-repeat center center; width: 18px; height: 18px; } .icon-fx{ display: inline-block; background: url('../images/icon-analysis.png') no-repeat center center; width: 18px; height: 18px; } .icon-weixin{ display: inline-block; background: url('../images/icon-weixin.png') no-repeat center center; width: 18px; height: 18px; } .icon-qq{ display: inline-block; background: url('../images/icon-qq.png') no-repeat center center; width: 18px; height: 18px; } .icon-xinlang{ display: inline-block; background: url('../images/icon-xinlang.png') no-repeat center center; width: 18px; height: 18px; } .icon-kongjian{ display: inline-block; background: url('../images/icon-kongjian.png') no-repeat center center; width: 18px; height: 18px; } .icon-kz{ display: inline-block; background: url('../images/u_b1.png') no-repeat center center; width: 18px; height: 18px; } .icon-tz{ display: inline-block; background: url('../images/u_b4.png') no-repeat center center; width: 18px; height: 18px; } .icon-sc{ display: inline-block; background: url('../images/u_b5.png') no-repeat center center; width: 18px; height: 18px; } .icon-zf{ display: inline-block; background: url('../images/wb-zf.png') no-repeat center center; width: 14px; height: 12px; } .icon-pl{ display: inline-block; background: url('../images/wb-pl.png') no-repeat center center; width: 14px; height: 12px; } .icon-dz{ display: inline-block; background: url('../images/wb-dz.png') no-repeat center center; width: 14px; height: 12px; } .icon-bdzzl{ display: inline-block; background: url('../images/u_bdzzl_b.png') no-repeat center center; width: 18px; height: 18px; }<file_sep>/app/less/jquery.paging.less @charset "utf-8"; .ui-paging-container { color: #333; font-size: 14px; -moz-user-select: none; ul { /* overflow: hidden;*/ text-align: center; list-style: none; li{ list-style: none; display: inline-block; vertical-align: middle; padding: 3px 10px; margin-left: 5px; color: #666; font-size: 14px; //普通页码样式 &.ui-pager { cursor: pointer; color: #333; background: #fff; box-shadow: 1px 0 4px #a8bbc7; } &.focus,&.ui-pager:hover{ background: #03acef; color: #FFFFFF; } //...样式 &.ui-paging-ellipse { border: none; } //页码不可点击时状态 &.ui-pager-disabled,&.ui-pager-disabled:hover{ background: #f5f5f5; cursor: default; color: #999; } &.ui-pager-disabled:hover{ border: 0; } //条数总数 &.data-count{ color: #333; } //下拉条数 &.ui-paging-toolbar { padding: 0; margin-left: 10px; select { display: inline-block; vertical-align: middle; padding: 3px 10px 7px; border: 1px solid #d2dae2; background: #fff; /*去掉默认的下拉三角*/ /* appearance:none; -moz-appearance:none; -webkit-appearance:none;*/ option { font-size: 14px; color: #444; } } //快速翻页 span { display: inline-block; vertical-align: middle; } input.inp-gofast { padding: 0 4px; border: 1px solid #ddd; text-align: center; width: 60px; height: 30px; border-radius: 2px; margin: 0 0 0 5px; display: inline-block; vertical-align: middle; } } //确认 .btn-dogo { display: inline-block; vertical-align: middle; margin-left: 5px; border: 1px solid #ddd; padding: 4px 12px; border-radius: 2px; background: #fff; cursor: pointer; color: #666; } //下拉 .dropdown-menu{ >li{ padding: 0; margin-left: 0; display: block; } } } } } <file_sep>/app/templates/header.ejs <div class="header"> <div class="nav"> <ul class="clearfix"> <li class="<%= local.qj?'active':'' %>"> <a href="#">全局分析<i class="fa fa-caret-down "></i></a> <ul> <li class="<%= local.qjfx?'active':'' %>"><a href="index.html">全局分析</a></li> <li class="<%= local.shyq?'active':'' %>"><a href="涉华舆情.html">涉华舆情</a></li> <li class="<%= local.gnyq?'active':'' %>"><a href="国内舆情.html">国内舆情</a></li> <li class="<%= local.bdyq?'active':'' %>"><a href="本地舆情.html">本地舆情</a></li> </ul> </li> <li class="<%= local.gz?'active':'' %>"> <a href="#">关注点<i class="fa fa-caret-down "></i></a> <ul> <li class="<%= local.oldgz?'active':'' %>"><a href="关注点0.html">关注点</a></li> <li class="<%= local.newgz?'active':'' %>"><a href="新版关注点.html">新版关注点</a></li> <li class="<%= local.newgz?'active':'' %>"><a href="关注点-无锡.html">关注点-无锡</a></li> <li class="<%= local.newgz?'active':'' %>"><a href="浙江首页.html">关注点-浙江</a></li> </ul> </li> <li class="<%= local.rm?'active':'' %>"><a href="热点排行.html">热敏</a></li> <li class="<%= local.zd?'active':'' %>"> <a href="#">重点监控<i class="fa fa-caret-down "></i></a> <ul> <li class="<%= local.zdjk?'active':'' %>"><a href="重点监控.html">重点监控</a></li> <li class="<%= local.zdr?'active':'' %>"><a href="重点人.html">重点人浅色导航</a></li> </ul> </li> <li class="<%= local.yqjk?'active':'' %>"> <a href="#">舆情分析<i class="fa fa-caret-down "></i></a> <ul> <li class="<%= local.xwcbfx?'active':'' %>"><a href="舆情分析-新闻传播分析.html">新闻传播分析</a></li> </ul> </li> <li class="<%= local.yqjk?'active':'' %>"> <a href="#">舆情简报<i class="fa fa-caret-down "></i></a> <ul> <li class="<%= local.sck?'active':'' %>"><a href="素材库.html">素材库</a></li> <li class="<%= local.jbk?'active':'' %>"><a href="简报库.html">简报库</a></li> <li class="<%= local.mbgl?'active':'' %>"><a href="模板管理.html">模板管理</a></li> <li class="<%= local.zdymb?'active':'' %>"><a href="自定义模板.html">自定义模板</a></li> <li class="<%= local.cjmb?'active':'' %>"><a href="创建简报.html">创建简报</a></li> <li class="<%= local.cjmb?'active':'' %>"><a href="模板预览.html">模板预览</a></li> </ul> </li> <li class="<%= local.xc?'active':'' %>"><a href="巡查.html">巡查</a></li> <li class="<%= local.zddx?'active':'' %>"> <a href="#">重点对象<i class="fa fa-caret-down "></i></a> <ul> <li class="<%= local.zddxwz?'active':'' %>"><a href="重点对象-网站.html">网站</a></li> <li class="<%= local.zddxwb?'active':'' %>"><a href="重点对象-微博.html">微博</a></li> <li class="<%= local.newzddxwb?'active':'' %>"><a href="重点对象-微博0.html">新微博</a></li> <li class="<%= local.zddxwx?'active':'' %>"><a href="重点对象-微信.html">微信</a></li> <li class="<%= local.zddxxc?'active':'' %>"><a href="重点对象-巡查.html">巡查</a></li> <li class="<%= local.nzddxwz?'active':'' %>"><a href="重点对象4.0-网站.html">重点对象4.0-网站</a></li> </ul> </li> <li class="<%= local.zddx?'active':'' %>"> <a href="#">重点对象4.0<i class="fa fa-caret-down "></i></a> <ul> <li class="<%= local.zddxwb?'active':'' %>"><a href="重点对象4.0-首页.html">网站</a></li> <li class="<%= local.newzddxwb?'active':'' %>"><a href="重点对象4.0-首页.html">微博</a></li> <li class="<%= local.zddxwx?'active':'' %>"><a href="重点对象4.0-首页.html">公众号</a></li> </ul> </li> <li class="<%= local.yj?'active':'' %>"> <a href="###">预警<i class="fa fa-caret-down"></i></a> <ul> <li class="<%= local.yj?'active':'' %>"><a href="预警.html">预警</a></li> <li class="<%= local.yjzy?'active':'' %>"><a href="预警主页.html">预警2.1</a></li> <li class="<%= local.grxx?'active':'' %>"><a href="个人信息2.1.html">个人信息</a></li> <li><a href="预警范围管理.html">预警范围管理</a></li> <li><a href="预警-有害信息配置页.html">有害信息配置</a></li> <li><a href="预警-热点排行配置页.html">热敏排行配置</a></li> </ul> </li> <li class="<%= local.jw?'active':'' %>"> <a href="#">境外浏览<i class="fa fa-caret-down "></i></a> <ul> <li class="<%= local.oldjw?'active':'' %>"><a href="境外浏览.html">境外浏览</a></li> <li class="<%= local.newjw?'active':'' %>"><a href="新版境外浏览.html">新版境外浏览</a></li> </ul> </li> <li class="<%= local.yx?'active':'' %>"><a href="影响力分析.html">影响力分析</a></li> <li class="<%= local.al?'active':'' %>"> <a href="#">专题分析<i class="fa fa-caret-down "></i></a> <ul> <li class="<%= local.n15?'active':'' %>"><a href="案例-案例概况.html">专题old</a></li> <li class="<%= local.ztfx?'active':'' %>"><a href="专题分析.html">专题分析</a></li> <li class="<%= local.newztfx?'active':'' %>"><a href="新版专题分析.html">新版专题分析</a></li> <li class="<%= local.newztfxbg?'active':'' %>"><a href="新版专题分析报告.html">新版专题分析报告</a></li> <li class="<%= local.ksfx?'active':'' %>"><a href="快速分析.html">快速分析</a></li> <li class="<%= local.ztfxv4?'active':'' %>"><a href="专题分析4.0.html">快速分析4.0</a></li> <li class="<%= local.ztfxv4?'active':'' %>"><a href="专题分析-山西.html">专题分析-山西</a></li> <li class="<%= local.ztfxv4?'active':'' %>"><a href="专题分析4.1.html">专题分析4.1</a></li> </ul> </li> <li class="<%= local.js?'active':'' %>"> <a href="#">检索<i class="fa fa-caret-down "></i></a> <ul> <li class="<%= local.xbjs?'active':'' %>"><a href="新版检索-本地检索-微博博主.html">新版检索2</a></li> <li class="<%= local.n15?'active':'' %>"><a href="检索.html">检索old</a></li> <li class="<%= local.ztfx?'active':'' %>"><a href="检索8.html">检索</a></li> <li class="<%= local.ztfx?'active':'' %>"><a href="检索new.html">检索new</a></li> <li class="<%= local.xbjs?'active':'' %>"><a href="新版检索.html">检索3.0</a></li> <li class="<%= local.xbjsn2?'active':'' %>"><a href="检索4.0.html">检索4.0</a></li> <li class="<%= local.xbjsn3?'active':'' %>"><a href="检索4.1.html">检索4.1</a></li> <li class="<%= local.xbjsn3?'active':'' %>"><a href="中萱检索-元搜索-微博博主.html">中萱检索</a></li> </ul> </li> <li class="<%= local.ztjk?'active':'' %>"> <a href="#">专题监控<i class="fa fa-caret-down "></i></a> <ul> <li class="<%= local.oldztjk?'active':'' %>"><a href="专题监控.html">专题监控</a></li> <li class="<%= local.newztjk?'active':'' %>"><a href="新版专题监控.html">专题监控3.0</a></li> <li class="<%= local.newztjk?'active':'' %>"><a href="新版专题监控-中部导航.html">新版专题监控-中部导航</a></li> <li class="<%= local.ztjkv4?'active':'' %>"><a href="专题监控4.0.html">专题监控4.0</a></li> <li class="<%= local.ztjkv4?'active':'' %>"><a href="专题监控-无锡.html">专题监控-无锡</a></li> </ul> </li> <li class="<%= local.yhxx?'active':'' %>"> <a href="#">有害信息<i class="fa fa-caret-down "></i></a> <ul> <li class="<%= local.n15?'active':'' %>"><a href="有害信息.html">有害信息</a></li> <li class="<%= local.ztjk?'active':'' %>"><a href="有害信息v1.2.html">有害信息v1.2</a></li> </ul> </li> <li class="<%= local.flck?'active':'' %>"> <a href="#">分类查看<i class="fa fa-caret-down "></i></a> <ul> <li class="<%= local.n15?'active':'' %>"><a href="分类查看.html">分类查看1</a></li> <li class="<%= local.ztjk?'active':'' %>"><a href="#">分类查看2</a></li> </ul> </li> <li class="<%= local.sbxf?'active':'' %>"><a href="上报下发.html">上报下发</a></li> <li class="<%= local.glpt?'active':'' %>"><a href="X-收到的指令.html">X管理平台</a></li> <li class="<%= local.qwrd?'active':'' %>"> <a href="javascript:;">全网热点 <i class="fa fa-caret-down "></i></a> <ul> <li class="<%= local.n15?'active':'' %>"><a href="全网热点.html">全网热点</a></li> <li class="<%= local.ztjk?'active':'' %>"><a href="全网热点-新版.html">全网热点2.0</a></li> </ul> </li> <li class="<%= local.sjgj?'active':'' %>"><a href="数据工具.html">数据工具</a></li> <li class="<%= local.list?'active':'' %>"><a href="新闻微博列表.html">新闻微博列表</a></li> <li class="<%= local.nfxbg?'active':'' %>"> <a href="javascript:;">分析报告 <i class="fa fa-caret-down "></i></a> <ul> <li class="<%= local.nbzfx?'active':'' %>"><a href="舆情分析-微博博主分析.html">博主分析</a></li> <li class="<%= local.nwbcbfx?'active':'' %>"><a href="舆情分析-微博传播分析.html">微博传播分析</a></li> <li class="<%= local.ngzhfx?'active':'' %>"><a href="舆情分析-微信公众号分析.html">微信公众号分析</a></li> <li class="<%= local.nwxwzfx?'active':'' %>"><a href="微信文章分析.html">微信文章分析</a></li> <li class="<%= local.zhcbfx?'active':'' %>"><a href="综合传播分析.html">综合传播分析</a></li> </ul> </li> <li class="<%= local.ycts?'active':'' %>"> <a href="javascript:;">宜昌推送 <i class="fa fa-caret-down "></i></a> <ul> <li class="<%= local.ycsy?'active':'' %>"><a href="宜昌推送-首页.html">首页</a></li> <li class="<%= local.ycxx?'active':'' %>"><a href="宜昌推送-推送信息库.html">推送信息库</a></li> </ul> </li> <li class="more"><a href="#"><span></span></a></li> </ul> </div> <div class="logo"> <h1> <span class="logo-btn pull-left"></span> <a href="index.html" class="pull-left"></a> </h1> </div> <div class="set"> <div class="search"> <input type="text" placeholder="搜索"> <span class="search-btn"><i class="fa fa-search"></i></span> </div> <div><a href="消息提醒.html"><i class="fa fa-bell"></i></a></div> <div><a href="系统属地.html"><i class="fa fa-cog"></i></a></div> <div class="user"> <a class="user-name" href="javascript:;">第一个用户</a> <a href="javascript:;"><i class="fa fa-caret-down"></i></a> <div class="user-box bgw"> <ul class="user-box-list"> <li> <a href="个人信息.html"><i class="fa fa-user"></i>个人信息</a> </li> <li> <a href="login.html"><i class="fa fa-sign-out"></i>退出登录</a> </li> </ul> </div> </div> </div> </div> <div class="nav2"> <ul class="clearfix"> </ul> </div> <file_sep>/app/js/table.js $(window).on('load resize',function(){ $(".z-tree").niceScroll({ cursorcolor: "#a3c2cb", cursorwidth:"0", cursorborder:"none", }); $('input').iCheck({ checkboxClass: 'icheckbox_flat-blue', radioClass: 'iradio_flat-blue', increaseArea: '20%' }); var leftNavWidth = $('.leftnvvbar2').width(); $('.leftnvvbar2').css('left',-leftNavWidth+'px'); }); $(document).ready(function(e) { // $(".ic_img").on('click',function(){ // var strSrc = $(this).attr("src"); // if(strSrc.indexOf("f")!=-1) // { // console.log(1); // $(this).attr("src","../images/icon_on.png"); // $(this).parent().next('.checkbtn').show(); // } // else // { // console.log(2); // $(this).attr("src","../images/icon_off.png"); // $(this).parent().next('.checkbtn').hide(); // } // }); }); $('.checkout').click(function(){ $('.gjxx').slideToggle(400); }); $('.sech-gj').click(function(){ $('.senior').slideDown(); }); $('.sen-go a').click(function(){ $('.senior').slideUp(); }); $('.real-btn').on('click',function() { $('.Real-hot').stop().animate({'right':0},300); }); // $('.Real-hot').on('mouseleave',function() { // $(this).stop().animate({'right':'-300px'},300); // }); $('.time-list-tit').click(function(){ $(this).siblings(".er-list").slideToggle(); }); $('.leftbar-go').on('click',function() { var selfWidth = $(this).width(); var bgImage = $(this).css('backgroundImage'); var thatBgImage = bgImage.replace('right','left'); $('.leftnvvbar2').stop().animate({'left':0},300); $('.pads').css("padding-left",selfWidth); $(this).css('backgroundImage',thatBgImage); }); $('.newzt-left-v4 .btn-trapezoid').on('click',function() { var selfWidth = $(this).width(); $('.newzt-left-v4').stop().animate({'left':0},300); $('.btn-trapezoid.hide-bar').hide(); }); upcaret(); function upcaret(){ $('.border-r').on('click',function(){ if($(this).children().hasClass('upcaret')){ $(this).find('.upcaret').addClass('caret').removeClass('upcaret'); } else{ $(this).find('.caret').addClass('upcaret').removeClass('caret'); } }); } hoverLi(); function hoverLi(){ $('.innerLi').on('mouseenter',function(){ $(this).find('.innerBox').css("display","block"); $(this).find('.exband').css("display","block"); }); } leaveLi(); function leaveLi(){ $('.innerLi').on('mouseleave',function(){ $(this).find('.innerBox').css("display","none"); $(this).find('.exband').css("display","none"); }); } $('.leftnvvbar2').on('mouseleave',function() { var selfWidth = $(this).width(); var leftbarGo = $(this).find('.leftbar-go'), bgImage = leftbarGo.css('backgroundImage'); var thatBgImage = bgImage.replace('left','right'); $(this).stop().animate({'left':-selfWidth+'px'},300); $('.pads').css("padding-left",0); leftbarGo.css('backgroundImage',thatBgImage); }); $('.newzt-left-v4').on('mouseleave',function() { var selfWidth = $(this).width(); $(this).stop().animate({'left':-selfWidth+'px'},300); $(this).find('.btn-trapezoid.hide-bar').show(); }); catalogue(); function catalogue(){ $('.anli-navbar').on('click', '.catalogue', function() { $(this).parents('.anli-navbar').animate({'right':0}, 300); }); $('.anli-navbar').on('mouseleave',function() { $(this).stop().animate({'right':'-160px'},300); }); } // 案例演变中间线条高度 anliLine(); function anliLine(){ var liLenght = $('.anliyanbian>li').length; $('.anlibox').append('<i class="vertical-line"></i>'); $('.vertical-line').css('height',138*liLenght-80); } $(".plus-add").click(function(){ $(".ly-tc").show(); }); $(".ly-tc .btn").click(function(){ $(".ly-tc").hide(); }); $(".mulu-list .mulu-list-tit").click(function(){ var Parent = $(this).parent(); if(Parent.is('.active')){ Parent.removeClass("active"); }else{ Parent.addClass("active").siblings().removeClass("active"); } }); $(".fa-filter").click(function(){ $(".ml-js").slideToggle(); }); /* 左边导航检索 */ navser(); function navser(){ $('.leftnvvbar2').on('click', '.navser', function(event) { var layutInput = $(this).siblings('.layut-input'); if(layutInput.is(':hidden')){ layutInput.show(); }else{ layutInput.hide(); } event.stopPropagation(); }); } /*表格高度*/ tableh(); function tableh(){ var winh=$(window).height(); $('.table-n').css('height',winh-300+'px'); } <file_sep>/app/less/other/newoutside.less @import "../base/conn.less"; /* 境外网站 start*/ .submang-top{ margin-bottom: 10px; p{ display: inline-block; } .title-tip{ display: inline-block; position: relative; .circle-answer{ width: 18px; height: 18px; line-height: 18px; cursor: pointer; } span{ position: absolute; top: 0px; left: 35px; background: #fedfa5; border-radius: 3px; margin-left: 10px; font-weight: normal; line-height: 28px; padding: 2px 10px; z-index: 2; display: inline-block; width: 400px; display: none; &:after { content: ''; width: 0; height: 0; border-top: 5px solid transparent; border-right: 10px solid #f7dfa5; border-bottom: 5px solid transparent; position: absolute; left: -7px; top: 7px; display: block; } } } } .submang-main{ width: 100%; border: 1px solid #ddd; padding: 18px 15px; p{ label{ margin-right: 25px; margin-left: 0; &:last-child{ margin: 0; } } } } @media screen and (max-width:1300px){ .submang-top{ .title-tip{ span{ line-height: 25px; } } } } /* ========================================================================== */ .tab-item{ height: 30px; line-height: 30px; border-radius: 3px; overflow: hidden; margin-bottom: 10px; display: inline-block; a{ position: relative; float: left; padding:0 20px; background: @hui; display: block; color:#333; border-right: 1px solid #ccc; &:last-child{ border-right: none; } // &:after { // content: ''; // position: absolute; // right:0px; // top:5px; // height: 20px; // width: 2px; // background: @green; // display: block; // } &:hover, &.active{ color:#fff; background:@green; } } } .new-tool{ position: relative; .njw-tip{ display: none; position: absolute; left: -438px; top: 0; width: 422px; border-radius: 3px; margin-right: 10px; line-height: 30px; padding: 0 10px; background: #fedfa5; &:after { content: ''; width: 0; height: 0; border-top: 6px solid transparent; border-left: 10px solid #fedfa5; border-bottom: 6px solid transparent; position: absolute; right: -9px; top: 8px; display: block; } } .circle-answer{ margin-right: 20px; margin-left: 0; } } @media (max-width: 1250px) { .new-tool{ .njw-tip{ left: -382px; width: 366px; } } } .njw-btn{ min-width: 60px; height: 30px; line-height: 28px; padding: 0 10px; background-image: -webkit-linear-gradient(top, #FFFFFF 0%, #e9edf2 100%); background-image: linear-gradient(-180deg, #FFFFFF 0%, #e9edf2 100%); border: 1px solid #d3dbe3; border-radius: 3px; text-align: center; display: inline-block; color:#333; &+.njw-btn{ margin-left: 20px; } } .njw-top{ line-height: 30px; padding: 10px 20px; .tab-item{ margin-right: 50px; margin-bottom: 0; } .n-fil-box{ line-height: 30px; } .layut-input{ display: inline-block; margin-left: 20px; margin-bottom: 0; padding-bottom: 0; } .form-control,.dropdown-toggle{ border-radius:3px; color:#333; } input::-webkit-input-placeholder { /* WebKit browsers */ color: #8ea5c3; } input:-moz-placeholder { /* Mozilla Firefox 4 to 18 */ color: #8ea5c3; } input::-moz-placeholder { /* Mozilla Firefox 19+ */ color: #8ea5c3; } input:-ms-input-placeholder { /* Internet Explorer 10+ */ color: #8ea5c3; } } .njw-tables{ position: relative; table{ width: 100%; border: 1px solid #d3dbe3; } thead{ th{ text-align: center; background: #cfd5de; } .njw-th-title{ padding: 15px 50px; height: 45px; text-align: left; } } tbody{ tr{ border-bottom: 2px solid #d3dbe3; } th,td{ line-height: 43px; } th{ text-align: center; background: #fff; border-bottom: 1px solid #d3dbe3; border-right:2px solid #d3dbe3; } td{ padding: 0 0 0 20px; background: url(../images/table_bg.png) left 1px; } } .njw-ul{ li{ float: left; min-width: 165px; margin:0 10px; .t-avatar{ display: inline-block; width: 18px; height: 18px; vertical-align: middle; margin-top: -2px; background: url(../images/icon_njw_hui.png) no-repeat; margin-right: 6px; cursor:pointer; &.on,&:hover{ background-image: url(../images/icon_njw_yellow.png); } } } } } /* ========================================================================== */ .njw-modal{ padding: 40px 0; text-align: center; .dropdown-toggle{ color: #000; } input{ padding-left: 10px; } } .njw-group-modal{ padding: 25px; } .addgroup-text{ margin-bottom: 25px; &:last-child{ margin-bottom: 0; } input{ line-height: 28px; border: 1px solid #d6e1e5; border-radius: 3px; padding: 0 8px; outline: none; } } .modal-content{ .inline-button{ padding-right: 0; } } .add-web{ padding: 30px 0; th{ span{ margin-right: 10px; } } .web-logo{ .logo-up{ position: relative; display: inline-block; width: 200px; height: 60px; line-height: 60px; border: 1px solid #e8e7ed; text-align: center; background: #eef1fa; color: #1389d0; input{ position: absolute; left: 0; top: 0; width: 100%; height: 100%; font-size: 0; opacity: 0; cursor: pointer; } } .msg-size{ display: inline-block; vertical-align: bottom; margin-left: 5px; color: #aeb5bd; } } } .del-collect{ display: none; position: fixed; left: 50%; top: 50%; width: 240px; height: 120px; text-align: center; border-radius: 3px; padding: 25px 10px; background: rgba(23,56,89,.8); color: #fff; -webkit-transform: translate(-50%, -50%); -moz-transform: translate(-50%, -50%); -ms-transform: translate(-50%, -50%); -o-transform: translate(-50%, -50%); transform: translate(-50%, -50%); p{ margin-bottom: 10px; .icon-del-collect{ display: block; width: 40px; height: 40px; margin: 0 auto; background: url(../images/icon_cancellcollect.png) no-repeat center center; } } } .u-edit{ background: url(../images/icon_exit.png) no-repeat center center; } .u-del{ background: url(../images/icon_del.png) no-repeat center center; } .tables-bw{ display: inline-block; max-width: 100%; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; } <file_sep>/app/less/main.less @import "./base/base.less"; .logo{ >h1{ .logo-nx{ width: 100%; height: 100%; display: block; background: url(../images/logo-nx.png) no-repeat left center; background-size: 100% auto; } } } /*外层div*/ .nxjk-wrap{ padding-left: 50px; } .nxjk{ padding-left: 300px; .tool{ height: auto; .layut-input{ padding: 0; } } .main{ height:100%; padding:0; .anli{ line-height:27px; padding:10px 13px 0; } } } /*多级菜单*/ .nav-wrap{ padding: 0!important; overflow: auto; float:left; border:1px solid #d7d7d7; background:#fff; position:absolute; z-index: 2; min-height:100%; .tab-item{ border-radius: 0; height: auto; width: 100%; line-height: 40px; margin-bottom: 0; a{ width: 50%; text-align: center; &:hover,&.active{ font-weight: bold; } } } } /*右边列表*/ .r-ul{ >li{ margin-right:15px; } .date-ld{ margin-top:10px; } .check-report{ min-width:80px; text-align:center; border:1px solid #d7d7d7; background:#fff; height:30px; line-height:28px; margin:10px 0 0 20px; border-radius:3px; } } .bt-line{ .r-ul { .date-ld{ margin: 0 10px 0 0; } } } .u-icon{ .u-8{ background: url(../images/u_8.png) no-repeat center center; } } /*搜索框的样式*/ .h-search{ padding:11px 14px; .layut-input { position: relative; padding: 0; border-bottom: none; margin-bottom: 0; >input{ padding-right: 25px; } >a{ position: absolute; right: 5px; top: 0; color: #d3dbe3; } } } /*搜索框样式-end*/ /*列表的样式*/ .tree-ul{ >ul{ >li{ position:relative; border-bottom: 1px solid #d7d7d7; &:first-child{ border-top: 1px solid #d7d7d7; } .de-tree{ display:none; >li{ .tags-list { min-height: 400px; border: 1px solid #d3dbe3; padding: 10px; } } } .layut-input{ display: none; } >a{ padding:11px 14px; display: inline-block; color:#029be5; width:100%; >i{ position: absolute; right: 23px; top: 13px; font-size: 18px; } &:hover{ background:#029be5; color:#fff; } } } .active{ background:#029be5; color:#fff; } } } /*列表样式-end*/ /*底部按钮的样式*/ .f-btn{ text-align: center; width: 100%; position: absolute; bottom: 57px; background: #fff; padding: 20px; .i-button{ margin:0 auto; padding:0; text-align:center; >a{ display: inline-block; min-width: 60px; height: 28px; line-height: 28px; margin-right: 20px; background: #029be5; color:#fff; border-radius: 3px; } } } /*--end--*/ /*报道核实 start*/ .bdhs{ background:#eef1f7; width:100%; height:100%; padding:20px; } .bd-head{ width:100%; background:#23a3e7; color:#fff; padding:15px 20px; font-weight: 700; } .bd-body{ background:#fff; .bd-left{ width:70%; .pd0{ .zt-ft{ background:#fff; border:1px solid #d3dbe3; padding:10px; } } } .bd-right{ width:30%; min-height:580px; } } #myModal{ .modal-body{ min-height:500px; } } /*报道核实 end*/ /*巡查左侧树形下拉菜单 start*/ .jstree-default > .jstree-container-ul > .jstree-node{ padding:0px 15px; width: 95%; } .jstree-default .jstree-anchor{ overflow: hidden; text-overflow: ellipsis; white-space: nowrap; width: 90%; } .jstree-wholerow-ul{ width: 100%; } /*巡查左侧树形下拉菜单 end*/ /*巡查微博 start*/ .title-tag{ span.green{ margin-left: 20px; font-weight: normal; } } .po-infmt{ margin-left: 0px; padding-left: 20px; .new-weibo{ background: #fff; .list-l{ margin-top: 0; } .po-left{ display: inline-block; h3{ display: inline-block; vertical-align: middle; margin-right: 30px; a{ vertical-align: middle; color:#1389d0; &:hover{ color:#06bdf2; } } } span{ margin-right: 15px; } .grey{ color:#e5e6e9; } ul{ li{ display: inline-block; margin-right: 5px; a{ color:#fff; background: #ffab0a; border-radius: 1px; padding:0 9px; line-height: 20px; } } } } .po-right{ margin-top: 10px; position: relative; .renew{ top: 5px; right: 5px; } } } } .right-infl .wb-list .list-r h3 { min-height: 28px; } .c-items{ position: relative; } .patrol-page{ width: 100%; border-top: 1px solid @line-color; } .sort-item{ .dropdown-menu{ right:0; left:auto; min-width:130px; img{ display: inline-block; } } } .new-weibo .weibo-tit .gril{ a{ color:#1389d0; &:hover{ color:@f-blue; } } } .new-weibo .news-details{ .gril{ a{ color:#ffab0a; &:hover{ color:@f-blue; } } } } .new-weibo .weibo-tit > p .btn{ color:@red; &:hover{ color:@f-blue; } } .r-ul > li{ &:last-child{ margin-right: 0; } } .bt-line{ margin-bottom: 0; } .wb-list > ul > li { padding: 15px 0 20px; border-bottom: 1px solid #d3dbe3; margin-bottom: 0; &:last-child{ border-bottom: none; } } #jstree1 .jstree-children .jstree-children .jstree-children .jstree-children .jstree-themeicon-custom, #jstree-add .jstree-children .jstree-children .jstree-children .jstree-children .jstree-themeicon-custom{ border-radius: 100%; -webkit-background-size: cover!important; background-size: cover!important; } /*巡查微博 end*/ /*巡查 影响力分析 start*/ .c-items2{ .con{ margin-top: 15px; border-bottom: 1px solid @line-color; .wb-list{ .list-r{ h3{ .ident{ background: #ffb024; color:#fff; padding: 7px; border-radius: 15px; margin:0 15px; img{ margin-top: 1px; margin-right: 5px; } } span{ vertical-align: middle; } } .about{ span{ margin-right: 30px; } } } } } .ft-msg{ p{ height: auto; } } } /*巡查 影响力分析 end*/ /*巡查 微博传播分析 start*/ .c-items3{ .bz-msg-con{ .wb-list{ .list-r{ div{ margin-right: 20px; display: inline-block; } ul{ display: inline-block; vertical-align: top; li{ display: inline-block; vertical-align: middle; margin:0 10px; &:first-child{ margin-left: 0; } } span{ color:#e5e6e9; } } } } .ft-msg{ margin: 15px 0 0; padding: 10px; line-height: 24px; p{ height: 48px; overflow: hidden; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; text-overflow: ellipsis; } } .msg{ -webkit-line-clamp: 7; height: 168px; } .ic-influence{ top: 90px; } } } .left-list{ border-top: 1px solid @line-color; li{ padding: 14px; border-bottom: 1px solid @line-color; .left-pic{ a{ width: 50px; height: 50px; display: block; overflow: hidden; border-radius: 50%; background: url(../images/def.png) no-repeat; background-size: cover; img{ width: 100%; border: 1px solid #ddd; border-radius: 50%; } } } .right-msg{ margin-left: 60px; h4{ margin-bottom: 5px; a{ font-weight: bold; color:#1389d0; } } p{ line-height: 20px; overflow: hidden; display: -webkit-box; -webkit-line-clamp: 6; -webkit-box-orient: vertical; text-overflow: ellipsis; max-height: 120px; } div{ text-align: right; position: relative; margin-top: 5px; .renew{ top: 6px; right: 6px; } .circle2{ height: 29px; display: none; } .left-list-rebtn{ background: #ffb024; color:#fff; border: none; } } } } } .zt-ft{ padding: 10px 10px 10px; } /*巡查 微博传播分析 end*/ /*巡查 微信 start*/ .list1{ .tables{ tr{ .remark{ width: 550px; color:#333; position: absolute; top: 35px; background: #fff; padding: 15px 20px 15px 17px; border: 1px solid @line-color; border-radius: 3px; z-index: 2; display: none; -webkit-box-shadow: 0 0 10px 0 rgba(0, 27, 54, 0.1); -moz-box-shadow: 0 0 10px 0 rgba(0, 27, 54, 0.1); -o-kit-box-shadow: 0 0 10px 0 rgba(0, 27, 54, 0.1); -ms-box-shadow: 0 0 10px 0 rgba(0, 27, 54, 0.1); box-shadow: 0 0 10px 0 rgba(0, 27, 54, 0.1); .text-mark{ color:#ffab0a; } } } } } .add-cont{ position: fixed; left: 140px; display: none; cursor: pointer; } .weixin{ .wb-list{ .date-ld{ display: inline-block; } } .table-responsive{ th{ background: #eee; } .bgw{ background: #fff; } .td-label{ font-weight: bold; padding: 2px 22px!important; height: auto!important; } } } .fuchuan{ right: -136px; .byduibi{ background: #5ec45e; } .duibi,.delduibi{ background: #fff; } .duibi { li { .delet{ top:8px; } } } .right-btn{ color:#fff; position: absolute; top: 50%; left: -25px; width: 25px; height: auto; padding: 10px 0; text-align: center; line-height: 20px; border-top-left-radius: 3px; border-bottom-left-radius: 3px; transform: translateY(-50%); -moz-transform: translateY(-50%); -ms-transform: translateY(-50%); -o-transform: translateY(-50%); -webkit-transform: translateY(-50%); box-shadow: -1px 0px 10px 0px #777777; cursor: pointer; } } /*巡查 微信 end*/ /*重点对象 网站 start*/ .zddx{ .nav-wrap{ width: 19%; } .tree-ul{ border-top: 1px solid @line-color; padding: 0px 12px 0px 15px; >ul{ padding-bottom: 5px; .active{ background: transparent; } >li{ border: none; margin-top: 10px; .tree-root{ border: 1px solid @line-color; background: #eef1f7; font-weight: bold; color: #333; border-radius: 5px; height: 40px; line-height: 40px; .root-text{ display: inline-block; width: 100%; padding-right: 35px; padding-left: 15px; margin-right: -35px; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; } .tree-caret{ display: inline-block; width: 35px; height: 100%; border-left: 1px solid @line-color; text-align: center; color: #8ea5c3; line-height: 38px; } } &.active{ .tree-root{ background: #1389d0; .tree-caret{ border-left: 1px solid #89c4e8; background: #006daf; border-top-right-radius: 5px; border-bottom-right-radius: 5px; } >a{ color: #fff; } } .de-tree,.layut-input{ display: block; } } .de-tree{ margin-top: 10px; a{ color: #666; } } } } } .h-search{ .layut-input{ input{ background: #f6f8fb; } } } .nxjk{ padding-left: 19%; } .tab-box{ h3{ font-weight: bold; display: inline-block; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; max-width: 215px; } } .sort{ margin-right: 0; button{ vertical-align: middle; } } .tables .tables-bt{ color: #666; } } .layut-input{ input{ padding-right: 25px; } } .nzddx{ .icon-box{ overflow: hidden; .moreList{ cursor: pointer; position: absolute; top: 11px; right: 8px; z-index: 999; >div{ width: 5px; height: 5px; background: #8EA5C3; border-radius: 50%; margin-bottom: 5px; } &:hover{ >div{ background: #FFA643!important; } } } } .u-icon{ position: absolute; top: 0px; z-index: 1; width: 451px; right: -177px; padding-top: 11%; height: 100%; .hides{ display: none; } } .u-icon a { width: 26px; height: 26px; display: inline-block; margin: 0 5px; background: #EEF1F7!important; border: 1px solid #D7DFE6; border-radius: 50%; i{ width: 20px; height: 20px; display: inline-block; } } .u-b4{ position: relative; top: 2px; left: 1px; &:hover{ top:1px; } } .u-b5{ position: relative; top: 2px; &:hover{ top:1px; } } .u-b2{ position: relative; top: 1px; } .u-b8{ background: url(../images/xuan/pubuliu-icon.png); width: 20px; height: 20px; display: inline-block; background-position: -10px -156px; position:relative; top: 4px; left: 1px; &:hover{ background-position-y: -197px; } } .u-b9{ background: url(../images/xuan/pubuliu-icon.png); width: 20px; height: 20px; display: inline-block; background-position: -45px -156px; position:relative; top: 4px; &:hover{ background-position-y: -197px; } } .u-b10{ background: url(../images/xuan/pubuliu-icon.png); width: 20px; height: 20px; display: inline-block; background-position: -190px -153px; position:relative; top: 2px; left: 1px; &:hover{ background-position-y: -194px; } } .u-b13{ background: url(../images/xuan/pubuliu-icon.png); width: 20px; height: 20px; display: inline-block; background-position: -228px -154px; position:relative; top: 3px; left: 1px; &:hover{ background-position-y: -195px; } } .u-b14{ background: url(../images/xuan/pubuliu-icon.png); width: 20px; height: 20px; display: inline-block; background-position: -265px -155px; position:relative; top: 4px; left: 1px; &:hover{ background-position-y: -196px; } } .u-b15{ background: url(../images/xuan/pubuliu-icon.png); width: 20px; height: 20px; display: inline-block; background-position: -152px -156px; position:relative; top: 3px; &:hover{ background-position-y: -197px; } } } /* @media screen and (max-width:1800px){ .nzddx .u-icon .esp{ display: none; } } */ .icon-box .u-icon .u-set{ display: inline-block; width: 18px; height: 18px; color: rgb(22,155,213); font-size: 18px; &:hover{ color: rgb(239,201,38); } } .resize-box{ position: absolute; right:0; top:0; width: 10px; height: 100%; cursor: w-resize; z-index: 15; } .nothing{ width: 100%; position: relative; span{ position: absolute; top: 50%; left: 50%; transform: translate(-50%,-50%); display: inline-block; } } .tables{ .icon-box{ position: relative; text-align: center; .moreicon{ width: 25px; margin-right: 0; display: none; } .ellipsis-box{ position: absolute; top: 100%; right: 10px; background: #cfd5de; border-radius: 5px; padding-top: 5px; width: 235px; display: none; z-index: 2; } } } /*重点对象 网站 end*/ /*重点对象 微博 start*/ .zddx{ .main{ padding: 0; } .bt-line{ padding: 13px; padding-bottom: 0; } .po-infmt,.right-infl{ margin: 0; } .po-infmt{ border-bottom: 1px solid @line-color; padding: 13px; .new-weibo .po-left { h3 a{ color: #333; } ul li a{ border-radius: 2px; padding: 2px 9px; } } } .list-l{ div{ top: -18px; } .user{ display: inline-block; } } .right-infl{ padding-top: 0; } .new-weibo .weibo-tit > p .btn{ color: #333; &:hover{ color: #06bdf2; } } .nav-top { padding: 16px; padding-bottom: 0; .tab-item{ border-radius: 4px; } a{ font-weight: bold; padding: 0; } } .wb-list .list-r .fens,.ft-forward{ span{ img{ display: inline-block; margin-right: 5px; vertical-align: inherit; } } } .new-weibo .news-details{ margin-left: 40px; } .wb-list .list-r .fens,.ft-forward span{ color: #333; } .ft-forward span{ margin-right: 20px; } .pic span{ width: 80px; } .wb-list > ul > li{ padding:15px 13px 20px 13px; } .wb-right-infl{ padding: 0; .list-r{ margin-left: 90px; } } } /*重点对象 微博 end*/ /*重点对象-微博传播分析 start*/ .zddx{ .left-list li .right-msg div .left-list-rebtn{ background: initial; color: initial; border:1px solid @line-color; } .left-list li .right-msg { h4 a{ color: #333; } div{ text-align: left; height: 34px; span{ display: inline-block; margin-top: 8px; img{ display: inline-block; margin-right: 5px; vertical-align: initial; } } .renew{ top: 11px; display: none; margin-top: 0; img{ display: block; } } .circle2{ float: right; } button{ margin-top: 5px; } } } .title-tag span{ font-size: 12px; color: #556482; font-weight: normal; margin-left: 25px; } .c-items3 .bz-msg-con .ft-msg{ .pull-right{ img{ display: inline-block; vertical-align: baseline; margin: 0 5px 0 20px; } } } .gz-table{ td.bule.tleft{ position: relative; } } } .cbfx{ .nav-wrap{ width: 350px; } .nxjk{ padding-left: 350px; } } /*重点对象-微博传播分析 end*/ /*重点对象-公众号对比 start*/ .zddx{ .weixin .table-responsive th{ background: none; } .weixin{ .introduce{ th,td{ vertical-align: middle; } td{ padding: 30px 50px; text-align: left; } } } .add-cont{ left: 100px; } } .gzh{ .new-weibo{ border-bottom: 1px solid @line-color; padding-bottom: 20px; margin-bottom: 20px; } } /*重点对象-公众号对比 end*/ @media screen and (max-width: 1300px){ .jstree-default .jstree-anchor{ font-size: 12px; } .zddx{ .nav-wrap{ min-width:260px; } .nxjk { padding-left: 260px; } } .tool{ padding:0 5px; } .r-ul .check-report{ margin-right: 0!important; min-width: 75px; } .zddx .po-infmt{ margin: 0!important; } .cbfx{ .nav-wrap{ width:260px; } } .tables td > a{ margin: 0; } } @media screen and (max-width: 1200px){ .zddx .tab-box h3{ display: none; } .zddx .bt-line{ padding: 9px; } .zddx .bt-line .tab-item a{ padding: 0 5px; } .zddx .bt-line .r-ul .layut-input{ width: 90px; } } @media screen and (max-width: 1070px){ .cbfx-box .bt-line .r-ul{ position: relative; } .cbfx-box .bt-line .r-ul .date-ld{ display: none; position: absolute; top: 100%; right: 0; } } /* 重点对象4.0 */ .nzddx{ // table{ // tr:nth-last-child(1){ // .g-zlm-hHvBox{ // top: -158px; // } // } // tr:nth-last-child(2){ // .g-zlm-hHvBox{ // top: -108px; // } // } // tr:nth-last-child(3){ // .g-zlm-hHvBox{ // top: -58px; // } // } // tr:nth-last-child(4){ // .g-zlm-hHvBox{ // top: -8px; // } // } // } .pd0{ position:relative; } .hoverTd{ position:relative; >a{ color: #029BE5; } .g-zlm-hHvBox{ display: none; } &:hover{ .g-zlm-hHvBox{ display: block; } } } .dropdown-toggle { color: #363636; } .zt-ft{ .search-list{ padding-left:20px; .more-btn{ display: inline-block; width: 30px; height: 30px; background: url(../images/zm/icon-zm-1.png); margin-left:20px; } } } .tab-box h3 { position: relative; top: 6px; } .g-chartBox { width: 100%; height: 354px; display: none; padding-top: 8px; border-bottom: 1px solid #D3DBE3; position: absolute; background: #fff; z-index: 9999; } } .g-zlm-tc{ border:1px solid #D3DBE3; width:100%; height: 317px; padding-top: 7px; position: absolute; z-index: 9999; background: #fff; display: none; ul{ li{ font-weight: 600; color: #494949; width: 100%; line-height: 50px; display: flex; .screen-left { width: 10%; text-align: right; } .screen-right { width: 78%; label { padding-right: 30px; } } .i-button { margin: 0 auto; text-align: center; a { display: inline-block; min-width: 94px; height: 28px; line-height: 28px; margin-right: 20px; background: #1389d0; color: #fff; border-radius: 3px; font-weight: 400; } } } } } .g-zlm-hHvBox{ width:180px; height:253px; background:url(../images/zlm619_03.png); position:absolute; top: 34px; left: 50%; margin-left: -95px; padding: 24px 0 0 26px; z-index: 4; li{ color: #363636; line-height: 35px; font-size: 14px; /* .num{ width: 31px; overflow: hidden; } */ i{ width:20px; height:20px; display: inline-block; position:relative; top: 7px; } .i1{ background:url(../images/zlm619_01_03.png) no-repeat; } .i2{ background:url(../images/zlm619_01_07.png) no-repeat; top: 9px; } .i3{ background:url(../images/zlm619_01_11.png) no-repeat; } .i4{ background:url(../images/zlm619_01_14.png) no-repeat; } .i5{ background:url(../images/zlm619_01_17.png) no-repeat; } .i6{ background:url(../images/zlm619_01_20.png) no-repeat; } } } /* 弹出框新闻样式 */ .modal-nzddx{ .modal-header{ background: #DDDDDD; height:34px; span{ font-size: 16px; position: relative; top: -4px; font-weight: 600; } } } .g-zlm-modal{ .zlm-box{ ul{ padding-top:10px; li{ border-bottom: 1px solid #D3DBE3; padding:4px 12px 10px 10px; .b-title{ a{ color:#029BE5; margin-left:10px; } } .b-content{ padding-left: 50px; .ct-lt{ width:85px; height:68px; img{ max-height: 100%; max-width:100%; } } .ct-rt{ overflow:hidden; padding-top:2px; .rt-tp{ span{ margin-right:10px; } } .rt-bt{ display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 2; overflow: hidden; text-align: justify; } } } } } } } @media screen and (max-width: 1366px){ .modal-nzddx{ .zt-ft{ .layut-input{ display: none; } } .tab-box{ .title{ display: block!important; top:13px; } .r-ul{ margin-top: -16px; position: relative; top: -5px; } .check-report{ margin-right:6px!important; } } } } /* 重点对象4.0-网址 start*/ .shouye .main{ padding: 10px; } .shouye .ch-box1{ padding-right: 5px; } .shouye .w50{ height: 420px; float: left; } .mb5{ margin-bottom: 5px; } // .nzddx .u-icon a{ // &:last-child{ // margin-right: 60px; // } // } .nzddx .icon-box .moreList{ right: 18px; } .nzddx .u-icon{ right: -150px; } .bg-gray{ background: #d3dbe3; border-radius: 3px; padding: 4px 6px; } /* 重点对象4.0-网址 end*/ /* 公众号管理2 start*/ .weixin-title{ .a-btn{ margin-right: 0; margin-left: -4px; // float: left; } a{ &:first-child{ border-radius: 3px 0 0 3px; } &:last-child{ border-radius: 0 3px 3px 0; } } } .bulk-import{ .u-btn{ border-radius: 3px; } } .tab-box{ .btn-black{ background: #fff; color: #364347; border-radius: 3px; } } .url-box{ border-radius: 12px; border: 1px solid #ddd; padding: 2px 10px; outline:none; margin-top: -2px; } .lsm-tag{ position: relative; border-radius: 12px; border: 1px solid #8ea5c3; background: #dde4ed; color: #444546; padding: 2px 6px; margin-top: -2px; margin-bottom: 2px; a{ position: absolute; display: inline-block; top: -3px; right: -3px; color: #fff; background: #f06567; border-radius: 50%; border: 0 none; font-size: 10px; width: 12px; height: 12px; line-height: 12px; font-size: 12px; text-align: center; &:hover{ color: #fff; } } } .tag-title{ padding: 10px 4px; border: 1px solid #d3dbe3; border-bottom: 0 none; li{ float: left; &:first-child{ margin-top: 6px; margin-right: 6px; } } } .tag-table{ border: 1px solid #d3dbe3; tr{ border-right: 0 none; border-left: 0 none; } } .lsm-P-number .P-number-list .p-btn:hover{ color: #fff; border-color: transparent; } .lsm-P-number .P-number-list .p-btn{ border: 0 none; background: #eef1f7; button{ font-size: 12px; line-height: 20px; border: 0 none; color: #fff; padding: 0 10px; display: none; border-radius: 2px; &:first-child{ background: #3abc3a; margin-right: 7px; } &:nth-child(2){ background: #ffab0a; margin-right: 12px; } } } .lsm-P-number .P-number-list{ background: #eef1f7; padding-bottom: 7px; .user .raduis0{ border-radius: 0; } } .lsm-P-number .P-number-list:hover .p-btn button{ display: block; } .lsm-P-number{ .P-number-list .P-right p{ line-height: normal; max-width: 250px; overflow: visible; white-space: normal; .lsm-tag{ float: left; margin-bottom: 8px; margin-right: 6px; line-height: 16px; } } } .lsm-modal-body{ padding: 0 16px; p{ padding-left: 6px; } label{ min-width: 100px; color: #364347; font-weight: normal; margin-bottom: 10px; } } .lkgamecom-main{ padding: 16px; background: #eef1f7; .tab-box{ border: 1px solid #d3dbe3; background: #fff; } .main-box{ border: 1px solid #d3dbe3; border-top: 0 none; } } .hover-yellow i:hover{ color: #e59539 !important; } .lsm-P-number .P-number-list{ box-shadow: none; -webkit-box-shadow: none; } .tc-table .lsm-z-tree{ border: 0 none; background: #eef1f7; } /* 公众号管理2 end*/ /* 公众号管理2-公众号标签 start*/ .text-right{ text-align: right; } .lsm-P-number table { thead{ tr{ background: #babfc7; } } td{ font-size: 14px; } } .pr24{ padding-right: 10px; } /* 公众号管理2-公众号标签 end*/ /*无图上报 过滤 start*/ .u-b20{ background: url(../images/u_b20.png) no-repeat center center; &:hover{ background: url(../images/u_20.png) no-repeat center center; } } .u-wtsb{ background: url(../images/u_wtsb.png) no-repeat center center; &:hover{ background: url(../images/u_20.png) no-repeat center center; } } .u-b21{ background: url(../images/ich_Filter2.png) no-repeat center center; &:hover{ background: url(../images/ich_Filter3.png) no-repeat center center; } } .u-bdzzl-b{ background: url(../images/u_bdzzl_b.png) no-repeat center center; &:hover{ background: url(../images/u_bdzzl_b.png) no-repeat center center; } } .icon-filter{ display: inline-block; width: 16px; height: 16px; background: url(../images/ich_Filter1.png) no-repeat center center; vertical-align: sub; } .icon-up{ color: #8ea5c3; font-size: 20px; vertical-align: middle; margin-right: 5px; } .icon-wtsb{ display: inline-block; width: 18px; height: 18px; background: url(../images/icon_wtsb.png) no-repeat center center; vertical-align: sub; margin-right: 5px; } .btn:hover{ .icon-up{ color: @key-blue; } .icon-wtsb{ background: url(../images/u_b20.png) no-repeat center center; } } .timepopup-box{ background: rgba(0,36,72,.9); border-radius: 3px; color: #fff; min-width: 250px; padding:30px 60px; text-align: center; position: absolute; top: 50%; left: 50%; display: none; h3{ line-height: 25px; } } /*无图上报 过滤 end*/<file_sep>/app/templates/zdzd-left.ejs <div class="zddx_nav_box"> <div class="leftnavbar leftnavbar1 menu-box"> <div class="navtop"> <div class="menu"><i class="fa fa-navicon"></i></div> </div> <div class="nicescroll"> <ul class="menu-li"> <li class="<%= local.gxt?'active':'' %>"> <a href="../html/重庆重点对象-重点关系图.html"> <div><img src="../images/cqdnk/guanxi.png" alt=""></div> <em class="fz16">重点关系网</em> </a> </li> <li class="<%= local.zdr?'active':'' %>"> <a href="../html/重庆重点对象-重点人-事业人物.html"> <div><img src="../images/cqdnk/guanzhu.png" alt=""></div> <em class="fz16">重点人</em> </a> </li> <li class="<%= local.zdzdw?'active':'' %> zdzd-nav"> <a href="重庆重点对象-重点阵地-网站2.html"> <div><img src="../images/cqdnk/mudidi.png" alt=""></div> <em class="fz16">重点阵地</em> </a> </li> <li class="<%= local.zdsj?'active':'' %>"> <a href="../html/重庆重点对象-重点事件.html"> <div><img src="../images/cqdnk/shijian.png" alt=""></div> <em class="fz16">重点事件</em> </a> </li> </ul> </div> </div> </div> <div class="zddx_nav_box"> <div class="zddx-left"> <div class="left-top"> <div class="top-search-box"> <input type="text" placeholder="搜索"/> <a href="javascript:;"><i class="fa fa-search"></i></a> </div> </div> <ul class="herf-btn clearfix"> <li class="active"><a href="重庆重点对象-重点阵地-目录管理.html"><i class="icon-cata"></i>目录管理</a></li> <li><a href="重庆重点对象-重点阵地-添加分组.html"><i class="fa fa-plus"></i>添加分组</a></li> </ul> <div class="list-box"> <ul class="plista"> <li> <a href="###" class="fz16"> 事业人物 <i class="fa fa-caret-down pull-right"></i> </a> <div class="operate-sj-box pull-right"> <i class="fa fa-ellipsis-v"></i> <ul class="operate-btna clearfix"> <li><a href="../html/重庆重点对象-重点人-编辑.html"><i class="fa fa-pencil"></i>编辑</a></li> <li><a href="###"><i class="fa fa-times"></i>删除</a></li> </ul> </div> <div class="clist" style="background-color: #063657;"> <div class="jstree nicescroll" style=" max-height: 280px"></div> </div> </li> <li> <a href="###" class="fz16">分组1<i class="fa fa-caret-right pull-right"></i></a> <div class="operate-sj-box pull-right"> <i class="fa fa-ellipsis-v"></i> <ul class="operate-btna clearfix"> <li><a href="../html/重庆重点对象-重点人-编辑.html"><i class="fa fa-pencil"></i>编辑</a></li> <li><a href="###"><i class="fa fa-times"></i>删除</a></li> </ul> </div> <div class="clist" style="background-color: #063657;"> <div class="jstree nicescroll" style=" max-height: 280px"></div> </div> </li> <li> <a href="###" class="fz16">分组2<i class="fa fa-caret-right pull-right"></i></a> <div class="operate-sj-box pull-right"> <i class="fa fa-ellipsis-v"></i> <ul class="operate-btna clearfix"> <li><a href="../html/重庆重点对象-重点人-编辑.html"><i class="fa fa-pencil"></i>编辑</a></li> <li><a href="###"><i class="fa fa-times"></i>删除</a></li> </ul> </div> <div class="clist" style="background-color: #063657;"> <div class="jstree nicescroll" style=" max-height: 280px"></div> </div> </li> <li> <a href="###" class="fz16">分组2<i class="fa fa-caret-right pull-right"></i></a> <div class="operate-sj-box pull-right"> <i class="fa fa-ellipsis-v"></i> <ul class="operate-btna clearfix"> <li><a href="../html/重庆重点对象-重点人-编辑.html"><i class="fa fa-pencil"></i>编辑</a></li> <li><a href="###"><i class="fa fa-times"></i>删除</a></li> </ul> </div> <div class="clist" style="background-color: #063657;"> <div class="jstree nicescroll" style=" max-height: 280px"></div> </div> </li> </ul> </div> </div> </div><file_sep>/app/less/table.less @charset "utf-8"; @import "./base/base.less"; @import "./base/conn.less"; @import "./temple.less"; @blue2:#73c8c9; @orange2:#edb926; @yellow2:#7790dd; @pink2:#8ea5c3; @violet2:#4cbea1; @green2:#169bd5; @sky2:#2286d3; @redu2:#ff4500; /*微博管理*/ .weibo{ .wb-list{ width: 50%; float: left; background: rgba(255, 255, 255, 0.5); border-bottom: 1px solid #d3dbe3; border-right: 1px solid #d3dbe3; padding: 10px 20px; &:nth-child(2n){ border-right:none; } } } /* 微信微博 end */ /*公众号管理*/ .P-number-list{ padding:15px; background:#fff; width:32%; margin-right:2%; float:left; margin-bottom:20px; position:relative; .user{ width:50px; height:50px; border-radius:50%; float:left; background: url(../images/def.png) no-repeat; background-size: cover; img{ border-radius:50%; } } .P-right{ p{ line-height:25px; i{ color:#8ea5c3; } a{ color:@bule; } .omit(); } margin-left:60px; h3{ margin-bottom:10px; font-weight:bold; a{ max-width: 115px; max-width: 150px; display: inline-block; vertical-align: middle; .omit; } .t-tag{ color:#fff; font-weight:normal; background:@green; border-radius:3px; padding:2px 5px; margin:0 5px; } } } .p-btn{ border:1px solid @border; background:#fff; color:@red; padding:2px 8px; border-radius:3px; position:absolute; top:10px; right:20px; font-weight:bold; &:hover{ color:@bule; border-color:@bule; } } .ic_wx{ position:absolute; top:-9px; left:-9px; width:40px; height:40px; background:url(../images/icon_we.png) center center no-repeat; } &:nth-child(3n){ margin-right:0; } .box-shadow(0,0,8px,0,#ddd); } /*公众号管理end*/ /*检索*/ .box{ margin: 0; } .sech-box{ width:800px; margin:20px auto; lable{ margin:0 5px; } >span{ margin-left:10px; } } .seach-time{ border:1px solid @border; background:#fff; padding:0 5px; line-height:22px; display:inline-block; width:162px; input{ border:none; outline:none; width:68px; line-height:22px; text-align:center; font-size:12px; } } .sech-btn{ width:89px; height:30px; line-height:30px; display:inline-block; text-align:center; margin-right:5px; background:#d3dbe3; border-radius:3px 3px 0 0; &.active{ background:#1389d0; color:#fff; } } .sech-mid{ margin-top:-1px; position:relative; line-height:35px; input{ width:690px; background:#fff; border:2px solid #1389d0; padding:0 10px; height:39px; } .sech-go{ width:100px; height:39px; line-height:39px; background:#1389d0; color:#fff; text-align:center; position:absolute; top:0; right:12px; } .sech-gj{ position:absolute; top:0; right:-35px; } } .key-top{ padding:0 20px; border-bottom:2px solid @green; .a-btn{ border-radius:3px 3px 0 0; padding:2px 10px; i{ margin-left:10px; } } } .key-bott{ padding:10px 20px; background:#fff; } .sec-inp, .tool .sec-inp{ border:1px solid @border; border-radius:3px; line-height:26px; padding:0 20px 0 10px; width:160px; height:28px; background:url(../images/icon_sea.png) #fff 138px center no-repeat; } /*高级检索*/ .senior{ display:none; position:fixed; top:60px; width:100%; background:#eef1f7; z-index:9; .box-shadow(0,0,10px,0,rgba(0,0,0,.5)); .sen-top{ height:40px; padding:0 20px; border-bottom:1px solid #e6e6e6; .sen-tit{ padding:0 10px; line-height:39px; display:inline-block; color:#1388cf; border-bottom:3px solid #1388cf; } } .hui{ background:#f3f3f3; } table{ width:100%; label{ min-width:80px; } th{ text-align:right; font-weight:normal; } th,td{ padding:6px 10px; vertical-align: top; i{ margin-left:20px; } } td{ .assign-custom{ width: 70%; .zd-box{ td{ vertical-align: middle; min-width:60px; } .classtly{ border:1px solid @border; padding:0 20px 15px; a{ text-align: center; min-width: 85px; padding: 3px 10px; border-radius: 3px; display: inline-block; margin: 15px 10px 0; background: @line-color; } &.subs-list-blue{ a.on{ color:#fff; background: #1389d0; } } &.subs-list-red{ a.on{ color:#fff; background: #f54545; } } &.subs-list-green{ a.on{ color:#fff; background: #5ec45e; } } } } } } .form-control{ width:300px; height:30px; } } .dropdown-toggle{ height:25px; line-height:23px; border-color:#aaa; color:#333; } .dropdown-menu{ border-color:#aaa; } } .sen-go{ margin:20px 150px; a{ padding:4px 30px; border-radius:4px; color:#93a4aa; background:#d3dbe3; display:inline-block; margin-right:15px; &.sen-yes{ color:#fff; background:#1389d0; } } } /*右侧实时热点*/ .Real-hot{ position:fixed; padding:20px; right:-300px; top:60px; width:300px; background:#fff; z-index:9; .box-shadow(0,0,4px,0,rgba(0,0,0,.3)); .real-tit{ background:url(../images/hot.png) left center no-repeat; padding-left:20px; border-bottom:1px solid @border; line-height:35px; } .real-inp{ background:url(../images/icon_sea.png) left center no-repeat; border-bottom:1px solid @border; padding-left:20px; margin-bottom:10px; line-height:30px; input{ border:none; outline:none; height:30px; } } .real-btn{ width:35px; height:96px; display:block; background:url(../images/icon_l_btn.png) center center no-repeat; position:absolute; top:50%; left:-35px; margin-top:-100px; } } .real-list{ padding:10px 0 20px 0; li{ border-bottom:1px dashed @border; line-height:40px; .omit(); a{ color:@bule; text-decoration:underline; &:hover,&focus{ color:@red; } } span{ display:inline-block; width:20px; height:20px; line-height:20px; text-align:center; background:#8ea5c3; color:#fff; border-radius:3px; margin-right:8px; } .reds{ background:@red; } .greens{ background:@green; } .yellows{ background:@yellow; } } } .real-key-list{ li{ line-height:35px; .time{ float:right; } } } /*检索end*/ /*巡查和案例研判左侧浮框*/ .leftnvvbar2,.yichang-push-nav-left{ background:#002e4a; position:fixed; top:0; left:-18%; width:18%; min-width:200px; height:100%; padding:80px 0 20px; -webkit-box-shadow: 0 0 30px 0 rgba(0, 0, 0, 0.6); -moz-box-shadow: 0 0 30px 0 rgba(0, 0, 0, 0.6); -o-kit-box-shadow: 0 0 30px 0 rgba(0, 0, 0, 0.6); -ms-box-shadow: 0 0 30px 0 rgba(0, 0, 0, 0.6); box-shadow: 0 0 30px 0 rgba(0, 0, 0, 0.6); .ip-box{ h5{ background:#006daf; color:#fff; font-weight:bold; text-align:center; line-height:30px; border-radius:3px; margin-bottom:20px; } padding:0 20px; position:relative; input{ color:#fff; background:#006daf; border:none; outline:none; width:100%; padding-right: 30px; } a{ color:#fff; position:absolute; right:30px; top:7px; z-index:3; display:block; } } } .bar2-tab{ margin:20px; border:1px solid #029be5; border-radius:3px; font-size:0; a{ width:33.3%; border-right:1px solid #029be5; height:30px; line-height:30px; color:#fff; display:inline-block; text-align:center; line-height:30px; &.active,&:hover{ background:#029be5; } &:nth-child(1){ border-radius:3px 0 0 3px; } &:nth-child(3){ border-radius:0 0 3px 3px; border-right:none; } } } .zd-link{ a{ display:block; background:#043553; color:#029be5; line-height:40px; margin-bottom:5px; padding:0 15px; &.active{ background:#029be5; color:#fff; } } } .time-list{ margin-bottom:4px; .time-list-tit{ color:#fff; background:#043553; padding:0 20px; line-height:35px; cursor:pointer; i{ margin-top:10px; } } .er-list{ display:none; a{ padding:0 20px; display:block; line-height:35px; color:#029be5; .omit(); &.active,&:hover{ background:#1389d0; color:#fff; font-weight:bold; } } } } .leftbar-go{ display:block; width:33px; height:90px; position:absolute; top:50%; right:-32px; margin-top:-45px; background:url(../images/btn-right.png) center center no-repeat; } /*浮框end*/ /*案例研判*/ .case{ padding: 60px 0 0; .main{ padding:0 20px; } } .anli-navbar{ z-index: 100; position:fixed; top:50%; -webkit-transform: translateY(-50%); -moz-transform: translateY(-50%); -ms-transform: translateY(-50%); -o-transform: translateY(-50%); transform: translateY(-50%); right: -160px; ul{ width:160px; padding:10px; background:#fff; .box-shadow(0,0,6px,0,rgba(0,0,0,.3)); } li{ height:42px; line-height:40px; margin-bottom:5px; &.active a,&:hover a{ background:@green; border-color:@green; color:#fff; i{ color:#fff; } } a{ display:block; border:1px solid @border; background:#eef1f7; padding:0 15px; border-radius:3px; } i{ width: 20px; color:#8ea5c3; } } .go-top{ width:160px; display:block; .box-shadow(0,0,6px,0,rgba(0,0,0,.3)); background:#fff; text-align: center; color:@yellow; padding:10px 25px; margin-top:15px; i{ margin-right:10px; } } .catalogue{ position: absolute; top: 50%; left: -25px; margin-top: -55px; width: 25px; height: 110px; color: #fff; background: #06bdf2; display: block; text-align: center; padding: 10px 5px; font-size: 14px; border-radius: 5px 0 0 5px; .box-shadow(0,1px,4px,0,rgba(0,0,0,.3)); } } /*案例研判内容*/ .anli{ padding:12px 0; >div{ background:#fff; .box-shadow(0,0,6px,0,rgba(0,0,0,.2)); padding:15px; margin-bottom:20px; } } .dropdown-box{ height:30px!important; margin-right:22px; } .all-news{ padding:10px; background:#eef1f7; >a{ display:inline-block; padding: 0 10px; } } .diyu{ padding:10px; i{ color:#8ea5c3; margin-right:10px; } } .anli-tit{ padding:10px 20px; background:#fff; margin-bottom:20px; .box-shadow(0,0,6px,0,rgba(0,0,0,.2)); a{ border-left:3px solid @bule; padding-left:15px; color:@bule; } } .explain{ background:#f6f8fb; border:1px solid @border; padding:15px; margin:15px 0; p{ line-height:25px; .omit-more(3); max-height:75px; } } .time-change{ text-align:center; .tm-tab{ display:inline-block; margin:0 5px; padding:1px 8px; border-radius:3px; cursor:pointer; &.active,&:hover{ color:#fff; background:@green; } } } /* 案例-地域分析 */ .echart-map{ position: relative; .maptab{ top:20px; } } .analyze-list{ td{ a{ margin-right: 0; } } } .analyze-num{ td{ border-right:1px solid #d3dbe3; &:last-child{ border-right: none; } a{ margin-right: 0; } &.text-right{ text-align: right; } &.fw{ font-weight: bold; } em{ color:@red; } } th{ border-right:1px solid #d3dbe3; &:last-child{ border-right: none; } } } /* 网民分析 */ .theory{ width: 100%; padding: 10px 0; } .chart-wm{ width: 40%; height: 282px; } .theory-list{ ul{ li{ border-top:1px solid @line-color; padding: 30px 10px 20px 25px; } } } .theory-img{ width: 60px; height: 60px; display: block; border-radius: 50%; overflow: hidden; background: url(../images/def.png) no-repeat; background-size: cover; border:1px solid @line-color; margin-top: 0; } .theory-con{ float: left; width: 60%; border:1px solid @line-color; h4{ background: #eef1f7; padding: 12px; } a{ color:#333; } .tit{ height: 30px; line-height: 30px; border-bottom: 1px solid @bg-blue; span{ height: 30px; padding: 0 15px; color:#fff; display: inline-block; background: @bg-blue; } } .ft-con{ margin-left: 75px; background: none; border: none; margin-top: 0; padding: 0; a:hover{ color:#333; } p{ margin-bottom: 6px; height: 66px; .omit-more(3); } } } .hot-netizen{ a{ float: left; height: 30px; line-height: 30px; border:1px solid @line-color; border-radius: 3px; margin:0 25px 15px 0; padding:0 15px 0 35px; display: block; background: #f6f8fb url(../images/wm.png) no-repeat 10px center; &:hover{ border-color:@bg-blue; } } } /*影响力-微博-博主概况*/ .titcol-bg{ height: 30px; line-height: 30px; border-bottom: 2px solid #169bd5; span{ height: 30px; padding: 0 15px; color: #fff; display: inline-block; background:#169bd5; } } /*影响力-微博-博主概况end*/ /*影响力-微博-转发人分析*/ .zf-people{ li{ background:#f4f4f4; border:1px solid @border; margin-top:15px; width:23.5%; margin-right:2%; padding:8px; float:left; .zf-hed-img{ float:left; width:38px; height:38px; overflow:hidden; margin-right:8px; } .zf-text{ float:left; line-height:18px; em{ display:block; } } &:nth-child(4n){ margin-right:0; } } } /*影响力-微博-博主概况end*/ @media screen and (min-width: 1250px) and (max-width: 1650px) { .zf-people{ li{ width:32%; &:nth-child(4n){ margin-right:2%; } &:nth-child(3n){ margin-right:0; } } } } @media screen and (max-width: 1250px) { .zf-people{ li{ width:49%; &:nth-child(4n){ margin-right:2%; } &:nth-child(2n){ margin-right:0; } } } } @media screen and (max-width: 1300px) { .chart-wm{ height: 258px; } .theory-con .ft-con p{ height: 57px; } } /*案例研判end*/ /*巡查原文*/ .xcxq-top{ padding:20px 10%; border-bottom:1px solid #efefef; .xq-tit{ color:#000; line-height:50px; text-align:center; .omit(); } .cx-laiyuan{ line-height:30px; color:@bule; em{ color:#8ea5c3; } .pull-left{ margin-right:10px; } .pull-right{ margin-left:10px; } } } .xq-text{ padding:20px 10%; p{ white-space: pre-wrap; text-indent: 2em; line-height:25px; } .xq-link{ display:block; line-height:60px; text-align:right; color:@bule; } } /*原文浮窗*/ .xg-Article{ width:300px; background:#fff; padding:20px 15px; position:fixed; top:60px; right:0; .box-shadow(0,0,5px,0,rgba(0,0,0,.3)); .real-list{ li{ a{ display:block; .omit(); } span{ width:auto; background:#fff; color:#8ea5c3; } } } } .xqA-tit{ border-bottom:1px solid @border; line-height:40px; i{ margin-right:5px; color:#8ea5c3; } } /*巡查end*/ /*个人设置*/ .seted-bg{ width:420px; top:50%; left:50%; margin-left:-110px; margin-top:-200px; position:absolute; background:url(../images/st-bg.png) center bottom no-repeat; } .seted-box{ margin-bottom:40px; background:#fff; .box-shadow(0,0,4px,0,rgba(0,0,0,.3)); border-radius:5px; position:relative; .user{ width:80px; height:80px; border-radius:50%; display:block; position:absolute; left:170px; top:-40px; // .box-shadow(0,0,4px,0,rgba(0,0,0,.2)); padding:2px; background:#fff; overflow:hidden; background: url(../images/def.png) no-repeat; background-size: cover; img{ width:100%; } } } .text-box{ .in-list{ margin-bottom:20px; } padding:66px 80px 20px 80px; i{ width:30px; height:30px; background:#8ea5c3; text-align:center; line-height:30px; color:#fff; font-size:16px; float:left; border-radius:3px 0 0 3px; } .form-control{ float:left; width:230px; color:@bule; border-radius:0 3px 3px 0; height:30px; line-height:28px; background:url(../images/icon_p.png) 205px center no-repeat; &:focus{ background:#fff; } } .form-control[disabled], fieldset[disabled]{ background:#fff; } .sen-go{ margin:0; text-align:center; } } /*浮窗*/ .fuchuan { margin: auto; color: #000; width: 136px; border-radius: 5px; background: #f1f6fb; border:1px solid @border; position: fixed; right: 0; top: 50%; transform: translateY(-50%); -moz-transform: translateY(-50%); -ms-transform: translateY(-50%); -o-transform: translateY(-50%); -webkit-transform: translateY(-50%); } .fuchuan .title { line-height: 36px; border-radius: 5px 5px 0 0; font-size: 14px; font-weight: normal; text-align: center; } .duibi li { padding: 10px 0; text-align: center; border-top: 1px solid @border; position: relative; h5{ font-weight:bold; line-height:28px; } } .duibi li .name { width: 60px; height: 60px; border: 1px solid @border; overflow: hidden; margin: 0 auto; } .duibi li .name img { width: 100%; } .duibi li .delet { position: absolute; right: 8px; bottom: 8px; cursor: pointer; } .fuchuan .byduibi { background: #ffab0a; height: 32px; line-height: 32px; text-align: center; font-size: 14px; cursor: pointer; } .fuchuan .byduibi a { color: #fff; display:block; } .fuchuan .delduibi { box-shadow: none; background:none; border-radius:0 0 4px 4px; } .point { width: 40px; height: 40px; border-radius: 500px; background: #0C0; overflow: hidden; } .point img { width: 100%; border-radius: 500px; } /*浮窗end*/ /*关键词*/ .hot-key{ margin:10px 0; h5{ font-weight:bold; margin-bottom:5px; i{ margin-right:5px; } } .key-box{ padding:0 10px; >span{ display:inline-block; min-width:100px; text-align:center; line-height:25px; margin-right:10px; } } } .key-data{ width:10%; float:left; text-align:center; >span{ display:block; line-height:30px; .omit(); } .date-zhou{ color:@bule; border-top:2px solid @bule; i{ height:4px; width:2px; float:right; background:@bule; } } } .bor-bottom{ border-bottom:1px dashed @border; margin-bottom:20px; } .key-bule{ font-weight:bold; i{ margin-right:5px; } } /*关键词end*/ /*典型观点*/ .dx-pd20{ padding:0 20px; margin:20px 0; } .dx-btn-bor{ border:1px solid @border; padding:10px 15px; } .dx-left,.dx-right,.anxg-right,.anxg-left{ width:50%; padding:20px; } .dx-fenxi{ padding:20px; li{ margin-bottom:15px; a{ color:#333; padding-left:10px; font-weight:bold; max-width:70%; .omit(); float:left; } em{ float:left; } span{ width:60px; height:20px; float:left; &.bg01{ background:#169bd5; } &.bg02{ background:#73c8c9; } &.bg03{ background:#ffab0a; } &.bg04{ background:#7790dd; } &.bg05{ background:#8ea5c3; } &.bg06{ background:#4cbea1; } } } } .dx-pd20 .news-right{ .news-ly{ margin-top:5px; } .news-t { .fz16{ float:left; max-width:60%; width:auto; } .dx-nub{ font-weight:normal; i{ color:@bule; } } } } /*典型观点end*/ /* 源头推测 */ /* 插件css开始 */ .swiper-container { width: 100%; height: 100%; } .swiper-slide { display: -webkit-box; display: -ms-flexbox; display: -webkit-flex; display: flex; // -webkit-box-pack: center; // -ms-flex-pack: center; // -webkit-justify-content: center; // justify-content: center; // -webkit-box-align: center; // -ms-flex-align: center; // -webkit-align-items: center; // align-items: center; } .swiper-button-prev,.swiper-button-next{ display: none; } .swiper-container-rtl .swiper-button-next{ left:0!important; } .swiper-container-rtl .swiper-button-prev{ right: 0!important; } /* 插件css结束 */ .speculation-list{ margin-bottom: 20px; padding-top:20px; dt{ float: left; margin-top: 31px; a{ width: 140px; height: 50px; line-height: 50px; display: block; background: #2286d3; border-radius: 5px; font-size: 20px; text-align: center; color: #fff; img{ display:inline; } } } dd{ margin-left: 140px; overflow: hidden; margin-right: 95px; .swiper-container{ height: 190px; } } } .swiper-slide{ position: relative; .list-line{ z-index: 10; position: absolute; left:0; top:55px; height: 2px; width: 100%; background: #94a3c4; display: block; } } .list-item{ width: 50%; padding:0 25px; text-align: left; .time{ position: relative; padding:0 20px ; height: 40px; line-height: 40px; display: inline-block; margin-top: 2px; background:#eef1f7; border:1px solid @border; em{ float:left; margin:11px 6px 0 -10px; } i{ z-index: 100; position: absolute; left: 50%; bottom: -19px; margin-left: -5px; width: 10px; height: 10px; background: #2286d3; display: block; border-radius: 50%; } } .list-item{ padding: 10px 20px; } } .speculation-con{ height: 136px; padding: 27px 0 0; .sm-shadow{ background:#eef1f7; border:1px solid @border; padding:15px; border-radius:5px; } strong{ position: relative; font-size: 18px; font-weight: bold; height: 22px; line-height: 22px; display: block; color: #4f5f6f; overflow: hidden; /* white-space: nowrap; */ text-overflow: ellipsis; margin-bottom: 8px; padding-left: 15px; &:after { content: ''; position: absolute; left:0; top:8px; width: 8px; height: 8px; display: block; border-radius: 50%; background: red; } } p{ padding-left: 15px; font-size: 14px; height: 59px; color:#7e8e9f; .omit-more(3); } } .list-color1{ .speculation-con strong{ &:after { background:#169bd5; } } dt a{ background:#169bd5; } .list-item .time{ color:#169bd5; i{ background: #169bd5; .box-shadow(0,0,0,5px,rgba(34,134,211,.3)); } } } .list-color2{ .speculation-con strong{ &:after { background: #f54545; } } dt a{ background:#f54545; } .list-item .time{ color:#f54545; i{ background: #f54545; .box-shadow(0,0,0,5px,rgba(245,69,69,.3)); } } } .list-color3{ .speculation-con strong{ &:after { background:#4cbea1; } } dt a{ background: #4cbea1; } .list-item .time{ color:#4cbea1; i{ background: #4cbea1; .box-shadow(0,0,0,5px,rgba(76,192,161,.3)); } } } /*源头推测结束*/ /*案例演变*/ .anlibox{ position: relative; } .vertical-line{ z-index: 5; position: absolute; left:50%; margin-left: -1px; top:45px; width: 2px; height:80%; background: #9c9c9c; } .anliyanbian { position: relative; // background: url(../images/anli_bg.png) no-repeat center 0%; padding:27px 4px; overflow: auto; .inCenter { z-index: 9; position: relative; float: left; width:14%; height: 122px; text-align: center; font-size: 24px; color: #4c4c4c; background: url(../images/alli_001.png) no-repeat center center; } .suntitle { z-index: 1; position: relative; float: left; height: 100px; line-height: 100px; margin-top:10px; width:30%; color: #0c0c0c; display: table; margin-left:9%; border-radius:5px; &:after { content: ''; position: absolute; left:-40%; top:0; width: 40%; height: 100px; background: url(../images/alli_right.png) no-repeat left center; display: block; } i{ float:left; margin:20px 0 0 15px; font-size:18px; } .txt { display: inline-block; line-height: 33px; display: table-cell; padding:10px 10px 10px 20px; vertical-align: middle; font-weight:bold; max-height:80px; .omit-more(3); } } >li{ margin-bottom:18px; &:nth-child(2n){ .suntitle{ margin-left:5.5%; margin-right:7.5%; &:after{ left:auto; right: -40%; background-image: url(../images/alli_left.png); } } .con{ margin-left:4%; margin-right:0; } } } .con { float: left; width: 39%; margin-right:4%; height: 122px; padding:10px; border-radius:5px; overflow: hidden; background:#eef1f7; border:1px solid @border; a{ color:#333; line-height:25px; display:block; .omit(); }; .circle{ width:10px; height:10px; margin:0 10px 0 0; border-radius:50%; display:inline-block; } } } .bglightbule{ .circle{ background:@blue2; }; .suntitle{ background:#ebf7f7; .txt,i{ color:@blue2; }; }; }; .bglightorange{ .inCenter{ background-image: url(../images/alli_002.png); } .circle{ background:@orange2; }; .suntitle{ background:#f4efe6; .txt,i{ color:@orange2; }; }; }; .bglightyellow{ .inCenter{ background-image: url(../images/alli_003.png); } .circle{ background:@yellow2; }; .suntitle{ background:#edf0f8; .txt,i{ color:@yellow2; }; }; }; .bglightpink{ .inCenter{ background-image: url(../images/alli_004.png); } .circle{ background:@pink2; }; .suntitle{ background:#ecf1f7; .txt,i{ color:@pink2; }; }; }; .bglightviolet{ .inCenter{ background-image: url(../images/alli_005.png); } .circle{ background:@violet2; }; .suntitle{ background:#e6f6f2; .txt,i{ color:@violet2; }; }; }; .bglightgreen{ .inCenter{ background-image: url(../images/alli_006.png); } .circle{ background:@green2; }; .suntitle{ background:#e8f3f8; .txt,i{ color:@green2; }; }; }; /*案例演变end*/ /*境外浏览*/ .tools-link{margin-right: 10px;} .tools-link a{margin-right: 10px; color:#06bdf2;} .tr1{ display: block; margin-bottom: 20px; } .jw-box{ background: #fff; margin-top: 20px; .box-shadow(0,0,10px,0,rgba(0,0,0,.3)); .layut-input{ margin-right: 10px; padding: 0; } .jw-con{ padding:20px; .tit{ border-bottom: 1px solid #06bdf2; height: 30px; line-height: 30px; margin-bottom: 20px; span{ color: #FFF; background: #06bdf2; display: inline-block; padding: 0 15px; } } } // .tables .tables-bt{ // max-width: 100%; // } .jw-link{ max-width: 300px; } } .jw-table{ margin-bottom: 20px; table{ padding: 2px; border: 2px solid #dadada; width: 100%; } th,td{ padding: 5px 10px; border-bottom: 1px solid #dadada; } th{ background: #f1f1f1; width: 150px; text-align: center; } td{ >a{ color: #006daf; display: inline-block; width: 150px; margin: 0 10px 5px 0; .omit(); } } } .jw-wz-tit{ background: #F1F1F1; padding:10px; margin-bottom: 10px; } /*智库亚太 start*/ .jw-zk{ .jw-table{ table{ .zk-a{ display: inline-block; width: 200px; height: 110px; padding-top: 10px; text-align: center; line-height: 40px; .zk-sp1{ display:block; width: 200px; height: 70px; padding: 10px 0; background-color: #D3DBE3; img{ height: 100%; } } .zk-sp2{ display:block; width: 200px; height: 70px; background-color: #D3DBE3; img{ margin: 0 auto; } } } } } } /*智库亚太 eng*/ /*境外浏览end*/ /*分类查看*/ .fa-filter{ width: 40px; height: 27px; display: inline-block; background: #fff; border: 1px solid @border; color: @pink2; text-align: center; line-height: 25px; font-size: 18px; } .example{ color: @pink2; margin-top: 8px; } .ly-bj{ width: 180px; float: left; background: #ebf3fb; color: #8ea5c3; padding: 3px 10px; border-radius: 2px; i{ cursor: pointer; margin-top: 4px; margin-left: 5px; color: #1389d0; } .fa-close{ color: #e9530a; } } .plus-add{ color:#fff; margin-left: 10px; width: 28px; height: 28px; text-align: center; line-height: 26px; font-weight:bold; border-radius: 3px; font-size: 24px; background: #1389d0; float: left; &:hover{ color: #fff; } } .ly-tc{ display: none; position: absolute; top: 100px; left:10%; width: 80%; padding: 20px 10px; background: #fff; border: 1px solid @border; .box-shadow(0,0,20px,0,rgba(0,0,0,.2)); } .mulu-list{ border-bottom:1px solid #002e4a; .er-list{ display: none; li{ line-height: 35px; padding: 0 10px; overflow: hidden; background: #1a2939; a{ color: #0298e1; display: inline-block; width: 140px; .omit(); float: left; } i{ display: none; color: #fff; float: right; margin-top: 10px; cursor: pointer; } .fa-close{ color: #e9530a; margin-left: 10px; } &.active,&:hover{ a{ color: #fff; } i{ display: block } } } } .er-list-b{ li{ line-height: 35px; padding: 0 10px; overflow: hidden; background: #1a2939; a{ color: #0298e1; display: inline-block; width: 140px; .omit(); float: left; } i{ display: none; color: #fff; float: right; margin-top: 10px; cursor: pointer; } .fa-close{ color: #e9530a; margin-left: 10px; } &.active,&:hover{ a{ color: #fff; } i{ display: block } } } } &.active{ h3.mulu-list-tit{ color: #fff; background: #029be5; } .er-list{ display: block; } } } .mulu-list-tit{ position: relative; cursor: pointer; padding: 0 10px; color: #0298e1; min-height: 45px; line-height: 45px; >i{ margin-top: 16px; margin-left: 10px; font-size: 16px; } } .tables{ .fa-arrow-up{ color: #cf2c20; font-size: 18px; margin-right: 10px; cursor: pointer; } .fa-arrow-down{ color: #029be5; font-size: 18px; cursor: pointer; } .bq-modal-tip{ .circle-answer{ margin-left: 0; } span{ left: 20px; } } } .mulu-title{ font-size: 16px; color: #333; font-weight: bold; margin-right: 10px; } .ml-js{ display: none; position: absolute; left: 0; top: 52px; width: 100%; background: #F9FAFC; border-bottom:1px solid @border ; padding: 0 20px; .ml-table{ width: 100%; th{ text-align: right; } td{ text-align: left; >a{ padding: 4px 15px; margin-right: 10px; color: #333; border-radius: 3px; &.active{ background: #5EC45E; color: #fff; } } } } } /*分类查看end*/ @media screen and (max-width: 1300px) { .P-number-list{ width:49%; &:nth-child(3n){ margin-right:2%; } &:nth-child(2n){ margin-right:0; } } .sech-mid{ input{ width:635px; height:35px; } .sech-go{ right:97px; line-height:35px; height:35px; } .sech-gj{ right:50px; } } .text-box{ .in-list{ margin-bottom:15px; } } .sech-btn{ width:75px; margin-right:2px; } .anli-tit{ margin-bottom: 10px; } // .anliyanbian .suntitle{ // margin-left:12%; // } // .anliyanbian > li:nth-child(2n) .suntitle { // margin-left: 2.5%; // margin-right: 12.5%; // } .hot-key .key-box > span{ min-width:80px; } .jw-table td > a{ width: 140px; } } @media screen and (max-height: 850px) { .anli-navbar{ li{ height:35px; line-height:33px; } .go-top{ padding:5px 25px; } } .Real-hot{ padding:15px 20px; .real-list{ li{ line-height:30px; } } .real-key-list{ li{ line-height:25px; } } } } /* 专题监控*/ /*字体内容*/ .sub-title{ line-height: 52px; font-weight: bold; color:#333333; display: inline-block; } .date-wrapper{ padding: 10px 15px; border-bottom: 1px solid @hui; .time-ser .layout-data{ margin-right: 10px; } .layut-input{ padding: 0; } .left-item{ padding-top: 5px; float:left; } .right-item{ float: right; >ul,>.dropdown{ float: left; margin-left: 10px; } .dropdown-menu{ min-width:130px; left:auto; right:0; a{ img{ display: inline-block; } } } .icon-select{ .select-item{ position:relative; } >li{ cursor: pointer; width:38px; height:30px; padding:4px 8px; border:1px solid #d3dbe3; display:inline-block; margin-left:10px; .select-content::before{ position:absolute; content:""; width:0; height:0; top:-10px; left:50%; border-right:5px solid transparent; border-left:5px solid transparent; border-bottom:10px solid #d3dbe3; } .hide{ display:none; } .select-content{ position:absolute; background:#fff; top:35px; left:-38px; border:1px solid #d3dbe3; >li{ width:100px; text-align:center; >a{ display:inline-block; width:90px; border-bottom:1px solid #d3dbe3; img{ display:inline-block; } } } } } } } } .u-icon{ a{ width: 18px; height: 18px; line-height: 20px; display: inline-block; margin: 0 5px; color:@key-blue; em{ margin-left: 20px; font-size: 12px; vertical-align: text-bottom; } } .u-up{ background: url(../images/u_up.png) no-repeat center center; color:#767676; &:hover{ background: url(../images/u_9.png) no-repeat center center; } } .u-down{ background: url(../images/u_down.png) no-repeat center center; &:hover{ background: url(../images/u_10.png) no-repeat center center; } } .u-kz{ background: url(../images/u_kz.png) no-repeat center center; &:hover{ background: url(../images/u_1.png) no-repeat center center; } } .u-js{ background: url(../images/u_js.png) no-repeat center center; &:hover{ background: url(../images/u_2.png) no-repeat center center; } } .u-yj{ background: url(../images/u_yj.png) no-repeat center center; &:hover{ background: url(../images/u_3.png) no-repeat center center; } } .u-tz{ background: url(../images/u_tz.png) no-repeat center center; &:hover{ background: url(../images/u_4.png) no-repeat center center; } } .u-sc{ background: url(../images/u_sc.png) no-repeat center center; &:hover{ background: url(../images/u_5.png) no-repeat center center; } } .u-cs{ background: url(../images/u_cs.png) no-repeat center center; &:hover{ background: url(../images/u_6.png) no-repeat center center; } } .u-bdzzl{ background: url(../images/u_bdzzl.png) no-repeat center center; &:hover{ background: url(../images/u_bdzzl_h.png) no-repeat center center; } } .u-wtsb{ color:#767676; } } .tables-hover{ tr:hover{ background: #029be5!important; a{ color:#fff!important; } span{ color:#fff!important; } } } .tables .txt{ max-width: 0; } .tables .txt .tables-bt{ float: left; max-width: 100%; padding-right: 100px; } .tables .pri{ float: left; margin-left: -100px; } .zt-ft{ padding:10px 10px 30px; } .zt-page{ >div{ display: inline-block; } .dropdown-toggle{ color:#333; height: 28px; display: inline-block; vertical-align: middle; } .btn:hover,.btn.active{ color:#fff; background: @blue; border-color: @blue; } .btn,.a-btn{ height: 28px; } .quick{ input{ width: 50px; height: 26px; display: inline-block; vertical-align: middle; text-align: center; border: 1px solid #d3dbe3; } } } .zt-box{ line-height: 1; border-bottom: 1px solid @hui; } .zt-tab{ padding: 10px; border-radius: 3px; overflow: hidden; display: inline-block; a{ position: relative; float: left; padding:0 20px; background: @hui; display: block; height: 30px; line-height: 30px; color:#333; border-right: 1px solid #ccc; &:last-child{ border-right: none; } // &:after { // content: ''; // position: absolute; // right:0px; // top:5px; // height: 20px; // width: 2px; // background: @green; // display: block; // } &:hover, &.active{ color:#fff; background:@green; } } } /* 显示数字和loading */ .show-num-tab{ a{ text-align: center; line-height: initial; min-width: 80px; font-size: 14px; height: 40px; padding: 2px 5px 0; } p{ margin-top: 1px; font-size: 12px; } img{ width: 30px; margin: 1px auto 0; } } .mulu-boxs{ dt{ border-bottom: 1px solid #1a2939; } dd{ } } h2.mulu-list-tit{ font-size: 16px; background: #043553; } h3.mulu-list-tit{ font-size: 14px; background: #04274d; } .mulu-boxs dl.active{ h2.mulu-list-tit{ background: #029be5; color:#fff; >a>i{ color:#fff; } .dropdown{ >i{ width: 30px; text-align: center; height: 100%; display: inline-block; } } } } .navser{ z-index:99; position: absolute; right: 15px; top: 0; color: #029be5; } .mulu-list-tit{ .layut-input{ display: none; i{ color:#ccc; } } } /* 专题监控 end */ /*用户日志*/ .logbox{ padding: 0 20px; } .title-tag{ h4{ height: 36px; line-height: 34px; font-weight: bold; } .calendar{ >i{ font-size: 16px; margin-right: 5px; } .a-btn{ margin-right: 0; margin-left: 6px; height: 24px; line-height: 24px; } } } .log-t{ padding: 10px 0 0; >div{ margin-right: 5px; margin-bottom: 10px; .tm{ display: inline-block; margin-left: 10px; &+.layout-data{ display: inline-block; } } .a-btn{ margin:0 5px 0 0; } } } .vivify{ .w28{ width: 28%; } .w70{ width: 70%; } } .rz-list{ height:475px; overflow-y: auto; } /*有害信息 start*/ .leftnvvbar3,.yichang-push-nav-left{ .bar2-tab{ a{ width: 50%; } } .time-list .time-list-tit{ color: @blue; &.active{ color: #fff; } } } .harmful{ .tool-r{ line-height:50px; padding-right:15px; } .fl-btn:hover,a.active{ color: #fff; background: #5ec45e; } .right-item{ .pull-left{ margin-left: 10px; } } .tables{ .txt{ position: relative; .tz-del{ width: 42px; height: 34px; position: absolute; top: 4px; left: 0; } } .tables-bt{ padding-left: 35px; } .edit{ width: 15px; height: 15px; display: inline-block; margin-left: 10px; vertical-align: middle; cursor: pointer; } tr{ &:hover{ .sshot{ color: #364347; } } } .u-icon{ position: relative; .sshot{ position: absolute; top: 20px; background: #fff; z-index: 2; border: 1px solid #d3dbe3; width: 45px; display: none; li{ cursor: pointer; &:hover{ background: #eef1f7; color: #029be5; } } } } } } .u-bs{ background: url(../images/icon_baosong.png) no-repeat center center; } .u-jt{ background: url(../images/icon_jietu.png) no-repeat center center; } #reset{ .modal-body{ padding: 10px 30px; .reset-time{ margin-top: 10px; display: flex; >label{ width: 100px; } } } } .export-list{ li{ line-height: 50px; input{ width: 200px; } } } /*微博 start*/ .harmful{ .weibo-msg{ position: relative; .tz-del{ position: absolute; top: 15px; left: 0; width: 42px; height: 34px; } .left{ width: 48px; height: 48px; margin-left: 40px; img{ width: 46px; height: 46px; border: 1px solid #d3dbe3; border-radius:100%; } } .right{ margin-left: 95px; text-align: left; position: relative; .user-msg{ a{ color: @blue; font-weight: bold; } .grey{ color: #8ea5c3; } .orange{ color: #ffab0a; } } p{ line-height: 22px; height: 44px; overflow: hidden; display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 2; cursor: pointer; } .remark{ position: absolute; top: 70px; width: 800px; background: #fff; padding: 15px 20px 15px 17px; border: 1px solid @line-color; border-radius: 3px; z-index: 2; -webkit-box-shadow: 0 0 10px 0 rgba(0, 27, 54, 0.1); -moz-box-shadow: 0 0 10px 0 rgba(0, 27, 54, 0.1); -o-kit-box-shadow: 0 0 10px 0 rgba(0, 27, 54, 0.1); -ms-box-shadow: 0 0 10px 0 rgba(0, 27, 54, 0.1); box-shadow: 0 0 10px 0 rgba(0, 27, 54, 0.1); display: none; } } } } .weibo-table{ .txt{ position: relative; .remark{ text-align: left; position: absolute; top: 30px; width: 600px; background: #fff; padding: 15px 20px 15px 17px; border: 1px solid @line-color; border-radius: 3px; z-index: 2; -webkit-box-shadow: 0 0 10px 0 rgba(0, 27, 54, 0.1); -moz-box-shadow: 0 0 10px 0 rgba(0, 27, 54, 0.1); -o-kit-box-shadow: 0 0 10px 0 rgba(0, 27, 54, 0.1); -ms-box-shadow: 0 0 10px 0 rgba(0, 27, 54, 0.1); box-shadow: 0 0 10px 0 rgba(0, 27, 54, 0.1); display: none; } } } /*微博 end*/ /*创建信息 start*/ .yhxx{ .modal-header{ .btn{ margin-right: 20px; } } .huoh{ display: inline-block; width: 80px; height: 30px; line-height: 30px; text-align: center; border: 1px solid #000; color: #000; border-radius: 10px; margin-left: 70%; } .tc-table{ td{ .detection{ display: inline-block; width: 70px; height: 30px; line-height: 30px; text-align: center; border: 1px solid #d6e1e5; border-radius: 5px; margin-left: .8rem; color: #000; } } .yhlx{ .btns{ width: 16rem; color: #000; position: relative; .caret{ position: absolute; right: 5px; top:13px; } } .dropdown-menu{ width: 191px; color: #000; } } } .gjxx{ padding-bottom: 20px; } } /*创建信息 end*/ /*手工添加 start*/ .yhsg{ .main-body{ padding-left: 15px; } .huoh{ display: inline-block; width: 80px; height: 30px; line-height: 30px; text-align: center; border: 1px solid #000; color: #000; border-radius: 10px; margin-left: 70%; } .tc-table { td { .detection { display: inline-block; width: 70px; height: 30px; line-height: 30px; text-align: center; border: 1px solid #d6e1e5; border-radius: 5px; margin-left: .8rem; color: #000; } input{ width: 200px; } .dropdown{ width: 200px; } } } .yhlx{ .btns{ width: 200px; .caret{ position: absolute; right: 5px; top:13px; } } .dropdown-menu{ width: 100%; color: #000; } .times{ width: 200px; display: inline-block; } } .contents{ .m-set-r{ float: right; margin-right: 38%; margin-top: 8px; .dropup, .dropdown { width: 214px; position: relative; .caret{ margin-left: 141px; } .dropdown-menu { width: 100%; } } } } } .analysis-cue{ position: absolute; top: 300px; left: 45%; background: #fff; padding: 30px; box-shadow: 0px 0 4px 0px #337ab7; border-radius:3px; display: none; } /*手工添加 end*/ /*有害信息 end*/ /*上报下发 start*/ /*已接收 start*/ .leftnvvbar3,.yichang-push-nav-left{ .time-list{ .time-list-tit1{ padding:0; a{ padding: 0 20px; color: @blue; display: block; &.active{ color: #fff; } } } } } .sbxf{ .sbxf-top{ display: inline-block; label{ margin-left: 15px; } .layout-data{ display: inline-block; } } .tool-r{ line-height: normal; } .tables{ .cu{ cursor: pointer; } } } .u-icon .u-cz { background: url(../images/handle.png) no-repeat center center; } .handle-msg{ margin-bottom: 15px; label+label{ margin-left: 100px; } .grey{ color:#8ea5c3; } } .tables2{ td{ background: #fff; } .txt{ .tables-bt{ padding: 0; } } } .handle-list{ border-left: 1px solid #d3dbe3; border-right: 1px solid #d3dbe3; .class-fun{ display: none; } >li{ border-bottom: 1px solid #d3dbe3; display: flex; label{ width: 115px; margin: 0; position: relative; span{ position:absolute; top:50%; left:50%; transform:translate(-50%,-50%); } } .right{ border-left: 1px solid #d3dbe3; flex:1; padding: 10px; position: relative; p{ padding: 20px 20px 20px 10px; } .file{ position: absolute; top: 5px; left: 10px; height: 29px; width: 78px; opacity: 0; } .btn{ margin: 0; } .dropdown-menu{ li{ border: none; a{ width: 100%; } } } } } } .proc-list{ padding: 20px 10px; li{ height: 35px; position: relative; .tit{ width: 10px; position: absolute; top: -16px; left: 1px; img{ display: inline-block; } } .tit-t{ top: 3px; left: 0; } .tit-b{ left: 0; } .proc-time{ width:175px; margin-right: 30px; margin-left: 15px; text-align: right; } } } /*已接收 end*/ /*添加报送 start*/ .ret-tree{ border: 1px solid #d6e1e5; width: 523px; height: 270px; padding:10px; } .yhsg .tc-table .file-fj{ position: relative; .file-fj-c{ position: absolute; width: 100px; height: 28px; opacity: 0; } } /*添加报送 end*/ /*已发送 start*/ .u-icon .u-xq { background: url(../images/details.png) no-repeat center center; } .download{ cursor: pointer; img{ display: inline-block; } } /*已发送 end*/ /*信息处置统计 start*/ .vivifyLine{ width:100%; height: 400px; #vivifyLine{ width: 100%; height: 100%; } } .ret{ margin-bottom: 10px; display: none; } .count-table{ display: none; th,td{ border: 1px solid #dee4ea; } thead{ tr:nth-child(2){ th{ background: #e7eaee; } } } .deploy{ display: none; td:first-child{ text-align: left; padding-left:70px; cursor:pointer; } } .deploy1{ display: table-row; } .deploy2{ td:first-child{ padding-left:80px; } } .deploy3{ td:first-child{ padding-left:90px; } } .deploy4{ td:first-child{ padding-left:100px; } } .deploy5{ td:first-child{ padding-left:110px; } } .user-num,.classtly-num,.classtly-num-user{ cursor: pointer; color: @blue; } } .count-table-all{ display: inline-table; } .range{ position: relative; cursor: pointer; display: inline-block; padding:0; label{ margin-left: 0!important; cursor: pointer; padding: 0 10px; } .menuContent{ position: absolute; left: 0; top: 100%; display: none; z-index: 2; margin-top: 2px; .ztree{ margin-top:0; min-width:98px; background: #fff; box-shadow: 0 6px 12px rgba(0, 0, 0, 0.175); font-size: 14px; } } } /*信息处置统计 end*/ /*上报下发 end*/ /*检索 start*/ .main .box{ height:-webkit-calc(100% - 116px); height:-moz-calc(100% - 116px); height:calc(100% - 116px); } .rd-jujiao { width: 70%; min-width:900px; margin: 20px auto; } .rd-jujiao-tit { margin-bottom: 15px; div{ >.dropdown{ margin-left: 20px; } } } .rd-jujiao-tit span.active{ color: #029be5; } .rd-jujiao-tit span { font-weight: bold; margin-right: 10px; cursor:pointer; } .check-list{ display: inline-block; li{ display: inline-block; a{ width: 150px; text-align: center; &.active,&:hover{ font-weight: bold; } } } } .change-list{ display: inline-block; vertical-align: middle; li{ width: 44px; height: 30px; border: 2px solid #fff; cursor: pointer; display: inline-block; margin-left: 10px; position: relative; a{ display: inline-block; width: 28px; height: 16px; position: absolute; top: 50%; left: 50%; transform: translate(-50%,-50%); } &.active,&:hover{ a{ width: 36px; height: 22px; } } &.all-box{ text-align: center; vertical-align: top; line-height: 22px; a{ width: 36px; height: 22px; } &.active,&:hover{ border-color: #06bdf2; a{ color: #06bdf2; } } } &.blue-box{ &.active,&:hover{ border-color: #029be5; } a{ background: #029be5; } } &.green-box{ &.active,&:hover{ border-color: #aee1ae; } a{ background: #aee1ae; } } &.pink-box{ &.active,&:hover{ border-color: #f6abb3; } a{ background: #f6abb3; } } } } .re-jujiao-li>li { float: left; width: 49%; margin-right: 2%; padding: 15px; border: 1px solid #d3dbe3; margin-bottom: 15px; background: rgba(255, 255, 255, 0.8); &:nth-child(2n){ margin-right: 0; } .topmub{ display: inline-block; color: #fff; background: #1389d0; border-radius: 3px; width: 23px; height: 23px; line-height: 23px; text-align: center; float: left; } .re-jujiao-right{ margin-left: 35px; .tit{ font-weight: bold; display: block; margin-bottom: 15px; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; } } } .laiy{ display: inline-block; margin-right: 20px; &:last-child{ margin-right: 0; } } .re-jujiao-tab { text-align: center; margin-top: 10px; } .re-jujiao-tab a { display: inline-block; width: 10px; height: 10px; background: #8ea5c3; border-radius: 50%; margin: 0 10px; } .re-jujiao-tab a.active { background: #029be5; } .topic-page-right { position: absolute; right: 0; top: 260px; font-size: 30px; height: 50px; cursor: pointer; display: none; } .topic-page-left { position: absolute; left: 0; top: 260px; font-size: 30px; height: 50px; cursor: pointer; display: none; } .tables-hover-new{ tr{ &:hover{ background: #93cff3!important; a{ color: unset!important; } .u-icon{ a{ color:inherit; } } } } } @media screen and (max-width: 1400px){ .laiy { margin-right: 5px; } } @media screen and (max-width: 1200px){ .check-list li a { width: auto; } .rd-jujiao-tit div > .dropdown { margin-left: 5px; } .change-list li.all-box{ margin-left: 0; } .change-list li{ margin-left: 5px; } } @media screen and (max-height: 800px){ .re-jujiao-li > li{ margin-bottom: 10px; } } @media screen and (max-height: 780px){ .re-jujiao-li > li{ margin-bottom: 5px; } } @media screen and (max-height: 750px){ .re-jujiao-li > li{ padding: 10px; } } /*检索 end*/ /* 宜昌推送 */ .yichang-push{ .yichang-push-nav-left{ left: auto; width: auto; position: relative; top:auto; min-width: initial; height: 100%; padding:20px 0; .left-box{ width: 300px; } .newztfx-left-btn{ display:block; width:33px; height:90px; position:absolute; top:50%; right:-32px; margin-top:-45px; background:url(../images/btn-right.png) center center no-repeat; } } .main{ margin-left: 300px; .icon-submit{ background: url(../images/icon_submit_b.png) no-repeat center center; } .icon-submit:hover{ background: url(../images/icon_submit_y.png) no-repeat center center; } .icon-check-eye{ background: url(../images/icon_eye_b.png) no-repeat center center; } .icon-check-eye:hover{ background: url(../images/icon_eye_y.png) no-repeat center center; } } .modal-header{ position: relative; } .push-back-arrow{ position: absolute; top: 0; right: 0; width: 40px; height: 40px; img{ width: 100%; height: 100%; } } .tc-table{ th{ width: 130px; } td{ position: relative; } .form-control{ color: #333; } textarea{ resize: none; } .right{ position: relative; } } } .yichang-push-modal{ .handle-list{ label{ text-align: center; span{ position: inherit; left: auto; top: auto; } .text-mid{ display: inline-block; vertical-align: middle; width: 0; height: 100%; } } .form-control{ width: 180px; color: #333; } textarea.form-control{ width: 100%; } } } .yichang-push,.yichang-push-modal{ .right{ .file{ position: absolute; top: 3px; left: 6px; height: 29px; width: 78px; opacity: 0; } .text-astrict{ right: 15px; bottom: 15px; } } .ip-g{ background: #eef1f7; } .cut-pic{ display: inline-block; width: 30px; height: 30px; border: 1px solid #d3dbe3; margin-left: 5px; vertical-align: middle; position: relative; img{ width: 100%; height: 100%; } &::after{ content: ' '; position: absolute; top: -6px; right: -6px; width: 12px; height: 12px; background: url(../images/icon_close_r.png) no-repeat center center; background-size: 100%; cursor: pointer; } } .icon-cut{ display: inline-block; width: 24px; height: 24px; background: url(../images/icon_cutp.png) no-repeat center center; margin-left: 5px; vertical-align: middle; cursor: pointer; } .icon-dnl{ display: inline-block; width: 20px; height: 13px; background: url(../images/icon_download_b.png) no-repeat center center; margin-left: 5px; vertical-align: middle; cursor: pointer; } .icon-daytime-wrap{ position: relative; display: inline-block; &::before{ content: " "; position: absolute; right: 10px; width: 22px; height: 28px; background: url(../images/u-day.png) no-repeat center center; background-size: 80%; } } .btn-bg-lg{ background: -webkit-linear-gradient(top, #ffffff , #f0f3f6); /* Safari 5.1 - 6.0 */ background: -o-linear-gradient(bottom, #ffffff, #f0f3f6); /* Opera 11.1 - 12.0 */ background: -moz-linear-gradient(bottom, #ffffff, #f0f3f6); /* Firefox 3.6 - 15 */ background: linear-gradient(to bottom, #ffffff , #f0f3f6); /* 标准的语法 */ border-radius: 2px; color: #333; border: 1px solid #d6e1e5; } .zt-page{ .btn{ &.btn-bg-lg{ color: #333; border: 1px solid #d6e1e5; } &.at{ background: #35afea; color: #fff; border-color: #35afea; } } } .text-astrict{ position: absolute; font-size: 12px; } } /* 宜昌推送 */ /* 预警范围管理 */ .yj-manage{ .yj-switch{ position: relative; width: 50px; height: 20px; line-height: 20px; background: #779bb5; border-radius: 24px; cursor: pointer; display: inline-block; vertical-align: middle; margin-top: -2px; i{ position: absolute; left: 2px; top: 2px; width: 16px; height: 16px; background: #fff; border-radius: 50%; } span{ color: #fff; margin-left: 15px; line-height: 20px; font-size: 12px; } } .change-i{ background: #029be5; i{ left: 32px; } span{ margin-left: -15px; } } .tables{ tr{ height: 50px; .fa-plus-square-o{ display: none; } &:last-child{ .fa-plus-square-o{ display: inline-block; } } .title{ cursor: pointer; } } label{ position: relative; margin: 0 5px; .yj-tips{ display: none; position: absolute; left: 50%; bottom: -40px; padding: 5px; width: 210px; color: #fff; text-align: center; background: rgba(0, 109, 175, .8); margin-left: -105px; border-radius: 3px; z-index: 1; &::after{ content: ''; position: absolute; left: 50%; bottom: 100%; width: 0; height: 0; border: 3px solid transparent; border-bottom-color: rgba(0, 109, 175, .8); margin-left: -3px; } } &:hover{ .yj-tips{ display: block; } } } } } .yj-modal{ .yj-modal-body{ padding: 0 15px; .zt-tab{ width: 100%; border-bottom:0; border-top:1px solid #d3dbe3; a{ margin-right: 5px; } } } .yj-select-wrap{ border: 1px solid #d3dbe3; border-radius: 3px; } .yj-search{ padding: 10px 5px; background: #f2f2f2; input{ display: inline-block; width: 170px; height: 32px; padding: 5px 15px; border-radius: 3px; border-right: 0; vertical-align: middle; } span{ display: inline-block; width: 50px; height: 32px; text-align: center; font-size: 22px; background: #029be5; color: #fff; margin-left: -5px; border-radius: 0 3px 3px 0; vertical-align: middle; } } .jstree-wrap{ height: 250px; } .yj-project-wrap{ padding: 15px 10px; background: #ebf3f6; border: 1px solid #d3dbe3; border-radius: 3px; margin: 15px 0 30px; label{ margin-right: 5px; } } .dropdown-toggle{ color: #333; } } /* 预警范围管理 */ /*过滤列表 start*/ .filter-table{ .txt { position: relative; .tables-bt{ padding:0; margin: 0; } .remark{ width: 550px; color: #333; position: absolute; top: 25px; background: #fff; padding: 15px 20px 15px 17px; border: 1px solid #d3dbe3; border-radius: 3px; z-index: 2; display: none; .box-shadow(0,0,10px,0,rgba(0, 27, 54, 0.1)); } } } /*过滤列表 end*/ /* 标签3.0 start */ .bq-tip{ line-height: 30px; display: inline-block; .circle-answer{ margin-left: 0; } &.border-bt-dash{ border-bottom: 1px dashed #d6e1e5; padding: 10px 0; margin: 0 10px; display: block; } } .bq-hdr{ >a,>div{ display: inline-block; vertical-align: middle; margin: 0!important; margin-left:10px!important; } } .gj-title{ font-weight: bold; margin-bottom: 10px; margin-left: 15px; } .gj-sets{ background: #f6f7f9; padding: 10px 0; } .bq-gj{ margin-bottom: 40px; } .bd-tab-tree,.bd-tab-box{ padding: 15px; border: 1px solid #d6e1e5; height: 300px; } .bd-tab-box{ a{ position: relative; margin: 5px; .u-close{ position: absolute; right:-6px; top: -6px; width: 14px; height: 14px; background: #f76a6a; display: inline-block; text-align: center; line-height: 14px; border-radius:50%; color:#fff; } } } /* 标签3.0 end */ /*评论模式 start*/ .comment{ padding:60px 200px 0 200px; } .xq-cont{ height:calc(~'100% - 122px'); } .comment-box{ border-top:1px solid #cdcdcd; position:relative; margin-bottom: 50px; padding: 0 10%; .comment-title{ font-size:16px; background:#fff; padding:0 15px; line-height:24px; position:absolute; top:-12px; left:50%; transform: translateX(-50%); } } .comment-list{ li{ padding:20px 0; &+li{ border-top:1px solid #e8e8e8; } .comment-name{ font-size:16px; color:#555; font-weight:blod; display:inline-block; } .comment-time{ color:#999; font-size:12px; margin-left:10px; } .comment-text{ line-height:21px; } } } /*评论模式 end*/<file_sep>/app/less/other/ser.less /* 新版检索-元搜索 start */ .js-con-box .js-search-box .btn{ border-radius:0; } .search-art{ } .ser-tabs{ padding: 0!important; .boxbg{ background: #eef1f7; } .u-tabs-g { display: none; &.tabs-on{ display: block; } a{ float: left; min-width:86px; padding: 0 10px; height: 30px; line-height: 30px; display: inline-block; text-align: center; background: #d3dbe3; margin: 8px 0 8px 15px; border-radius: 2px; color:#364347; &.on{ background: @green; color:#fff; } } } } .tem-box{ border-top:0; background: #fff; .bt-line{ line-height: 1; padding: 13px; .tab-item{ width: 100%!important; margin-bottom: 0; height: auto; } } .fil-check{ label{ margin-right: 25px; } } .m-sort{ display: inline-block; margin-right: 10px; .dropdown-toggle{ color:#666; } } .js-tab-list dl{ margin:0 5px; } .js-tab-list .hd-title h3 a{ .txt; } .js-tab-list .hd-title{ padding-right: 0; } .sim{ color:@blue; } .news-rf .u-office{ margin-right: 15px; } .wb-list .list-r{ margin-left: 68px; } .wb-list .gril { padding-right: 0; margin-right: 0; } .user{ vertical-align: top; } .u-time{ float: left; color:#8ea5c3; } .wb-list .pic span{ width:auto; } .new-weibo .weibo-p a{ text-decoration:none; } .new-weibo .news-details{ padding: 15px; } .u-forward{ float: right; color:#8ea5c3; span{ margin-left: 10px; } .fa{ margin-right: 3px; &.fa-commenting-o{ margin-top: -3px; } } } .weibo-p{ margin-bottom: 10px; } .weibo .wb-list .list-r h3{ padding-right: 150px; margin-right: -150px; float: none; overflow: inherit; white-space: nowrap; text-overflow: clip; } .weibo .wb-list{ padding: 15px; } .gril a.fz16{ max-width:60%; } .gril-add{ min-width:55px; height: 24px; padding: 0 10px; display: block; font-size: 12px; background: #35afea; line-height: 24px; text-align: center; color:#fff; border-radius:3px; &:hover{ background: @bule+#111; } } .u-ewm{ position: relative; width: 31px; height: 24px; background: url(../images/ewm.png) no-repeat; -webkit-background-size: contain; background-size: contain; display: inline-block; margin-right: 10px; .dropdown-ewm{ display: none; z-index:11; position: absolute; bottom: -150px; left: 50%; margin-left: -60px; width: 120px; height: 150px; padding-top: 5px; >div{ padding: 10px; background: #fff; } } .sys{ text-align: center; font-size: 12px; font-weight: normal; margin-bottom: 6px; } } } .add-bz-tag,.add-lang-modal{ border: 1px solid #d6e1e5; padding: 10px; border-radius:3px; height: 200px; overflow: hidden; } .add-lang-modal{ height: 350px; } .pdlr10{ padding-left: 10px!important; padding-right: 10px!important; } @media screen and (max-width: 1300px){ .tem-box{ .gril-add{ min-width:45px; height: 20px; padding: 0 5px; display: block; font-size: 12px; background: #35afea; line-height: 20px; text-align: center; color:#fff; border-radius:3px; &:hover{ background: @bule+#111; } } .u-ewm{ width: 28px; height: 20px; } } .ser-tabs .u-tabs-g a{ min-width: 74px; margin: 6px 0 6px 12px; } .tem-box .bt-line{ padding: 9px; } .gril a.fz16{ max-width:45%; } .tem-box .wb-list .list-l .user { width: 35px; height: 35px; } .tem-box .wb-list .list-r { margin-left: 50px; } .tem-box .wb-list .list-r h3{ font-size: 14px; } .wb-list .list-r h3 em{ margin:-2px 0; } .tem-box .weibo .wb-list{ padding: 9px; } } /* 新版检索-元搜索 end */ /* 新版检索-本地检索 start*/ .add-lang{ .btn{ margin:0 0 5px; } } .lang-list{ li{ .tan-title{ i{ width: 20px; height: 20px; background: #35afea; display: inline-block; border-radius:50%; color:#fff; font-size: 12px; text-align: center; line-height: 20px; margin-left: 10px; -webkit-transform: scale(0.9); -moz-transform: scale(0.9); -ms-transform: scale(0.9); -o-transform: scale(0.9); transform: scale(0.9); } } .tan-txt{ line-height: 24px; border: 1px solid #d3dbe3; background: #fff; margin-bottom: 5px; padding: 5px; color:#35afea; } } } .bill-box{ height: 100%; padding: 20px 5%; tr .u-words{ padding-left: 30px; } .text-left{ text-align:left!important; } .list-box{ border: 1px solid @line-color; float: left; width: 29.333333%; margin: 0 2% 20px; .u-txt{ width: 100%; .txt; display: block; } .icon-s{ display: inline-block; display: none; vertical-align: top; width: 18px; height: 18px; color: #636363; font-size: 18px; font-size: 20px; // margin: 0 auto; // background: url(../images/icon_s.png) no-repeat center center; // -webkit-background-size: contain; // background-size: contain; // cursor:pointer; } h4{ padding: 10px; font-weight: bold; background: #eef1f7; color: #fff; i{ color:#fff; font-size: 14px; margin-right: 5px; } } .bg1{ background: #41c6be; } .bg2{ background: #67aae8; } .bg3{ background: #fc7e72; } .bg4{ background: #f6aa32; } .bg5{ background: #67aae8; } .bg6{ background: #fc7e72; } .bg7{ background: #41c6be; } } .sec-box{ margin-right: 0!important; } .fil-change-arrow{ width: 60%; position: relative; padding-right: 38px; .u-arrow{ position: absolute; right: 0; top: 1px; } .fil-change{ width: 100%; overflow: hidden; height: 20px; display: block; position: relative; .u-box{ width: 1000000%; position: absolute; left: 0; top: 0; } } } .fil-change{ display: inline-block; a{ position: relative; float: left; padding: 0 15px; color:#fff; &.active { &:after { content: ''; content: ''; position: absolute; left: 0; top: 3px; width: 0; height: 0; border-top: 5px solid transparent; border-left: 7px solid #fff; border-bottom: 5px solid transparent; } } } } .u-arrow{ display: inline-block; i{ width: 0; height: 0; border-top: 7px solid transparent; border-bottom: 7px solid transparent; display: inline-block; cursor:pointer; opacity:.5; &:hover{ opacity:1; } } .arrow-l{ border-right: 10px solid #fff; } .arrow-r{ border-left: 10px solid #fff; } } .list-table{ height: 406px; overflow:hidden; .list-num{ width: 16px; height: 16px; line-height: 16px; font-size: 12px; text-align: center; color:#333333; display: inline-block; background: #cfd5de; &.top{ color:#fff; background: @red; } } } .table{ margin-bottom: 0; } .table > thead > tr > th{ border-bottom: 1px solid #ddd; } .table > caption + thead > tr:first-child > th, .table > colgroup + thead > tr:first-child > th, .table > thead:first-child > tr:first-child > th, .table > caption + thead > tr:first-child > td, .table > colgroup + thead > tr:first-child > td, .table > thead:first-child > tr:first-child > td{ text-align: center; font-size: 14px; } .table > thead > tr > th, .table > tbody > tr > th, .table > tfoot > tr > th, .table > thead > tr > td, .table > tbody > tr > td, .table > tfoot > tr > td{ text-align: center; vertical-align: middle; font-size: 14px; max-width:0; line-height: 20px; padding: 10px 0; } .pic span{ height: 50px; display: inline-block; } .wb-list{ padding: 0 15px; } .ft-forward span{ display: inline-block; img{ display: inline-block; } } .weibo-p{ margin-bottom: 5px; } .wb-list > ul > li{ margin-bottom: 0; padding: 10px 0; } .hot-topic.wb-list{ .list-l .user{ width: 80px; height: 80px; border-radius:0; } .list-r{ margin-left: 90px; h3{ height: 22px; font-size: 14px; } } .user img{ border:none; } .weibo-p{ .txtmore(2); } .weibo-tit{ padding-top: 0; } .ft-forward{ em{ color:@blue; } } } } @media (max-width: 1250px) { .bill-box .list-box{ width: 46%; } } /* 新版检索-本地检索 end */ /* 全网热点新版 start */ .g-new-hot{ height: 100%; .zt-box{ background: #fff; border-bottom: none; a{ margin-right: 10px; } .btn-export{ width: 80px; height: 30px; border: 1px solid #d3dbe3; margin-top: 12px; margin-right: 15px; text-align: center; line-height: 30px; border-radius: 2px; background: -webkit-linear-gradient(top, #ffffff , #f0f3f6); /* Safari 5.1 - 6.0 */ background: -o-linear-gradient(bottom, #ffffff, #f0f3f6); /* Opera 11.1 - 12.0 */ background: -moz-linear-gradient(bottom, #ffffff, #f0f3f6); /* Firefox 3.6 - 15 */ background: linear-gradient(to bottom, #ffffff , #f0f3f6); /* 标准的语法 */ } } .bill-box{ padding: 20px 10px 0; } .bill-box .list-box { width: 33.33333%; margin: 0 0 20px; padding: 0 10px; border:none; } .bill-box .list-table{ height: 440px; background: #fff; border-radius: 0 0 4px 4px; th{ padding: 5px 0!important; } } .bill-box .list-box h4{ position: relative; border-radius:4px 4px 0 0; overflow: hidden; line-height: 30px; padding: 5px 34px 5px 10px; height: 40px; } .icon-baidu{ width: 20px; height: 30px; background: url(../images/icon_baidu.png) no-repeat center center; display: inline-block; vertical-align: middle; margin-top: -2px; } .icon-toutiao{ width: 20px; height: 30px; background: url(../images/icon_toutiao.png) no-repeat center center; display: inline-block; vertical-align: middle; margin-top: -2px; } .icon-zhihu{ width: 20px; height: 30px; background: url(../images/icon_zhihu.png) no-repeat center center; display: inline-block; vertical-align: middle; margin-top: -2px; } .icon-hexin{ width: 20px; height: 30px; background: url(../images/icon_hexin.png) no-repeat center center; display: inline-block; vertical-align: middle; margin-top: -2px; } .bill-box .fil-change{ a{ font-size: 14px; padding: 0 10px; height: 30px; line-height: 26px; border-radius:30px; border:1px solid transparent; &.current,&:hover{ background: rgba(0,0,0,.2); border-color:rgba(255,255,255,0.6); } } } .bill-box .fil-change-arrow .u-arrow{ position: static; } .fil-change-box{ position: relative; padding: 0 20px; height: 30px; display: inline-block; vertical-align: middle; .u-arrow .arrow-l{ position: absolute; left: 0; top: 7px; } .u-arrow .arrow-r{ position: absolute; right: -2px; top: 7px; } } .bill-box .fil-change-arrow .fil-change{ height: 30px; } .icon-daochu{ position: absolute; right:10px; top:9px; width: 20px; height: 20px; background: url(../images/ic_daochu.png) no-repeat; display: inline-block; vertical-align: middle; } .operate-box{ width: 20px; height: 20px; margin: 0 auto; position: relative; .operate-more{ width: 25px; text-align: center; color:#8ea5c3; cursor: pointer; font-size: 18px; } .operate-btn{ display: none; font-size: 20px; border-radius: 1px; padding: 0 6px 0px; width: 100%; z-index: 2; color:#8ea5c3; } .operate{ display: none; background: #1389d0; position: absolute; padding: 4px; right: -9px!important; top: 35px; width: 115px; border-radius: 3px; li{ float: left; } a{ color:#fff; display: inline-block; width: 35px; text-align: center; font-size: 12px; &:hover{ background: rgba(255,255,255,.2); } span{ display: block; } } .arrow-t { content: ""; width: 0; height: 0; border-left: 10px solid transparent; border-right: 10px solid transparent; border-bottom: 10px solid #1389d0; position: absolute; top: -10px; right: 8px; } .arrow-b { content: ""; width: 0; height: 0; border-left: 10px solid transparent; border-right: 10px solid transparent; border-top: 10px solid #1389d0; position: absolute; bottom: -10px; right: 8px; display: none; } } } } .g-new-hot{ .bill-box .list-table.hexin th{ padding: 0!important; } .u-yuan{ width: 20px; height: 20px; background: url(../images/icon_yuan.png) no-repeat right center; display: inline-block; vertical-align: middle; } .u-hide{ display: none; } .u-txt-more{ margin-left: 6px; display: inline-block; } .bill-box .list-table.hexin{ thead{ th{ } } .u-sort{ vertical-align: top; } td{ .hexin-p{ .u-txt{ max-width: 100%; width:auto; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; display: inline-block; float: left; padding-right: 25px; } .u-yuan{ float: left; margin-left: -25px; } } .text-left{ } .u-txt-ft{ font-size: 12px; color:#909294; } } } .zh-hot{ position: relative; width: 100%; height: 4px; background: #e7ecf3; display: block; i{ position: absolute; left:0; top:0; width:auto; height: 100%; background: #fc7e72; display: block; } } .bill-box .table{ display: none; &.active{ display:table; } } } .ex-num{ height: 30px; width: 85px!important; line-height: 30px; border-color:#8ea5c3; display: inline-block; } .ex-text{ font-size: 12px; color:#999; line-height: 30px; margin-left: 10px; } .top-title{ a{ font-size: 14px; color: #1d1d1d; font-weight: bold; display: block; height: 22px; overflow: hidden; } } .u-laiy{ margin-right: 20px; } .bill-box .hot-topic.wb-list.day-hot{ .weibo-p{ a{ color:#2b2a2a; text-decoration:none; &:hover{ color:#06bdf2; } } } } .bill-box .hot-topic.wb-list.day-hot .list-l .user{ width: 80px; height: 60px; img{ height: 100%; } } .bill-box .wb-list > ul > li.ope-box{ padding-right: 20px; position: relative; .operate-box{ position: absolute; right: -7px; top: 42px; text-align: center; } } @media (max-width: 1250px) { .g-new-hot{ .bill-box .fil-change-arrow{ width:50%; } } .g-new-hot .bill-box .list-box{ width: 50%; } } /* 一键导出 */ .export-all-list-wrap{ padding-left: 80px; .export-all-list{ position: relative; margin-bottom: 15px; .export-all-list-title{ position: absolute; left: -65px; top: 4px } label{ margin-right: 40px; } .list-bg-g{ padding: 5px 10px; background: #f4f7fa; } } } .add-data{ border: 0 none; border-radius: 4px; background: #019bf0; color: #fff; padding: 2px 12px; } .mt10{ margin-top: 10px; } .mr30{ margin-right: 30px; } #material2{ .tc-table th{ width: 120px; } .modal-body{ max-height: 640px; } } .placeholder-c { background-color: #fff !important; } .placeholder-c::-webkit-input-placeholder{ color: #8fa6c5; } /* 全网热点新版 end */ <file_sep>/app/html/重庆重点对象-重点事件详情.html <%- include('../templates/head') %> <body> <%- include('../templates/header') %> <div class="content case cqzdr"> <%- include('../templates/zddx-zdsj-left') %> <div class="zddx-right zddx-eventDetails"> <div class="zddx-right-box"> <div class="breadCrumb"> <a href="#">重点人</a>/ <a href="#">关注情况</a>/ <a href="#">关注情况详情</a> </div> <div class="zddx-right-title detail-rightTit"> <div class="title-aleft"> <div class="detail-navBox"> <ul> <li class="active"> <a href="重庆重点对象-重点事件详情.html"> <i class="sj-xiangqing"></i> 事件详情 </a> </li> <li> <a href="重庆重点对象-重点事件详情2.html"> <i class="sj-xinxi"></i> 事件信息 </a> </li> </ul> </div> </div> <div class="title-aright pull-right"> <a href="../html/重庆重点对象-重点事件-暴乱事件.html" class="btn">返回</a> </div> </div> <div class="bottom-detailCont rollHeight2"> <table class="detail-table"> <tr> <td> <p class="p1">标题</p> <p class="p2">中共重庆市委 重庆市人民政府</p> </td> <td> <p class="p1">创建人</p> <p class="p2">易烊千玺</p> </td> <td> <p class="p1">创建时间</p> <p class="p2">2018-10-12 10:15</p> </td> </tr> <tr> <td> <p class="p1">涉及地区</p> <p class="p2">重庆</p> </td> <td> <p class="p1">事件时间</p> <p class="p2">2018-10-21 10:00</p> </td> <td> <p class="p1">事件分组</p> <p class="p2">事件组</p> </td> </tr> <tr> <td colspan="3"> <p class="p1">事件描述</p> <p class="p2">组件拖出来特别多一个一个删麻烦,这个问题,首先将组件拖入画布中,然后按住“shift”键,用鼠标点击要使用的组件,使该组件取消选择。再点击delete键, 即可删除剩余不需要使用的组件。这里是500个字</p> </td> </tr> <tr> <td colspan="3"> <p class="p1">附件:</p> <ul class="b-fileList"> <li> 照片09987554如55255.jpg <a href="#" class="down"></a> </li> </ul> </td> </tr> </table> </div> </div> </div> </div> <%- include('../templates/foot') %> <file_sep>/dist/js/global.js (function($){ $.fn.autoTextarea = function(options) { var defaults={ maxHeight:null, minHeight:$(this).height() }; var opts = $.extend({},defaults,options); return $(this).each(function() { $(this).bind("paste cut keydown keyup focus blur",function(){ var height,style=this.style; this.style.height = opts.minHeight + 'px'; if (this.scrollHeight > opts.minHeight) { if (opts.maxHeight && this.scrollHeight > opts.maxHeight) { height = opts.maxHeight; style.overflowY = 'scroll'; } else { height = this.scrollHeight; style.overflowY = 'hidden'; } style.height = height + 'px'; } }); }); }; var hight=$(window).height(); var h=hight-149; var h2=hight-188; var h3=hight-416; var h4=hight-133; var h5=hight-213; var h6=hight-130; var h7=hight-147; var h8=hight-147; $('#zdr-jbxx').height(h7); $('#zdr-jbxx2').height(h8); $('#g-zlm-zdzdwb').height(h6); $('#browserHeight').height(h5); $('.g-zlm-wbReport').height(h4); $('#g-zlm-weibo').height(h3); $('.browserHeight').height(h); $("#ciyun-box").height(h2); })(jQuery);//文本域 $(document).ready(function(){ //模块js初始化 commonJs.fn.init(); $('.checkout').click(function(){ //$('.gjxx').slideToggle(); var txt=$(this).text(); if(txt=="切换为高级版"){ $('.gjxx').css('display','block'); $(this).html("切换为精简版"); } else{ $('.gjxx').css('display','none'); $(this).html("切换为高级版"); } }); var unPi = $(".unPi"); unPi.each(function(index, element) { $(this).click( function() { var strSrc = $(this).find('img').attr("src"); if(strSrc.indexOf("f")!=-1) { $(this).find('img').attr("src","../images/icon_on.png"); $(this).next('.checkbtn').show(); } else { $(this).find('img').attr("src","../images/icon_off.png"); $(this).next('.checkbtn').hide(); } } ); });//不匹配按钮 //设置文本域高度 $(".allTextarea").autoTextarea({ maxHeight:126, minHeight:62 }); $(".objArea").autoTextarea({ maxHeight:126, minHeight:62 }); }); var commonJs = $(window).commonJs || {}; commonJs.fn = { init : function(){ var _this = this; _this.dropdown(); }, /* 下拉菜单 */ dropdown : function () { $('.dropdown,.dropup').on('click','.dropdown-menu li a', function(event) { var txt = $(this).text(); if ($(this).parents('.dropdown-menu').siblings('.dropdown-toggle').find('em').hasClass('name')){ $(this).parents('.dropdown-menu').siblings('.dropdown-toggle').find('.name').text(txt + ' '); } $(this).parents('.dropdown-menu').siblings('.dropdown-toggle')[0].childNodes[0].nodeValue = txt + ' '; if($(this).parents('.dropdown-menu').siblings('.border-r').children().hasClass('upcaret')){ $(this).parents('.dropdown-menu').siblings('.border-r').find('.upcaret').addClass('caret').removeClass('upcaret'); } }); } }; // 时间控件 var date = '%y-%M-{%d}'; var DatePicker = { //联动模式1 dateId1: function (){ var d02=$dp.$('d02'); WdatePicker({ skin:'whyGreen', dateFmt: 'yyyy-MM-dd', alwaysUseStartDate: true, readOnly:true, onpicked:function(){ if(!d02.value) d02.click(); }, minDate:'%y-%M-{%d-180}', maxDate: date }); }, dateId2: function (){ var d01 = $dp.$('d01'); WdatePicker({ skin:'whyGreen', dateFmt: 'yyyy-MM-dd', alwaysUseStartDate: true, readOnly:true, onpicked:function(){ if(!d01.value){ date = '#F{$dp.$D(\'d02\')}'; d01.click(); return date; } }, minDate:'#F{$dp.$D(\'d01\')}', maxDate:'%y-%M-{%d}' }); }, //联动模式1 dateId3: function (){ var d04=$dp.$('d04'); WdatePicker({ skin:'whyGreen', dateFmt: 'yyyy-MM-dd', alwaysUseStartDate: true, readOnly:true, onpicked:function(){ if(!d04.value) d04.click(); }, minDate:'%y-%M-{%d-180}', maxDate: date }); }, dateId4: function (){ var d03 = $dp.$('d03'); WdatePicker({ skin:'whyGreen', dateFmt: 'yyyy-MM-dd', alwaysUseStartDate: true, readOnly:true, onpicked:function(){ if(!d03.value){ date = '#F{$dp.$D(\'d04\')}'; d03.click(); return date; } }, minDate:'#F{$dp.$D(\'d03\')}', maxDate:'%y-%M-{%d}' }); }, //正常模式 dateId5: function (){ WdatePicker({ skin:'whyGreen', dateFmt: 'yyyy-MM-dd', alwaysUseStartDate: true, readOnly:true, maxDate: date }); }, // 联动时分秒 dateId6: function (){ var d07=$dp.$('d07'); WdatePicker({ skin:'whyGreen', dateFmt: 'yyyy-MM-dd H:mm:ss', alwaysUseStartDate: true, readOnly:true, onpicked:function(){ if(!d07.value) d07.click(); }, minDate:'%y-%M-{%d-180}', maxDate: date }); }, dateId7: function (){ var d06 = $dp.$('d06'); WdatePicker({ skin:'whyGreen', dateFmt: 'yyyy-MM-dd H:mm:ss', alwaysUseStartDate: true, readOnly:true, onpicked:function(){ if(!d06.value){ date = '#F{$dp.$D(\'d07\')}'; d06.click(); return date; } }, minDate:'#F{$dp.$D(\'d06\')}', maxDate:'%y-%M-{%d}' }); }, }; $(function(){ lay('.test-item').each(function(){ laydate.render({ elem: this, type: 'datetime', range: true }); }); function conheight(){ var winHeight = $(window).height(), headerHeight = $('.header').height(), leftbtnHeight=$('.f-btn').height(), tabiconHeight=$('.tab-item').height(), searchHeight=$('.h-search').height(), tabBoxHeight = $('.tab-box').height(), sechHeight = $('.sech-box').height(), keyHeight = $('.key-box').height(), poHeight=$('.po-infmt').height(), btHeight=$('.bt-line').height(), ztHeight=$('.zt-ft').height(); var main = winHeight-headerHeight; var mainBox = main-tabBoxHeight; var weiboh=main-poHeight-btHeight-ztHeight-70; $('.content,.leftnavbar').height(main); // 整个页面高度 // $('.main,.nav-list').height(main); $('.main-box').height(mainBox-40); //右边内容区带有padding的高度 $('.main-box2').height(mainBox); //右边内容区没有padding的高度 $('.content1 .nav-list').height(main-51); // 配置页左边导航高度 $('.j-height').height(mainBox-33); //影响力分析 // $('.right-infl').css('max-height',main-poHeight-40); //影响力分析 $('.tree-ul').height(main-tabiconHeight-searchHeight-leftbtnHeight-62); $('.left-list').height(main-tabiconHeight-searchHeight-52); var navtop=$('.nav-top').height(); $('.weibo-nav').height(main-searchHeight-leftbtnHeight-navtop-78); $('.nav-wrap').height(main-2); $('.wb-list.nicescroll').css('max-height',weiboh); // $('.cont').height(weiboh+20); // $('.zddx .right-infl').css('max-height',main-30); // $('.zddx .wb-list').css('max-height',main-btHeight-ztHeight-50); var mainbox2 = main - sechHeight - keyHeight; var realH = main-40; var mainh=main-tabBoxHeight-20; $('.main').height(main); $('.list.nicescroll').css('max-height',mainh-ztHeight-20); // $('.zddx .list').css('max-height',mainh-ztHeight-10); var tableh=$('.zddx .tables').height(); $('.zddx .nothing').css('height',mainh-tableh-ztHeight-10); $('.list1.nicescroll').css('max-height',main-btHeight-ztHeight-70); $('.weixin').css('max-height',main-btHeight-50); $('.Real-hot,.mulu-boxs').height(realH); $('.Real-hot, .xg-Article').height(realH); $('.time-boxs').height(realH-130); // $('.cbfx-box,.cbfx-box .weixin').css('max-height',main); // $('.cont').css({ // 'max-height': main, // 'height': 'auto' // }); $('.zddx .list1.nicescroll').css('max-height',mainh-ztHeight-65); $('.gzh-box').css('max-height',main); var bth=$('.bt-line').height(); $('.gzh-box .weixin').css('max-height',mainh-bth); var poh=$('.po-infmt').height(); // $('.yxlfx').css('max-height',mainh-bth-poh-32); // $('.yxlfx .cont').css('max-height',mainh-bth-poh-45); $('.js-con-box').height(main-50); var $conUl = $('.js-con-box-ul').height(), $conLi1 = $('.js-con-box-ul').children('li').eq(0).height(), $conLi2 = $('.js-con-box-ul').children('li').eq(1).height(), $conLi3 = $('.js-con-box-ul').children('li').eq(2).height(), $infmtH1 = $('.js-con-box-ul').find('.infmt-source-h').height(); $('.realm-name-list-box').height($conUl-$conLi1-$conLi2-$conLi3-$infmtH1-182); $(window).resize(function(){ var $conUl = $('.js-con-box-ul').height(), $conLi1 = $('.js-con-box-ul').children('li').eq(0).height(), $conLi2 = $('.js-con-box-ul').children('li').eq(1).height(), $conLi3 = $('.js-con-box-ul').children('li').eq(2).height(), $infmtH1 = $('.js-con-box-ul').find('.infmt-source-h').height(); $('.realm-name-list-box').height($conUl-$conLi1-$conLi2-$conLi3-$infmtH1-182); }); // var xbjsHeight=$('.xbjs-right-top').height(); // jiansuo = main-xbjsHeight-ztHeight-36; // $('.xbjs-right-middle.nicescroll').css('max-height',jiansuo); var newqjrighth=$('.newqj-right').height(), newqjtitleh=$('.newqj-title').height(), screenboxh=$('.screen-box').height(), newqjfooth=$('.newqj-foot').height(); $('.newqj-right-list-box').height(newqjrighth-newqjtitleh-screenboxh-newqjfooth-48); } conheight(); $(window).resize(function(event) { conheight(); $('.more').insertAfter($('.nav>ul>li').eq(-1)); $('.nav2>ul>li').insertBefore($('.more')); more(); if(!$('.js-box').is(':hidden')){ $('.xbjs-right-box').css('padding-left',$('.js-box').width()); } var winHeight = $(window).height(), headerHeight = $('.header').height(); var main = winHeight-headerHeight; $('.js-con-box').height(main-50); }); // 头部下拉菜单 hddown(); function hddown(){ $('.header .nav>ul>li').on('click', function() { if($(this).find('i').hasClass('fa-caret-down')){ $(this).find('i').addClass('fa-caret-up').removeClass('fa-caret-down'); $(this).find('ul').slideDown('fast'); $(this).addClass('active'); var lisib=$(this).siblings().find('ul').parent(); lisib.removeClass('active'); lisib.find('ul').slideUp('fast'); lisib.find('i').addClass('fa-caret-down').removeClass('fa-caret-up'); } else if($(this).find('i').hasClass('fa-caret-up')){ $(this).find('i').addClass('fa-caret-down').removeClass('fa-caret-up'); $(this).find('ul').slideUp('fast'); $(this).removeClass('active'); } }); $('.nav2>ul>li').on('click', function() { if($(this).find('i').hasClass('fa-caret-down')){ $(this).find('i').addClass('fa-caret-up').removeClass('fa-caret-down'); $(this).find('ul').slideDown('fast'); var lisib=$(this).siblings().find('ul').parent(); lisib.find('ul').slideUp('fast'); lisib.find('i').addClass('fa-caret-down').removeClass('fa-caret-up'); } else if($(this).find('i').hasClass('fa-caret-up')){ $(this).find('i').addClass('fa-caret-down').removeClass('fa-caret-up'); $(this).find('ul').slideUp('fast'); } }); $('.more').on('click', function() { $(this).addClass('active'); var lisib=$(this).siblings().find('ul').parent(); lisib.removeClass('active'); lisib.find('ul').slideUp('fast'); lisib.find('i').addClass('fa-caret-down').removeClass('fa-caret-up'); if($('.nav2').is(':hidden')){ $('.nav2').slideDown('fast'); } else{ nav2hide(); } }); $('body').on('click', function(e) { if($('.nav2').is(':hidden')){ if(!$(e.target).is('.header .nav>ul *')){ var ulchild=$('.header .nav>ul>li').find('ul'); if(ulchild){ ulchild.slideUp('fast'); ulchild.parent().find('i').addClass('fa-caret-down').removeClass('fa-caret-up'); ulchild.parent().removeClass('active'); } } } else{ if(!$(e.target).is('.nav2 *') && !$(e.target).is('.more *')){ nav2hide(); } } }); function nav2hide(){ $('.more').removeClass('active'); $('.nav2').slideUp('fast'); var nav2li=$('.nav2>ul>li'); if(nav2li.find('i').hasClass('fa-caret-up')){ nav2li.find('i').addClass('fa-caret-down').removeClass('fa-caret-up'); nav2li.find('ul').slideUp('fast'); } } } // 点击logo字隐藏 logochange(); function logochange(){ $('.logo-btn').on('click', function() { $(this).siblings('a').animate({width: 'toggle'},function(){ var logow=$(this).parents('.logo').width()+50; $('.nav').css('overflow','hidden'); $('.nav>ul').animate({marginLeft:logow+'px'},'fast',function(){ more(); $('.nav').css('overflow',''); }); }); }); } more(); function more(){ var ulw=$('.nav>ul').width(), li=$('.nav>ul>li'), AllLiw=0; for (var i = 0; i < li.length; i++) { AllLiw+=li.eq(i).width()+17; } if(AllLiw>ulw){ var dvalue=AllLiw-ulw, liw=0, morew=$('.more').width(); for (var z = li.length-2; z >= 0; z--) { liw+=li.eq(z).width()+17; if(morew+liw>=dvalue){ for (var j = z-1; j < li.length-1; j++) { $('.more').insertAfter(li.eq(z-2)).show(); li.eq(j).appendTo($('.nav2>ul')); } break; } } } else{ $('.more').insertAfter(li.eq(-1)).hide(); $('.nav2>ul>li').insertBefore($('.more')); } } // 侧边条 $(".nicescroll4px").niceScroll({ cursorcolor: "#ccc", cursorwidth:"4px", cursorborder:"none" }); $(".yc-modal-body").niceScroll({ //宜昌推送专用 cursorcolor: "#ccc", cursorwidth:"4px", cursorborder:"none", autohidemode: false }); $(".nicescroll,.modal-body").niceScroll({ cursorcolor: "#ccc", cursorwidth:"0px", cursorborder:"none" }); $(".nicescroll2").niceScroll({ cursorcolor: "#ccc", cursorwidth:"0", cursorborder:"none" }); $(".nicescroll-big").niceScroll({ cursorcolor: "#ccc", cursorwidth:"13px", cursorborder:"none" }); $(".nicescroll10").niceScroll({ cursorcolor: "#ccc", cursorwidth: "10px", cursorborder: "none" }); // 左侧树图重置滚动条 treeclick(); function treeclick(){ $('.tree-ul').on('click', function() { $(".nicescroll").getNiceScroll().resize(); }); } // 选择后出现图标 check(); function check(){ $('.gjxx .table-label').on('ifChanged','input[name="check1"]',function(event){ if ($(this).is(':checked')){ $(this).parent().parent().next('span').find('img').css('display','inline-block'); var cbnum=$('input[name="check1"]').length, checknum=$('input[name="check1"]:checked').length; if(cbnum===checknum){ $('#checkall').iCheck('check'); } } else{ $(this).parent().parent().next('span').find('img').hide(); $('#checkall').iCheck('uncheck'); } }); } // 全选 allcheck(); function allcheck(){ $('.gjxx').on('ifClicked','#checkall' ,function(event) { if(!$(this).is(':checked')){ $("input[name='check1']").iCheck('check'); } else{ $("input[name='check1']:checked").iCheck('uncheck'); } }); } // $('input').iCheck({ checkboxClass: 'icheckbox_flat-blue', radioClass: 'iradio_flat-blue', increaseArea: '20%' }); //侧边栏 content1(); function content1(){ $('.leftnavbar').on('mouseenter', function(event) { var winWidth =$(window).width(); if(winWidth<1300){ $(this).animate({'width':'130px'}, 500,function(){ $(this).find('.menu-li em').show(); // chinaMap.resize(); }); $('.content').animate({'padding-left':+130+'px'}, 500,function(){ // chinaMap.resize(); }); }else{ } // if($('.menu-list').is(":hidden")){ // $('.menu-list').css('display','block'); // $('.nav-list').css('display','none'); // $('.content').animate({'padding-left':+54+'px'}, 500,function(){ // if($('.content').hasClass('map')){ // chinaMap.resize(); // } // }); // }else{ // $('.menu-list').css('display','none'); // $('.nav-list').css('display','block'); // $('.content').animate({'padding-left':+navWidth+'px'}, 500,function(){ // if($('.content').hasClass('map')){ // chinaMap.resize(); // } // }); // } }); } $(window).resize(function(event) { content(); content1(); contenti(); }); //侧边栏 content(); function content(){ $('.menu-box').on('mouseenter', function(event) { $(this).stop().animate({'width':'140px'}, 500,function(){ $(this).find('.menu-li em').show(); if($('.content').hasClass('map')){ // chinaMap.resize(); } }); }); } contenti(); function contenti(){ $('.menu-box').on('mouseenter', function(event) { $(this).stop().animate({'width':'140px'}, 200,function(){ $(this).find('.menu-li em').show(); if($('.content1').hasClass('map')){ chinaMap.resize(); } }); }); } // 左侧边栏重点阵地hover事件 // zzsjNav(); // function zzsjNav(){ // $(".zdzd-nav").hover(function(){ // var w=$(".menu-box").width(); // if(w==40){ // setTimeout(function () { // $(".zdzd-nav").children(".li-menu-li").show(); // }, 300); // }else{ // $(".zdzd-nav").children(".li-menu-li").show(); // } // },function(){ // $(".zdzd-nav").children(".li-menu-li").hide(); // }); // } contentLeave(); function contentLeave(){ $('.menu-box').on('mouseleave', function(event) { var winWidth =$(window).width(); $(this).find('.menu-li em').hide(); $(this).stop().animate({'width':'50px'}, 500,function(){ if($('.content').hasClass('map')){ chinaMap.resize(); } }); $('.content').stop().animate({'padding-left':+50+'px'}, 500,function(){ if($('.content').hasClass('map')){ chinaMap.resize(); } }); }); } //影响力分析 左边 leftTab(); function leftTab(){ $('.list-down').on('click', 'li dt', function() { $(this).siblings('dd').stop().slideToggle(); }); } //鼠标经过出现提示 hoverCircle(); function hoverCircle(){ $('.norSpan .circle-answer').on('mouseenter',function(){ $(this).parent('.norSpan').find('.tishi').css('display','inline-block'); }); } leaveCircle(); function leaveCircle(){ $('.norSpan .circle-answer').on('mouseleave',function(){ $(this).parent('.norSpan').find('.tishi').css('display','none'); }); } hoverOtherCircle(); function hoverOtherCircle(){ $('.relSpan .circle-answer').on('mouseenter',function(){ $(this).parent('.relSpan').find('.tishi').css('display','block'); }); } leaveOtherCircle(); function leaveOtherCircle(){ $('.relSpan .circle-answer').on('mouseleave',function(){ $(this).parent('.relSpan').find('.tishi').css('display','none'); }); } hoverBtnCircle(); function hoverBtnCircle(){ $('.relbtn .btn').on('mouseenter',function(){ $(this).parent('.relbtn').find('.tishi').css('display','block'); }); } leaveBtnCircle(); function leaveBtnCircle(){ $('.relbtn .btn').on('mouseleave',function(){ $(this).parent('.relbtn').find('.tishi').css('display','none'); }); } //弹出框事件 // $('#leaderModal .modal-dialog .modal-footer .yes').on('click',function(){ // text = $("input:checkbox[name='leader']:checked").map(function(index,elem) { // return $(elem).val(); // }).get().join('|'); // $('.objWords').val(text); // $('#leaderModal').modal('hide'); // }); $('.main-body .tc-table .checkObj').on('click',function(){ objWords = $("input:checkbox[name='objWords']:checked").map(function(index,elem) { return $(elem).val(); }).get(); if($('.objArea').val()!=""){ $('.objArea').val(""); } else{ $('.objArea').val(objWords); } }); //搜索图标点击事件 $('.search-icon').on('click',function(){ if($('.search-box input').css('display')=='none'){ $('.search-box input').css('display','inline-block'); $('.search-icon2').css('display','inline-block'); $('.xiala').css('display','none'); $(this).css('display','none'); } }); //弹出框事件 //获取时间 $('#period .days:first').on('ifClicked',function(){ if($(this).find('span').text()==""){ var myDate =new Date(); var nextDate = new Date(myDate.getTime() + 7 * 24 * 3600 * 1000); var str=""; str+= "("+(myDate.getMonth()+1) + "月"; str+=myDate.getDate() + "日-"; str+=(nextDate.getMonth()+1)+"月"+nextDate.getDate()+"日)"; $(this).find('span').html(str); $(this).next().find('span').html(""); $('#period .days span .MyDateP').css('display','none'); } else{ $(this).find('span').html(""); $(this).find('input').iCheck("uncheck"); } }); $('#period .days').eq(1).on('ifClicked',function(){ if($(this).find('span').text()==""){ var myDate =new Date(); var lastDay=new Date(myDate.getFullYear(), myDate.getMonth() + 1, 0, 23, 59, 59); var str=""; str+= "("+(myDate.getMonth()+1) + "月"; str+=1 + "日-"+(myDate.getMonth()+1)+ "月"+lastDay.getDate()+"日)"; $(this).find('span').html(str); $(this).prev().find('span').html(""); $('#period .days span .MyDateP').css('display','none'); } else{ $(this).find('span').html(""); $(this).find('input').iCheck("uncheck"); } }); $('#period .days').eq(2).on('ifClicked',function(){ if($(this).find('.MyDateP').css('display')=='none'){ $(this).find('.MyDateP').css('display','inline-block'); $(this).prevAll().find('span').html(""); } else{ $(this).find('.MyDateP').css('display','none'); $(this).find('input').iCheck("uncheck"); } }); //更新图标转动 //左侧边栏 icon_anim(); function icon_anim(){ $('.show-circle').on('click', function(event) { var ele = $('#soleId'); ele.find('.load-circle i').hide(); ele.find('.circle').circleProgress({ value: 0.9, size:26, fill: { color: '#ffab0a' }, animation:{ duration: 10000 } }); ele.find('.renew,.load-circle').show(); $('.list-set-btn').remove(); }); } var updateNum = 0; loadCircle(); function loadCircle(){ var set = '<li class="list-set-btn">'+ '<div class="operationb">'+ '<div class="operation">'+ '<label data-toggle="modal" data-target="#time"><i class="fa fa-rotate-left" class="updateBtn"></i>更新</label>'+ '<label><i class="fa fa-pencil"></i>编辑</label>'+ '<label data-toggle="modal" data-target="#del"><i class="fa fa-close"></i>删除</label>'+ '</div>'+ '</div>'+ '</li>'; var set2 = '<li class="list-set-btn">'+ '<div class="operationb">'+ '<div class="operation">'+ '<a href="有害信息-创建任务.html"><i class="fa fa-pencil"></i>编辑</a>'+ '<a data-toggle="modal" data-target="#del"><i class="fa fa-close"></i>删除</a>'+ '</div>'+ '</div>'+ '</li>'; $('.leftnvvbar2').on('click', '.load-circle', function(event) { $('.time-boxs li').attr('id',''); $(this).parents('li').attr('id','soleId'); var parentsLi = $(this).parents('li'); if(parentsLi.next('li').is('.list-set-btn') === false){ parentsLi.parents('.time-boxs').find('.list-set-btn').remove(); if($(this).parents().hasClass('leftnvvbar3')){ parentsLi.after(set2); } else{ parentsLi.after(set); } }else{ parentsLi.parents('.time-boxs').find('.list-set-btn').remove(); } event.stopPropagation(); }); } // 影响力分析 icon_anim2(); function icon_anim2(){ $('.force-btn').on('click', function(event) { event.preventDefault(); $('.circle2').circleProgress({ value: 1, size:26, fill: { color: '#ffab0a' }, animation:{ duration: 10000 } }); $(this).siblings('.renew,.circle2').css('display','inline-block'); $(this).hide(); if($(this).text()=="影响力分析"){ $(this).text("更新分析"); } else{ $(this).text("影响力分析"); } clearTimeout(c2()); c2(); }); function c2(){ setTimeout(function(){ $('.circle2,.renew').hide(); $('.force-btn').show(); },10000); } } // 微博传播分析 icon_anim3(); function icon_anim3(index){ $('.left-list-rebtn').on('click', function(event) { event.preventDefault(); var that=$(this); that.siblings('.circle2').circleProgress({ value: 1, size:28, fill: { color: '#ffab0a' }, animation:{ duration: 10000 } }); that.siblings('.renew,.circle2').css('display','inline-block'); that.hide(); function c3(index){ that.siblings('.renew,.circle2').hide(); that.show(); } function _c3(index){ return function(){ c3(index); }; } clearTimeout(c33); var c33=setTimeout(_c3(index),10000); }); } // 下拉菜单时间 time_cros(); function time_cros(){ $('.time-con').on('click', 'ul li', function(event) { event.preventDefault(); var text=$(this).find('a').text(), date=new Date(), threedate=new Date((+date)-3*24*3600*1000), weekdate=new Date((+date)-7*24*3600*1000), newdate=date.getFullYear()+'-'+(date.getMonth()+1)+'-'+date.getDate(), threeday=threedate.getFullYear()+'-'+(threedate.getMonth()+1)+'-'+threedate.getDate(), week=weekdate.getFullYear()+'-'+(weekdate.getMonth()+1)+'-'+weekdate.getDate(), month=date.getFullYear()+'-'+date.getMonth()+'-'+date.getDate(); if(text=='近3天'){ $(this).parents('.time-con').next('.layout-data').find('input').attr('value',''); $(this).parents('.time-con').next('.layout-data').find('#d01').attr('value',threeday); $(this).parents('.time-con').next('.layout-data').find('#d02').attr('value',newdate); } else if(text=='一周'){ $(this).parents('.time-con').next('.layout-data').find('input').attr('value',''); $(this).parents('.time-con').next('.layout-data').find('#d01').attr('value',week); $(this).parents('.time-con').next('.layout-data').find('#d02').attr('value',newdate); } else if(text=='一月'){ $(this).parents('.time-con').next('.layout-data').find('input').attr('value',''); $(this).parents('.time-con').next('.layout-data').find('#d01').attr('value',month); $(this).parents('.time-con').next('.layout-data').find('#d02').attr('value',newdate); } else{ $(this).parents('.time-con').next('.layout-data').find('input').attr('value',''); } }); } // 导出报告弹窗 // exp_pic(); // function exp_pic(){ // $('#export').on('mouseenter ', '.module li', function(ev) { // var y = $(this).offset().top, // x = $(this).offset().left, // index=$(this).index(); // $('.thumbnail-pic').fadeIn().css({'top':y-62+'px','left':x-384+'px'}); // $('.thumbnail-pic').find('span').eq(index).fadeIn().siblings('span').hide(); // }); // $('#export').on('mouseleave', function(ev) { // $('.thumbnail-pic').hide(); // }); // } // 摘要 remark(); function remark(){ $('.list1 .tleft .tables-bt,.filter-table .txt .tables-bt').on('mousemove', function(event) { event.preventDefault(); var x=event.pageX, remark=$(this).next('.remark'), rmh=remark.height(), bom=$('.zt-ft').offset().top, t=remark.offset().top; if(t>0){ var remtop=t+rmh+35; if(remtop>=bom){ remark.css('top',-rmh-30+'px'); } $('.list1').scroll(function() { if(remtop>=bom){ remark.css('top',-rmh-30+'px'); } else{ remark.css('top','35px'); } }); } remark.css('left',x-390+'px').show(); }); $('.list1').on('mouseleave', '.tleft .tables-bt', function(event) { event.preventDefault(); $(this).next('.remark').hide(); }); $('.filter-table .txt .tables-bt').on('mouseleave', function(event) { event.preventDefault(); $(this).next('.remark').hide(); }); } // 加入对比 addcont(); function addcont(){ $('#jstree-add').on('mouseenter','[aria-level="4"],[aria-level="4"] div,[aria-level="4"] a,[aria-level="4"] i', function(event) { var y=$(this).offset().top; $('.add-cont').css('top', y+3+'px').show(); }); $('.add-cont').on('mouseenter', function(event) { event.preventDefault(); $(this).show(); }); $('#jstree-add').on('mouseleave','[aria-level="4"]', function(event) { $('.add-cont').hide(); event.stopPropagation(); }); } // 删除清空对比 delcont(); function delcont(){ // 清空对比 $('.fuchuan').on('click', '.delduibi', function(event) { event.preventDefault(); $('.fuchuan').animate({right:'-136px'}); $(this).siblings('.duibi').find('li').remove(); $('.fuchuan .title i').html(0); }); // 删除对比 $('.fuchuan').on('click', '.delet', function(event) { event.preventDefault(); $(this).parent().remove(); $('.fuchuan .title i').html($('.fuchuan .title i').html()-1); if($('.fuchuan .duibi').children().length==0){ $('.fuchuan').animate({right:'-136px'}); } }); } /* 重点对象 */ /* 侧边栏拖动 start */ $('.resize-box').on('mousedown', function(e) { var nowMousedownLeft = $(this).offset().left+10; resizeBoxMouseMove(nowMousedownLeft); }); $(document).on('mouseup', function(event) { $(document).off('mousemove'); }); function resizeBoxMouseMove(nowLeft) { $(document).on('mousemove', function(e) { var moveWidth = e.pageX - nowLeft; var newWidth = nowLeft + moveWidth; var winWidth = $(window).width(); if(winWidth<1400){ if(newWidth < 350 && newWidth > 260) { $('.zddx .nav-wrap').css('width',newWidth); $('.zddx .nxjk').css('paddingLeft',newWidth); } else if (newWidth > 350) { $('.zddx .nav-wrap').css('width',350); $('.zddx .nxjk').css('paddingLeft',350); } else if (newWidth < 260) { $('.zddx .nav-wrap').css('width',260); $('.zddx .nxjk').css('paddingLeft',260); } } else{ if(newWidth < 400 && newWidth > 320) { $('.zddx .nav-wrap').css('width',newWidth); $('.zddx .nxjk').css('paddingLeft',newWidth); } else if (newWidth > 400) { $('.zddx .nav-wrap').css('width',400); $('.zddx .nxjk').css('paddingLeft',400); } else if (newWidth < 320) { $('.zddx .nav-wrap').css('width',320); $('.zddx .nxjk').css('paddingLeft',320); } } return false; }); } function resizeAutoWidth(){ var navWrap = $('.zddx .nav-wrap'), LeftNavwrap = navWrap.width(), winWidth = $(window).width(); var percentage = (LeftNavwrap/winWidth); navWrap.css('width',percentage); } /* 侧边栏拖动 end */ // 新版检索 //左侧栏 xbjsleft(); function xbjsleft(){ $('.left-lock').on('click', function() { if($(this).find('i').hasClass('fa-lock')){ $(this).css('color','#5ec45e'); $(this).find('i').addClass('fa-unlock-alt').removeClass('fa-lock'); $('.js-box').on('mouseleave', function() { if($('.layui-laydate').css('display')=='block'){ } else{ $('.js-box').hide(); $('.xbjs-right-box').css('padding-left',0); var topWidth = $('.xbjs-right-top').width(); $('.topNav').css('width', topWidth - 2); } }); } else{ $(this).css('color','#8ea5c3'); $(this).find('i').addClass('fa-lock').removeClass('fa-unlock-alt'); $('.js-box').off('mouseleave'); } }); $('.xbjs-left .btn-blue').on('click', function() { $('.js-box').show(); $('.xbjs-right-box').css('padding-left',$('.js-box').width()); var topWidth = $('.xbjs-right-top').width(); $('.topNav').css('width', topWidth - 2); }); } // 添加信源 addsour(); function addsour(){ $('.subs-list').on('click', 'dd a', function() { if(!$(this).hasClass('on')){ $(this).addClass('on'); } else{ $(this).removeClass('on'); } }); $('.ac-normal').on('click', 'a', function() { if(!$(this).hasClass('active')){ $(this).addClass('active'); } else{ $(this).removeClass('active'); } }); $('.ac-top').on('click', 'a', function(event) { var $this = $(this); var thatIndex = $this.index(); var acBox = $this.parent('.ac-top').siblings('.ac-box'); acBox.find('>div').eq(thatIndex).addClass('active').siblings().removeClass('active'); $this.addClass('active').siblings().removeClass('active'); }); } // 高级选项 senior(); function senior(){ $(".opt-btn").on('click', function() { if($(this).siblings('.opt-con').is(":hidden")){ $(this).html('收起高级选项<i class="fa fa-angle-double-up"></i>'); $(this).siblings('.opt-con').slideDown("fast"); } else{ $(this).html('展开高级选项<i class="fa fa-angle-double-down"></i>'); $(this).siblings('.opt-con').slideUp("fast"); } }); } // 国家属地 colonycheck(); function colonycheck(){ $('.multi').on('ifChanged', '.dropdown-menu li label input', function() { var text=$(this).parents('label').text(), btn=$(this).parents('ul').siblings('button').find('.text'), btntext=btn.text(); if(btntext=='请选择'){ btntext=''; } if($(this).is(':checked')){ btn.text(btntext+text+','); } else{ btn.text(btntext.replace(text+',','')); if(btn.text()==''){ btn.text('请选择'); } } }); } // 元搜索开关 yssrectangle(); function yssrectangle() { $('.rectangle').on('click', function() { if($(this).hasClass('change-i')){ $(this).removeClass('change-i'); $(this).find('span').text('OFF'); } else{ $(this).addClass('change-i'); $(this).find('span').text('ON'); } }); } // 日期时间范围 lay('.time-range').each(function(){ laydate.render({ elem: this, range: '至', format:'yyyy-MM-dd HH:mm', type: 'datetime', }); }); lay('.time-range1').each(function(){ laydate.render({ elem: this, range: '至', format:'yyyy-MM-dd', }); }); lay('.time-rangeZlm').each(function(){ laydate.render({ elem: this, range: '至', format:'yyyy-MM-dd', }); }); lay('.time-rangeZlm2').each(function(){ laydate.render({ elem: this, range: '至', format:'yyyy-MM-dd', }); }); lay('.time-rangeZlm3').each(function(){ laydate.render({ elem: this, range: '至', format:'yyyy-MM-dd', }); }); laydate.render({ elem: '.test1', istoday: true, issure: true }); laydate.render({ elem: '.test2' }); laydate.render({ elem: '.test3' }); laydate.render({ elem: '.test4' }); laydate.render({ elem: '.test5' }); laydate.render({ elem: '.test6' }); // 日期 function getDay(month,day){ var seperator = "-"; var today = new Date(); var time=today.getTime() + 1000 * 60 * 60 * 24 * day; today.setTime(time); // 关键时间 today.setMonth(today.getMonth() + month); var tYear = today.getFullYear(); var tMonth = today.getMonth(); var tDate = today.getDate(); tMonth = tMonth + 1; if (tMonth == 0) { tMonth = 12; tYear = parseInt(tYear) - 1; } if (tMonth < 10) tMonth = '0' + tMonth; if (tDate < 10) tDate = '0' + tDate; return tYear + seperator + tMonth + seperator + tDate; } // 默认日期 $('.test1').val( getDay(-1,0)); $('.test2').val( getDay(0,0)); // 切换日期 switchDay(); function switchDay(){ $('.choice-day li').click(function() { if($(this).hasClass('d1')){ $('.test1').val((getDay(0, -3))); $('.test2').val( getDay(0,0)); } if($(this).hasClass('d2')){ $('.test1').val((getDay(0, -7))); $('.test2').val( getDay(0,0)); } if($(this).hasClass('d3')){ $('.test1').val((getDay(-1, 0))); $('.test2').val( getDay(0,0)); } if($(this).hasClass('d4')){ $('.test1').val((getDay(-3, 0))); $('.test2').val( getDay(0,0)); } if($(this).hasClass('d5')){ $('.test1,.test2').val(''); } }); } // 重点监控 // 左侧列表切换 leftchange(); function leftchange() { $('.plist').on('click', '>li a', function() { $('.operate-btn').hide(); $(this).parent('li').addClass('active').siblings('li').removeClass('active'); $(this).find('.fa-caret-right').addClass('fa-caret-down').removeClass('fa-caret-right'); $(this).parent('li').siblings('li').find('.fa-caret-down').addClass('fa-caret-right').removeClass('fa-caret-down'); }); } // 左侧查看更多操作 showmore(); function showmore(){ $('.operate-more').on('click', function(event) { event.stopPropagation(); $(this).siblings('.operate-btn').toggle(); $(this).parent().parent('li').siblings('li').find('.operate-btn').hide(); }); } // $(document).on('click', function() { // $('.operate-btn').hide(); // }); // 重庆档案库 // 左侧列表切换 leftchangea(); function leftchangea() { $('.plista').on('click', '>li a', function() { if($(this).parent('li').hasClass('active')){ $('.operate-btn').hide(); $(this).parent('li').removeClass('active'); $(this).find('.fa-caret-down').addClass('fa-caret-right').removeClass('fa-caret-down'); $(this).parent('li').siblings('li').find('.fa-caret-down').addClass('fa-caret-right').removeClass('fa-caret-down'); }else{ $('.operate-btn').hide(); $(this).parent('li').addClass('active').siblings('li').removeClass('active'); $(this).find('.fa-caret-right').addClass('fa-caret-down').removeClass('fa-caret-right'); $(this).parent('li').siblings('li').find('.fa-caret-down').addClass('fa-caret-right').removeClass('fa-caret-down'); } }); } // 左侧查看更多操作 showmorea(); function showmorea(){ $('.operate-morea').on('click', function(event) { event.stopPropagation(); $(this).siblings('.operate-btn').toggle(); $(this).parent().parent('li').siblings('li').find('.operate-btn').hide(); }); } $(".plista_sj").on("click",">li",function(){ $(this).addClass("active").siblings("li").removeClass('active'); }); }); // 头部点击用户名 userbox(); function userbox(){ $('.user').on('click', function(event) { event.stopPropagation(); $(this).find('.user-box').toggle(); }); } $(document).on('click', function() { $('.user-box').hide(); }); // 全局分析右侧操作按钮 newqjright(); function newqjright(){ $('.newqj-right-list').on('click','.operate-btn' , function(event) { event.stopPropagation(); if($(this).siblings('.operate-list').is(":hidden")){ $(this).siblings('.operate-list').show(); $(this).parent('.operate-box').css('z-index', '2'); $(this).parents('li').addClass('active').siblings('li').removeClass('active'); $(this).parents('li').siblings('li').find('.operate-list').hide(); $(this).parents('li').siblings('li').find('.operate-box').css('z-index', '1'); } else{ $(this).siblings('.operate-list').hide(); $(this).parent('.operate-box').css('z-index', '1'); $(this).parents('li').removeClass('active'); } }); $(document).on('click', function() { $('.operate-list').hide(); $('.operate-box').css('z-index', '1'); $('.newqj-right-list li').removeClass('active'); }); } // 下拉菜单图标移入变色 dropdownpic(); function dropdownpic(){ $('.dropdown-menu li').hover(function() { if($(this).find('img').length > 0){ $(this).find('img').attr('src',$(this).find('img').attr('src').replace(/1/ig, '2')); } }, function() { if($(this).find('img').length > 0){ $(this).find('img').attr('src',$(this).find('img').attr('src').replace(/2/ig, '1')); } }); } // 选择时分 lay('.datetime').each(function(){ laydate.render({ elem: this, type: 'time', range: '~', format:'HH:mm', }); }); // 下拉菜单点击边框变蓝 ddblue(); function ddblue(){ $('.dropdown').on('click', function(event) { $('.dropdown').not($(this)).find('.dropdown-toggle').css('border-color', '#d3dbe3'); if($(this).find('.dropdown-toggle').css('border')=='1px solid rgb(211, 219, 227)'){ $(this).find('.dropdown-toggle').css('border', '1px solid #029be5'); } else{ $(this).find('.dropdown-toggle').css('border', '1px solid #d3dbe3'); } }); $(document).on('click', function(event) { $('.dropdown').find('.dropdown-toggle').css('border', '1px solid #d3dbe3'); }); } // 中信table鼠标 $('.zx-brand-box .tables').each(function() { $(this).find('tr:gt(0)').hover(function() { $(this).addClass('hover').siblings().removeClass('hover'); },function() { $(this).removeClass('hover'); }); $(this).find('tr').click(function() { $(this).addClass('on').siblings().removeClass('on'); }); }); // 中信自适应高度 $(document).ready(function() { var oHieghtBox = $('.zdjk-left').height() - $('.zx-global-title').height() - 35; $('.currency-box').height(oHieghtBox); var oConHieght = $('.con-h-50').height() - $('.title-tag').height(); $('.chart-height').height(oConHieght); var oScroll = $('.selected-tables').height() - $('.title-tag').height() - $('.th-title').height() - 3; $('.b-l-scroll').height(oScroll); }); // 中信指数千位数加分隔符 $(function() { function toThousands(num) { var num = (num || 0).toString(), result = ''; while (num.length > 3) { result = ',' + num.slice(-3) + result; num = num.slice(0, num.length - 3); } if (num) { result = num + result; } return result; } $('.separate-symbol').each(function() { var oSymbol = $(this).text(); var oText = toThousands(oSymbol); $(this).text(oText); }); }); // 焦点变蓝 inputChange(); function inputChange() { $('.input-blue').on('focus', function(event){ $(this).closest('.input-change').css('border','1px solid #66afe9'); }); $('.input-blue').on('blur', function(event){ $(this).closest('.input-change').css('border','1px solid #d3dbe3'); }); } // 下拉菜单图标 dropdown(); function dropdown() { $(".dropdown-menu").on('click', 'li a', function(event) { if(!$(this).find('img').length==0){ var imgsrc=$(this).find('img').attr('src'); imgsrc=imgsrc.replace('2','1'); $(this).parents('.dropdown-menu').siblings('.dropdown-toggle').find('img').attr('src', imgsrc); } }); } // 点击弹出 clickaicon(); function clickaicon() { $(".icon-box.new-icon").on('click', '.a-more', function(event) { var oBox = $(this).siblings('.hide-box').find('.rf-hide'); if (!oBox.hasClass('on')) { $(this).closest('.u-icon').find('.a-default').hide(); oBox.stop().animate({'right':'0'},1000,function(){ $(this).addClass('on'); }); } else { oBox.stop().animate({'right':'-425px'},1000,function(){ $(this).removeClass('on'); $(this).closest('.u-icon').find('.a-default').show(); }); } $(".nicescroll").getNiceScroll().resize(); }); } // 新时间控件 jQuery.datetimepicker.setLocale('ch'); jQuery('.datetimepicker').datetimepicker({format:'Y-m-d H:i'}); jQuery(function(){ jQuery('.date_timepicker_start').datetimepicker({ format:'Y-m-d H:i', onShow:function( ct ){ this.setOptions({ maxDate:jQuery('.date_timepicker_end').val()?jQuery('.date_timepicker_end').val():false }) }, }); jQuery('.date_timepicker_end').datetimepicker({ format:'Y-m-d H:i', onShow:function( ct ){ this.setOptions({ minDate:jQuery('.date_timepicker_start').val()?jQuery('.date_timepicker_start').val():false }) }, }); }); // 提示弹窗 $("[data-prompt]").on('click', function(event) { var idname=$(this).attr('data-prompt'); $('#'+idname).fadeIn(); setTimeout(() => { $('#'+idname).fadeOut(); }, 2000); }); $(function () { /*滚动条高度计算*/ resize(); function resize(){ var height = $(".zddx-right").height() - $(".breadCrumb").outerHeight(true) - $(".control-nav").outerHeight(true) - 37; $(".rollHeight").outerHeight(height); } /*滚动条高度计算1*/ resize1(); function resize1(){ var height1 = $(".zddx-right").height() - $(".breadCrumb").outerHeight(true) - $(".control-nav").outerHeight(true) - $(".undertakings-title").outerHeight(true) - 37; $(".rollHeight1").outerHeight(height1); } /*滚动条高度计算2*/ resize2(); function resize2(){ var height2 = $(".zddx-right").height() - $(".breadCrumb").outerHeight(true) - $(".zddx-right-title").outerHeight(true) - 37; $(".rollHeight2").outerHeight(height2); } /*滚动条高度计算3*/ resize3(); function resize3(){ var height3 = $(".zddx-right").height() - $(".zddx-right-title").outerHeight(true) - 30; $(".rollHeight3").outerHeight(height3); } /*滚动条高度计算4*/ resize4(); function resize4(){ var height4 = $(".zddx-right").height() - $(".breadCrumb").outerHeight(true) - $(".control-nav").outerHeight(true) - 30; $(".rollHeight4").outerHeight(height4); } /*滚动条高度计算5*/ resize5(); function resize5(){ var height5 = $(".gxw-right").height() - $(".breadCrumb").outerHeight(true) - $(".big-blueTit").outerHeight(true) - 12; $(".rollHeight5").outerHeight(height5); } /*滚动条高度计算6*/ resize6(); function resize6(){ var height6 = $(".gxw-right").height() - $(".breadCrumb").outerHeight(true) - $(".gxw-tab").outerHeight(true); $(".rollHeight6").outerHeight(height6); } /*滚动条高度计算7*/ resize7(); function resize7(){ var height7 = $(".zddx-right").height() - $(".breadCrumb").outerHeight(true) - $(".control-nav").outerHeight(true) - $(".undertakings-title").outerHeight(true) - 30; $(".rollHeight7").outerHeight(height7); } $(window).resize(function(){ resize(); resize1(); resize2(); resize3(); resize4(); resize5(); resize6(); resize7(); }); //分页器 page(); function page(){ $(".pagging").Paging({ dom:{ pageno: true, // 页码:1、2、3、4、5 pagesize: false, // 每页显示多少条 datacount: true, // 数据总数 pagecount: false, // 页码总数 pagebtn: true, // 上一页,下一页按钮 pagefirst: false, // 首页按钮 pagelast: false, // 尾页按钮 fastgo: false // 快速跳转 }, pagesize: 5, current: 1, count: 100, pageSizeList: [10, 20, 30, 40, 50], prevTpl:"<", nextTpl:">" }); } //时间控件 time(); function time() { $(document).on('click', function(event) { $(".dataList").hide(); }); jQuery('.ts-range,.ts-range2').datetimepicker({ format:'Y-m-d H:i', lang:'ru', onChangeDateTime:function(dp,$input){ $(".sure").click(function () { $(this).parents('.data-times').find(".allData").val($(this).parents('.data-times').find('.ts-range').val()+" 至 "+$(this).parents('.data-times').find('.ts-range2').val()); $(this).parents(".dataList").siblings('.timebox').find(".allData").css({width:'295px'}); $(this).parents(".dataList").hide(); }) } }); $('.data-times').on('click',function(event){ event.stopPropagation(); }); $('.allData').on('click', function (event) { $(".dataList").hide(); event.stopPropagation(); $(this).parent().siblings(".dataList").show(); }); $('.ts-range,.ts-range2').on('click', function(event) { event.stopPropagation(); }); $(".dataList ul li a").click(function (event) { var $text=$(this).text(); $(this).parents(".data-times").find(".allData").val($text); $(this).parents(".dataList").hide(); $(this).parents(".dataList").siblings('.timebox').find(".allData").css({width:'115px'}); event.stopPropagation(); }); } });<file_sep>/app/less/global.less @charset "utf-8"; @import "./base/base.less"; @import "./base/conn.less"; /* 自定义 start */ .wh100 { width: 100%; height: 100%; } .df { color: #333; } .zi { color: @f-zise; } .green { color: @green !important; } .red { color: @red !important; } .bule { color: @bule !important; } .blue { color: @bule !important; } .def { color: #8ea5c3 !important; } .yellow { color: @yellow !important; } a.yellow:hover { color: @f-blue !important; } .bg-blue { background: @bule !important; } .bg-yellow { background: @yellow !important; } .bg-green { background: @green !important; } /* 自定义 end */ .mg0 { margin: 0 !important; } .mb15 { margin-bottom: 15px !important; } .mb10 { margin-bottom: 10px !important; } .mb30 { margin-bottom: 30px !important; } .ml15 { margin-left: 15px !important; } .ml30 { margin-left: 30px !important; } .mr10 { margin-right: 10px !important; } .mr15 { margin-right: 15px !important; } .pd0 { padding: 0 !important; } .pd10 { padding: 10px !important; } .pd15 { padding: 15px !important; } .pdr60 { padding-right: 60px !important; } .pdr165 { padding-right: 165px !important; } .plt20 { padding: 0 20px 0 !important; } .pd20 { padding: 20px !important; } .w35 { width: 35%; } .o-inherit { overflow: inherit !important; } .box { margin: 0 20px; } /* 背景 */ .shadow { padding: 10px; border: 1px solid @line-color; background: #fff; .box-shadow(0, 0, 10px, 0, rgba(0, 27, 54, 0.1)); } .txt-shadow { background: rgba(255, 255, 255, .4); .box-shadow(0, 0, 10px, 0, rgba(0, 27, 54, 0.1)); } /* 小标题 */ .title-tag { position: relative; padding: 0 15px; border: 1px solid @line-color; background: #f6f8fb; width: 100%; height: 36px; line-height: 36px; font-weight: bold; &:after { content: ''; position: absolute; left: 0; top: 5px; width: 2px; height: 25px; background: @bg-blue; } } .layout-data { border: 1px solid @line-color; height: 30px; line-height: 30px; border-radius: 3px; background: #fff; input { padding: 0; height: 26px; line-height: 26px; width: 90px; border: none; text-align: center; border-radius: 3px; color: @f-blue; } } .layut-input { position: relative; padding: 0 0 10px 0; input { padding-right: 25px; } a { position: absolute; right: 5px; top: 0; font-size: 18px; color: @line-color; } } .border { border-left: 1px solid @line-color; border-bottom: 1px solid @line-color; border-right: 1px solid @line-color; } .ft-forward { span { color: @f-zise; margin-right: 8px; em { color: #333; } } } .ft-con { background: #f6f8fb; border: 1px solid @line-color; padding: 10px; margin-top: 10px; } /* bootstrap初始化 start */ .form-control { height: 30px; line-height: 30px; padding: 0 15px 0 10px; display: inline-block; border-color: #d3dbe3; box-shadow: none; color: @f-blue; &:hover { outline: none; } &:focus { border-color: none; outline: none; box-shadow: none; } } .modal-body { max-height: 400px; overflow-y: auto; padding: 0 15px; } // .table-bordered > thead > tr > th{ // border:none; // text-align: center; // background: #f9fafc; // color:#93a4aa; // } .table-striped > tbody > tr:nth-of-type(odd) { background: #fff; } .table-striped > tbody > tr:nth-of-type(even) { background: #f9fafc; } .modal-header .modal-title { font-size: 16px; } .modal-header { padding: 10px 15px; border-bottom: none; } .modal-header .modal-title { color: #1389d0; text-align: left; } .close { color: #8ea5c3; opacity: 1; } .modal-footer { text-align: center; border-top: none; } .modal-footer .btn { padding: 0 30px; color: #93a4aa; background: #d3dbe3; border: none; &:hover { color: #93a4aa; } } .modal-footer .yes { background: #1389d0; color: #fff; } .dropdown { display: inline-block; } .dropdown-toggle { background: #fff; border: 1px solid @border; height: 30px; line-height: 28px; padding: 0 10px; min-width: 40px; color: #333; border-radius:2px; } .caret { border-top: 5px dashed; border-top: 5px solid \9; border-right: 5px solid transparent; border-left: 5px solid transparent; } .dropdown-menu { min-width: 80px; border-radius: 0; border: 1px solid @border; } .dropdown-menu > li > a:hover, .dropdown-menu > li > a:focus { background: #eef1f7; color: #029be5; } .icheckbox_flat-blue, .iradio_flat-blue { margin-right: 5px; margin-top: -5px; } .modal-header .modal-title { font-weight: bold; } .modal-dialog { margin: 10% auto 0 auto; } /* bootstrap初始化 end */ .maptab { position: absolute; left: 50%; top: 90px; width: 225px; height: 30px; margin-left: -114px; line-height: 30px; color: @green; overflow: hidden; border-radius: 30px; a { float: left; min-width: 75px; height: 30px; background: @hui; display: block; text-align: center; border-right: 1px solid #ccc; &:last-child { border-right: none; } &:hover, &.active { color: #fff; background: @bg-blue; } } } html, body, .content { width: 100%; height: 100%; overflow: hidden; } /* 头部 start */ .header { z-index: 10; width: 100%; height: 60px; padding: 0 10px; background: url('../images/hd_bg_l.png') no-repeat left, url('../images/hd_bg_r.png') no-repeat right top; background-color: #006daf; position: fixed; left: 0; top: 0; } .nav { float: left; width: 100%; height: 100%; > ul { margin: 0 370px 0 450px; line-height: 57px; text-align: center; .more { span { width: 30px; height: 6px; padding: 6px 25px; display: inline-block; background: url('../images/more.png') no-repeat; background-position: center center; } } > li { display: inline-block; height: 100%; position: relative; border-top: 3px solid transparent; margin-right: 15px; &:hover, &.active { background: #1d5098; border-top: 3px solid #00c6ff; } a { padding: 0 15px; height: 100%; font-size: 18px; color: #fff; display: block; i { margin-left: 5px; } } ul { width: 100%; position: absolute; top: 100%; left: 0; background: rgba(4, 61, 141, 0.9); border-bottom-left-radius: 5px; border-bottom-right-radius: 5px; padding: 10px 0; display: none; li { &:hover, &.active { a { color: #00c5fe; } } a { font-size: 16px; line-height: 38px; } } } } } } .logo { float: left; height: 100%; margin-left: -100%; h1 { width: 100%; height: 100%; .logo-btn { width: 53px; height: 100%; background: url(../images/logo.png) no-repeat left center; background-size: 100% auto; cursor: pointer; } a { width: 337px; height: 100%; background: url(../images/logo-z.png) no-repeat left center; background-size: 100% auto; } } } .search { width: 200px; height: 100%; color: #fff; position: relative; padding-right: 10px; input { width: 100%; height: 32px; background: rgba(29, 80, 152, 0.7); border: 1px solid #0e7ac9; border-radius: 20px; padding: 0 30px 0 20px; outline: none; margin-top: 14px; } input::-webkit-input-placeholder { /* WebKit browsers */ color: #d3dbe3; } input:-moz-placeholder { /* Mozilla Firefox 4 to 18 */ color: #d3dbe3; } input::-moz-placeholder { /* Mozilla Firefox 19+ */ color: #d3dbe3; } input:-ms-input-placeholder { /* Internet Explorer 10+ */ color: #d3dbe3; } .search-btn { position: absolute; top: 14px; right: 0; width: 32px; height: 32px; line-height: 32px; display: inline-block; cursor: pointer; } } .set { float: left; width: 374px; margin-left: -374px; > div { height: 100%; display: inline-block; vertical-align: top; line-height: 60px; color: #fff; margin: 0 5px; a { color: #fff; &:hover { color: @f-blue; } } } .set-box { margin-right: 10px; a { font-size: 18px; } } .user { height: 100%; position: relative; a { vertical-align: top; display: inline-block; i { font-size: 20px; vertical-align: middle; } } .user-img { width: 36px; height: 36px; line-height: 36px; border-radius: 50%; overflow: hidden; margin: 12px 5px; } .user-name { max-width: 78px; line-height: 60px; .txt; } &:hover { > a { color: #fff; } } } .user-box { width: 130px; position: absolute; top: 50px; right: 0; display: none; .box-shadow (0, 0, 18px, 0, rgba(51, 55, 57, 0.2)); .user-box-list { padding: 0 10px; li { padding-left: 10px; line-height: 32px; & + li { border-top: 1px solid @line-color; } } } a { color: #8ea5c3; display: block; i { margin-right: 15px; width: 16px; } &:hover { color: @f-blue; } } &:before { content: ''; width: 0; height: 0; border-left: 6px solid transparent; border-bottom: 8px solid #fff; border-right: 6px solid transparent; position: absolute; top: -8px; right: 15px; display: block; } } .exit { a { height: 100%; display: block; font-size: 16px; } } } .nav2 { width: 100%; z-index: 1000; position: absolute; top: 60px; left: 0; background: rgba(4, 61, 141, 0.9); display: none; > ul { line-height: 60px; text-align: center; > li { display: inline-block; height: 100%; position: relative; margin-right: 15px; a { padding: 0 15px; height: 100%; font-size: 18px; color: #fff; display: block; i { margin-left: 5px; } } ul { width: 100%; position: absolute; top: 100%; left: 0; background: rgba(4, 61, 141, 0.9); border-bottom-left-radius: 5px; border-bottom-right-radius: 5px; padding: 10px 0; display: none; li { &:hover, &.active { a { color: #00c5fe; } } a { font-size: 16px; line-height: 38px; } } } } } } /* 头部 end */ /* 左边导航 start */ .leftnavbar { z-index: 9; position: fixed; left: 0; top: 0; padding-top: 60px; height: 100%; background: #ff0; } .leftnavbar { background: #002e4a; font-size: 14px; } .system-settings { height: 50px; padding: 10px 20px; a { width: 100%; height: 30px; background: #006daf; border-radius: 5px; text-align: center; line-height: 30px; color: #fff; display: inline-block; &:hover, &.active { background: @hover-blue; color: #fff; } } } .nav-list { width: 200px; overflow-y: auto; li { height: 46px; background: #043553; margin-bottom: 1px; a { line-height: 46px; padding: 0 15px; color: @key-blue; display: block; i { margin-right: 5px; width: 15px; } } &:hover, &.active { background: @hover-blue; } &:hover a, &.active a { color: #fff; } } } .navtop { text-align: center; width: 50px; .menu { height: 51px; line-height: 50px; font-size: 24px; color: #fff; } a { color: #fff; display: block; &:hover { color: @bule; } } .menu-list { a { position: relative; font-size: 16px; width: 30px; height: 30px; line-height: 30px; display: inline-block; border-radius: 50%; background: #006daf; margin-bottom: 15px; &:hover { color: #fff; background: @bule; } } // span{ // z-index: 100; // position: absolute; // left:54px; // top:0; // min-width: 150px; // padding: 0 15px; // height: 30px; // line-height: 30px; // background: #002e4a; // color:#fff; // display: block; // border-radius: 5px; // &:after { // content: ''; // position: absolute; // left: -8px; // top: 34%; // width: 0; // height: 0; // border-top: 5px solid transparent; // border-right: 10px solid #002e4a; // border-bottom: 5px solid transparent; // } // } } } .menu-li { background: #043553; li { height: 51px; background: #043553; margin-bottom: 1px; } a { width: 100%; height: 100%; display: block; padding: 10px; span { font-size: 16px; width: 30px; height: 30px; line-height: 30px; display: inline-block; border-radius: 50%; background: #006daf; text-align: center; color: #fff; } em { display: none; color: #fff; margin-left: 5px; } } } /* 左边导航 end */ /* 右边内容区 start */ .content { padding: 60px 0 0 200px; } .content1 { padding: 60px 0 0 50px; } .main { width: auto; height: 100%; } .tab-box { height: 52px; } .main-box { padding: 20px; overflow-y: auto; > div { padding-bottom: 20px; } } .main-box2 { overflow-y: auto; > div { padding-bottom: 20px; } } /* table列表 Start */ .weibo { .wb-list .list-r h3 { height: auto; } } .tool { padding: 0 20px; border-bottom: 1px solid @border; line-height: 50px; .list { display: inline-block; margin-right: 20px; } input { width: 150px; border: 1px solid @border; border-radius: 3px; color: #8ea5c3; padding: 0 8px; height: 30px; line-height: 28px; } .green { color: #fff; background-color: @green; border-color: @green; } } .tables { width: 100%; border-left: 1px solid @border; border-right: 1px solid @border; th { padding: 10px 10px; background: #cfd5de; color: @tit; text-align: center; } td { padding: 10px; text-align: center; border-bottom: 1px solid @border; > a { margin-right: 15px; display: inline-block; } > .ic_img { display: inline; cursor: pointer; } } > tbody > tr:nth-child(even) { background: #eef1f7; } .tables-bt { color: @bule; display: inline-block; max-width: 70%; .omit(); } > a { display: inline-block; } } .tc-table { width: 100%; position: relative; .tdlogo { position: absolute; right: 0; top: 0; .preview { position: relative; width: 200px; height: 70px; text-align: center; border: 1px solid #d6e1e5; border-radius: 4px; line-height: 33px; img { margin: 0 auto; position: absolute; top: 50%; left: 50%; width: 100%; transform: translate(-50%, -50%); .img { height: 70px; margin: 0 auto; } } } } .files { display: inline-block; width: 80px; height: 22px; line-height: 22px; position: relative; overflow: hidden; color: #fff; cursor: pointer; margin-left: 60px; margin-top: 5px; background-color: #1389d0; text-align: center; border-radius: 6px; &:hover { color: #fff; } input { position: absolute; left: 0; top: 0; zoom: 1; filter: alpha(opacity=0); opacity: 0; cursor: pointer; } } th { width: 100px; text-align: right; font-weight: normal; color: #333333; padding: 6px; line-height: 27px; vertical-align: top; } td { padding: 6px; color: @tit; } input[type="text"], textarea { width: 100%; line-height: 28px; border: 1px solid #d6e1e5; border-radius: 3px; padding: 0 8px; outline: none; } textarea { line-height: 22px; padding: 8px; resize: vertical; min-height: 40px; max-height: 210px; height: 70px; overflow: auto; } textarea::-webkit-scrollbar { display:block !important; } .border { border-bottom: 1px dashed #8ea5c3; } .z-tree { max-height: 150px; // padding: 10px; border: 1px solid #d6e1e5; } label { min-width: 100px; color: #364347; font-weight: normal; margin-bottom: 10px; } .jians { width: 20px; height: 20px; position: absolute; top: 12px; right: 17px; z-index: 9; background: url(../images/icon_sea.png) center center no-repeat; display: block; } } .nf-tables{ th { width: 120px; } .bq-modal-tip{ .circle-answer{ margin-left: 0; } span{ top: 38px; left: -18px; width: 150px; text-align: left; padding: 5px; &::after{ border-top: 5px solid transparent; border-bottom: 10px solid #eaf0f2; border-right: 5px solid transparent; border-left: 5px solid transparent; left: 12px; top: -14px; } } } } textarea{ line-height: 22px; padding: 8px; resize: vertical; min-height: 40px; max-height: 210px; height: 70px; overflow: auto; } textarea::-webkit-scrollbar { display:block !important; } // } // } // .files{ // display:inline-block; // width:80px; // height:22px; // line-height:22px; // position:relative; // overflow:hidden; // color:#fff; // cursor:pointer; // margin-left: 60px; // margin-top: 5px; // background-color: #1389d0; // text-align: center; // border-radius: 6px; // &:hover{ // color:#fff; // } // input{ // position:absolute; // left:0; // top:0; // zoom:1; // filter:alpha(opacity=0); // opacity:0; // cursor:pointer; // } // } // th{ // width:100px; // text-align:right; // font-weight:normal; // color:#333333; // padding:6px; // line-height: 27px; // vertical-align: top; // }; // td{ // padding:6px; // color:@tit; // } // input[type="text"],textarea{ // width:100%; // line-height:28px; // border:1px solid #d6e1e5; // border-radius:3px; // padding:0 8px; // outline:none; // } // .border{ // border-bottom:1px dashed #8ea5c3; // } // .z-tree{ // max-height:150px; // padding:10px; // border:1px solid #d6e1e5; // } // label{ // min-width:100px; // color:#364347; // font-weight:normal; // margin-bottom:10px; // } // .jians{ // width:20px; // height:20px; // position:absolute; // top:12px; // right:17px; // z-index:9; // background:url(../images/icon_sea.png) center center no-repeat; // display:block; // } // } // .files{ // display:inline-block; // width:80px; // height:22px; // line-height:22px; // position:relative; // overflow:hidden; // color:#fff; // cursor:pointer; // margin-left: 60px; // margin-top: 5px; // background-color: #1389d0; // text-align: center; // border-radius: 6px; // &:hover{ // color:#fff; // } // input{ // position:absolute; // left:0; // top:0; // zoom:1; // filter:alpha(opacity=0); // opacity:0; // cursor:pointer; // } // } // th{ // width:100px; // text-align:right; // font-weight:normal; // color:#333333; // padding:6px; // line-height: 27px; // vertical-align: top; // }; // td{ // padding:6px; // color:@tit; // } // input[type="text"],textarea{ // width:100%; // line-height:28px; // border:1px solid #d6e1e5; // border-radius:3px; // padding:0 8px; // outline:none; // } // textarea{ // line-height: 22px; // padding: 8px; // resize: vertical; // min-height: 40px; // max-height: 210px; // height: 70px; // overflow: auto; // } // textarea::-webkit-scrollbar { // display:block !important; // } // .border{ // border-bottom:1px dashed #8ea5c3; // } // .z-tree{ // max-height:150px; // padding:10px; // border:1px solid #d6e1e5; // } // label{ // min-width:100px; // color:#364347; // font-weight:normal; // margin-bottom:10px; // } // .jians{ // width:20px; // height:20px; // position:absolute; // top:12px; // right:17px; // z-index:9; // background:url(../images/icon_sea.png) center center no-repeat; // display:block; // } // } /* table列表 end */ .tleft { text-align: left !important; } .omit() { overflow: hidden; white-space: nowrap; text-overflow: ellipsis; } .omit-more(@number) { overflow: hidden; display: -webkit-box; -webkit-line-clamp: @number; -webkit-box-orient: vertical; } /*微博管理*/ .wb-list { .list-l { margin-top: 3px; float: left; .user { width: 50px; height: 50px; display: block; overflow: hidden; border-radius: 50%; background: url(../images/def.png) no-repeat; background-size: cover; img { width: 100%; border: 1px solid #ddd; } } .del-btn { border: 1px solid @border; background: #fff; color: @red; font-weight: bold; margin-top: 10px; padding: 3px 10px; display: block; &:hover { border-color: @bg-blue; color: @bg-blue; } } } .list-r { margin-left: 68px; color: @tit; h3 { font-weight: bold; height: 28px; .txt; span { font-weight: normal; display: inline-block; vertical-align: top; } em { width: 20px; height: 20px; display: inline-block; margin: -2px 10px; } &.gril { em { background: url(../images/icon_g.png) center center no-repeat; } } &.boy { em { background: url(../images/icon_b.png) center center no-repeat; } } } .fens { line-height: 24px; color: #8ea5c3; span { display: inline-block; margin-right: 15px; &:last-child { margin-right: 0; } i { color: @tit; } } } .tags { color: #8ea5c3; span { display: inline-block; background: @yellow; color: #fff; padding: 0 10px; min-width: 44px; border-radius: 4px; text-align: center; } } .profile { line-height: 24px; .omit(); i { color: #8ea5c3; } ; } } } .gril { a.fz16 { overflow: hidden; white-space: nowrap; text-overflow: ellipsis; max-width: 70%; height: 100%; display: inline-block; } } /* 右边内容区 end */ .anli-navbar { z-index: 100; position: fixed; top: 80px; right: -160px; ul { width: 160px; padding: 10px; background: #fff; .box-shadow(0, 0, 6px, 0, rgba(0, 0, 0, .3)); } li { height: 42px; line-height: 40px; margin-bottom: 5px; &.active a, &:hover a { background: @green; border-color: @green; color: #fff; i { color: #fff; } } a { display: block; border: 1px solid @border; background: #eef1f7; padding: 0 15px; border-radius: 3px; } i { width: 20px; color: #8ea5c3; } } .go-top { width: 160px; display: block; .box-shadow(0, 0, 6px, 0, rgba(0, 0, 0, .3)); background: #fff; text-align: center; color: @yellow; padding: 10px 25px; margin-top: 15px; i { margin-right: 10px; } } .catalogue { position: absolute; top: 50%; left: -25px; margin-top: -55px; width: 25px; height: 110px; color: #fff; background: #06bdf2; display: block; text-align: center; padding: 10px 5px; font-size: 14px; border-radius: 5px 0 0 5px; .box-shadow(0, 1px, 4px, 0, rgba(0, 0, 0, .3)); } } .weibo-nav { top: 133px; } //预警管理右边 .zddx .right-content { > div { box-shadow: 0 0 6px 0 rgba(0, 0, 0, 0.2); margin: 15px; background: #fff; .sub-title { display: inline-block; color: #029be5; font-size: 16px; } .nav-wrap { border-top: none; border-left: none; min-height: 85%; width: 25%; position: inherit; } .nxjk { width: 75%; padding-left: 0; background: #fff; .r-ul { width: 100%; } .list-bottom-left { span { margin-left: 15px; i { color: @bule; } } } } } } .clearfloat:after { display: block; clear: both; content: ""; visibility: hidden; height: 0 } .clearfloat { zoom: 1 } .yj-zhh-zt { img { display: inline-block; cursor: pointer; } } .yj-tree .jstree-default .jstree-anchor { color: #333; width: 99%; .yj-tree-title { .txt(); display: inline-block; max-width: 36%; } .yj-tree-box { display: inline-block; vertical-align: super; .yj-icon { display: inline-block; //display: none; a { display: inline-block; width: 18px; height: 18px; vertical-align: middle; } } } } //弹窗 .alert-del { text-align: center; margin-top: 20px; margin-bottom: 20px; i { color: #029be5; } } .modal-dialog-del{ width: 410px; } .alert-gn { border: 1px solid #ddd; margin: 20px; border-radius: 3px; padding: 15px; min-height: 160px; ul { li { display: inline-block; width: 24%; margin-top: 10px; label { font-weight: normal; } } } } .sf-tongbu{ margin: 15px 0 20px 36px; color: #333; label{ font-weight: normal; margin-left: 15px; color: #333; } } .alert-new { margin: 20px; li { text-align: center; margin-bottom: 15px; span { display: inline-block; width: 80px; text-align: right; } input { border: 1px solid #ddd; border-radius: 3px; padding-left: 10px; width: 300px; } textarea { width: 300px; height: 100px; border-radius: 3px; padding: 0 10px; border: 1px solid #ddd; resize: none; overflow: hidden; vertical-align: text-top; } } } .alert-newuser { margin-top: 20px; > li { text-align: center; margin-bottom: 15px; > span { display: inline-block; width: 80px; text-align: right; vertical-align: top; line-height: 30px; img { display: inline-block; width: 5px; height: 5px; } } input { border: 1px solid #ddd; border-radius: 3px; padding-left: 10px; width: 300px; line-height: 28px; } textarea{ width: 300px; border: 1px solid #ddd; border-radius: 3px; padding-left: 10px; } .mod-fils{ width: 300px; display: inline-block; text-align: left; label{ min-width:70px; margin-right: 10px; } } p{ width: 300px; display: inline-block; text-align: left; label:last-child { margin-left: 15px; } } .pz-deatil{ width: inherit; } .alert-select { width: 300px; text-align: left; .dropdown-toggle { width: 160px; color: #333; display: flex; justify-content: space-between; align-items: center } .dropdown-menu { width: 160px; } } } .btn-u{ margin-left: 0; } } .bq-alert-newuser{ &.alert-newuser > li > span{ width: 90px; } >li{ .mod-fils,input,textarea{ width: 400px!important; } &.text-a-left{ text-align: left; } } .bq-modal-tip{ .circle-answer{ margin-left: 0; } span{ top: 38px; left: -18px; width: 110px; text-align: left; padding: 5px; &::after{ border-top: 5px solid transparent; border-bottom: 10px solid #eaf0f2; border-right: 5px solid transparent; border-left: 5px solid transparent; left: 12px; top: -14px; } } } .bq-add-btn-wrap{ display: inline-block; vertical-align: top; margin-left: 5px; width: 20px; i{ display: inline-block; width: 20px; height: 20px; border-radius: 3px; background: #a0b3cc; text-align: center; line-height: 16px; font-size: 32px; color: #fff; cursor: pointer; &.btn-bg-b{ background: #1389d0; } &:first-of-type{ margin-bottom: 30px; line-height: 20px; font-size: 26px; } } } .word-nums{ width: auto !important; height: 20px; line-height: 20px; vertical-align: top; margin-left: 10px; background: #eaf0f2; font-size: 12px; color: #556482; border-radius: 10px; padding: 0 10px; text-align: center; } .bq-tree-wrap{ display: inline-block; height: 220px; width: 400px; border: 1px solid #ddd; border-radius: 3px; padding: 10px 15px; .layut-input{ display: inline-block; input{ width: 200px !important; } } p{ color: #a0b3cc; font-size: 12px; margin-bottom: 5px; } .jstree{ width: 100%; height: 140px; } } } .dialog-wrap{ position: absolute; top: 50%; left: 50%; width: 206px; height: 80px; margin-left: -103px; margin-top: -40px; border-radius: 4px; box-shadow: 0 0 20px rgba(51,55,57,0.1); background-color: rgba(0,36,72,0.9); color: #fff; font-size: 18px; font-weight: bold; text-align: center; line-height: 80px; } .bq-modal-tip{ display: inline-block; position: relative; .circle-answer{ width: 18px; height: 18px; line-height: 18px; cursor: pointer; } span{ position: absolute; top: -2px; left: 35px; background: #eaf0f2; display: inline-block; border-radius: 3px; margin-left: 10px; font-weight: normal; line-height: 24px; padding: 2px 10px; z-index: 3; width: 400px; display: none; color: #556482; font-size: 12px; &:after { content: ''; width: 0; height: 0; border-top: 5px solid transparent; border-right: 10px solid #eaf0f2; border-bottom: 5px solid transparent; position: absolute; left: -7px; top: 9px; display: block; } } } .alert-userdetail { border: 1px solid #ddd; padding-top: 15px; margin-top: 10px; margin-bottom: 20px; >li{ text-align: left; span{ margin-right: 10px; } } } .alert-userdetail-title { color: #000; font-size: 16px; } .userdetail-body { max-height: inherit; margin: 0 50px 20px 50px; } @media screen and (max-width: 1600px) { .nav { li a { padding: 0 5px; } } .right-content .warn-box{ .tables td{ max-width: 8%; .txt(); } .dropdown-toggle{ min-width: 60px; } } .zddx .right-content > div .nav-wrap{ width: 30%; min-height: inherit; } .zddx .right-content > div .nxjk{ width: 70%; } } @media screen and (max-width: 1450px) { .nav > ul > li > a, .nav2 > ul > li > a { font-size: 16px; } .nav > ul > li ul li a, .nav2 > ul > li ul li a { font-size: 14px; } .nav-list { width: 150px; } .yj-tree .jstree-default .jstree-anchor { width: 103%; } .content { padding: 60px 0 0 150px; } .content1 { padding: 60px 0 0 50px; } .weibo-nav { top: 123px; } .tables { th { padding: 6px; } ; td { padding: 6px; } } .r-ul { > li { margin-right: 5px !important; } .order { a { margin-right: 0; } } .check-report { margin-left: 0 !important; } } .tool .layout-data input { width: 75px !important; } .tool input { width: 90px; } .harmful .tables .txt .tz-del { top: 0 !important; } .sbxf .sbxf-top label { margin-left: 8px !important; } } @media screen and (max-width: 1400px) { .logo { a { display: none; } } .nav { > ul { margin-left: 100px; } } .yj-tree .jstree-default .jstree-anchor { width: 112%; } .yj-tree .jstree-default .jstree-anchor .yj-tree-title { max-width: 26%; } } @media screen and (max-width: 1200px) { .nav, .nav2 { ul li a { font-size: 14px; padding: 0 5px; } } .set .user .user-name { max-width: 70px; } .yj-tree .jstree-default .jstree-anchor .yj-tree-title { max-width: 22%; } } @media screen and (max-width: 1024px){ .zddx .right-content > div .nxjk{ width: 69%; .zddx .tree-ul{ padding: 0 2px 0 5px; } } .right-content .warn-box{ .dropdown-toggle{ min-width: 60px; } } .yj-tree .jstree-default .jstree-anchor .yj-tree-title{ max-width: 18%; } .yj-tree .jstree-default .jstree-anchor { width: 156%; } .yj-tree .jstree-default .jstree-node{ margin-left: 10px; } } /* 任务统计 */ .tc-table { .layout-data input { padding: 0; height: 26px; line-height: 26px; width: 94px; border: none; text-align: center; border-radius: 3px; color: #06bdf2; } .once { display: block; } .dropdown-toggle { width: 100%; color: #333; border-radius: 3px; } .symbol { span { width: 20px; height: 20px; background: @line-color; display: inline-block; border-radius: 2px; color: #8ea5c3; text-align: center; line-height: 20px; cursor: pointer; &:hover { color: #fff; background: @bg-blue; } } } .table-label { label { margin-bottom: 0; } } } /*------------------*/ .search-icon { display: inline-block; position: absolute; top: 77px; right: 20px; color: #fff; cursor: pointer; } .search-icon2 { display: none; position: absolute; top: 81px; right: 20px; color: #029be5; cursor: pointer; } .search-box { height: 55px; background: #029be5; margin-top: -20px; margin-bottom: 2px; > input { display: none; width: 172px; height: 32px; line-height: 32px; margin-top: 12px; border-radius: 5px; margin-left: 14px; padding-left: 12px; border: none; } } .tabs-box{ width: 100%; display: flex; a{ display: inline-block; flex: 1; border-right: 1px solid #b3a3a3; padding: 3px 10px; text-align: center; color: #fff; background: #029be5; font-size: 14px; &:last-child{ border-right: 0 none; } &:hover{ color: #333; background: #fff; } &.active{ color: #333; background: #fff; } } } .xiala { display: block; position: absolute; left: 11px; top: 71px; .dropdown-menu { border-radius: 5px; } .border-r { border-radius: 5px; width: 101px; } } /*二级导航栏*/ .padd { position: absolute; left: 99px; top: 0; padding-left: 5px; } .innerLi { position: relative; width: 101px; .exband { display: none; position: absolute; right: 5px; } .innerBox { display: none; width: 106px; z-index: 9999; background: #fff; border: 2px solid transparent; border-radius: 5px; > li { width: 100%; height: 26px; line-height: 26px; text-align: center; > a { display: inline-block; width: 100%; &:hover { background: #eef1f7; color: #029be5; } } } } } .assign-user { display: inline-block; vertical-align: middle; margin-top: -2px; margin-left: 4px; } .tree-list { min-height: 390px; border: 1px solid #d3dbe3; padding: 10px; } /* 水利 start*/ .bar-main { position: relative; height: 100%; margin: 20px 60px 0; .regionBar { width: 100%; height: 90%; margin-bottom: 20px; #regionBar { width: 100%; height: 100%; } } } .left-btn { position: absolute; left: -47px; top: 50%; transform: translate(0, -50%); cursor: pointer; width: 36px; height: 36px; background: url('../images/btn-l.png'); &:hover { background: url('../images/btn-l-h.png'); } } .right-btn { position: absolute; right: -47px; top: 50%; transform: translate(0, -50%); cursor: pointer; width: 36px; height: 36px; background: url('../images/btn-r.png'); &:hover { background: url('../images/btn-r-h.png'); } } /* 水利 end*/ /*全局分析 start*/ .left-map { .red { position: absolute; bottom: 30px; left: 150px; } } .leader-box { padding-top: 5%; } .leader-table { width: 80%; margin: 0 auto 2%; padding: 30px; > h2 { margin-bottom: 20px; } .data { overflow: hidden; li { display: inline-block; width: 50%; float: left; padding: 15px 0; h2 { display: inline-block; vertical-align: middle; } } } } /*全局分析 end*/ .fayuzhi{ width:260px; padding: 15px; .yz-p{ margin-bottom: 12px; span{ width: 80px; height: 24px; line-height: 24px; display: inline-block; color:#8ea5c3; } input{ width: 65px; height: 24px; line-height: 22px; display: inline-block; border:1px solid #d3dbe3; color:#d3dbe3; padding: 0 4px; } input::-webkit-input-placeholder { /* WebKit browsers */ color: #9cb0c9; } input:-moz-placeholder { /* Mozilla Firefox 4 to 18 */ color: #9cb0c9; } input::-moz-placeholder { /* Mozilla Firefox 19+ */ color: #9cb0c9; } input:-ms-input-placeholder { /* Internet Explorer 10+ */ color: #9cb0c9; } } } .yz-ft{ text-align: right; .yz-btn{ width: 65px; height: 24px; background: #1389d0; display: inline-block; text-align: center; margin-left: 10px; color:#fff; font-size: 14px; border-radius:2px; } } .btn.btn-bg-lg{ background: -webkit-linear-gradient(top, #ffffff, #f0f3f6); background: linear-gradient(to bottom, #ffffff, #f0f3f6); border-radius: 2px; color: #333; border: 1px solid #d6e1e5; } .rm-manage{ .tool{ .btn-bg-lg{ min-width:80px; } } } .tip-sub-title{ font-size: 12px; color:#ffa640; } .yh-modal-edit{ padding: 15px 20px 5px; >div{ margin-bottom: 12px; } } /*全局分析右侧话题列表 start*/ .bg-red{ background:@red!important; } .topic-list{ ul{ li{ margin:0 14px; line-height:52px; border-bottom:1px dashed @border; .flex(); .num{ display:inline-block; width:25px; height:25px; line-height:25px; border-radius:1px; background:@bg-zise; color:#fff; text-align:center; margin-top: 12px; } .topic-text{ .l_flex(); .txt(); width:100%; display:inline-block; padding:0 10px; } .similar-reports{ color:@f-zise; } } } } /*全局分析右侧话题列表 end*/ /*下拉菜单 start*/ .dropdown-menu > { li{ > a{ line-height:30px; &+a{ border-bottom:1px solid @line-color; } &:hover,&:focus { background: #5ec45e; color: #fff; } } } } /*下拉菜单 end*/ /*新时间控件 start*/ .datetimepicker{ width: 135px; padding: 0 10px; line-height:28px; height:30px; } .timepicker-tange{ .border(); border-radius:1px; display:inline-block; line-height:28px; input{ border:none; width: 120px; padding: 0 5px; height:28px; } } /*新时间控件 end*/ /*提示弹窗 start*/ .prompt-box { display: none; background: rgba(0, 36, 72, 0.9); border-radius: 3px; color: #fff; text-align: center; padding: 35px 65px; position: absolute; z-index: 100; top: 50%; left: 50%; -webkit-transform: translateY(-50%); transform: translateY(-50%); } /*提示弹窗 end*/ @import "./_module.less"; /*原生滚动条样式 start*/ .g-scroll{ overflow-y:auto; } .g-scroll::-webkit-scrollbar { display:block; width: 4px; } .g-scroll::-webkit-scrollbar-thumb{ border-radius: 2px; background-color: rgb(204, 204, 204); } .g-scroll::-webkit-scrollbar-track{ background: #fff; } /*原生滚动条样式 end*/<file_sep>/app/less/other/warn.less /*预警管理 start*/ .table-btn { width: 22px; height: 22px; display: inline-block; } .icon-dx { background: url('../images/icon-dx.png') no-repeat center center; } .icon-tc { background: url('../images/icon-tc.png') no-repeat center center; } .icon-zd { background: url('../images/icon-zd.png') no-repeat center center; } .icon-rg { background: url('../images/icon-rg.png') no-repeat center center; } .icon-hot { background: url('../images/ic-hot.png') no-repeat center center; background-size: 14px 16px; width: 14px; height: 16px; display: inline-block; vertical-align: sub; } .icon-warm { display: inline-block; width: 16px; height: 15px; background: url('../images/icon-warm.png') no-repeat center center; vertical-align: sub; } .enread-sign { width: 30px; height: 16px; line-height: 16px; color: #fff; border-radius: 1px; background: #ff6068; font-size: 12px; text-align: center; display: inline-block; position: absolute; top: 2px; right: -35px; } .warn-box { .tables { tr { &:hover { .blue { color: @blue !important; } } } td { position: relative; } .pdr35 { padding-right: 35px; } .weibo { i { color: @red; font-size: 14px; } } .wechat { i { color: #34cf9d; font-size: 12px; } } .fwb { font-weight: bold; } } } .left-sign { width: 18px; height: 18px; display: inline-block; border-radius: 1px; text-align: center; line-height: 18px; color: #fff; position: absolute; left: -15px; &.hot { background: #ff6068; } &.tactful { background: #7180f4; } } .warn-cont { text-align: left; a { display: inline-block; } .title { font-weight: bold; position: relative; } .summary { font-size: 12px; } .warn-cont-msg { li { display: inline-block; font-size: 12px; margin-right: 15px; } } } .datetime { width: 110px !important; text-align: center; } #inform { .table-box { border: 1px solid @line-color; min-height: 200px; padding-top: 15px; } .form-control { width: 60px; text-align: center; } .dropdown { .dropdown-menu { max-height: 140px; } } } /*预警管理 end*/ /*自动预警方案 start*/ .warn-box { .anli { padding: 15px; } .newztfx-cont { margin-left: 0; } .tab-box, .zt-box { .btn { margin-top: 10px; margin-left: 15px; } } .tab-box { a { margin-right: 0; } .layut-input { padding: 0; input { width: 200px; } } } .zt-box { padding-top: 10px; .dropdown { float: left; margin-right: 5px; } .layut-input { a { top: 5px; } } } .dropdown-toggle { background: none; color: #333; min-width: 96px; } .dropdown-menu { min-width: 96px; text-align: center; } .sort-item { float: left; margin-right: 5px; .dropdown-toggle { min-width: 40px; } } .operate-icon { font-size: 18px; line-height: 18px; } .zt-ft { border-top: none; } } .main { position: relative; } .modal-auto { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); width: 320px; height: 140px; border-radius: 3px; background: #002448; opacity: 0.9; color: #fff; display: none; .box-shadow (0, 0, 20px, 0, rgba(51, 55, 57, 0.1)); .modal-auto-con { position: absolute; top: 50%; transform: translateY(-50%); width: 100%; text-align: center; } } /*自动预警方案 end*/ /*预警方案配置 start*/ .m-hd { .newztfx-cont { margin-left: 30px; } } .title-tip { .title-tip-box { position: absolute; top: 0px; left: 38px; background: #f7f1e5; display: inline-block; border-radius: 3px; margin-left: 10px; font-weight: normal; line-height: 24px; padding: 10px 20px; z-index: 2; width: 400px; .box-shadow (0, 0, 18px, 0, rgba(51, 55, 57, 0.2)); display: none; &:before { content: ''; width: 0; height: 0; border-top: 5px solid transparent; border-right: 10px solid #f7f1e5; border-bottom: 5px solid transparent; position: absolute; left: -10px; top: 5px; display: block; } h5 { line-height: 21px; padding: 5px 0; } } .exp-box { border-radius: 1px; line-height: 21px; margin-bottom: 10px; .box-shadow (0, 0, 18px, 0, rgba(51, 55, 57, 0.2)); p { padding: 10px 15px; } img { width: 100%; } } } .warn-body { .tc-table { td { padding-left: 0; } } .hide-text { top: 23px; left: 65px; color: #333; } } .warn-con { border: 1px solid @line-color; padding: 10px 20px; margin-bottom: -1px; > li { padding: 5px 0; position: relative; } .rectangle { margin-left: 10px; } .hide-text { position: relative; top: unset; left: unset; margin-left: 15px; display: inline-block; } .hot-msg { display: none; input { width: 60px; text-align: center; margin-right: 6px; padding: 0 5px; } } .sens-msg { display: none; label { margin-bottom: 0; } } .orange { color: #ff6b0f; } } .auto-warn-con { border: 1px solid @line-color; padding-top: 10px; margin-top: 20px; > li { padding: 5px 20px; } .more-box { padding: 0; .btn-more { font-weight: bold; margin-top: 10px; } .gjxx { margin-bottom: 0px; padding: 0px; } table { margin-bottom: 0; width: 100%; } } } .grey12.auto-warn { margin-left: 10px; } .grey12.artificial-warn { margin-left: 10px; display: none; } .grey12 { color: #999; font-size: 12px; } /*预警方案配置 end*/ /*个人信息 start*/ .msg-cont { width: 80%; margin: 30px auto 0; padding: 0px 150px 20px; h3 { color: @blue; font-weight: bold; position: relative; padding-left: 20px; margin: 35px 0 20px; &:before { content: ""; width: 4px; height: 20px; display: block; background: @blue; position: absolute; left: 0; top: 0; } } .pers-infmt-box { li { padding: 13px 0; } .pers-infmt-list { border: 1px solid @line-color; border-radius: 1px; h4 { font-weight: bold; background: #f2f8fb; line-height: 40px; padding: 0 20px 0 18px; span { font-weight: normal; color: #666; margin-left: 10px; } } .infmt-con { border-top: 1px solid @line-color; padding: 7px 20px 7px 18px; span { font-weight: bold; } } } } } .modal-msg { .modal-dialog { width: 460px; } .modal-body { height: 140px; position: relative; } .msg-body { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); li { white-space: nowrap; min-width: 250px; & + li { margin-top: 15px; } } .send-code { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; input { -webkit-box-flex: 1; -webkit-flex: 1; -ms-flex: 1; flex: 1; min-width: 140px; } .btn { margin-right: 0; } } } .modal-footer { padding: 0 0 40px 0; .btn { width: 100px; } } } /*个人信息 end*/ /*预警弹窗 start*/ /*右下弹窗 start*/ .warn-popup { width: 355px; max-height: 600px; position: absolute; bottom: -100%; right: 0; border-radius: 5px; padding: 0; } .warn-popup-title { color: #fff; padding: 8px; border-top-left-radius: 5px; border-top-right-radius: 5px; /*FILTER: progid: DXImageTransform . Microsoft . Gradient(gradientType = 0, startColorStr = #ff645c, endColorStr = #ff4454); !*IE 6 7 8*!*/ background: -ms-linear-gradient(left, #ff645c, #ff4454); /* IE 10 */ background: -moz-linear-gradient(left, #ff645c, #ff4454); /*火狐*/ background: -webkit-gradient(linear, 0% 100%, 0% 0%, from(#ff645c), to(#ff4454)); /*谷歌*/ background: -webkit-gradient(linear, 0% 100%, 0% 0%, from(#ff645c), to(#ff4454)); /* Safari 4-5, Chrome 1-9*/ background: -webkit-linear-gradient(left, #ff645c, #ff4454); /*Safari5.1 Chrome 10+*/ background: -o-linear-gradient(left, #ff645c, #ff4454); /*Opera 11.10+*/ h4 { display: inline-block; i { margin-right: 10px; } } a { color: #fff; display: inline-block; width: 25px; height: 100%; text-align: center; &:hover { color: #fff; } } } .warn-popup-main { max-height: 515px; padding-top: 5px; } .warn-popup-main-tab { border-bottom: 1px solid @line-color; ul { padding: 0 5px; margin-bottom: -1px; li { float: right; line-height: 37px; border-top-left-radius: 5px; border-top-right-radius: 5px; position: relative; height: 37px; margin-left: -30px; text-align: center; line-height: 45px; a { display: block; padding: 0 10px; } em { background: @red; color: #fff; border-radius: 15px; position: absolute; top: 0px; right: 15px; line-height: 14px; font-size: 12px; padding: 0 2px; z-index: 1; .box-shadow (0, 0, 2px, 0, rgba(18, 32, 40, 0.2)); } &:hover, &.active { z-index: 1; a { color: #ff6169; font-weight: bold; } } } .tab-left { background: url('../images/tab-left.png') no-repeat center bottom; width: 99px; padding-right: 10px; &:hover, &.active { background: url('../images/tab-left-a.png') no-repeat center bottom; } } .tab-mid { background: url('../images/tab-mid.png') no-repeat center bottom; width: 119px; &:hover, &.active { background: url('../images/tab-mid-a.png') no-repeat center bottom; } } .tab-right { background: url('../images/tab-right.png') no-repeat center bottom; width: 96px; padding-left: 10px; &:hover, &.active { background: url('../images/tab-right-a.png') no-repeat center bottom; } em { right: -3px; } } } } .warn-popup-main-list { max-height: 390px; ul { li { padding: 10px 15px; position: relative; & + li { border-top: 1px solid @line-color; } &:hover { .box-shadow (0, 0, 18px, 0, rgba(51, 55, 57, 0.3)); a { font-weight: bold; } } a { position: relative; display: inline-block; span { display: inline-block; font-size: 12px; color: #fff; width: 14px; height: 14px; border-radius: 1px; line-height: 14px; text-align: center; } .hot { background: @red; } .tactful { background: #7180f4; } } .icheckbox_flat-blue { width: 20px; margin: 0; float: left; } .weibo { color: @red; } .wechat { color: #34cf9d; } .remark { position: absolute; z-index: 1; width: 95%; top: 70%; left: 10px; display: none; .arrow-up { position: absolute; top: -10px; left: 35px; &:before { content: ""; width: 0; height: 0; border-left: 8px solid transparent; border-right: 8px solid transparent; border-bottom: 10px solid @line-color; position: absolute; top: -1px; } &:after { content: ""; width: 0; height: 0; border-left: 8px solid transparent; border-right: 8px solid transparent; border-bottom: 10px solid #fff; position: absolute; } } .arrow-down { position: absolute; bottom: 0px; left: 35px; display: none; &:before { content: ""; width: 0; height: 0; border-left: 8px solid transparent; border-right: 8px solid transparent; border-top: 10px solid @line-color; position: absolute; bottom: -11px; } &:after { content: ""; width: 0; height: 0; border-left: 8px solid transparent; border-right: 8px solid transparent; border-top: 10px solid #fff; position: absolute; } } &.shadow { .box-shadow (0, 0, 20px, 0, rgba(51, 55, 57, 0.4)); } } } } } .essay { vertical-align: middle; } .icon-essay { background: url('../images/icon-essay.png') no-repeat center center; width: 14px; height: 12px; display: inline-block; } .icon-topic { background: url('../images/icon-topic.png') no-repeat center center; display: inline-block; width: 14px; height: 14px; vertical-align: text-top; background-size: cover; } .icon-social { background: url('../images/icon-social.png') no-repeat center center; display: inline-block; width: 14px; height: 14px; vertical-align: text-top; background-size: cover; } .icon-website { background: url('../images/icon-website.png') no-repeat center center; display: inline-block; width: 14px; height: 14px; vertical-align: text-top; background-size: cover; } .warn-popup-list-right { margin-left: 30px; line-height: 18px; .unread { background: @red; width: 10px; height: 10px; border-radius: 50%; display: inline-block; vertical-align: middle; margin-right: 2px; position: absolute; top: -6px; right: -6px; } .warn-popup-list-msg { font-size: 12px; margin-top: 5px; .pull-right { color: #666; } } } .warn-popup-footer { background: #fff; border-top: 1px solid @line-color; padding: 10px; border-bottom-left-radius: 5px; border-bottom-right-radius: 5px; } .input-change { border: 1px solid #d6e1e5; border-radius: 3px; display: inline-block; .input-blue { border: none !important; } } /*右下弹窗 end*/ /*操作弹窗 start*/ .warn-popup-box { .modal-dialog { max-width: 750px; min-width: 600px; width: 50%; margin-top: 4%; } .newztfx-cont { margin-left: 0; } .modal-title { display: inline-block; } .modal-body { max-height: 700px; } .form-control, .dropdown-toggle { color: #333; } .warn-list { > li { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; padding: 5px 0; } .category { display: inline-block; width: 95px; text-align: right; margin-right: 5px; em { vertical-align: sub; margin-right: 10px; } } .warn-cause-tip { .warn-right { span { padding: 0 8px; height: 30px; border: 1px solid @line-color; border-radius: 3px; line-height: 28px; background: #fff; display: inline-block; position: relative; } .mg-level { display: none; &:before { content: ""; width: 0; height: 0; border-left: 8px solid transparent; border-right: 8px solid transparent; border-bottom: 10px solid @line-color; position: absolute; top: -11px; left: 10px; } &:after { content: ""; width: 0; height: 0; border-left: 8px solid transparent; border-right: 8px solid transparent; border-bottom: 10px solid #fff; position: absolute; top: -10px; left: 10px; } } .hot-value { &:before { content: ""; width: 0; height: 0; border-left: 8px solid transparent; border-right: 8px solid transparent; border-bottom: 10px solid @line-color; position: absolute; top: -11px; left: 80px; } &:after { content: ""; width: 0; height: 0; border-left: 8px solid transparent; border-right: 8px solid transparent; border-bottom: 10px solid #fff; position: absolute; top: -10px; left: 80px; } } } } .hot-value { line-height: 30px; .warn-right { input { width: 60px; text-align: center; padding: 0 5px; } } } .mg-level { line-height: 30px; display: none; } } .bgg { background: #f7f8fa; margin-top: 10px; padding: 15px 0; } .warn-right { display: inline-block; -webkit-box-flex: 1; -webkit-flex: 1; -ms-flex: 1; flex: 1; textarea { line-height: 21px; padding: 5px 10px; min-height: 80px; } label { padding-right: 20px; } .orange { color: #ff6b0f; } .dropdown { .dropdown-menu { max-height: 200px; } } } .btn-more { color: @blue; font-weight: bold; width: 88px; text-align: right; display: inline-block; line-height: 40px; } .gjxx { padding: 20px 0; > li { padding: 5px 0; } } .inline-button { padding-right: 15px; } } .warn-type { li { display: inline-block; margin-right: 10px; margin-bottom: 5px; a { border: 1px solid @line-color; border-radius: 1px; padding: 0 15px; line-height: 28px; display: inline-block; background: #fff; &:hover, &.active { color: #fff; background: @green; } } } } .modal-footer .btn:hover { color: #fff; } /*操作弹窗 end*/ /*预警弹窗 end*/ /* 预警主页提醒设置弹窗样式 */ .g-zlm-txsz { .table-box { background: #F4F7FA; width: 560px; height: 260px; margin: 0 auto; } .modal-title { margin-left: 5px; } .modal-footer { margin: 10px 0; } .g-zlm-ul { li { float: left; margin: 0 6px 11px 5px; a { display: inline-block; width: 58px; height: 24px; line-height: 24px; text-align: center; border-radius: 2px; border: 1px solid #049BE5; color: #049BE5; } &:hover { a { color: #fff; background: #5EC45E; border: none; } } } .active { a { color: #fff; background: #5EC45E; border: none; } } } .tc-table td { padding: 0; .esp { width: 38px !important; margin: 0 6px; } input { height: 24px; margin-right: 14px !important; } } .dropdown-toggle { height: 24px; line-height: 24px; .caret { color: #8EA5C3; } } .g-zlm-ulyjsz { li { margin-bottom: 12px; margin-left: 6px; color: #5E5E5E; .sp1 { color: #1489D0; } textarea { vertical-align: top; outline: none; border: 1px solid #D6E1E5; width: 513px; height: 78px; padding: 10px 10px 0 10px; overflow: auto; } } } } #inform .modal-body .table-box { border: none; } /* 预警主页舆情预警弹窗 */ .g-zlm-warn.warn-popup { width: 400px; } .g-zlm-warn { .hot, .mg { position: relative; display: inline-block; margin-left: 19px; .active { background: #BF4546; border-radius: 20px; border: 2px solid #FF8E8E; } .num { color: #FF5057; font-size: 12px; background: #fff; position: absolute; top: -3px; right: -7px; border-radius: 20px; padding: 0px 6px; line-height: 1; height: 13px; } } .hot, .mg { a { color: #fff; width: 48px; height: 24px; text-align: center; line-height: 21px; font-size: 12px; } } .zlm-popup-main { li { padding: 18px; border-bottom: 1px dotted #D3DBE3; a { margin-bottom: 5px; color: #363636; font-size: 16px; .sp2 { display: inline-block; width: 333px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } } .sp1 { position: relative; top: -6px; } .sp3 { color: #029BE5; } .sp4 { color: #8EA5C3; } .tm { font-size: 12px; i { display: inline-block; width: 12px; height: 12px; background: url(../images/zlm717_03.png); position: relative; top: 1px; } } } } } .g-zlm-yjzy { .zt-box { padding-left: 20px; .wd { margin-top: 9px; } div.dropdown { margin-right: 20px; } } .zt-page { padding-left: 227px; a.active, a:hover { background: #38AFEA; color: #fff; } } .dropdown-toggle { line-height: 30px; } .btn { line-height: 28px; } .inline-button > a { line-height: 32px; } } .g-zlm-yjnew { ul { li { position: relative; border-bottom: 1px solid #D6DDE5; padding-bottom: 1px; .big-box { padding: 16px 16px 16px 20px; } .title-box { > div { float: left; color: #363636; font-size: 16px; a { color: #363636; } } .d1 { font-weight: 900; } .word { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; max-width: 995px; } .hot { color: #fff; background: #F65858; width: 32px; height: 18px; line-height: 18px; text-align: center; font-size: 12px; position: relative; top: 4px; margin: 0 4px; } .like { color: #8EA5C3; margin-left: 4px; } } .bottom-intro { position: relative; margin-top: 4px; font-size: 12px; .intro-l { .i1 { display: inline-block; width: 12px; height: 12px; background: url(../images/zlm717_03.png); position: relative; top: 1px; } .sp3 { color: #37AEEA; } .sp4 { color: #8EA5C3; } .ep { margin-right: 20px; } } .intro-r { margin-left: 20px; color: #FFA643; .number { background: #FFF6EC; border: 1px solid #FFA643; padding: 0 7px; border-radius: 10px; margin-right: 10px; } } .toggleBtn { width: 37px; height: 7px; background: url(../images/zlm7171_03.png); position: absolute; bottom: -17px; left: 525px; cursor: pointer; } } .orign { display: none; height: 30px; width: 100%; background: #F4F7FA; font-size: 12px; color: #7A7A7A; padding-left: 20px; line-height: 30px; .cr { color: #363636; margin-right: 24px; } } .btnList { position: absolute; right: 24px; top: 46px; i { width: 20px; height: 20px; display: inline-block; cursor: pointer; } .i1 { background: url(../images/zlm717_05.png) no-repeat; } .i2 { background: url(../images/zlm717_07.png) no-repeat; margin: 0 5px; } .i3 { background: url(../images/zlm717_09.png) no-repeat; } } } } } .g-zlm-yjfzsz { .objectbox { > div { padding: 14px 0 0 18px; width: 296px; height: 300px; background: #F4F7FA; } .layut-input { width: 260px; } .box-rt { ul { padding-top: 14px; } li { position: relative; padding: 0px 15px; border: 1px solid #D3DBE3; color: #363636; background: #F9FAFD; float: left; margin: 0 10px 10px 0; .close { position: absolute; right: -7px; top: -6px; width: 14px; height: 14px; background: #F54848; line-height: 14px; text-align: center; color: #fff; border-radius: 50%; font-size: 12px; } } .wxtz { color: #666; font-size: 12px; margin: 32px 0 0 90px; } } } .g-zlm-ulyjsz { padding-left: 18px; } } .g-zlm-jzbj { .form-control { color: #a5a5a5; } width: 1200px; margin: 0 auto; background: #fff; height: 100%; padding-top: 60px; .titleBox { padding: 10px 20px; border: 1px solid #E0E5EB; border-bottom: none; .title { padding-top: 4px; font-size: 18px; color: #1289D0; font-weight: 900; } } .contentBox { position: relative; padding: 26px 0 0 14px; border: 1px solid #E0E5EB; height: 100%; .ct-ul { > li { margin-bottom: 16px; span { display: inline-block; width: 90px; text-align: right; color: #363636; i { color: #F66D6D; position: relative; top: 3px; margin-right: 4px; } } input { margin-right: 20px; } input.esp { padding-left: 10px; } .esp { width: 720px; height: 28px; border: 1px solid #E0E8EB; border-radius: 3px; } textarea { vertical-align: top; height: 72px !important; color: #90A6C4; } label { margin-right: 20px; } .closeBox { position: relative; padding: 2px 15px; border: 1px solid #D3DBE3; color: #363636; background: #F9FAFD; float: left; margin-right: 20px; border-radius: 3px; .close { position: absolute; right: -7px; top: -6px; width: 14px; height: 14px; background: #F54848; line-height: 14px; text-align: center; color: #fff; border-radius: 50%; font-size: 12px; } } .addBox { width: 60px; height: 28px; background: #1289D0; border-radius: 3px; text-align: center; line-height: 28px; float: left; cursor: pointer; .add { font-size: 16px; color: #fff; font-weight: 900; } } } } .btnBox { margin-top: 70px; position: absolute; left: 50%; transform: translateX(-50%); > div { width: 100px; height: 30px; text-align: center; line-height: 30px; border-radius: 5px; background: #1289D0; color: #fff; margin-right: 10px; cursor: pointer; } } } } .ZlmUlBox { width: 560px; height: 206px; border: 1px solid #E0E9EC; border-radius: 3px; padding: 18px 0 0 18px; li { float: left; margin: 0 26px 14px 0; } } .ZlmUlBigBox { .choose { margin: 13px 0 0 334px; color: #8D8D8D; span { color: #029BE5; } } } /*预警主页管理 提醒设置弹窗 New start*/ .st-remind { &.g-zlm-txsz { .g-zlm-ul { li { margin: 0 6px 18px 5px; } } } .modal-body { overflow: inherit !important; } .tc-all { padding: 10px 18px 1px; min-height: 200px; border-radius: 1px; background-color: #f2f6fa; .tc-modal { > ul { > li { padding-left: 12px; margin-bottom: 19px; &:nth-of-type(1) { margin-bottom: 20px; } label { width: 70px; line-height: 27px; margin-right: 5px; text-align: right; font-size: 14px; margin-left: 12px; color: #333333; } .dx-all { > span { margin-top: 3px; margin-right: 14px; display: inline-block; } } &.yj-type { position: relative; padding: 20px 0 15px 12px; background-color: #ffffff; border: 1px solid #ebf1f7; &:before { display: inline-block; content: '预警类型设置'; color: #1389d0; font-weight: bold; position: absolute; top: -11px; } .esp { width: 40px !important; height: 24px; border-radius: 2px; background-color: #ffffff; border: 1px solid #d3dbe3; padding: 0; text-align: center; letter-spacing: 1px; color: #333333; margin: 0 6px; } .yj-xi { &:nth-of-type(2) { margin-top: 20px; p { > span { margin-right: 14px; } } } } } //日期 .dropdown { .dropdown-menu { width: 66px; min-width: 66px; } .dropdown-toggle { line-height: 22px; } } .input-change { margin-left: -7px; input { width: 58px; padding: 2px 10px 0; height: 24px; border-radius: 2px; background-color: #ffffff; border: 1px solid #d3dbe3; } &.ch-er{ margin-left: 0; } } .pl-all { > span { margin-right: 3px; } .esp { width: 40px !important; height: 24px; border-radius: 2px; background-color: #ffffff; border: 1px solid #d3dbe3; padding: 0; font-size: 14px; letter-spacing: 1px; color: #8ea5c3; text-align: center; margin: 0 2px; } } } } } .r-sort{ color: #8ea5c3; padding-left: 91px; font-size: 12px; margin-top: 12px; } .icheckbox_flat-blue, .iradio_flat-blue { margin-top: -2px; } } } /*预警主页管理 提醒设置弹窗 New end*/ /*预警主页 微信绑定弹窗 start*/ #wechat{ .modal-dialog{ width:500px; } } .wechat-box{ padding:20px; position:relative; .wechat-right{ margin-left:15px; position:absolute; top: 50%; transform: translateY(-50%); left: 200px; p{ line-height:36px; } } } /*预警主页 微信绑定弹窗 end*/
e89939b4ba173089213329f9f6a0d801c9899e6f
[ "HTML", "EJS", "JavaScript", "JSON", "Less" ]
24
HTML
kekeen/chongqingzhongdian
17876241da5c982ef444a0af7ffa2f7cd1471f41
42873618b57a58457236fe95b801301ec7ef989b
refs/heads/master
<file_sep># micro-ROS-Agent [![GitHub license](https://img.shields.io/github/license/microROS/micro-ROS-Agent.svg)](https://github.com/microROS/micro-ROS-Agent) [![GitHub release](https://img.shields.io/github/release/microROS/micro-ROS-Agent.svg)](https://github.com/microROS/micro-ROS-Agent/releases) ROS 2 package using Micro XRCE-DDS Agent. <file_sep># Copyright 2018 Proyectos y Sistemas de Mantenimiento SL (eProsima). # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Set CMake version cmake_minimum_required(VERSION 3.5) # Set proyect name project(micro_ros_agent) set(CMAKE_C_CLANG_TIDY clang-tidy -checks=*) # Default to C++14 if(NOT CMAKE_CXX_STANDARD) set(CMAKE_CXX_STANDARD 14) endif() if(CMAKE_COMPILER_IS_GNUCXX OR CMAKE_CXX_COMPILER_ID MATCHES "Clang") add_compile_options(-Wall -Wextra -Wpedantic) endif() # Find packages depencences find_package(rosidl_cmake REQUIRED) find_package(ament_cmake REQUIRED) find_package(fastcdr REQUIRED CONFIG) find_package(fastrtps REQUIRED CONFIG) find_package(microxrcedds_agent REQUIRED CONFIG) find_package(ament_cmake_python REQUIRED) # Export dependencies to downstream packages ament_export_dependencies(fastcdr) ament_export_dependencies(fastrtps) ament_export_dependencies(microxrcedds_agent) # Set variables set(_OUTPUT_PATH "${CMAKE_CURRENT_BINARY_DIR}/python") set(_XML_INTERFACE_GEN_BIN "${_OUTPUT_PATH}/bin/Xml_interface_gen.py") normalize_path(_XML_INTERFACE_GEN_BIN "${_XML_INTERFACE_GEN_BIN}") set(_XML_DEFAULT_READ_BIN "${_OUTPUT_PATH}/bin/Xml_read_default_profiles.py") normalize_path(_XML_DEFAULT_READ_BIN "${_XML_DEFAULT_READ_BIN}") set(_PYTHON_PKG_TOOL ${PROJECT_NAME}) set(_RESOURCE_DIR "${_OUTPUT_PATH}/resource") normalize_path(_RESOURCE_DIR "${_RESOURCE_DIR}") set(_DEFAULT_FASTRTPS_PROFILES_PATH "${_OUTPUT_PATH}/gen/DEFAULT_FASTRTPS_PROFILES.xml") normalize_path(_DEFAULT_FASTRTPS_PROFILES_PATH "${_DEFAULT_FASTRTPS_PROFILES_PATH}") # Get colcon call dir get_filename_component(_COLCON_CALL_DIR "${PROJECT_BINARY_DIR}" DIRECTORY) get_filename_component(_COLCON_CALL_DIR "${_COLCON_CALL_DIR}" DIRECTORY) # Generate python header set( _PYTHON_SCRIPT_HEAD " import os\n import sys\n sys.path.append('${_OUTPUT_PATH}')\n from ${_PYTHON_PKG_TOOL} import *\n " ) # Copy pyton files file(COPY "bin" "${_PYTHON_PKG_TOOL}" "resource" DESTINATION "${CMAKE_CURRENT_BINARY_DIR}/python") # Extract all packages and manifiest paths execute_process( COMMAND "${PYTHON_EXECUTABLE}" "-c" "${_PYTHON_SCRIPT_HEAD}for package in GetInterfacePackages(GetPackageList('${_COLCON_CALL_DIR}')): print ('%s,%s' % (package, GetPackageName(package)))" OUTPUT_VARIABLE _packages RESULT_VARIABLE _result OUTPUT_STRIP_TRAILING_WHITESPACE ) if(NOT _result EQUAL 0) message(FATAL_ERROR "Error finding xml packages") endif() # Convert output to list string(REPLACE "\n" ";" _packages ${_packages}) # Extract all msg from each package (stored in ${package}_MSG_FILES) set(ALL_MSG_FILES "") foreach(package ${_packages}) # Extract info string(REPLACE "," ";" package ${package}) list(GET package 0 package_file) list(GET package 1 package) # Get all msg files execute_process( COMMAND "${PYTHON_EXECUTABLE}" "-c" "${_PYTHON_SCRIPT_HEAD}for msg in GetInterfacePackageMsgs('${package_file}'): print ('%s' % msg)" OUTPUT_VARIABLE ${package}_MSG_FILES RESULT_VARIABLE _result OUTPUT_STRIP_TRAILING_WHITESPACE ) if(NOT _result EQUAL 0) message(FATAL_ERROR "Error finding .msg files") endif() # Skip if there are no msgs to create if(${package}_MSG_FILES STREQUAL "") continue() endif() # Generate list string(REPLACE "\n" ";" ${package}_MSG_FILES ${${package}_MSG_FILES}) endforeach() # Append defaul xml profiles execute_process( COMMAND "${PYTHON_EXECUTABLE}" "${_XML_DEFAULT_READ_BIN}" "--default-xml-path" "${_RESOURCE_DIR}" OUTPUT_VARIABLE _XmlDoc RESULT_VARIABLE _result ) if(NOT _result EQUAL 0) message(FATAL_ERROR "Error in typesuppor generation") endif() # Create one xml for each message foreach(package ${_packages}) string(REPLACE "," ";" package ${package}) list(GET package 0 package_file) list(GET package 1 package) # Skip this generation if there are no msgs to process if(${package}_MSG_FILES STREQUAL "") continue() endif() # generate script argument file set(generator_arguments_file "${_OUTPUT_PATH}/XML_ArgFiles/${package}_Args.json") rosidl_write_generator_arguments( "${generator_arguments_file}" PACKAGE_NAME "${package}" ROS_INTERFACE_FILES "${${package}_MSG_FILES}" ROS_INTERFACE_DEPENDENCIES "NULL" OUTPUT_DIR "NULL" TEMPLATE_DIR "NULL" TARGET_DEPENDENCIES "NULL" ADDITIONAL_FILES "" ) # execute python script execute_process( COMMAND "${PYTHON_EXECUTABLE}" "${_XML_INTERFACE_GEN_BIN}" --generator-arguments-file "${generator_arguments_file}" OUTPUT_VARIABLE _XmlGen RESULT_VARIABLE _result ) if(NOT _result EQUAL 0) message(FATAL_ERROR "Error in typesuppor generation") endif() # Strore xml set(_XmlDoc "${_XmlDoc}${_XmlGen}") endforeach() # Close profile set (_XmlDoc "<profiles>\n${_XmlDoc}</profiles>\n") # Save file(WRITE "${_DEFAULT_FASTRTPS_PROFILES_PATH}" "${_XmlDoc}") # Only compile uROS agent if rclcpp is found find_package(rclcpp QUIET) if (rclcpp_FOUND) find_package(microxrcedds_agent REQUIRED) add_executable(${PROJECT_NAME} src/main.cpp) ament_target_dependencies( ${PROJECT_NAME} rclcpp microxrcedds_agent ) # TODO(Javier) Temporal until thread error is solver target_link_libraries( ${PROJECT_NAME} microxrcedds_agent ) else() message("uROS agent node will be not build") endif() # Install the package.xml file, and generate code for ``find_package`` so that other packages can get information about this package. ament_package() # Only install if uROS_Agent is comiled if (rclcpp_FOUND) install(TARGETS ${PROJECT_NAME} DESTINATION lib/${PROJECT_NAME} ) endif() #Install install( FILES "${_DEFAULT_FASTRTPS_PROFILES_PATH}" DESTINATION lib/${PROJECT_NAME} ) # Install package #install( # DIRECTORY cmake resource # DESTINATION share/${PROJECT_NAME} #) <file_sep>#include <rclcpp/rclcpp.hpp> #include <std_msgs/msg/string.hpp> class TestSubscriber : public rclcpp::Node { private: rclcpp::Subscription<std_msgs::msg::String>::SharedPtr subscription_; void topic_callback_(const std_msgs::msg::String::SharedPtr msg); public: TestSubscriber(); };<file_sep>#include "test_subscriber.hpp" void TestSubscriber::topic_callback_(const std_msgs::msg::String::SharedPtr msg) { RCLCPP_INFO(this->get_logger(), "I heard: %s", msg->data.c_str()); } TestSubscriber::TestSubscriber() : Node("test_subscriber_note") { subscription_ = this->create_subscription<std_msgs::msg::String>( "topic_test", std::bind(&TestSubscriber::topic_callback_, this, std::placeholders::_1)); }<file_sep>#! /bin/bash set -e set -o nounset set -o pipefail [ -d $FW_TARGETDIR ] || mkdir $FW_TARGETDIR pushd $FW_TARGETDIR >/dev/null vcs import --input $PREFIX/config/$RTOS/generic/uros_packages.repos >/dev/null # install uclibc if [ ! -d "NuttX/libs/libxx/uClibc++" ] then pushd uclibc >/dev/null ./install.sh ../NuttX popd >/dev/null fi # ignore broken packages touch mcu_ws/ros2/rcl_logging/rcl_logging_log4cxx/COLCON_IGNORE touch mcu_ws/ros2/rcl/rcl_action/COLCON_IGNORE rosdep install -y --from-paths mcu_ws -i mcu_ws --rosdistro dashing --skip-keys="$SKIP" # turn off features which don't compile on NuttX currently echo -e ",s/PROFILE_DISCOVERY=TRUE/PROFILE_DISCOVERY=FALSE/\n,s/PROFILE_TCP_TRANSPORT=TRUE/PROFILE_TCP_TRANSPORT=FALSE/g\nw" | ed $(find mcu_ws -name client.config) >/dev/null popd >/dev/null cp $PREFIX/config/$RTOS/generic/package.xml $FW_TARGETDIR/apps/package.xml rosdep install -y --from-paths $FW_TARGETDIR/apps -i $FW_TARGETDIR/apps --rosdistro dashing <file_sep># micro-ROS build support ## Installation and Building This package contains submodules. Please clone it using ```git clone --recursive ...``` ## micro_ros_setup Support scripts for creating Micro-ROS agent and client workspaces, and cleanly doing cross-compilation. See [micro_ros_setup README](micro_ros_setup/README.md) for usage instructions. ## Purpose of the project The software is not ready for production use. It has neither been developed nor tested for a specific use case. However, the license conditions of the applicable Open Source licenses allow you to adapt the software to your needs. Before using it in a safety relevant setting, make sure that the software fulfills your requirements and adjust it according to any applicable safety standards (e.g. ISO 26262). ## License micro-ros-build is open-sourced under the Apache-2.0 license. See the [LICENSE](LICENSE) file for details. micro-ros-build does not include other open source components, but uses some at compile time. See the file [3rd-party-licenses.txt](3rd-party-licenses.txt) for a detailed description. ## Known issues/limitations * There are currently sometimes compile issues when building the firmware for the first time. When building it a second time, this disappear. It it not known why this happens, we're investigating it. <file_sep>pushd $FW_TARGETDIR >/dev/null # Install toolchain mkdir toolchain # Install toolchain echo "Downloading ARM compiler, this may take a while" curl -fsSLO https://developer.arm.com/-/media/Files/downloads/gnu-rm/8-2019q3/RC1.1/gcc-arm-none-eabi-8-2019-q3-update-linux.tar.bz2 tar --strip-components=1 -xvjf gcc-arm-none-eabi-8-2019-q3-update-linux.tar.bz2 -C toolchain > /dev/null rm gcc-arm-none-eabi-8-2019-q3-update-linux.tar.bz2 # Import repos vcs import --input $PREFIX/config/$RTOS/$PLATFORM/board.repos >/dev/null # ignore broken packages touch mcu_ws/ros2/rcl_logging/rcl_logging_log4cxx/COLCON_IGNORE touch mcu_ws/ros2/rcl/rcl_action/COLCON_IGNORE touch mcu_ws/ros2/rcl/COLCON_IGNORE rosdep install -y --from-paths mcu_ws -i mcu_ws --rosdistro dashing --skip-keys="$SKIP" # Turn off features MicroXRCEClient echo -e ",s/PROFILE_DISCOVERY=TRUE/PROFILE_DISCOVERY=FALSE/\n,s/PROFILE_UDP_TRANSPORT=TRUE/PROFILE_UDP_TRANSPORT=FALSE/\n,s/PROFILE_TCP_TRANSPORT=TRUE/PROFILE_TCP_TRANSPORT=FALSE/g\nw" | ed $(find mcu_ws -name client.config) >/dev/null &>/dev/null popd >/dev/null<file_sep># ROS2_practice This repository is the "src" directory in the workspace of ROS2(dashing)
41b142508c7b2b3e19fa072b6ec4e8e12d75e18e
[ "Markdown", "C++", "Shell", "CMake" ]
8
Markdown
YasuChiba/ROS2_practice
dd832ec4369577d37859b80e3fe7ea12bfd5a30a
c4f5d17dfd11074de5f7d4eb08b9cc1f47d52dc9
refs/heads/master
<repo_name>nicktindall/cyclon.p2p-vanillajs-example<file_sep>/README.md # Minimal vanilla JS example of cyclon.p2p to run: `npm install && npm run start` <file_sep>/src/StatsReporter.js class StatsReporter { constructor(logger) { this.logger = logger; this.successfulShuffles=0; this.errorShuffles=0; this.timeoutShuffles=0; } logStats() { let totalShuffles = this.successfulShuffles + this.errorShuffles + this.timeoutShuffles; let successPct = ((this.successfulShuffles / totalShuffles) * 100).toFixed(0); let errorPct = ((this.errorShuffles / totalShuffles) * 100).toFixed(0); let timeoutPct = ((this.timeoutShuffles / totalShuffles) * 100).toFixed(0); this.logger.info( `${totalShuffles} shuffles completed: ------------------------ ${this.successfulShuffles} successful shuffles (${successPct}%) ${this.errorShuffles} errored shuffles (${errorPct}%) ${this.timeoutShuffles} timed out shuffles shuffles (${timeoutPct}%)`); } recordSuccesss() { this.successfulShuffles++; this.logStats(); } recordError() { this.errorShuffles++; this.logStats(); } recordTimeout() { this.timeoutShuffles++; this.logStats(); } } module.exports.StatsReporter = StatsReporter;
24ebb8b4293609862b2c0ba542ad6bf3b0c9d995
[ "Markdown", "JavaScript" ]
2
Markdown
nicktindall/cyclon.p2p-vanillajs-example
47d104a72c27563a3f0bb066f09762de7b7070c0
5e00c4a709712cebdab46da2ab256d7869441717
refs/heads/master
<file_sep>[sripagadala@ip-172-31-11-85 root]$ time hadoop jar /opt/cloudera/parcels/CDH-5.9.1-1.cdh5.9.1.p0.4/lib/hadoop-mapreduce/hadoop-mapreduce-examples-2.6.0-cdh5.9.1.jar teragen -Dmapreduce.job.maps=4 -D dfs.block.size=33554432 100000000 /user/sripagadala/teragen.out real 2m24.434s user 0m6.063s sys 0m0.261s [sripagadala@ip-172-31-11-85 root]$ hadoop fs -du -s -h /user/sripagadala/teragen.out 9.3 G 18.6 G /user/sripagadala/teragen.out [sripagadala@ip-172-31-11-85 root]$ time sudo -u hdfs hadoop jar /opt/cloudera/parcels/CDH-5.9.1-1.cdh5.9.1.p0.4/lib/hadoop-mapreduce/hadoop-mapreduce-examples-2.6.0-cdh5.9.1.jar terasort /user/sripagadala/teragen.out /user/hduser/terasort-output.out real 6m16.941s user 0m9.119s sys 0m0.354s <file_sep>1.What is ubertask optimization? Enabling it runs “sufficiently small” jobs sequentially within a single JVM. This property can be changed in Performance category. Property name is mapreduce.job.ubertask.enable 2. Where in CM is the Kerberos Security Realm value displayed? The Kerberos default realm is configured in the libdefaults property in the /etc/krb5.conf file on every host in the cluster In the Cloudera Manager Admin Console, select Administration > Settings. Click the Security category, and enter the Kerberos realm for the cluster in the Kerberos Security Realm field (for example, YOUR-LOCAL-REALM.COM or YOUR-SUB-REALM.YOUR-LOCAL-REALM.COM) that you configured in the krb5.conf file. Click Save Changes 3.Which CDH service(s) host a property for enabling Kerberos authentication? 4.How do you upgrade the CM agents? 5.Give the tsquery statement used to chart Hue's CPU utilization? 6.Name all the roles that make up the Hive service 7.What steps must be completed before integrating Cloudera Manager with Kerberos? <file_sep>1. Check vm.swappiness on all your nodes Set the value to 1 if necessary cat /proc/sys/vm/swappiness echo 1 > /proc/sys/vm/swappiness 2.Show the mount attributes of your volume(s) [root@ip-172-31-6-38 etc]# mount -v sysfs on /sys type sysfs (rw,nosuid,nodev,noexec,relatime,seclabel) proc on /proc type proc (rw,nosuid,nodev,noexec,relatime) devtmpfs on /dev type devtmpfs (rw,nosuid,seclabel,size=15340256k,nr_inodes=3835064,mode=755) securityfs on /sys/kernel/security type securityfs (rw,nosuid,nodev,noexec,relatime) tmpfs on /dev/shm type tmpfs (rw,nosuid,nodev,seclabel) devpts on /dev/pts type devpts (rw,nosuid,noexec,relatime,seclabel,gid=5,mode=620,ptmxmode=000) tmpfs on /run type tmpfs (rw,nosuid,nodev,seclabel,mode=755) tmpfs on /sys/fs/cgroup type tmpfs (ro,nosuid,nodev,noexec,seclabel,mode=755) cgroup on /sys/fs/cgroup/systemd type cgroup (rw,nosuid,nodev,noexec,relatime,xattr,release_agent=/usr/lib/systemd/systemd-cgroups-agent,name=systemd) pstore on /sys/fs/pstore type pstore (rw,nosuid,nodev,noexec,relatime) cgroup on /sys/fs/cgroup/cpuset type cgroup (rw,nosuid,nodev,noexec,relatime,cpuset) cgroup on /sys/fs/cgroup/cpu,cpuacct type cgroup (rw,nosuid,nodev,noexec,relatime,cpuacct,cpu) cgroup on /sys/fs/cgroup/hugetlb type cgroup (rw,nosuid,nodev,noexec,relatime,hugetlb) cgroup on /sys/fs/cgroup/memory type cgroup (rw,nosuid,nodev,noexec,relatime,memory) cgroup on /sys/fs/cgroup/devices type cgroup (rw,nosuid,nodev,noexec,relatime,devices) cgroup on /sys/fs/cgroup/blkio type cgroup (rw,nosuid,nodev,noexec,relatime,blkio) cgroup on /sys/fs/cgroup/freezer type cgroup (rw,nosuid,nodev,noexec,relatime,freezer) cgroup on /sys/fs/cgroup/net_cls type cgroup (rw,nosuid,nodev,noexec,relatime,net_cls) cgroup on /sys/fs/cgroup/perf_event type cgroup (rw,nosuid,nodev,noexec,relatime,perf_event) configfs on /sys/kernel/config type configfs (rw,relatime) /dev/xvda2 on / type xfs (rw,relatime,seclabel,attr2,inode64,noquota) selinuxfs on /sys/fs/selinux type selinuxfs (rw,relatime) systemd-1 on /proc/sys/fs/binfmt_misc type autofs (rw,relatime,fd=27,pgrp=1,timeout=300,minproto=5,maxproto=5,direct) debugfs on /sys/kernel/debug type debugfs (rw,relatime) mqueue on /dev/mqueue type mqueue (rw,relatime,seclabel) hugetlbfs on /dev/hugepages type hugetlbfs (rw,relatime,seclabel) tmpfs on /run/user/1000 type tmpfs (rw,nosuid,nodev,relatime,seclabel,size=3045488k,mode=700,uid=1000,gid=1000) [root@ip-172-31-6-38 etc]# df -h Filesystem Size Used Avail Use% Mounted on /dev/xvda2 10G 928M 9.1G 10% / devtmpfs 15G 0 15G 0% /dev tmpfs 15G 0 15G 0% /dev/shm tmpfs 15G 17M 15G 1% /run tmpfs 15G 0 15G 0% /sys/fs/cgroup tmpfs 3.0G 0 3.0G 0% /run/user/1000 3.If you have ext-based volumes, list the reserve space setting XFS volumes do not support reserve space [root@ip-172-31-6-38 dev]# sudo parted -l Model: Xen Virtual Block Device (xvd) Disk /dev/xvda: 10.7GB Sector size (logical/physical): 512B/512B Partition Table: gpt Disk Flags: pmbr_boot Number Start End Size File system Name Flags 1 1049kB 2097kB 1049kB bios_grub 2 2097kB 10.7GB 10.7GB xfs 4. Disable transparent hugepage support if test -f /sys/kernel/mm/transparent_hugepage/enabled; then echo never > /sys/kernel/mm/transparent_hugepage/enabled fi 5. List your network interface configuration [root@ip-172-31-9-175 network-scripts]# cat ifcfg-eth0 DEVICE="eth0" BOOTPROTO="dhcp" ONBOOT="yes" TYPE="Ethernet" USERCTL="yes" PEERDNS="yes" IPV6INIT="no" [root@ip-172-31-6-38 etc]# cat /etc/sysconfig/network NETWORKING=yes NOZEROCONF=yes 6. Show correct forward and reverse host lookups For /etc/hosts, use getent For DNS, use nslookup Forward DNS lookup is using an Internet domain name to find an IP address. Reverse DNS lookup is using an Internet IP address to find a domain name. $yum install bind-utils - to install nslookup, dig utilities [ec2-user@ip-172-31-9-175 ~]$ getent ahosts ip-172-31-9-175.ap-southeast-2.compute.internal has address 172.31.9.175 STREAM ip-172-31-9-175.ap-southeast-2.compute.internal 172.31.9.175 DGRAM 172.31.9.175 RAW [ec2-user@ip-172-31-9-175 ~]$ dig -x 172.31.9.175 ; <<>> DiG 9.9.4-RedHat-9.9.4-38.el7_3.3 <<>> -x 172.31.9.175 ;; global options: +cmd ;; Got answer: ;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 62773 ;; flags: qr rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 1 ;; OPT PSEUDOSECTION: ; EDNS: version: 0, flags:; udp: 4096 ;; QUESTION SECTION: ;172.16.17.32.in-addr.arpa. IN PTR ;; ANSWER SECTION: 172.16.17.32.in-addr.arpa. 60 IN PTR ip-172-31-9-175.ap-southeast-2.compute.internal. ;; Query time: 10 msec ;; SERVER: 172.31.0.2#53(172.31.0.2) ;; WHEN: Mon May 01 06:02:27 EDT 2017 ;; MSG SIZE rcvd: 115 [ec2-user@ip-172-31-9-175 ~]$ host 172.31.9.175 172.16.17.32.in-addr.arpa domain name pointer ip-172-31-9-175.ap-southeast-2.compute.internal. [ec2-user@ip-172-31-9-175 ~]$ host -t a ip-172-31-9-175.ap-southeast-2.compute.internal ip-172-31-9-175.ap-southeast-2.compute.internal has address 172.31.9.175 : 7.Show the nscd service is running Redirecting to /bin/systemctl status nscd.service â nscd.service - Name Service Cache Daemon Loaded: loaded (/usr/lib/systemd/system/nscd.service; disabled; vendor preset: disabled) Active: active (running) since Thu 2017-05-04 16:47:47 AEST; 5s ago Process: 28002 ExecStart=/usr/sbin/nscd $NSCD_OPTIONS (code=exited, status=0/SUCCESS) Main PID: 28003 (nscd) CGroup: /system.slice/nscd.service ââ28003 /usr/sbin/nscd May 04 16:47:47 ip-172-31-7-212.ap-southeast-2.compute.internal nscd[28003]: 28003 monitoring directory `/etc` (2) May 04 16:47:47 ip-172-31-7-212.ap-southeast-2.compute.internal nscd[28003]: 28003 monitoring file `/etc/hosts` (4) May 04 16:47:47 ip-172-31-7-212.ap-southeast-2.compute.internal nscd[28003]: 28003 monitoring directory `/etc` (2) May 04 16:47:47 ip-172-31-7-212.ap-southeast-2.compute.internal nscd[28003]: 28003 monitoring file `/etc/resolv.conf` (5) May 04 16:47:47 ip-172-31-7-212.ap-southeast-2.compute.internal nscd[28003]: 28003 monitoring directory `/etc` (2) May 04 16:47:47 ip-172-31-7-212.ap-southeast-2.compute.internal nscd[28003]: 28003 monitoring file `/etc/services` (6) May 04 16:47:47 ip-172-31-7-212.ap-southeast-2.compute.internal nscd[28003]: 28003 monitoring directory `/etc` (2) May 04 16:47:47 ip-172-31-7-212.ap-southeast-2.compute.internal nscd[28003]: 28003 disabled inotify-based monitoring for file `/etc/netgroup': No such file or directory May 04 16:47:47 ip-172-31-7-212.ap-southeast-2.compute.internal nscd[28003]: 28003 stat failed for file `/etc/netgroup'; will try again later: No such file or directory May 04 16:47:47 ip-172-31-7-212.ap-southeast-2.compute.internal systemd[1]: Started Name Service Cache Daemon. 8.Show the ntpd service is running - Requires configuration in aws?? [root@ip-172-31-6-38 init.d]# ntpstat Unable to talk to NTP daemon. Is it running? [root@ip-172-31-6-38 init.d]# ntpq -p ntpq: read: Connection refused [root@ip-172-31-6-38 init.d]# sudo service ntpd start Redirecting to /bin/systemctl start ntpd.service [root@ip-172-31-6-38 init.d]# sudo chkconfig ntpd on Note: Forwarding request to 'systemctl enable ntpd.service'. [root@ip-172-31-8-78 .ssh]# sudo service ntpd start Redirecting to /bin/systemctl start ntpd.service [root@ip-172-31-8-78 .ssh]# sudo chkconfig ntpd on Note: Forwarding request to 'systemctl enable ntpd.service'. Created symlink from /etc/systemd/system/multi-user.target.wants/ntpd.service to /usr/lib/systemd/system/ntpd.service. [root@ip-172-31-8-78 .ssh]# ntpstat synchronised to NTP server (172.16.31.10) at stratum 3 time correct to within 1068 ms polling server every 64 s [root@ip-172-31-8-78 .ssh]# ntpq -p remote refid st t when poll reach delay offset jitter ============================================================================== *y.ns.gin.ntt.ne 249.224.99.213 2 u 28 64 3 1.463 1.628 1.749 0.time.itoc.com 192.168.3.11 2 u 25 64 3 0.503 1.208 1.984 172.16.31.10 .GPS. 1 u 23 64 3 53.858 1.764 25.240 ec2-13-55-50-68 172.16.17.32 3 u 24 64 3 0.418 2.610 2.034 [root@ip-172-31-8-78 .ssh]# date Tue May 2 09:09:40 EDT 2017 To synchronise with sydney timezone ec2 instances: sudo ln -sf /usr/share/zoneinfo/Australia/Sydney /etc/localtime sudo reboot <file_sep>``` [root@ip-172-31-8-38 ec2-user]# hostname ip-172-31-8-38.ap-southeast-2.compute.internal ``` ``` [root@ip-172-31-8-38 ec2-user]# mysql -u root -p Enter password: Welcome to the MariaDB monitor. Commands end with ; or \g. Your MariaDB connection id is 11 Server version: 5.5.52-MariaDB MariaDB Server Copyright (c) 2000, 2016, Oracle, MariaDB Corporation Ab and others. Type 'help;' or '\h' for help. Type '\c' to clear the current input statement. MariaDB [(none)]> show databases; +--------------------+ | Database | +--------------------+ | information_schema | | hive | | hue | | mysql | | oozie | | performance_schema | | rman | | scm | | sentry | +--------------------+ 9 rows in set (0.00 sec) MariaDB [(none)]> ``` <file_sep>``` [root@ip-172-31-8-38 yum.repos.d]# cat MariaDB.repo ``` ``` # MariaDB 5.5 RedHat repository list - created 2017-05-05 00:22 UTC # http://downloads.mariadb.org/mariadb/repositories/ [mariadb] name = MariaDB baseurl = http://yum.mariadb.org/5.5/rhel7-amd64 gpgkey=https://yum.mariadb.org/RPM-GPG-KEY-MariaDB gpgcheck=1 ``` <file_sep>[hdfs@ip-172-31-7-212 ec2-user]$ sh YARNtest.sh Testing loop started on Thu May 4 16:10:24 AEST 2017 Mappers is 2 Containers is 2 container memory is 128 MAP_MB is 102 RED_MB is RED_MB real 1m29.979s user 0m5.720s sys 0m0.230s real 0m38.737s user 0m7.609s sys 0m0.288s Deleted /results/tg-10GB-2-2-128 Deleted /results/ts-10GB-2-2-128 container memory is 130 MAP_MB is 104 RED_MB is RED_MB real 1m29.121s user 0m5.521s sys 0m0.254s real 0m39.041s user 0m7.508s sys 0m0.248s Deleted /results/tg-10GB-2-2-130 Deleted /results/ts-10GB-2-2-130 Testing loop ended on Thu May 4 16:14:50 AEST 2017 [hdfs@ip-172-31-7-212 ec2-user]$ sh YARNtest.sh Testing loop started on Thu May 4 16:15:43 AEST 2017 Mappers is 4 Containers is 1 container memory is 512 MAP_MB is 409 RED_MB is 409 real 0m56.239s user 0m5.703s sys 0m0.211s real 2m35.036s user 0m7.985s sys 0m0.279s Deleted /results/tg-10GB-4-1-512 Deleted /results/ts-10GB-4-1-512 container memory is 1024 MAP_MB is 819 RED_MB is 819 real 0m55.141s user 0m5.779s sys 0m0.225s real 2m17.432s user 0m7.270s sys 0m0.266s Deleted /results/tg-10GB-4-1-1024 Deleted /results/ts-10GB-4-1-1024 Testing loop ended on Thu May 4 16:22:36 AEST 2017 [hdfs@ip-172-31-7-212 ec2-user]$ sh YARNtest.sh Testing loop started on Thu May 4 16:23:18 AEST 2017 Mappers is 4 Containers is 10 container memory is 512 MAP_MB is 409 RED_MB is 409 real 0m53.100s user 0m5.373s sys 0m0.227s real 1m41.887s user 0m7.640s sys 0m0.272s Deleted /results/tg-10GB-4-10-512 Deleted /results/ts-10GB-4-10-512 container memory is 1024 MAP_MB is 819 RED_MB is 819 real 0m53.118s user 0m5.423s sys 0m0.231s real 1m40.101s user 0m7.633s sys 0m0.264s Deleted /results/tg-10GB-4-10-1024 Deleted /results/ts-10GB-4-10-1024 Testing loop ended on Thu May 4 16:28:35 AEST 2017 [hdfs@ip-172-31-7-212 ec2-user]$ <file_sep>List the cloud provider you are using (AWS, GCE, Azure, other)-AWS List the nodes you are using by IP address and name ip-172-31-8-38.ap-southeast-2.compute.internal host1.example.com host1 ip-172-31-3-131.ap-southeast-2.compute.internal host2.example.com host2 ip-172-31-15-230.ap-southeast-2.compute.internal host3.example.com host3 ip-172-31-7-184.ap-southeast-2.compute.internal host4.example.com host4 ip-172-31-13-109.ap-southeast-2.compute.internal host5.example.com host5 List the Linux release you are using NAME="Red Hat Enterprise Linux Server" VERSION="7.2 (Maipo)" Demonstrate the disk capacity available on each node is >= 30 GB [root@ip-172-31-8-38 ec2-user]# df -h Filesystem Size Used Avail Use% Mounted on /dev/xvda2 30G 927M 30G 4% / devtmpfs 7.3G 0 7.3G 0% /dev tmpfs 7.2G 0 7.2G 0% /dev/shm tmpfs 7.2G 17M 7.2G 1% /run tmpfs 7.2G 0 7.2G 0% /sys/fs/cgroup tmpfs 1.5G 0 1.5G 0% /run/user/1000 List the command and output for yum repolist enabled [root@ip-172-31-8-38 ec2-user]# yum repolist enabled Loaded plugins: amazon-id, rhui-lb, search-disabled-repos rhui-REGION-client-config-server-7 | 2.9 kB 00:00:00 rhui-REGION-rhel-server-releases | 3.5 kB 00:00:00 rhui-REGION-rhel-server-rh-common | 3.8 kB 00:00:00 (1/7): rhui-REGION-client-config-server-7/x86_64/primary_db | 5.4 kB 00:00:00 (2/7): rhui-REGION-rhel-server-releases/7Server/x86_64/updateinfo | 1.9 MB 00:00:00 (3/7): rhui-REGION-rhel-server-rh-common/7Server/x86_64/group | 104 B 00:00:00 (4/7): rhui-REGION-rhel-server-releases/7Server/x86_64/group | 701 kB 00:00:00 (5/7): rhui-REGION-rhel-server-rh-common/7Server/x86_64/primary_db | 118 kB 00:00:00 (6/7): rhui-REGION-rhel-server-rh-common/7Server/x86_64/updateinfo | 33 kB 00:00:00 (7/7): rhui-REGION-rhel-server-releases/7Server/x86_64/primary_db | 35 MB 00:00:00 repo id repo name status rhui-REGION-client-config-server-7/x86_64 Red Hat Update Infrastructure 2.0 Client Configuration Server 7 6 rhui-REGION-rhel-server-releases/7Server/x86_64 Red Hat Enterprise Linux Server 7 (RPMs) 14,277 rhui-REGION-rhel-server-rh-common/7Server/x86_64 Red Hat Enterprise Linux Server 7 RH Common (RPMs) 228 repolist: 14,511 List the /etc/passwd entries for neymar and ronaldo [root@ip-172-31-8-38 ec2-user]# cat /etc/passwd|grep -e "neymar" -e "renaldo" neymar:x:2010:2018::/home/neymar:/bin/bash renaldo:x:2016:2017::/home/renaldo:/bin/bash List the /etc/group entries for barca and merengues [root@ip-172-31-8-38 ec2-user]# cat /etc/group|grep -e merengues -e barca barca:x:2017: merengues:x:2018:
73f0aaa5922c7c6036249cce88436a9cca0003e3
[ "Markdown" ]
7
Markdown
sripagadala/SEBC
f3f93292a6777e551683754c55292d481f22de81
160408316fb4c1a0098e8b443ce4c8974e772076
refs/heads/master
<file_sep>--- title: Learning Rmarkdown author: '' date: '2020-05-17' slug: learning-rmarkdown categories: [] tags: [] --- <p>test</p> <file_sep>--- title: Learning Rmarkdown author: '' date: '2020-05-17' slug: learning-rmarkdown categories: [] tags: [] --- test
b787ba9b78820fd27a62ffa20b845a80afd4281a
[ "RMarkdown", "HTML" ]
2
RMarkdown
yxzoe/LearnR
349f2244a9b0b74002c12b425da87382543c6dc4
b89b6082907f1ef3bfe676acfd53811fb046eca1
refs/heads/main
<file_sep># WEBSITE [uldl.me](https://uldl.me) <file_sep>import React from "react"; class Title extends React.Component { constructor() { super(); this.state = { text: "uldl" }; } //set the text onMouseover(e) { this.setState({ text: ` uplinkdownlink ` }); } //clear the text onMouseout(e) { this.setState({ text: "uldl" }); } render() { const { text } = this.state; return ( <div onMouseEnter={this.onMouseover.bind(this)} onMouseLeave={this.onMouseout.bind(this)} id="title" > {text} </div> ); } } export default Title; <file_sep>import React, { useEffect } from "react"; import "./styles.css"; import Title from "./Title"; import { BrowserView, MobileView } from "react-device-detect"; import { BrowserRouter as Router, Switch, Route, Link, useLocation } from "react-router-dom"; export default function App() { return ( <div className="App"> <Router> <Switch> <Route path="/app"> <HomeApp /> </Route> <Route path="/signin"> <SignIn /> </Route> <Route path="/signup"> <SignUp /> </Route> <Route exact path="/"> <Lander /> </Route> </Switch> </Router> </div> ); } function Lander() { return ( <div className="centered"> <div className="textCentered"> <Title /> </div> <div className="textCentered"> <span id="link"> <Link to="/signup" id="linktext"> sign up </Link> </span> <span id="link"> / </span> <span id="link"> <Link to="/signin" id="linktext"> sign in </Link> </span> </div> </div> ); } function useQuery() { return new URLSearchParams(useLocation().search); } function SignUp() { let url = useQuery(); async function checkError() { if (url.get("error") !== null) { console.log(url.get("error")); } } useEffect(() => { checkError(); }); return ( <div className="SignUp"> <div className="toHome"> <Link to="/" id="linktext"> <img src="https://img.icons8.com/250/e0e0e0/back" id="small-img" alt="back" /> </Link> </div> <div className="centered"> <div className="textCentered"> <span id="title-signup">sign up</span> <br /> <span>{url.get("error")}</span> </div> <br /> <br /> <div className="textCentered"> <form action="https://server.uldl.me/signup" method="post"> <input type="text" id="username" name="username" placeholder="username" /> <br /> <br /> <input type="<PASSWORD>" id="<PASSWORD>" name="password" placeholder="<PASSWORD>" suggested="<PASSWORD>" /> <br /> <br /> <div className="textCentered"> <input type="submit" value="submit" /> </div> </form> </div> </div> </div> ); } function SignIn() { let url = useQuery(); async function checkError() { if (url.get("error") !== null) { console.log(url.get("error")); } } useEffect(() => { checkError(); }); return ( <div className="SignIn"> <div className="toHome"> <Link to="/" id="linktext"> <img src="https://img.icons8.com/250/e0e0e0/back" id="small-img" alt="back" /> </Link> </div> <div className="centered"> <div className="textCentered"> <span id="title-signup">sign in</span> <br /> <span>{url.get("error")}</span> </div> <br /> <br /> <div className="textCentered"> <form action="https://server.uldl.me/signin" method="post"> <input type="text" id="username" name="username" placeholder="username" /> <br /> <br /> <input type="<PASSWORD>" id="password" name="password" placeholder="<PASSWORD>" /> <br /> <br /> <div className="textCentered"> <input type="submit" value="submit" /> </div> </form> </div> </div> </div> ); } function HomeApp() { let url = useQuery(); async function checkError() { if (url.get("username") !== null) { console.log(url.get("username")); } } useEffect(() => { checkError(); }); return ( <div className="HomeApp"> <div className="textCentered"> <BrowserView> <div className="sidebar"> <Link to="/"> <span className="title-home">uldl</span> </Link> <br /> <div id="username-home">{url.get("username")}</div> </div> <div id="textarea-wrapper"> <span id="message-send"> <input type="textarea" id="messagebarinput-home" placeholder="uplink" ></input> </span> </div> <button id="send-button" onClick={(e) => { console.log("sent"); }} > <img src="https://raw.githubusercontent.com/uldl/ui/main/uldltwotone.png" alt="send" id="send-button-img" width="35" /> </button> <div className="messagebar"></div> </BrowserView> <MobileView> <div className="sidebar-mobile"> <Link to="/"> <span className="title-home-mobile">uldl</span> </Link> <br /> <div id="username-home">{url.get("username")}</div> </div> <div id="textarea-wrapper-mobile"> <span id="message-send"> <input type="textarea" id="messagebarinput-home" placeholder="uplink" ></input> </span> </div> <button id="send-button" onClick={(e) => { console.log("sent"); }} > <img src="https://raw.githubusercontent.com/uldl/ui/main/uldltwotone.png" alt="send" id="send-button-img" width="35" /> </button> <div className="messagebar-mobile"></div> </MobileView> <br /> </div> </div> ); }
d8c63149142c6c9021f6a8a608897ef022807d7e
[ "Markdown", "JavaScript" ]
3
Markdown
uldl/web
176642d80b7922174c2e8ceb41e5a2b572dbcc69
d5cd714822a6ea84550c837438dd15c9df6d5042
refs/heads/master
<repo_name>cucuzzaro/CR<file_sep>/Royale.py #!/usr/local/bin/python3 ''' Web scraper for www.royaleapi.com Returns a web page with most popular decks filtered by the specification given in the argument ''' import argparse import django import os import requests import webbrowser from bs4 import BeautifulSoup as bSoup from django.conf import settings from django.template.loader import get_template def parse(): parser = argparse.ArgumentParser(description="Get information about Clash Royale decks' stats") parser.add_argument('-time', metavar='', help='Choose a date range for stats') parser.add_argument('-results', metavar='', default='10', type=int, help="Choose results' number") parser.add_argument('-type', metavar='', default='Ladder', help="Choose game type: 'Ladder' 'Grand Challenge' 'Ramp Up' 'Sudden Death' 'Double Elixir' 'Triple Elixir'") parser.add_argument('-in', '--include', metavar='', nargs='*', help="Include selected cards in the decks") parser.add_argument('-ex', '--exclude', metavar='', nargs='*', help="Exclude selected cards in the decks") parser.add_argument('-tvt', action='store_true', help="Select 2v2 mode") parser.add_argument('-wins', action='store_true', help="Sort by wins") parser.add_argument('-top200', action='store_true', help="most popular in Top 200 Ladder") parser.add_argument('-debug', action='store_true', help="Debug mode") args = parser.parse_args() return args def create_url(args, debug=False): url = 'https://royaleapi.com/decks/popular?' url += f'&time={args.time}d' if args.time else '' url += f'&size={args.results}' if args.results else '' if args.type and not args.tvt: try: req = {'ladder': 'Ladder', 'grand_challenge': 'GC', 'ramp_up': 'RampUpElixir_Ladder', 'sudden_death': 'Overtime_Ladder', 'double_elixir': 'DoubleElixir_Ladder', 'triple_elixir': 'TripleElixir_Ladder', 'top200': 'Top200Ladder'} index = args.type.lower().replace(" ", "_") url += f'&type={req[index]}' except: raise KeyError('Invalid game type') if args.include: for card in args.include: url += f'&inc={card.lower().replace(" ","-")}' if args.exclude: for card in args.exclude: url += f'&exc={card.lower().replace(" ","-")}' url += '&sort=win' if args.wins else '' url += '&players=TvT' if args.tvt else '' title = f'Most winning {args.type} decks ' if args.wins else f'Most popular {args.type} decks ' title += f'in the last {args.time} days' if args.time else '' return url, title def initialize_template(): path = os.path.dirname(os.path.realpath(__file__)) TEMPLATES = [{'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [f'{path}/Resources']}] settings.configure(TEMPLATES=TEMPLATES) django.setup() return path def get_info(url, debug=False): print('Retrieving decks information...') if not debug else print(f'\nURL: {url}') try: response = requests.get(url).text soup = bSoup(response, 'lxml') container = soup.find(id='decksContainer').find_all('a') except ConnectionError: raise ConnectionError(f'{response}'.raise_for_status()) except AttributeError: raise AttributeError(f'No decks found with these features') # Get all the decks in the page source hrefs = [href.get('href')[18:] for href in container if href.get('href').startswith('/decks/stats?name')] # List comprehension to delete all duplicates hrefs = [element for position, element in enumerate(hrefs) if element not in hrefs[:position]] # Create a list of lists with all the cards in the decks decks = [deck.split(',') for deck in hrefs] # Get elixir cost for all decks h5 = soup.find_all('h5') elix = [h.parent.text[11:].strip('\nn') for h in h5 if 'Avg Elixir' in h.parent.text] # Get decks' names name = soup.find_all(attrs={'class': 'header item mobile-hide tablet-hide'}) names = [elem.text.strip('\n').upper() for elem in name] win = soup.find_all(attrs={'class': 'header mobile-hide item'}) wins = [elem.text.strip('\nn') for elem in win] # Append elixir cost and name as last element of each deck #info = {'decks': decks, 'elixir': elix, 'name': name, 'wins': wins} info = list(zip(decks, elix, names, wins)) print('\nINFO: ' + str(info) + '\n\nHREFS: ' + str(hrefs)) if debug else '' return info def show(page, path): with open(f'{path}/Resources/page.html', 'w') as f: f.write(page) webbrowser.get('safari').open(f"file://{path}/Resources/page.html") def main(): args = parse() url, title = create_url(args, args.debug) info = get_info(url, args.debug) path = initialize_template() template = get_template('template.html') data = { 'title': title, 'type': args.type if not args.tvt else 'TvT', 'time': args.time, 'results': args.results, 'wins': args.wins, 'infos': info, 'path': path } page = template.render(data) show(page, path) if __name__ == '__main__': main()
1bad6c476bbaa69ef9593c1f199273491984c47a
[ "Python" ]
1
Python
cucuzzaro/CR
713d90ae18d359891aa80dfcc638c2e85fb3e40d
cfec43f504a80b95cbde7380e2cd18d4cf69f587
refs/heads/master
<repo_name>bhavneetSinghAhuja/WineTasting<file_sep>/src/main/java/CalculateResult.java import java.io.IOException; import java.sql.SQLException; /** * Created by bhavneet.ahuja on 24/11/14. */ public class CalculateResult { public static void main(String args[]) throws IOException, SQLException { ParseInput parseInput=new ParseInput("/Users/bhavneet.ahuja/Downloads/person_wine_3.txt"); //calculating the results and printing out in the console parseInput.calculateResults(); } } <file_sep>/src/test/java/DBManagerTest.java /** * Created by bhavneet.ahuja on 24/11/14. */ public class DBManagerTest { }
0993ca84dddabb14399cc86dbd494a6cc8de138a
[ "Java" ]
2
Java
bhavneetSinghAhuja/WineTasting
7c3701f51c1db3ff38e6e251714b11f094eaff3b
0df89d882348ffab94a111b691c0b481d6f23e63
refs/heads/master
<repo_name>AlfredMulder/Django_work<file_sep>/django_structure/lib/python3.6/reprlib.py /home/far/anaconda3/lib/python3.6/reprlib.py<file_sep>/django_structure/src/django_structure/settings.py """ Django settings for django_structure project. Generated by 'django-admin startproject' using Django 2.0.3. For more information on this file, see https://docs.djangoproject.com/en/2.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.0/ref/settings/ """ import os import django_heroku # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Подключение email- хоста: email_host = 'smtp.gmail.com' email_host_user = 'your gmail email' email_host_password = '<PASSWORD>' email_port = '587' email_use_tls = True # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '<KEY>' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['127.0.0.1', 'boiling-wildwood-73678.herokuapp.com'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', #'django-custom-user', 'profiles', 'contact', 'crispy_forms', 'allauth', 'allauth.account', 'allauth.socialaccount', 'django.contrib.sites', 'checkout', 'stripe' ] SITE_ID = 1 MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', ] ROOT_URLCONF = 'django_structure.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] TEMPLATE_CONTEXT_PROCESSORS = ( "django.core.context_processors.auth", "django.core.context_processors.debug", "django.core.context_processors.i18n", "django.core.context_processors.media", "django.core.context_processors.request", ) AUTHENTICATION_BACKENDS = ( # Needed to login by username in Django admin, regardless of `allauth` 'django.contrib.auth.backends.ModelBackend', # `allauth` specific authentication methods, such as login by e-mail 'allauth.account.auth_backends.AuthenticationBackend', ) WSGI_APPLICATION = 'django_structure.wsgi.application' # Database # https://docs.djangoproject.com/en/2.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'db', 'USER': 'joe', 'PASSWORD': '<PASSWORD>', 'HOST': '127.0.0.1', 'PORT': '5432', } } # Password validation # https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/2.0/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.0/howto/static-files/ STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' STATIC_URL = '/static/' # Указание путей нахождения медиа и статических файлов: if DEBUG: MEDIA_URL = '/media/' #STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static", "static-only") MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static", "media") STATICFILES_DIRS = ( os.path.join(os.path.dirname(BASE_DIR), "static", "static"), ) CRISPY_TEMPLATE_PACK = 'bootstrap4' SITE_ID = 1 # Подключение настроек allauth: LOGIN_URL = '/accounts/login/' LOGIN_REDIRECT_URL = '/' ACCOUNT_AUTHENTICATION_METHOD = "username_email" ACCOUNT_CONFIRM_EMAIL_ON_GET = False ACCOUNT_EMAIL_CONFIRMATION_ANONYMOUS_REDIRECT_URL = LOGIN_URL ACCOUNT_EMAIL_CONFIRMATION_AUTHENTICATED_REDIRECT_URL = None ACCOUNT_EMAIL_CONFIRMATION_EXPIRE_DAYS = 3 ACCOUNT_EMAIL_REQUIRED = False ACCOUNT_EMAIL_VERIFICATION = None ACCOUNT_EMAIL_SUBJECT_PREFIX = "My subject: " ACCOUNT_DEFAULT_HTTP_PROTOCOL = "https" ACCOUNT_LOGIN_ON_EMAIL_CONFIRMATION = False ACCOUNT_LOGOUT_ON_GET = False ACCOUNT_LOGOUT_REDIRECT_URL = "/" ACCOUNT_SIGNUP_FORM_CLASS = None ACCOUNT_UNIQUE_EMAIL = True ACCOUNT_SIGNUP_PASSWORD_VERIFICATION = True ACCOUNT_USER_MODEL_EMAIL_FIELD = "email" ACCOUNT_USER_MODEL_USERNAME_FIELD = "username" ACCOUNT_USERNAME_MIN_LENGTH = 1 ACCOUNT_USERNAME_BLACKLIST = [] ACCOUNT_USERNAME_REQUIRED = True ACCOUNT_PASSWORD_INPUT_RENDER_VALUE = False ACCOUNT_LOGIN_ON_EMAIL_CONFIRMATION = True ACCOUNT_PASSWORD_MIN_LENGTH = 6 # Настройки stripe: # Тестовые ключи STRIPE_PUBLISHABLE_KEY = '<KEY>' STRIPE_SECRET_KEY = '<KEY>' # Live ключи #STRIPE_PUBLISHABLE_KEY = '' #STRIPE_SECRET_KEY = '' django_heroku.settings(locals()) <file_sep>/django_structure/lib/python3.6/locale.py /home/far/anaconda3/lib/python3.6/locale.py<file_sep>/django_structure/lib/python3.6/bisect.py /home/far/anaconda3/lib/python3.6/bisect.py<file_sep>/django_structure/lib/python3.6/random.py /home/far/anaconda3/lib/python3.6/random.py<file_sep>/django_structure/lib/python3.6/io.py /home/far/anaconda3/lib/python3.6/io.py<file_sep>/django_structure/lib/python3.6/posixpath.py /home/far/anaconda3/lib/python3.6/posixpath.py<file_sep>/django_structure/lib/python3.6/abc.py /home/far/anaconda3/lib/python3.6/abc.py<file_sep>/django_structure/lib/python3.6/tempfile.py /home/far/anaconda3/lib/python3.6/tempfile.py<file_sep>/django_structure/lib/python3.6/hashlib.py /home/far/anaconda3/lib/python3.6/hashlib.py<file_sep>/django_structure/src/profiles/migrations/0010_auto_20180321_1743.py # Generated by Django 2.0.3 on 2018-03-21 17:43 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('profiles', '0009_auto_20180321_1738'), ] operations = [ migrations.AddField( model_name='profile', name='height', field=models.IntegerField(default=0), ), migrations.AddField( model_name='profile', name='width', field=models.IntegerField(default=0), ), migrations.AlterField( model_name='profile', name='image', field=models.ImageField(default='path/to/my/default/image.jpg', height_field=120, upload_to='profile_image', width_field=80), ), ] <file_sep>/django_structure/lib/python3.6/imp.py /home/far/anaconda3/lib/python3.6/imp.py<file_sep>/django_structure/lib/python3.6/warnings.py /home/far/anaconda3/lib/python3.6/warnings.py<file_sep>/django_structure/lib/python3.6/tokenize.py /home/far/anaconda3/lib/python3.6/tokenize.py<file_sep>/django_structure/lib/python3.6/rlcompleter.py /home/far/anaconda3/lib/python3.6/rlcompleter.py<file_sep>/django_structure/src/profiles/views.py from django.contrib.auth.decorators import login_required from django.shortcuts import render from django.views.generic.detail import SingleObjectMixin from django.views.generic import UpdateView from django.utils.decorators import method_decorator from django.core.files.uploadedfile import SimpleUploadedFile from profiles.models import Profile # Create your views here. # Подключение функций для работы страниц: home, about, userProfile: def home(request): context = {} template = 'home.html' return render(request, template, context) def about(request): context = {} template = 'about.html' return render(request, template, context) # Декоратор, требующий обязательного входа в профиль: @login_required def userProfile(request): user = request.user context = {'user': user} template = 'profile.html' return render(request, template, context) class ProfileObjectMixin(SingleObjectMixin): """ Provides views with the current user's profile. """ model = Profile def get_object(self): """Return's the current users profile.""" try: return self.request.user.get_profile() except Profile.DoesNotExist: raise NotImplemented( "What if the user doesn't have an associated profile?") @method_decorator(login_required) def dispatch(self, request, *args, **kwargs): """Ensures that only authenticated users can access the view.""" klass = ProfileObjectMixin return super(klass, self).dispatch(request, *args, **kwargs) class ProfileUpdateView(ProfileObjectMixin, UpdateView): """ A view that displays a form for editing a user's profile. Uses a form dynamically created for the `Profile` model and the default model's update template. """ pass # That's All Folks! <file_sep>/django_structure/lib/python3.6/ntpath.py /home/far/anaconda3/lib/python3.6/ntpath.py<file_sep>/source/index.rst .. django_work documentation master file, created by sphinx-quickstart on Thu Mar 22 23:44:42 2018. You can adapt this file completely to your liking, but it should at least contain the root `toctree` directive. Добро пожаловать в докуметацию проекта django_work ================================================== .. toctree:: :maxdepth: 2 1_chapter.rst 2_chapter.rst 3_chapter.rst <file_sep>/django_structure/lib/python3.6/sre_constants.py /home/far/anaconda3/lib/python3.6/sre_constants.py<file_sep>/django_structure/lib/python3.6/heapq.py /home/far/anaconda3/lib/python3.6/heapq.py<file_sep>/django_structure/lib/python3.6/functools.py /home/far/anaconda3/lib/python3.6/functools.py<file_sep>/django_structure/lib/python3.6/stat.py /home/far/anaconda3/lib/python3.6/stat.py<file_sep>/django_structure/lib/python3.6/linecache.py /home/far/anaconda3/lib/python3.6/linecache.py<file_sep>/django_structure/lib/python3.6/_dummy_thread.py /home/far/anaconda3/lib/python3.6/_dummy_thread.py<file_sep>/django_structure/lib/python3.6/types.py /home/far/anaconda3/lib/python3.6/types.py<file_sep>/django_structure/src/profiles/templates/home.html {% extends 'account/base.html' %} {% load staticfiles %} {% block styles %} <style media="screen"> .jumbotron { text-align: center; } </style> {% endblock %} <nav aria-label="breadcrumb"> <ol class="breadcrumb"> <li class="breadcrumb-item active" aria-current="page">Home</li> </ol> </nav> {% block jumbotron %} <div class="jumbotron jumbotron-fluid" style="background-color:#5ccb28"> <div class="container"> <h1 class="display-3">Welcome!</h1> <p class="lead">"We believe that payments is a problem rooted in code, not finance. We obsessively seek out elegant, composable abstractions that enable robust, scalable, flexible integrations. Because we eliminate needless complexity and extraneous details, you can get up and running with Stripe in just a couple of minutes. "</p> <a class="btn btn-default primaryAction" type="submit" href="https://stripe.com/" style="background-color:#dd2031">Learn more</a> </div> </div> {% endblock %} {% block content %} <div class="container marketing"> <!-- Three columns of text below the carousel --> <div class="row"> <div class="col-lg-4"> <img class="rounded-circle" src="{% static 'img/1.gif' %}" alt="Generic placeholder image" width="140" height="140"> <h2>Heading</h2> <p>Donec sed odio dui. Etiam porta sem malesuada magna mollis euismod. Nullam id dolor id nibh ultricies vehicula ut id elit. Morbi leo risus, porta ac consectetur ac, vestibulum at eros. Praesent commodo cursus magna.</p> <p><a class="btn btn-secondary" href="#" role="button">View details &raquo;</a></p> </div><!-- /.col-lg-4 --> <div class="col-lg-4"> <img class="rounded-circle" src="{% static 'img/2.gif' %}" alt="Generic placeholder image" width="140" height="140"> <h2>Heading</h2> <p>Duis mollis, est non commodo luctus, nisi erat porttitor ligula, eget lacinia odio sem nec elit. Cras mattis consectetur purus sit amet fermentum. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh.</p> <p><a class="btn btn-secondary" href="#" role="button">View details &raquo;</a></p> </div><!-- /.col-lg-4 --> <div class="col-lg-4"> <img class="rounded-circle" src="{% static 'img/3.gif' %}" alt="Generic placeholder image" width="140" height="140"> <h2>Heading</h2> <p>Donec sed odio dui. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Vestibulum id ligula porta felis euismod semper. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus.</p> <p><a class="btn btn-secondary" href="#" role="button">View details &raquo;</a></p> </div><!-- /.col-lg-4 --> </div><!-- /.row --> <!-- START THE FEATURETTES --> <hr class="featurette-divider"> <div class="row featurette"> <div class="col-md-7"> <h2 class="featurette-heading">First featurette heading. <span class="text-muted">It'll blow your mind.</span></h2> <p class="lead">Donec ullamcorper nulla non metus auctor fringilla. Vestibulum id ligula porta felis euismod semper. Praesent commodo cursus magna, vel scelerisque nisl consectetur. Fusce dapibus, tellus ac cursus commodo.</p> </div> <div class="col-md-5"> <img class="featurette-image img-fluid mx-auto" data-src="holder.js/500x500/auto" src="{% static 'img/1.png' %}" alt="Generic placeholder image"> </div> </div> <hr class="featurette-divider"> <div class="row featurette"> <div class="col-md-7 order-md-2"> <h2 class="featurette-heading">Oh yeah, it's that good. <span class="text-muted">See for yourself.</span></h2> <p class="lead">Donec ullamcorper nulla non metus auctor fringilla. Vestibulum id ligula porta felis euismod semper. Praesent commodo cursus magna, vel scelerisque nisl consectetur. Fusce dapibus, tellus ac cursus commodo.</p> </div> <div class="col-md-5 order-md-1"> <img class="featurette-image img-fluid mx-auto" data-src="holder.js/500x500/auto" src="{% static 'img/2.png' %}" alt="Generic placeholder image"> </div> </div> <hr class="featurette-divider"> <div class="row featurette"> <div class="col-md-7"> <h2 class="featurette-heading">And lastly, this one. <span class="text-muted">Checkmate.</span></h2> <p class="lead">Donec ullamcorper nulla non metus auctor fringilla. Vestibulum id ligula porta felis euismod semper. Praesent commodo cursus magna, vel scelerisque nisl consectetur. Fusce dapibus, tellus ac cursus commodo.</p> </div> <div class="col-md-5"> <img class="featurette-image img-fluid mx-auto" data-src="holder.js/500x500/auto" src="{% static 'img/3.png' %}" alt="Generic placeholder image"> </div> </div> <hr class="featurette-divider"> <!-- /END THE FEATURETTES --> </div><!-- /.container --> {% if not request.user.is_authenticated %} <div class="col-sm-3 col-sm-offset-10 mx-auto"> <form class="login" method="POST" action="{% url 'account_login' %}"> {% csrf_token %} <div id="div_id_login" class="control-group"> <label for="id_login" class="control-label requiredField"> Login<span class="asteriskField">*</span> </label> <div class="controls"> <input name="login" placeholder="Username <NAME>" autofocus="autofocus" class="textinput textInput" required="" id="id_login" type="text"> </div> </div> <div id="div_id_password" class="control-group"> <label for="id_password" class="control-label requiredField">Password<span class="asteriskField">*</span> </label> <div class="controls"> <input name="password" placeholder="<PASSWORD>" class="textinput textInput" required="" id="id_password" type="<PASSWORD>"> </div> </div> <div id="div_id_remember" class="control-group"> <div class="controls"> <label for="id_remember" class="checkbox "> <input name="remember" class="checkboxinput" id="id_remember" type="checkbox">Remember Me</label> </div> </div> <a class="btn btn-link button secondaryAction" href="{% url 'account_reset_password' %}">Forgot Password?</a> <a class="btn btn-link button secondaryAction" href="{% url 'account_signup' %}">Signup?</a> <button class="btn btn-lg btn-block btn-primary" type="submit">Sign In</button> </form> </div> {% else %} <main role="main" class="container"> <div class="starter-template mx-auto"> <h1>Join us</h1> <p class="lead">We're hope we will help you to improve your work.<br> There are some tarifes you can connect to your account:</p> </div> </main> <div class="container"> <div class="card-deck mb-3 text-center"> <div class="card mb-4 box-shadow"> <div class="card-header"> <h4 class="my-0 font-weight-normal">Free</h4> </div> <div class="card-body"> <h1 class="card-title pricing-card-title">$0 <small class="text-muted">/ mo</small></h1> <ul class="list-unstyled mt-3 mb-4"> <li>10 users included</li> <li>2 GB of storage</li> <li>Email support</li> <li>Help center access</li> </ul> <a href="{% url 'checkout' %}"><button type="submit" class="btn btn-lg btn-block btn-primary"> Sign up for free</button></a> </div> </div> <div class="card mb-4 box-shadow"> <div class="card-header"> <h4 class="my-0 font-weight-normal">Pro</h4> </div> <div class="card-body"> <h1 class="card-title pricing-card-title">$15 <small class="text-muted">/ mo</small></h1> <ul class="list-unstyled mt-3 mb-4"> <li>20 users included</li> <li>10 GB of storage</li> <li>Priority email support</li> <li>Help center access</li> </ul> <a href="{% url 'checkout' %}"><button type="submit" class="btn btn-lg btn-block btn-primary"> Get started</button></a> </div> </div> <div class="card mb-4 box-shadow"> <div class="card-header"> <h4 class="my-0 font-weight-normal">Enterprise</h4> </div> <div class="card-body"> <h1 class="card-title pricing-card-title">$29 <small class="text-muted">/ mo</small></h1> <ul class="list-unstyled mt-3 mb-4"> <li>30 users included</li> <li>15 GB of storage</li> <li>Phone and email support</li> <li>Help center access</li> </ul> <a href="{% url 'contact' %}"><button type="submit" class="btn btn-lg btn-block btn-primary"> Contact us</button></a> </div> </div> </div> <footer class="pt-4 my-md-5 pt-md-5 border-top"> <div class="row"> <div class="col-12 col-md"> </div> <div class="col-6 col-md"> <h5>Features</h5> <ul class="list-unstyled text-small"> <li><a class="text-muted" href="#">Cool stuff</a></li> <li><a class="text-muted" href="#">Random feature</a></li> <li><a class="text-muted" href="#">Team feature</a></li> <li><a class="text-muted" href="#">Stuff for developers</a></li> <li><a class="text-muted" href="#">Another one</a></li> <li><a class="text-muted" href="#">Last time</a></li> </ul> </div> <div class="col-6 col-md"> <h5>Resources</h5> <ul class="list-unstyled text-small"> <li><a class="text-muted" href="#">Resource</a></li> <li><a class="text-muted" href="#">Resource name</a></li> <li><a class="text-muted" href="#">Another resource</a></li> <li><a class="text-muted" href="#">Final resource</a></li> </ul> </div> <div class="col-6 col-md"> <h5>About</h5> <ul class="list-unstyled text-small"> <li><a class="text-muted" href="#">Team</a></li> <li><a class="text-muted" href="#">Locations</a></li> <li><a class="text-muted" href="#">Privacy</a></li> <li><a class="text-muted" href="#">Terms</a></li> </ul> </div> </div> </footer> </div> {% endif %} </div> {% endblock %} <file_sep>/django_structure/lib/python3.6/re.py /home/far/anaconda3/lib/python3.6/re.py<file_sep>/django_structure/lib/python3.6/_bootlocale.py /home/far/anaconda3/lib/python3.6/_bootlocale.py<file_sep>/django_structure/src/profiles/migrations/0008_auto_20180321_1733.py # Generated by Django 2.0.3 on 2018-03-21 17:33 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('profiles', '0007_remove_profile_location'), ] operations = [ migrations.AddField( model_name='profile', name='city', field=models.CharField(default='', max_length=100), ), migrations.AddField( model_name='profile', name='email', field=models.CharField(default='', max_length=120), ), migrations.AddField( model_name='profile', name='image', field=models.ImageField(default='path/to/my/default/image.jpg', height_field=800, upload_to='profile_image', width_field=600), ), migrations.AddField( model_name='profile', name='last_name', field=models.CharField(default='', max_length=120), ), migrations.AddField( model_name='profile', name='phone', field=models.IntegerField(default=0), ), migrations.AddField( model_name='profile', name='state', field=models.CharField(default='', max_length=100), ), migrations.AddField( model_name='profile', name='street', field=models.CharField(default='', max_length=100), ), migrations.AddField( model_name='profile', name='website', field=models.CharField(default='', max_length=120), ), migrations.AlterField( model_name='profile', name='job', field=models.CharField(default='', max_length=120, null=True), ), ] <file_sep>/django_structure/lib/python3.6/shutil.py /home/far/anaconda3/lib/python3.6/shutil.py<file_sep>/django_structure/lib/python3.6/sre_compile.py /home/far/anaconda3/lib/python3.6/sre_compile.py<file_sep>/django_structure/lib/python3.6/base64.py /home/far/anaconda3/lib/python3.6/base64.py<file_sep>/build/html/_sources/1_chapter.rst.txt *************************** Глава 1- приложение Profile *************************** **Состав и краткое описание** ============================= Данное приложение служит двум вещам: * Объявление полей профиля пользователя для редактирование и обновление оных через "админку". * Генерации уникального идентификатора службы Stripe. Состоит из следующих моделей(классов моделей): #. Profile #. userStripe Имеет следующие представления(классы представлений): #. Home #. About #. userProfile Включает в себя следующие шаблоны: #. about.html - страница с описанием приложения. #. base.html - шаблон- основа для всех остальных страниц. #. footer.html - элемент страницы для указания года выпуска приложения, организации производителя и т.д.. #. home.html - домашняя страница приложения. #. navbar.html - навигационная панель. #. profile.html - страница профиля пользователя. Разберем каждый класс отдельно. **Класс Profile** ================= Состоит из следующих полей: name, description, job, street, city, state, phone, website, image, last name, email, user. Имеет только один метод: __unicode__, возвращающий имя пользователя в юникоде. Данные поля заполняются пользователями- администраторами приложения. Листинг:: class Profile(models.Model): name = models.CharField(max_length=120) description = models.TextField(default='description default text') job = models.CharField(max_length=120, null=True, default='') street = models.CharField(default='', max_length=100) city = models.CharField(default='', max_length=100) state = models.CharField(default='', max_length=100) phone = models.IntegerField(default=0) website = models.CharField(max_length=120, default='') width_field = models.IntegerField(default=0) height_field = models.IntegerField(default=0) image = models.ImageField(upload_to="profile_image", default="path/to/my/default/image.jpg") last_name = models.CharField(max_length=120, default='') email = models.CharField(max_length=120, default='') user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete = models.CASCADE, null = True, blank = True) def __unicode__(self): return self.name **Результат:** .. image:: _static/profile.png :target: _static/profile.png **Класс userStripe** ==================== Состоит из следующих полей: user, stripe_id. Методы: * __unicode__ - то же самое, что и для класса profile, но рассчитанный в первую очередь на возвращение ID. * stripeCallback - отвечает за создание Stripe ID и Stripe профиля пользователя. * profileCallback - отвечает за изменения профиля пользователя и появление его в системе после регистрации. Данные поля заполняются пользователями- администраторами приложения. Листинг:: class userStripe(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete = models.CASCADE) stripe_id = models.CharField(max_length = 200, null = True, blank = True) def __unicode__(self): # Если есть ID, преобразуй в его в строку: if self.stripe_id: return str(self.stripe_id) # Иначе верни имя пользователя: else: return self.user.username def stripeCallback(sender, request, user, **kwargs): user_stripe_account, created = userStripe.objects.get_or_create(user = user) # Если Stripe пользователя создан, появляется его профиль. if created: print(f'created for {user.username}') # Если ID системы stripe не существует, то используй email пользователя для его создания: if user_stripe_account.stripe_id is None or user_stripe_account.stripe_id == '': new_stripe_id = stripe.Customer.create(email = user.email) user_stripe_account.stripe_id = new_stripe_id['id'] user_stripe_account.save() def profileCallback(sender, request, user, **kwargs): userProfile, is_created = Profile.objects.get_or_create(user = user) # Если пользователь создан, появляется его профиль. if is_created: userProfile.name = user.username userProfile.save() user_logged_in.connect(stripeCallback) user_signed_up.connect(stripeCallback) user_signed_up.connect(profileCallback) **Представления** ================= Состоит из следующих полей: user, stripe_id. Методы: * home - подключение начальной страницы приложения. * about - подключение страницы описания приложения. * userProfile - функция подключения страницы профиля, которая появляется в меню навигации только после входа в профиль. Листинг:: def home(request): context = {} template = 'home.html' return render(request, template, context) def about(request): context = {} template = 'about.html' return render(request, template, context) # Декоратор, требующий обязательного входа в профиль: @login_required def userProfile(request): user = request.user context = {'user': user} template = 'profile.html' return render(request, template, context) **Домашняя страница:** .. image:: _static/home.png :target: _static/home.png **Страница описания:** .. image:: _static/about.png :target: _static/about.png **Страница профиля:** .. image:: _static/profile2.png :target: _static/profile2.png <file_sep>/django_structure/lib/python3.6/codecs.py /home/far/anaconda3/lib/python3.6/codecs.py<file_sep>/django_structure/lib/python3.6/_weakrefset.py /home/far/anaconda3/lib/python3.6/_weakrefset.py<file_sep>/django_structure/lib/python3.6/copyreg.py /home/far/anaconda3/lib/python3.6/copyreg.py<file_sep>/source/2_chapter.rst **************************** Глава 2- приложение Checkout **************************** **Состав и краткое описание** ============================= Данное приложение служит цели оплаты услуги пользователем. Имеет только один шаблон(checkout.html) и только одно представление(checkout) **Представление Checkout** ========================== Листинг:: stripe.api_key = settings.STRIPE_SECRET_KEY @login_required def checkout(request): publishKey = settings.STRIPE_PUBLISHABLE_KEY customer_id = request.user.userstripe.stripe_id if request.method == 'POST': token = request.POST['stripeToken'] # Создание платежа: try: # Создание покупателя: customer = stripe.Customer.retrieve({customer_id}) customer.sources.create(source = {token}) charge = stripe.Charge.create( amount = 100, currenvy = "usd", customer = customer, description = "Example charge" ) except stripe.error.CardError as e: # Карта отклонена: pass context = {'publishKey': publishKey} template = 'checkout.html' return render(request, template, context) **Страница оплаты:** .. image:: _static/checkout.png :target: _static/checkout.png <file_sep>/django_structure/lib/python3.6/_collections_abc.py /home/far/anaconda3/lib/python3.6/_collections_abc.py<file_sep>/django_structure/lib/python3.6/tarfile.py /home/far/anaconda3/lib/python3.6/tarfile.py<file_sep>/django_structure/lib/python3.6/fnmatch.py /home/far/anaconda3/lib/python3.6/fnmatch.py<file_sep>/build/html/_sources/3_chapter.rst.txt *************************** Глава 3- приложение Contact *************************** **Состав и краткое описание** ============================= Данное приложение отвечает за отправку сообщений с аккаунта на email адрес. Включает в себя только одно представление(contact) и один шаблон(contact.html) **Представление contact** ========================= Листинг:: def contact(request): title = 'Contact' form = contactForm(request.POST or None) confirm_message = None if form.is_valid(): name = form.cleaned_data['name'] comment = form.cleaned_data['comment'] subject = 'Message from MYSITE.com' message = f'{comment} {name}' emailFrom = form.cleaned_data['email'] emailTo = [settings.EMAIL_HOST_USER] #Подключение стандартной django- функции для отправки сообщения на email- адрес. send_mail(subject, message, emailFrom, emailTo, fail_silently = True) title = "Thanks!" confirm_message = "Thanks for message. We will get right back to you." form = None context = {'title': title, 'form': form, 'confirm_message': confirm_message, } template = 'contact.html' return render(request, template, context) **Страница contact:** .. image:: _static/contact.png :target: _static/contact.png <file_sep>/django_structure/src/profiles/models.py from __future__ import unicode_literals from django.conf import settings from django.db import models from allauth.account.signals import user_logged_in, user_signed_up import stripe stripe_api_key = settings.STRIPE_SECRET_KEY # Create your models here. # Создание модели профиля пользователя админки: class Profile(models.Model): # Добавление новых полей: name, description, location, job: name = models.CharField(max_length=120) description = models.TextField(default='description default text') job = models.CharField(max_length=120, null=True, default='') street = models.CharField(default='', max_length=100) city = models.CharField(default='', max_length=100) state = models.CharField(default='', max_length=100) phone = models.IntegerField(default=0) website = models.CharField(max_length=120, default='') width_field = models.IntegerField(default=0) height_field = models.IntegerField(default=0) image = models.ImageField(upload_to="profile_image", default="path/to/my/default/image.jpg") last_name = models.CharField(max_length=120, default='') email = models.CharField(max_length=120, default='') # Создание профиля пользователя: user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete = models.CASCADE, null = True, blank = True) def __unicode__(self): return self.name class userStripe(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete = models.CASCADE) stripe_id = models.CharField(max_length = 200, null = True, blank = True) def __unicode__(self): # Если есть ID, преобразуй в его в строку: if self.stripe_id: return str(self.stripe_id) # Иначе верни имя пользователя: else: return self.user.username def stripeCallback(sender, request, user, **kwargs): user_stripe_account, created = userStripe.objects.get_or_create(user = user) # Если Stripe пользователя создан, появляется его профиль. if created: print(f'created for {user.username}') # Если ID системы stripe не существует, то используй email пользователя для его создания: if user_stripe_account.stripe_id is None or user_stripe_account.stripe_id == '': new_stripe_id = stripe.Customer.create(email = user.email) user_stripe_account.stripe_id = new_stripe_id['id'] user_stripe_account.save() def profileCallback(sender, request, user, **kwargs): userProfile, is_created = Profile.objects.get_or_create(user = user) # Если пользователь создан, появляется его профиль. if is_created: userProfile.name = user.username userProfile.save() user_logged_in.connect(stripeCallback) user_signed_up.connect(stripeCallback) user_signed_up.connect(profileCallback) <file_sep>/django_structure/src/profiles/admin.py from django.contrib import admin # Register your models here. from .models import Profile, userStripe # Создание модели профиля администратора: class profileAdmin(admin.ModelAdmin): class Meta: model = Profile admin.site.register(Profile, profileAdmin) # Создание модели профиля администратора Stripe: class userStripeAdmin(admin.ModelAdmin): class Meta: model = userStripe admin.site.register(userStripe, userStripeAdmin) <file_sep>/django_structure/lib/python3.6/enum.py /home/far/anaconda3/lib/python3.6/enum.py<file_sep>/django_structure/lib/python3.6/token.py /home/far/anaconda3/lib/python3.6/token.py<file_sep>/README.md # Django_work Django website-template with stripe pay system. <file_sep>/django_structure/lib/python3.6/__future__.py /home/far/anaconda3/lib/python3.6/__future__.py<file_sep>/django_structure/lib/python3.6/operator.py /home/far/anaconda3/lib/python3.6/operator.py
f3065d37482cffadb5fe8caa397a8cc946710485
[ "reStructuredText", "Markdown", "HTML", "Python" ]
48
reStructuredText
AlfredMulder/Django_work
5d347d6897f58f6977ab584a80edb111ed2dabaf
6d006f8b1e0c679ed43377fb891d215e870114a9
refs/heads/master
<file_sep>CSS PROJECT: Viết lại giao diện trang meetup.com
9b081ccaf93cafe63d1a5cfb012e57630a49ce52
[ "Markdown" ]
1
Markdown
kimduyenle/Meetup
052a49583d3ae507137b31242b28acfa5e38d0e2
a5eaa1397e5aabdc8437838dff4bfa60bb99f1ae
refs/heads/main
<repo_name>xiaohei-maker/apple<file_sep>/README.md # name # name # apple
92dded1626526ff3c851dcad9f5ee679e97beafd
[ "Markdown" ]
1
Markdown
xiaohei-maker/apple
4e9b09aaabd70e6346b1531a87b81b0d19d6f86d
cd20afeb5d529985dcc5f3d1693418d34783aadd
refs/heads/master
<repo_name>fancfd/Rails_10days<file_sep>/README.md # Rails_10days This is my learning notes of rails 10 days! There's 3 step used to push the file to github. ```bash git add README.md git commit -m "add one line in @README.md" git push origin master ``` or just use ```bash git commit -a -m "add one line in @README.md" git push origin master ``` It seems that web storm does not work! So I have to push my change to the github! I clone in home! Change readme
e536d4f6453b34ed37902875e61e9df62ed288f9
[ "Markdown" ]
1
Markdown
fancfd/Rails_10days
2c0011ea361379c22600bc55b6b9c3f9bfc01d8d
7f5da102246ed5ed504402b03b1d40428253ad74
refs/heads/master
<file_sep># mysample1 My sample repo for managing checkouts and branches
3aaf6711da25d667905ffc02f0709fbcf2e3f56c
[ "Markdown" ]
1
Markdown
rtp19/mysample1
0e92115ffed535a9e295191987744353133195f2
aeef042121bf58f1343565bda941f9449bf3f434
refs/heads/master
<repo_name>OpenMageModuleFostering/ds_similarorder<file_sep>/app/code/community/Ds/Similarorder/Block/Adminhtml/Similarorder/Grid.php <?php class Ds_Similarorder_Block_Adminhtml_Similarorder_Grid extends Mage_Adminhtml_Block_Widget_Grid { public function __construct() { parent::__construct(); $this->setId('ds_order_grid'); $this->setDefaultSort('increment_id'); $this->setDefaultDir('DESC'); $this->setSaveParametersInSession(true); $this->setUseAjax(true); $this->setFilterVisibility(false); } protected function _prepareCollection() { $ordersearch = Mage::getResourceModel('sales/order_collection'); if ($data = $this->getRequest()->getPost()) { if($data['order_id'] != '') { $ordersearch = $ordersearch->addAttributeToFilter('increment_id', array('neq' => $data['order_id'])); $order = Mage::getModel('sales/order')->getCollection()->addFieldToFilter('increment_id',$data['order_id'])->getFirstItem(); if($order->getData()) { if(in_array("IP", $data['filter'])) { $remote_ip = $order->getData('remote_ip'); $ordersearch = $ordersearch->addFieldToFilter('remote_ip',$remote_ip); /* echo "<pre>"; print_r($ordersearch->getData()); exit; */ } /* if(in_array("cookie", $data['filter'])) { $cookie = $order->getData('cookie'); $ordersearch = $ordersearch->addFieldToFilter('cookie',$cookie); } */ $addData = $order->getBillingAddress()->getData(); $postcode = $addData['postcode']; $street = $addData['street']; $city = $addData['city']; $telephone = $addData['telephone']; $country_id = $addData['country_id']; /* $cPhones[]=$telephone; */ if(in_array("Address", $data['filter'])) { $ordersearch = $ordersearch->addFieldToFilter('a.postcode',$postcode) ->addFieldToFilter('a.street',$street) ->addFieldToFilter('a.city',$city) ->addFieldToFilter('a.country_id',$country_id); } if(in_array("Phone", $data['filter'])) { $ordersearch = $ordersearch->addFieldToFilter('a.telephone',$telephone); } } else { $ordersearch = $ordersearch->addAttributeToFilter('increment_id', "0"); } } } $checkArray=array("IP","Phone","Address"); if(count(array_intersect($data['filter'], $checkArray)) == 0 || $data['order_id'] == '') { $ordersearch = $ordersearch->addAttributeToFilter('increment_id', "0"); } $collection = $ordersearch ->join(array('a' => 'sales/order_address'), 'main_table.entity_id = a.parent_id AND a.address_type = \'billing\'', array( 'city' => 'city', 'country_id' => 'country_id' )) ->addExpressionFieldToSelect( 'fullname', 'CONCAT({{customer_firstname}}, \' \', {{customer_lastname}})', array('customer_firstname' => 'main_table.customer_firstname', 'customer_lastname' => 'main_table.customer_lastname')) ->addExpressionFieldToSelect( 'products', '(SELECT GROUP_CONCAT(\' \', x.name) FROM sales_flat_order_item x WHERE {{entity_id}} = x.order_id AND x.product_type != \'configurable\')', array('entity_id' => 'main_table.entity_id') ); #echo $collection->getSelect()."<hr>"; /* echo "<pre>"; print_r($collection->getData()); exit; */ $this->setCollection($collection); parent::_prepareCollection(); return $this; } protected function _prepareColumns() { $helper = Mage::helper('similarorder'); $currency = (string) Mage::getStoreConfig(Mage_Directory_Model_Currency::XML_PATH_CURRENCY_BASE); $this->addColumn('increment_id', array( 'header' => $helper->__('Order #'), 'filter' => false, 'sortable' => false, 'index' => 'increment_id' )); $this->addColumn('purchased_on', array( 'header' => $helper->__('Purchased On'), 'type' => 'datetime', 'filter' => false, 'sortable' => false, 'index' => 'created_at' )); $this->addColumn('products', array( 'header' => $helper->__('Products Purchased'), 'index' => 'products', 'filter' => false, 'sortable' => false, 'filter_index' => '(SELECT GROUP_CONCAT(\' \', x.name) FROM sales_flat_order_item x WHERE main_table.entity_id = x.order_id AND x.product_type != \'configurable\')' )); $this->addColumn('remote_ip', array( 'header' => $helper->__('Ip Address'), 'filter' => false, 'sortable' => false, 'index' => 'remote_ip' )); $this->addColumn('fullname', array( 'header' => $helper->__('Name'), 'index' => 'fullname', 'filter' => false, 'sortable' => false, 'filter_index' => 'CONCAT(customer_firstname, \' \', customer_lastname)' )); $this->addColumn('city', array( 'header' => $helper->__('City'), 'filter' => false, 'sortable' => false, 'index' => 'city' )); $this->addColumn('country', array( 'header' => $helper->__('Country'), 'filter' => false, 'sortable' => false, 'index' => 'country_id', 'renderer' => 'adminhtml/widget_grid_column_renderer_country' )); $this->addColumn('grand_total', array( 'header' => $helper->__('Grand Total'), 'index' => 'grand_total', 'filter' => false, 'sortable' => false, 'type' => 'currency', 'currency_code' => $currency )); $this->addColumn('order_status', array( 'header' => $helper->__('Status'), 'index' => 'status', 'filter' => false, 'sortable' => false, 'type' => 'options', 'options' => Mage::getSingleton('sales/order_config')->getStatuses(), )); return parent::_prepareColumns(); } public function getGridUrl() { return $this->getUrl('similarorder/adminhtml_ordergrid/grid', array('_current' => true)); } public function getRowUrl($row) { return $this->getUrl('adminhtml/sales_order/view', array('order_id' => $row->getId())); } }<file_sep>/app/design/adminhtml/default/default/template/similarorder/orderform.phtml <?php $customerId = $this->getRequest()->getParams(); /* echo "<pre>"; print_r($customerId); exit; */ $orderId = $customerId['order_id']; $orders = Mage::getModel('sales/order')->load($orderId); $oId = $orders->getIncrementId(); ?> <div id="customer_info_tabs_customer_edit_tab_ordernote_content"> <form id="edit_form" name="edit_form" action="<?php echo $this->getUrl('similarorder/adminhtml_similarorder/filterbyorder'); ?>" method="post"> <?php echo $this->getBlockHtml('formkey')?> <div class="entry-edit"> <div class="entry-edit-head"> <h4 class="icon-head head-edit-form fieldset-legend">Find Similer Orders:</h4> </div> <div id="ordergrid_form" class="fieldset"> <table class="form-list" cellspacing="0"> <tbody> <tr> <td class="label"> <label for="order_id">Odrer ID</label> </td> <td class="value"> <input id="order_id" class="input-text" type="text" value="<?php if(isset($oId) && $oId){ echo $oId; } ?>" name="order_id" readonly /> </td> </tr> <tr> <td class="label"> <label for="modes">Find Similer By</label> </td> <td class="value"> <?php /* <input type="checkbox" id="cookie" name="filter[]" value="cookie" <?php if(in_array("cookie", $customerId['filter'])) { echo 'checked="checked"'; } ?> /> <label for="cookie" style="padding-right:10px;">Cookie</label> */ ?> <input type="checkbox" id="ip" name="filter[]" class="search_check" value="IP" <?php if(in_array("IP", $customerId['filter'])) { echo 'checked="checked"'; } ?> /> <label for="ip" style="padding-right:10px;">IP</label> <input type="checkbox" id="address" name="filter[]" class="search_check" value="Address" <?php if(in_array("Address", $customerId['filter'])) { echo 'checked="checked"'; } ?> /> <label for="address" style="padding-right:10px;">Billing Address</label> <input type="checkbox" id="phone" name="filter[]" class="search_check" value="Phone" <?php if(in_array("Phone", $customerId['filter'])) { echo 'checked="checked"'; } ?> /> <label for="phone">Phone</label> </td> </tr> <tr><td colspan="2">&nbsp;</td></tr> <tr> <td colspan="2" align="right"> <!--input id="add_note_submit" class="button" type="button" value="Add Note" /--> <button id="add_search" class="add_search" type="button" title="Add Search" onclick="search(this)"><span><span>Search</span></button> </td> </tr> </tbody> </table> </div> </div> </form> </div> <script type="text/javascript"> function search(thisform) { var chec = document.getElementsByName('filter[]'); var ln = 0; for(var i=0; i< chec.length; i++) { if(chec[i].checked) ln++; } if(ln == 0) { alert('please check at least one from IP/Address/Telephone.'); return false; } document.getElementById('edit_form').submit(); } </script><file_sep>/app/code/community/Ds/Similarorder/Helper/Data.php <?php class Ds_Similarorder_Helper_Data extends Mage_Core_Helper_Abstract { }<file_sep>/app/code/community/Ds/Similarorder/Model/Mysql4/Similarorder.php <?php class Ds_Similarorder_Model_Mysql4_Similarorder extends Mage_Core_Model_Mysql4_Abstract { public function _construct() { // Note that the similarorder_id refers to the key field in your database table. $this->_init('similarorder/similarorder', 'similarorder_id'); } }<file_sep>/skin/adminhtml/default/default/js/custom_grid.js function showbox(x){ document.getElementById(x).style.display = 'block'; } function hidebox(x) { document.getElementById(x).style.display = 'none'; }<file_sep>/app/code/community/Ds/Similarorder/controllers/Adminhtml/SimilarorderController.php <?php class Ds_Similarorder_Adminhtml_SimilarorderController extends Mage_Adminhtml_Controller_action { protected function _initAction() { $this->loadLayout() ->_setActiveMenu('similarorder/items') ->_addBreadcrumb(Mage::helper('adminhtml')->__('Items Manager'), Mage::helper('adminhtml')->__('Item Manager')); return $this; } public function indexAction() { $this->_initAction() ->renderLayout(); } public function gridAction() { $this->loadLayout(); $this->renderLayout(); } public function orderfilterAction() { $this->_title($this->__('Similar Order')) ->_title($this->__('Manage Items')); $this->_title($this->__('Order Filter')); $this->loadLayout() //->_setActiveMenu('ordergrid/items') ->_addContent($this->getLayout()->createBlock('similarorder/adminhtml_orderfilter')) ->renderLayout(); } public function filterbyorderAction() { $this->_title($this->__('Similar Order')) ->_title($this->__('Manage Items')); $this->_title($this->__('Order Filter')); $this->loadLayout() //->_setActiveMenu('ordergrid/items') ->_addContent($this->getLayout()->createBlock('similarorder/adminhtml_orderfilter')) ->renderLayout(); } }<file_sep>/app/code/community/Ds/Similarorder/Block/Adminhtml/Similarorder/View/Tab/Form.php <?php class Ds_Similarorder_Block_Adminhtml_Similarorder_View_Tab_Form extends Mage_Adminhtml_Block_Widget_Form implements Mage_Adminhtml_Block_Widget_Tab_Interface { protected function _prepareForm() { $form = new Varien_Data_Form(); $this->setForm($form); $fieldset = $form->addFieldset('similarorder_form', array( 'legend' => Mage::helper('similarorder')->__('Item information') ))->setRenderer($this->getLayout()->createBlock('adminhtml/widget_form_renderer_fieldset')->setTemplate( 'similarorder/orderform.phtml' )); return parent::_prepareForm(); } public function getTabLabel() { return Mage::helper('similarorder')->__('Find Similar'); } public function getTabTitle() { return Mage::helper('similarorder')->__('Find Similar'); } public function canShowTab() { return true; } public function isHidden() { return false; } }<file_sep>/app/code/community/Ds/Similarorder/Model/Similarorder.php <?php class Ds_Similarorder_Model_Similarorder extends Mage_Core_Model_Abstract { public function _construct() { parent::_construct(); $this->_init('similarorder/similarorder'); } }<file_sep>/app/code/community/Ds/Similarorder/Block/Adminhtml/Orderfilter.php <?php class Ds_Similarorder_Block_Adminhtml_Orderfilter extends Mage_Adminhtml_Block_Widget { public function __construct() { parent::__construct(); $this->setTemplate('similarorder/orderfilter.phtml'); } }
98588086f9db9cd5e60a0f8e968e992797b1ab3a
[ "HTML+PHP", "JavaScript", "PHP" ]
9
HTML+PHP
OpenMageModuleFostering/ds_similarorder
d813d97386e756aad5fb2c72c71dac1e54340e07
dfcf4f181c57c958789b7ac8fbb4ee81521be6ee
refs/heads/master
<repo_name>naveendewasurendra/PAF_2019<file_sep>/dashboard/scripts/users_handler.js $("#users_userlist").ready(function () { $.ajax("http://localhost:8080/sellnbye/api/user", { contentType: 'application/json', type: 'GET' }).done(function (response) { var newItem = ""; $.each(response, function (index, value) { newItem += `<hr class="soften"> <div class="row-fluid"> <div class="span2"> <img src="${value.profilePicture}" alt="" height="130" width="100"> </div> <div class="span6"> <h5>${value.username}</h5> <p> ${value.email} </p> </br> <p> ${value.contactNo} </p> </div> <div class="span4 alignR"> <form class="form-horizontal qtyFrm"> <h3> ${value.userType}</h3><br> <div class="btn-group"> <a href="product_details.html" class="shopBtn">EDIT</a> </div> </form> </div> </div>`; }); $("#users_userlist").append(newItem); }); }); $("#login_form").submit(function (event) { event.preventDefault(); data = { "password": <PASSWORD>($("#login_inputPassword").val()).<PASSWORD>(), "username": $("#login_inputUserName").val() } $.ajax("http://localhost:8080/sellnbye/api/user/login", { data: JSON.stringify(data), contentType: 'application/json', type: 'POST' }).done(function (response) { console.log(response); }); });
d25ef3f7a6aee55ac6a7f263437aca16eb1e8b02
[ "JavaScript" ]
1
JavaScript
naveendewasurendra/PAF_2019
5a5a96d62b7b597a881afad697b9ecc467bcd796
2f1d33bb61967b512ddc1693b4be82a60cf7ad24
refs/heads/master
<repo_name>guysmoilov/client<file_sep>/wandb/sweeps/__init__.py from wandb.sweeps.bayes_search import BayesianSearch from wandb.sweeps.grid_search import GridSearch from wandb.sweeps.random_search import RandomSearch from wandb.sweeps.hyperband_stopping import HyperbandEarlyTerminate from wandb.sweeps.envelope_stopping import EnvelopeEarlyTerminate
938be5aed9616aa44bf8ca9e5931bfeeb5a65234
[ "Python" ]
1
Python
guysmoilov/client
28b818c5302e935ba269b9d4480e97903c28b8b2
b4a8d935917307f0f3abaa753000bc4a92faea2b
refs/heads/master
<file_sep>#! /bin/bash sl -l clear echo "\n \n \n \t \t \t HELLO WORLD!!!" sleep 3 <file_sep>#! /bin/bash apt update -y apt upgrade -y apt-get install sl -y chmod +x ./hello_world.sh ./hello_world.sh <file_sep># hello-world пытаюсь разобраться что да как )))
28d1f2204aa52717606d12c2a8a0dd7588249b46
[ "Markdown", "Shell" ]
3
Markdown
kino46danila/hello-world
7f3291cf80766b59490edf9b16cafd12f4167ce4
c078625b662e4e49edfeafcb7202f289bac91e84
refs/heads/master
<file_sep>/*--------------------------------------Cloudinary--------------------------------------*/ /* https://cloudinary.com */ /* Dev. <NAME> */ /* Email: <EMAIL> */ /*--------------------------------------------------------------------------------------*/ // npm install crypto-js --save import CryptoJS from 'crypto-js' // Upload image to cloudinary function uploadImage(uri, progress, response, error) { const timestamp = (Date.now() / 1000 | 0).toString(); const api_key = '' const api_secret = '' const cloud = '' const hash_string = 'timestamp=' + timestamp + api_secret const signature = CryptoJS.SHA1(hash_string).toString(); const upload_url = 'https://api.cloudinary.com/v1_1/' + cloud + '/image/upload' let xhr = new XMLHttpRequest(); xhr.open('POST', upload_url); xhr.onload = () => { console.log(xhr); }; xhr.upload.addEventListener('progress', function(e) { //console.log('progress: ' + (e.loaded * 100/ e.total).toFixed(2) + '%'); progress(parseFloat(e.loaded * 100/ e.total).toFixed(2)) }, false); xhr.onreadystatechange = (e) => { if (xhr.readyState !== 4) { return; } if (xhr.status === 200) { response(xhr.responseText) // console.log('success', xhr.responseText); } else { console.log('errors'); console.log(xhr); error('errors') } }; let formdata = new FormData(); formdata.append('file', { uri: uri, type: 'image/png', name: 'upload.png' }); formdata.append('timestamp', timestamp); formdata.append('api_key', api_key); formdata.append('signature', signature); xhr.send(formdata); } // Delete image to cloudinary function deleteImage(publicId) { const timestamp = (Date.now() / 1000 | 0).toString(); const api_key = '' const api_secret = '' const cloud = '' const delete_url = 'https://api.cloudinary.com/v1_1/' + cloud + '/image/destroy'; const hash_string = 'public_id='+ publicId + '&timestamp=' + timestamp + api_secret const signature = CryptoJS.SHA1(hash_string).toString(); let xhr = new XMLHttpRequest(); xhr.open('POST', delete_url); xhr.onload = () => { console.log(xhr); }; xhr.onreadystatechange = (e) => { if (xhr.readyState !== 4) { return; } if (xhr.status === 200) { console.log(xhr.responseText) // console.log('success', xhr.responseText); } else { console.log('errors'); console.log(xhr); error('errors') } }; let formdata = new FormData(); formdata.append('public_id', publicId); formdata.append('timestamp', timestamp); formdata.append('api_key', api_key); formdata.append('signature', signature); xhr.send(formdata); } // Upload multi images to cloudinary - handle Redux Saga response // import { buffers, eventChannel, END } from 'redux-saga' function uploadMultiImages(arrImages) { return eventChannel(emitter => { let listPhoto = [] let arrProgress = [] let error = [] let countPhoto = arrImages.length let uploadPhoto = 0 for(let i=0; i<countPhoto; i++) { arrProgress[i] = 0 } for(let i=0; i<countPhoto; i++) { console.log(uploadPhoto); uploadImage(arrImages[i].path, (progress) => { console.log(i + '-----') arrProgress[i] = progress emitter({ progress: arrProgress }) }, (response) => { console.log(response) listPhoto[i] = response uploadPhoto++ if(uploadPhoto == countPhoto) { emitter({ success: listPhoto }) emitter(END) // console.log(arrProgress); // console.log(listPhoto); } }, (error) => { error[i] = error console.log(error) uploadPhoto++ }) } return () => {} }, buffers.sliding(2)) } // Upload multi images to cloudinary - handle Redux Saga response // import { call, put, take } from 'redux-saga/effects' export function * createPostWithMultiImages (postApi, uploadApi, action) { try { const { arrImagesUpload } = action const channel = yield call(uploadMultiImages, arrImagesUpload) while (true) { const { progress = 0, err, success } = yield take(channel); if (err) { console.log(err); //yield put(PostActions.createPostFailure(err)); return; } if (success) { console.log(success); //yield put(PostActions.createPostSuccess()); /**************** Call Other Api *****************/ return; } console.log(progress); // Calculate % progress upload let total = 0 for(let i=0; i<progress.length; i++) { total += parseFloat(progress[i]) } console.log((total / progress.length).toFixed(2) + '%') //yield put(PostActions.createPostProgress((total / progress.length).toFixed(2) + '%')); } } } <file_sep># Cloudinary Cloudinary Api Note
d5346db609e1930eee8fa4359bb0175f44fc3fcd
[ "Markdown", "JavaScript" ]
2
Markdown
TuNguyenThanh/Cloudinary
ca647407515619363ad9abfbf6ed68723892c548
4671a64b2fe79711cf34ff4a28a42a32cc1f0185
refs/heads/master
<repo_name>sami-suliman/rails-project-kanban-application<file_sep>/app/views/parts/show.html.erb <h2> Part Number: <%= @part.part_number %> </h2> <h2> Part Name: <%= @part.part_name %> </h2> <h2> Part Description: <%= @part.part_description %> </h2> <%= link_to "|Edit|", edit_part_path %> <file_sep>/app/views/orders/new.html.erb <center><h1>NEW STATION</h1></center> <% if @errors && !@errors.empty? %> <% @errors.each do |message|%> <p><%= message %></p> <% end %> <% end %> <%= form_for(@order) do |f| %> <%= f.label :station %> <%= f.text_field :station %> <%= f.label :station_name %> <%= f.text_field :station_name %> <%= f.submit %> <% end %><file_sep>/app/views/orders/index.html.erb <left><%= link_to "|Add New Station|", new_order_path %></left><center><h1>Stations List</h1></center> <p><h3>Please select your station to place your part order:</h3></p> <table> <thead> <tr> <th>|Station No |</th> <th>Station Name |</th> </tr> </thead> <tbody> <% @orders.each do |order| %> <tr> <td><%= link_to order.station, order_path(order) %></td> <td><%= order.station_name %></td> <td><%= link_to "| Edit |", edit_order_path(order)%></td> </tr> <% end %> </tbody> </table><file_sep>/test/fixtures/partorders.yml # Read about fixtures at https://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html one: qty: 1 picked: false order: one part: one two: qty: 1 picked: false order: two part: two <file_sep>/app/views/application/home.html.erb <html> <% if user_signed_in? %> <head> <h1> Home Page </h1> <h3> Welcom! <%= @user %></h3> </head> <body> <li><%= link_to "|Part Request|", orders_path %></li> <li><%= link_to "|Partordered List|", partorders_path %></li> <li><%= link_to "|Add New Part|", new_part_path %></li> <li><%= link_to "|Parts List|", parts_path %></li> </body> <% else %> <head> <h1> Home Page </h1> </head> <% end %> </html> <file_sep>/app/models/order.rb class Order < ApplicationRecord validates :station, presence:{message: "must be filled"} belongs_to :user has_many :partorders has_many :parts, through: :partorders end <file_sep>/app/views/layouts/_nav.html.erb <nav> <center> <%= link_to "|Home|", root_path %> . <% if !user_signed_in? %> <%= link_to "|Sign up|", new_user_registration_path %> . <%= link_to "|Log in|", new_user_session_path %> . <%= link_to "|Log in with Github|", user_github_omniauth_authorize_path %> <% else %> <%= link_to "|Edit Account|", edit_user_registration_path %> . <%= link_to "|Sign out|", destroy_user_session_path, method: :delete %> <% end %> </center> </nav><file_sep>/app/models/part.rb class Part < ApplicationRecord validates :part_number, presence:{message: "must be filled"} has_many :partorders has_many :orders, through: :partorders end <file_sep>/app/views/parts/index.html.erb <center><h1>Parts List</h1></center> <table> <thead> <tr> <th>| Part Number |</th> <th>Part Name |</th> <th>Description |</th> </tr> </thead> <tbody> <% @parts.each do |part| %> <tr> <td><%= link_to part.part_number, part_path(part) %></td> <td><%= part.part_name %></td> <td><%= part.part_description %></td> <td><%= link_to "| Edit |", edit_part_path(part)%></td> </tr> <% end %> </tbody> </table><file_sep>/app/views/orders/edit.html.erb <center><h1>EDIT STATION</h1></center> <%= form_with model:@order do |f| %> <%= f.label :station %> <%= f.text_field :station %> <%= f.label :station_name %> <%= f.text_field :station_name %> <%= f.submit %> <% end %><file_sep>/app/controllers/partorders_controller.rb class PartordersController < ApplicationController before_action :set_partorder, only: [:show, :edit, :update, :destroy] def index @partorders = Partorder.all end def show end def new @partorder = Partorder.new(order_id: params[:order_id]) #@partorder = Partorder.new end def edit end def create @partorder = Partorder.new(partorder_params) if @partorder.save redirect_to '/orders/:order_id/partorders' else @errors = @partorder.errors.full_messages render :new end end def notpicked @partorders = Partorder.all.select{|partorder| partorder.picked == false} end def update @partorder.update(partorder_params) redirect_to order_partorder_path(@partorder) end def destroy @partorder.destroy redirect_to partorders end private def set_partorder #@partorder = Partorder.find_by(id: params[:order_id]) @partorder = Partorder.find_by(id: params[:id]) end def partorder_params params.require(:partorder).permit(:partorder_id, :qty, :picked, :order_id, :part_id) end end <file_sep>/app/views/parts/new.html.erb <center><h1>ADD NEW PART </h1></center> <% if @errors && !@errors.empty? %> <% @errors.each do |message|%> <p><%= message %></p> <% end %> <% end %> <%= form_for(@part) do |f| %> <%= f.label :part_number %> <%= f.text_field :part_number %> <%= f.label :part_name %> <%= f.text_field :part_name %> <%= f.label :part_description %> <%= f.text_field :part_description %> <%= f.submit %> <% end %><file_sep>/app/views/partorders/show.html.erb <h2> Date Ordered : <%= @partorder.created_at.strftime("%m/%d/%Y") %> </h2> <h2> Time Order : <%= @partorder.created_at.strftime("%I:%M %p") %> </h2> <h2> Part Number: <%= @partorder.part_id %> </h2> <h2> Quantity: <%= @partorder.qty %> </h2> <h2> Status: <%= @partorder.picked ? "Picked" : "Not Picked" %> </h2> <h2> Time Picked : <%= @partorder.updated_at.strftime("%I:%M %p") %> </h2> <file_sep>/config/routes.rb Rails.application.routes.draw do resources :orders do resources :partorders, only: [:index, :show, :new, :edit] end resources :partorders resources :parts # resources :orders # get '/partorders', to: "partorders#index", as:"partorders" # get '/orders/:id/partorders', to: "partorders#show", as:"partorder" # get '/orders/:id/partorders/new', to: "partorders#new", as:"new_partorders" # post '/orders/:id/partorders', to: "partorders#create" devise_for :users, :controllers => { omniauth_callbacks: "callbacks" } root to: 'application#home' # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html end <file_sep>/app/models/partorder.rb class Partorder < ApplicationRecord validates :qty, presence:{message: "must be filled"} belongs_to :order belongs_to :part end <file_sep>/app/views/partorders/edit.html.erb <center><h1>EDIT PART ORDER</h1></center> <%= form_with model:@partorder do |f| %> <%= f.hidden_field :order_id %> <label>Part Number </label> <%= f.collection_select :part_id, Part.all, :id, :part_number%> <%= f.label :quantity %> <%= f.text_field :qty %> <%= f.label :picked %> <%= f.check_box :picked %> <%= f.submit %> <% end %><file_sep>/app/views/parts/edit.html.erb <center><h1>EDIT PART </h1></center> <% if @errors && !@errors.empty? %> <% @errors.each do |message|%> <p><%= message %></p> <% end %> <% end %> <%= form_with model:@part do |f| %> <%= f.label :part_number %> <%= f.text_field :part_number %> <%= f.label :part_name %> <%= f.text_field :part_name %> <%= f.label :part_description %> <%= f.text_field :part_description %> <%= f.submit %> <% end %><file_sep>/README.md # Kanban Application Kanban App  allows either an assembler or a warehouse picker to register as a user, assembler can request their parts with the quantities and warehouse picker get access to the parts list that need to be picked and then marked as picked when the parts get received by the assembler. - This application was created using Ruby version '2.6.1' And Rails version '6.0.1'. - To use this app: fork, clone, migrate db and run rails s. - Then log into your local server at port 3000 <file_sep>/app/views/orders/show.html.erb <li><%= link_to "|Back to all stations|", orders_path %></li> <h1>Station: <%= @order.station %> - Station Name: <%= @order.station_name %></h1> <h2><%= link_to "New Partorder", new_order_partorder_path(@order) %></h2> <table> <thead> <tr> <th>| PartNo |</th> <th>Ordered Date|</th> <th>Quantity |</th> <th>Status |</th> </tr> </thead> <p>Partorders:</p> <tbody> <% @order.partorders.each do |partorder| %> <tr> <td><%= partorder.part_id %></td> <td><%= partorder.created_at.strftime("%m/%d/%Y") %></td> <td><%= partorder.qty %></td> <td><%= partorder.picked ? "Picked" : "Not Picked" %></td> <td><%= link_to "| Edit |", edit_order_partorder_path(@order, partorder)%></td> </tr> <% end %> </tbody> </table> <file_sep>/db/seeds.rb # This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup). # # Examples: # # movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) # Character.create(name: 'Luke', movie: movies.first) parts = [{part_number: "The Killers", part_name: "<NAME>", part_description: "Mr. Brightside"}, {}, {}, {}, {}, {}, {}, {artist_name: "Pixies", title: "Monkey Gone to Heaven"}] parts.each do |part| Part.create(part) end # rake db:seed<file_sep>/app/views/partorders/index.html.erb <center><h1>Partorders List</h1></center> <table> <thead> <tr> <th>|PartNo|</th> <th>Quantity|</th> <th>Picked|</th> </tr> </thead> <tbody> <% @partorders.each do |partorder| %> <tr> <td><%= link_to partorder.part_id, partorder_path(partorder) %></td> <td><%= partorder.qty %></td> <td><%= partorder.picked ? "Picked" : "Not Picked" %></td> <td><%= link_to "| Edit |", edit_partorder_path(partorder)%></td> </tr> <% end %> </tbody> </table><file_sep>/app/views/partorders/new.html.erb <center><h1>NEW PART ORDER</h1></center> <% if @errors && !@errors.empty? %> <% @errors.each do |message|%> <p><%= message %></p> <% end %> <% end %> <%= form_for(@partorder) do |f| %> <p> <%= f.hidden_field :order_id %> <label>Part Number </label> <%= f.collection_select :part_id, Part.all, :id, :part_number %> <%= f.label :quantity %> <%= f.text_field :qty %> <%= f.label :picked %> <%= f.check_box :picked %> <%= f.submit %> </p> <% end %>
2f20226a5c4bb1d27eba8475822c9db822777feb
[ "HTML+ERB", "Markdown", "Ruby", "YAML" ]
22
HTML+ERB
sami-suliman/rails-project-kanban-application
c427e75d6d54cb76eacadec2657602db8c8643e4
c2cc225d42910b93f1ea480a8fd4d80f3626060c
refs/heads/master
<repo_name>Veivan/TwLogin<file_sep>/src/main/TwitterLogin.java package main; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.net.CookieHandler; import java.net.CookieManager; import java.net.URI; import java.net.URISyntaxException; import java.net.URLEncoder; import java.util.ArrayList; import java.util.List; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.config.CookieSpecs; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.protocol.HttpClientContext; import org.apache.http.client.utils.URIBuilder; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.client.LaxRedirectStrategy; import org.apache.http.message.BasicNameValuePair; import org.apache.http.Header; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; public class TwitterLogin { private static final String USER_AGENT = "Mozilla/5.0"; private String cookies; private String twitter_sess; private String guest_id; private String authenticity_token; private String auth_token; private String twid; /* * private HttpClient client = HttpClientBuilder.create() * .setRedirectStrategy(new LaxRedirectStrategy()).build(); */ private HttpClient client = HttpClientBuilder.create().setUserAgent(USER_AGENT).build(); /* private static final CloseableHttpClient client = HttpClients .custom() .setUserAgent(USER_AGENT) .setDefaultRequestConfig( RequestConfig.custom() .setCookieSpec(CookieSpecs.BROWSER_COMPATIBILITY) .build()).build(); */ public static void main(String[] args) { String urlLogin = "https://twitter.com/login"; String urlsess = "https://twitter.com/sessions"; String urlmain = "https://twitter.com/"; // make sure cookies is turn on CookieHandler.setDefault(new CookieManager()); TwitterLogin http = new TwitterLogin(); String result = ""; try { String page = http.GetPageContent(urlLogin); List<NameValuePair> postParams = http.getFormParams(page, "u", "p"); http.sendPost(urlsess, postParams); http.dotwit("Hi-people"); // result = http.GetPageContent(urlmain); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(result); System.out.println("Done"); } private void Save2file(String buffer, String filename) throws Exception { BufferedWriter bwr = new BufferedWriter(new FileWriter(new File( filename))); // write contents of StringBuffer to a file bwr.write(buffer); // flush the stream bwr.flush(); // close the stream bwr.close(); } private void sendPost(String url, List<NameValuePair> postParams) throws Exception { //CloseableHttpResponse response = null; HttpResponse response = null; try { HttpPost post = new HttpPost(url); // add header post.setHeader("Host", "twitter.com"); //post.setHeader("User-Agent", USER_AGENT); post.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); post.setHeader("Accept-Language", "ru-RU,ru;q=0.8,en-US;q=0.6,en;q=0.4,bg;q=0.2"); post.setHeader("Cookie", getCookies()); post.setHeader("Connection", "keep-alive"); post.setHeader("Referer", "https://twitter.com"); post.setHeader("Content-Type", "application/x-www-form-urlencoded"); post.setEntity(new UrlEncodedFormEntity(postParams, "UTF-8")); response = client.execute(post); int responseCode = response.getStatusLine().getStatusCode(); System.out.println("\nSending 'POST' request to URL : " + url); System.out.println("Post parameters : " + postParams); System.out.println("Response Code : " + responseCode); BufferedReader rd = new BufferedReader(new InputStreamReader( response.getEntity().getContent())); StringBuffer result = new StringBuffer(); String line = ""; while ((line = rd.readLine()) != null) { result.append(line); } Save2file(result.toString(), "d:/demo.txt"); String cooky = collectCookiesresponse(response .getHeaders("set-cookie")); System.out.println(cooky); } finally { /*if (response != null) { response.close(); } */ } // System.out.println(result.toString()); } private String GetPageContent(String url) throws Exception { HttpGet request = new HttpGet(url); request.setHeader("User-Agent", USER_AGENT); request.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); request.setHeader("Accept-Language", "ru-RU,ru;q=0.8,en-US;q=0.6,en;q=0.4,bg;q=0.2"); HttpResponse response = client.execute(request); int responseCode = response.getStatusLine().getStatusCode(); System.out.println("\nSending 'GET' request to URL : " + url); System.out.println("Response Code : " + responseCode); BufferedReader rd = new BufferedReader(new InputStreamReader(response .getEntity().getContent())); StringBuffer result = new StringBuffer(); String line = ""; while ((line = rd.readLine()) != null) { result.append(line); } // set cookies setCookies(response.getFirstHeader("set-cookie") == null ? "" : collectCookiesresponse(response.getHeaders("set-cookie"))); return result.toString(); } private void dotwit(String statusbody) throws Exception { List<NameValuePair> postParams = new ArrayList<NameValuePair>(); postParams.add(new BasicNameValuePair("status", URLEncoder.encode(statusbody, "UTF-8"))); sendPost("https://api.twitter.com/1.1/statuses/update.json", postParams); } private String collectCookiesresponse(Header[] headers) { StringBuilder result = new StringBuilder(); for (Header header : headers) { if (result.length() == 0) { result.append(header.toString()); } else { result.append(";" + header.getValue()); } } return result.toString(); } public List<NameValuePair> getFormParams(String html, String username, String password) throws UnsupportedEncodingException { System.out.println("Extracting form's data..."); Document doc = Jsoup.parse(html); // Login form id Element loginform = doc.getElementsByClass("LoginForm js-front-signin") .first();// getElementById("LoginForm.js-front-signin"); Elements inputElements = loginform.getElementsByTag("input"); List<NameValuePair> paramList = new ArrayList<NameValuePair>(); for (Element inputElement : inputElements) { String key = inputElement.attr("name"); String value = inputElement.attr("value"); if (key.equals("session[username_or_email]")) value = username; else if (key.equals("session[password]")) value = password; else if (key.equals("remember_me")) value = "0"; paramList.add(new BasicNameValuePair(key, value)); } /* * paramList.add(new BasicNameValuePair("session[username_or_email]", * URLEncoder.encode(username, "UTF-8"))); paramList.add(new * BasicNameValuePair("session[password]", URLEncoder .encode(password, * "UTF-8"))); * * paramList.add(new BasicNameValuePair("remember_me", "0")); */ /* * return_to_ssl:true * * scribe_log: redirect_after_login:/ * authenticity_token:<PASSWORD> */ return paramList; } public String getCookies() { return cookies; } public void setCookies(String cookies) { this.cookies = cookies; } }
e259bd3a43f2ae28e7d69c55f3504039cba11fbf
[ "Java" ]
1
Java
Veivan/TwLogin
2dea500c5b775457ef0f395480566d6016bef916
5501242e13e4496a237531075a6448d87c456374
refs/heads/main
<repo_name>AntonTech420/2d-Game<file_sep>/PewPew/Assets/Scripts/Asteroid.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class Asteroid : MonoBehaviour { public Sprite[] sprites; public float size = 1.5f; public float Minsize = 0.5f; public float Maxsize = 10.0f; public float AsteroidSpeed = 20.0f; public float MaxLifetime = 60.0f; private SpriteRenderer _spriteRenderer; private Rigidbody2D _rigidbody; private BoxCollider2D boxCollider; private void Awake() { _spriteRenderer =GetComponent<SpriteRenderer>(); _rigidbody = GetComponent<Rigidbody2D>(); boxCollider = GetComponent <BoxCollider2D>(); } // Start is called before the first frame update private void Start() { _spriteRenderer.sprite = sprites[Random.Range(0, sprites.Length)]; this.transform.eulerAngles = new Vector3(0.0f, 0.0f, Random.value * 360.0f); this.transform.localScale = Vector3.one * this.size; _rigidbody.mass = this.size * 2.0f; } public void SetTrajectory(Vector2 direction) { _rigidbody.AddForce(direction * this.AsteroidSpeed); Destroy(this.gameObject, this.MaxLifetime);//Asteroid life span before despawning } private void OnTriggerEnter2D() { if ((this.size * 0.05f) >= this.Minsize) { createSplit(); createSplit(); } Destroy(this.gameObject); } // private void OnCollisionEnter2D(Collision2D collision) // { // if (collision.gameObject.tag == "Bullet") // { // if ((this.size * 0.05f) >= this.Minsize) // { // createSplit(); // createSplit(); // } // Destroy(this.gameObject); // } // } private void createSplit() { Vector2 position = this.transform.position; position += Random.insideUnitCircle * 0.05f; Asteroid half = Instantiate(this, transform.position, this.transform.rotation); half.size = this.size * 0.05f; half.SetTrajectory(Random.insideUnitCircle.normalized * this.AsteroidSpeed); } } <file_sep>/PewPew/Assets/Scripts/SpaceshipScript.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class SpaceshipScript : MonoBehaviour { //public float speed = 20; public float maxSpeed=3.8f; public float rotSpeed=180f; private Rigidbody2D rb2d; void Start() { rb2d = GetComponent<Rigidbody2D> (); } //void FixedUpdate() //{ //float moveHorizontal = Input.GetAxis("Horizontal"); //float moveVertical = Input.GetAxis("Vertical"); //Vector3 movement = new Vector3(moveHorizontal, moveVertical); //rb2d.AddForce(movement*speed); //} void FixedUpdate() { Quaternion rot = transform.rotation; float z = rot.eulerAngles.z; z -= Input.GetAxis("Horizontal") * rotSpeed * Time.deltaTime; rot = Quaternion.Euler( 0, 0, z); transform.rotation = rot; Vector3 pos = transform.position; Vector3 velocity = new Vector3(0, Input.GetAxis("Vertical") * maxSpeed * Time.deltaTime, 0); pos += rot * velocity; transform.position = pos; } } <file_sep>/PewPew/Assets/Scripts/BulletScript.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class BulletScript : MonoBehaviour { public float speed =500f; public int damage = 25; private Rigidbody2D rb; public GameObject impactEffect; public GameObject collision; private void OnCollisionEnter2D(Collision2D collision) { Destroy(this.gameObject); } private void Awake() { rb = GetComponent<Rigidbody2D>(); } public void project(Vector2 direction) { rb.AddForce(direction * this.speed); } // Start is called before the first frame update void Start() { rb.velocity = transform.up * speed; } // private void OnTriggerEnter2D(Collider2D collision) // { // Asteroid enemy = collision.GetComponent<Asteroid>(); // Destroy(gameObject); // } void OnBecameInvisible() { enabled = false; Destroy(gameObject); } } <file_sep>/README.md # 2d-Game unity 2d game
00ae574698f4e41411ecd5206fd70e04f8258de2
[ "C#", "Markdown" ]
4
C#
AntonTech420/2d-Game
78ba58a55450c1faa08cda9b93fd8a5e02e7f9d9
4c92b3baf1143169f21707a1a2bca51b33cce6b3
refs/heads/master
<repo_name>afifafian/Phase-2-live-code<file_sep>/server/controllers/UserController.js "use strict" const {User} = require('../models') const jwt = require('jsonwebtoken') const bcrypt = require('bcrypt') class UserController { static register (req, res) { const newUser = { email: req.body.email, password: req.body.password } User.create(newUser) .then(function(data){ return res.status(201).json(data) }) .catch(function(err){ return res.status(500).json({message: err}) }) } static login (req, res) { User.findOne({ where: {email: req.body.email} }) .then(function(data){ if (!data) { res.status(404).json({message: `Data Not Found!`}) } else { if (bcrypt.compareSync(req.body.password, data.password)) { const token = jwt.sign( {id: data.id, email: data.email}, 'jwtSECRET' ) return res.status(200).json({access_token: token}) } else { return res.status(400).json({message: `Incorrect Email or Password!`}) } } }) .catch(function(err){ console.log(err) return res.status(500).json({message: err}) }) } } module.exports = UserController<file_sep>/server/routes/index.js const routes = require('express').Router() const UserController = require('../controllers/UserController') const passRoutes = require('../routes/passRouter') routes.post('/register', UserController.register) routes.post('/login', UserController.login) routes.use('/passwords', passRoutes) module.exports = routes<file_sep>/client/main.js $(document).ready(function(){ if (localStorage.token) { $("#buttonAdd").show() $("#buttonLogout").show() $("#login-form").hide() fetchPassword() } else { $("#buttonAdd").hide() $("#buttonLogout").hide() $("#login-form").show() $("#add-form").hide() $("#no-list").hide() $("#password-list").hide() } }); function afterLogin(event) { event.preventDefault() let email = $("#emailLogin").val() let password = $("#passwordLogin").val() $.ajax({ method: 'POST', url: 'http://localhost:3001/login', data: {email: email, password: password} }) .done(function(data){ localStorage.token = data.access_token fetchPassword() $("#buttonAdd").show() $("#buttonLogout").show() $("#login-form").hide() $("#password-list").show() }) .fail(function(err){ console.log(err.responseJSON) }) .always(function(_){ email = $("#emailLogin").val('') password = $("#passwordLogin").val('') }) } function fetchPassword() { $.ajax({ method: 'GET', url: 'http://localhost:3001/passwords', headers: {access_token:localStorage.token} }) .done(function(data){ $('#password-list').empty() for (let i = 0; i < data.length; i++) { $('#password-list').append(` <div class="col md-4"> <div class="card mb-4 box-shadow"> <div class="card-body"> <h5 class="card-title">${data[i].name}</h5> <p class="card-text">${data[i].url}</p> <p class="card-text">${data[i].username}</p> <p class="card-text">${data[i].password}</p> <div class="d-flex justify-content-between align-items-center"> <div class="btn-group mx-auto"> <button type="button" class="btn btn-sm btn-outline-danger" onclick="afterDelete(${data[i].id}, event)">Delete Password</button> </div> </div> </div> </div> </div> `) } if (data.length === 0) { $("#no-list").show() } else { $("#no-list").hide() } }) .fail(function(err){ console.log(err) }) .always(function(_){ $("#add-form").hide() }) } function addForm(){ $("#add-form").show() $("#password-list").hide() } function afterAdd(event) { event.preventDefault() $.ajax({ method: 'POST', url: 'http://localhost:3001/passwords', data: { name: $("#nameAdd").val(), url: $("#urlAdd").val(), username: $("#usernameAdd").val(), password:<PASSWORD>").val() }, headers: {access_token:localStorage.token} }) .done(function(data){ console.log(data) $("#add-form").hide() $("#password-list").show() fetchPassword() }) .fail(function(err){ console.log(err) }) .always(function(_){ $("#nameAdd").val(''), $("#urlAdd").val(''), $("#usernameAdd").val(''), $("#passAdd").val('') }) } function afterDelete(id, event) { event.preventDefault() $.ajax({ method: 'DELETE', url: `http://localhost:3001/passwords/${id}`, headers: {access_token: localStorage.token} }) .done(function(data){ console.log(data) }) .fail(function(err){ console.log(err) }) .always(function(_){ fetchPassword() console.log(`ALWAYS KETIKA DELETE`) }) } function afterLogout() { let email = $("#emailLogin").val() let password = $("#passwordLogin").val() localStorage.clear() $("#login-form").show() $("#password-list").hide() $("#buttonAdd").hide() $("#buttonLogout").hide() email = $("#emailLogin").val('') password = $("#passwordLogin").val('') }<file_sep>/server/routes/passRouter.js const routes = require('express').Router() const PasswordController = require('../controllers/PasswordController') const {authentication, authorization} = require('../middlewares/auth') routes.get('/', authentication,PasswordController.showPassword) routes.post('/', authentication, PasswordController.addPassword) routes.delete('/:id', authentication, authorization, PasswordController.deletePassword) module.exports = routes
bbd03856d6868cdc5845cabf059c10541f070bb8
[ "JavaScript" ]
4
JavaScript
afifafian/Phase-2-live-code
6c32f1c7e50af67289f69c0d94f60c2266ba87ef
6f874ebfbe6e7993fefd524382d581790125301e
refs/heads/master
<repo_name>demis-group/rucaptcha-client<file_sep>/src/Exception/RucaptchaException.php <?php /** * @author <NAME> <<EMAIL>> */ namespace Rucaptcha\Exception; use Exception; class RucaptchaException extends Exception { }<file_sep>/src/Extra.php <?php /** * @author <NAME> <<EMAIL>> */ namespace Rucaptcha; class Extra { const PHRASE = 'phrase'; const REGSENSE = 'regsense'; const QUESTION = 'question'; const NUMERIC = 'numeric'; const CALC = 'calc'; const MIN_LEN = 'min_len '; const MAX_LEN = 'max_len '; const IS_RUSSIAN = 'is_russian'; const SOFT_ID = 'soft_id'; const LANGUAGE = 'language'; const HEADER_ACAO = 'header_acao '; const TEXTINSTRUCTIONS = 'textinstructions'; const TEXTCAPTCHA = 'textcaptcha'; const CONTENT_TYPE = 'content_type'; }<file_sep>/README.md rucaptcha-client ================ PHP-клиент [rucaptcha.com](https://rucaptcha.com/) на базе [GuzzleHttp](https://github.com/guzzle/guzzle). [![Build Status](https://travis-ci.org/gladyshev/rucaptcha-client.svg?branch=master)](https://travis-ci.org/gladyshev/rucaptcha-client) [![Code Coverage](https://scrutinizer-ci.com/g/gladyshev/rucaptcha-client/badges/coverage.png?b=master)](https://scrutinizer-ci.com/g/gladyshev/rucaptcha-client/?branch=master) [![Scrutinizer Code Quality](https://scrutinizer-ci.com/g/gladyshev/rucaptcha-client/badges/quality-score.png?b=master)](https://scrutinizer-ci.com/g/gladyshev/rucaptcha-client/?branch=master) ### Примеры ### ```php /* Simple */ $rucaptcha = new Rucaptcha\Client('YOUR_API_KEY'); $captchaText = $rucaptcha->recognizeFile('captcha.png'); print_r($captchaText); ``` ```php /* Async example */ $rucaptcha = new Rucaptcha\Client('YOUR_API_KEY', [ 'verbose' => true ]); $taskIds = []; $taskIds[] = $rucaptcha->sendCaptcha(file_get_contents('captcha1.png')); $taskIds[] = $rucaptcha->sendCaptcha(file_get_contents('captcha2.jpg')); $taskIds[] = $rucaptcha->sendCaptcha(file_get_contents('captcha3.gif'), [ Rucaptcha\Extra::NUMERIC => 1 ]); $results = []; while (count($taskIds) > 0) { // Wait 5 sec sleep(5); // Try get results foreach ($taskIds as $i=>$taskId) { $results[$taskId] = $this->getCaptchaResult($taskId); // false == is not ready, on error we've got an exception if ($results[$taskId] === false) { continue; } else { unset($taskIds[$i]); } } } print_r($results); ``` ### Установка ### ```php "require": { ... "gladyshev/rucaptcha-client": "1.0.*" ... } ``` ### Методы `Rucaptcha\Client` ### ```php use Rucaptcha\Client; /* Constructor */ void Client::__construct($apiKey, array $options = []); /* Configuration */ void Client::setOptions(array $options); void Client::setHttpClient(GuzzleHttp\ClientInterface $client); void Client::setLogger(Psr\Log\LoggerInterface $logger); /* Solving captcha */ string Client::recognize(string $content, array $extra = []); string Client::recognizeFile(string $path, array $extra = []); string Client::sendCaptcha(string $content, array $extra = []); string Client::getCaptchaResult(string $captchaId); /* Other */ string Client::getLastCaptchaId(); string Client::getBalance(); bool Client::badCaptcha(string $captchaId); array Client::getLoad(array $paramsList = []); ``` ### Опции клиента ### Параметр | Тип | По умолчанию | Возможные значения ---| --- | --- | --- `verbose` | bool | false | Включает/отключает логирование в стандартный вывод `apiKey`| string | '' | Ключ API с которым вызывается сервис `rTimeout`| integer | 5 | Период между опросами серевера при получении результата распознавания `mTimeout` | integer | 120 | Таймаут ожидания ответа при получении результата распознавания `serverBaseUri`| string | 'http://rucaptcha.com' | Базовый URI сервиса ### Параметры распознавания капчи `$extra` ### Параметр | Тип | По умолчанию | Возможные значения ---| --- | --- | --- `phrase` | integer | 0 | 0 = одно слово <br/> 1 = капча имеет два слова `regsense`| integer | 0 | 0 = регистр ответа не имеет значения <br> 1 = регистр ответа имеет значение `question`| integer | 0 | 0 = параметр не задействован <br> 1 = на изображении задан вопрос, работник должен написать ответ `numeric` | integer | 0 | 0 = параметр не задействован <br> 1 = капча состоит только из цифр<br> 2 = Капча состоит только из букв<br> 3 = Капча состоит либо только из цифр, либо только из букв. `calc`| integer | 0 | 0 = параметр не задействован <br> 1 = работнику нужно совершить математическое действие с капчи `min_len` | 0..20 | 0 | 0 = параметр не задействован <br> 1..20 = минимальное количество знаков в ответе `max_len` | 1..20 | 0 | 0 = параметр не задействован<br> 1..20 = максимальное количество знаков в ответе `is_russian` | integer | 0 | параметр больше не используется, т.к. он означал "слать данную капчу русским исполнителям", а в системе находятся только русскоязычные исполнители. Смотрите новый параметр language, однозначно обозначающий язык капчи `soft_id` | string | | ID разработчика приложения. Разработчику приложения отчисляется 10% от всех капч, пришедших из его приложения. `language` | integer | 0 | 0 = параметр не задействован <br> 1 = на капче только кириллические буквы <br>2 = на капче только латинские буквы `header_acao` | integer | 0 | 0 = значение по умолчанию <br> 1 = in.php передаст Access-Control-Allow-Origin: * параметр в заголовке ответа. (Необходимо для кросс-доменных AJAX запросов в браузерных приложениях. Работает также для res.php.) `textinstructions` | string | |Текст, который будет показан работнику. Может содержать в себе инструкции по разгадке капчи. Ограничение - 140 символов. Текст необходимо слать в кодировке UTF-8. `textcaptcha` | string | | Текстовая капча. Картинка при этом не загружается, работник получает только текст и вводит ответ на этот текст. Ограничение - 140 символов. Текст необходимо слать в кодировке UTF-8. <file_sep>/src/Client.php <?php /** * @author <NAME> <<EMAIL>> */ namespace Rucaptcha; use Rucaptcha\Exception\RuntimeException; class Client extends GenericClient { const STATUS_OK_REPORT_RECORDED = 'OK_REPORT_RECORDED'; /** * @var string */ protected $serverBaseUri = 'http://rucaptcha.com'; /** * Your application ID in Rucaptcha catalog. * That value `1013` is ID of this library, set it in false if you want to turn off sending any id. * @see https://rucaptcha.com/software/view/php-api-client * @var string */ protected $softId = '1013'; /** * @inheritdoc */ public function sendCaptcha($content, array $extra = []) { if ($this->softId && !isset($extra[Extra::SOFT_ID])) { $extra[Extra::SOFT_ID] = $this->softId; } return parent::sendCaptcha($content, $extra); } /** * @return string */ public function getBalance() { $response = $this->getHttpClient()->request('GET', "/res.php?key={$this->apiKey}&action=getbalance"); return $response->getBody()->__toString(); } /** * @param $captchaId * @return bool * @throws RuntimeException */ public function badCaptcha($captchaId) { $response = $this->getHttpClient()->request('GET', "/res.php?action=reportbad&id={$captchaId}"); if ($response->getBody()->__toString() === self::STATUS_OK_REPORT_RECORDED) { return true; } throw new RuntimeException('Report sending trouble: ' . $response->getBody() . '.'); } /** * @param array $paramsList * @return array */ public function getLoad(array $paramsList = ['waiting', 'load', 'minbid', 'averageRecognitionTime']) { $response = $this->getHttpClient()->request('GET', "/load.php"); $responseText = $response->getBody()->__toString(); $statusData = []; foreach ($paramsList as $item) { // Fast parse tags $value = substr($responseText, strpos($responseText, '<' . $item . '>') + mb_strlen('<' . $item . '>'), strpos($responseText, '</' . $item . '>') - strpos($responseText, '<' . $item . '>') - mb_strlen('<' . $item . '>') ); if ($value !== false) { $statusData[$item] = $value; } } return $statusData; } }
93f58edf0d3ff6eac96cd8b90d506d8c818b3442
[ "Markdown", "PHP" ]
4
Markdown
demis-group/rucaptcha-client
0a64d2b64e0c3ac84fcba8500d280b5088926d2b
bd42406f1e3fb347860d21385bf7d60f7a537d3e
refs/heads/master
<repo_name>Aviala7/Ruby-exercices<file_sep>/Ruby/exo_16.rb puts " Ton age ?" user_age = gets.chomp.to_i user_year= 2020 - user_age i = user_age y = user_year x = 0 while y <= 2020 do i -=1 x +=1 y +=1 puts "Il y a" + i.to_s + "tu avais" + x.to_s + "ans" if i == 0 end end <file_sep>/Ruby/exo_19.rb ary = [] good_emails = [] 50.times do |i| if (i < 9 and i%2!=0) ary.append("<EMAIL>#{i + <EMAIL>") good_emails.append("<EMAIL>") elsif (i > 9 and i%2!=0) ary.append("<EMAIL> + <EMAIL>") good_emails.append("<EMAIL> + <EMAIL>") end end puts good_emails <file_sep>/Ruby/exo_13.rb puts "Choisis une année ?" user_year=gets.chomp.to_i while user_year<2021 puts user_year user_year += 1 end <file_sep>/Ruby/exo_12.rb puts "Dis un nombre ?" user_number=gets.chomp.to_i user_number.times do |index| puts index +1 if index==user_number end end <file_sep>/Ruby/exo_14.rb puts "Dis un nombre ?" user_number=gets.chomp.to_i user_number.times do user_number-=1 puts user_number end <file_sep>/Ruby/exo_05.rb puts "On va compter le nombre d'heures de travail à THP" puts "Travail : #{10 * 5 * 11}" #10h fois 5 jours semaines fois 11 puts " En minutes ça fait : #{10 * 5 * 11 * 60}" #converti en minutes puts " Et en secondes ?" puts 10 * 5 * 11 * 60 * 60 #converti en secondes en multipliant par 60 puts "Est-ce que c'est vrai que 3 + 2 < 5 - 7 ?" puts 3 + 5 < 5 - 7 #demande vrai ou faux puts " Ca fait combien 3 + 2 ? #{3 + 2}"#calcule le résultat puts " Ca fait combien 5 - 7 ? #{5 - 7}"#calcule le résultat puts "Ok c'est faux alors !" puts " C'est drôle ça, faisons-en plus :" puts "Est-ce que 5 est plus grand que -2 ? #{5 > -2}" puts "Est-ce que 5 est supérieur ou égal à -2 ? #{5 >= -2}" puts "Est-ce que 5 est inférieur ou égal à -2 ? #{5 <= -2}" #utilise true ou false <file_sep>/Ruby/exo_09.rb puts "What's your first name ?" user_firstname = gets.chomp puts "And your last name ?" user_name = gets.chomp puts "Hello " + user_firstname + user_name <file_sep>/Ruby/exo_21.rb puts "Salut, bienvenue dans ma super pyramide ! Combien d'étages veux-tu ?" user = gets.chomp.to_i n = 1 while n <= user puts ("#" * n) n += 1 end <file_sep>/Ruby/exo_15.rb puts "Année de naissance?" user_year=gets.chomp.to_i i = user_year while i <= 2020 do puts i i +=1 puts "Cette année là tu avais: #{ (i-1) - user_year}" if i == 2020 end end <file_sep>/Ruby/exo_11.rb puts "Dis un nombre ?" user_number=gets.chomp.to_i user_number.times do puts "Salut,ça farte ?" end <file_sep>/Ruby/exo_07.rb puts " Bonjour, c'est quoi ton blase ?" user_name = gets.chomp puts user_name #gets.chomp crée un input <file_sep>/Ruby/exo_07c.rb user_name = gets.chomp puts user_name #crée juste un input <file_sep>/Ruby/exo_17.rb puts " Ton age ?" user_age = gets.chomp.to_i user_year= 2020 - user_age i = user_age y = user_year x = 0 n = i==y while y <= 2020 do puts "Il y a" + i.to_s + "tu avais" + x.to_s + "ans" i -=1 x +=1 y +=1 if i == 0 end if i == x puts "il y a #{i = x} ans, tu avais la moitié de l'age que tu as aujourd'hui" end end <file_sep>/Ruby/exo_08.rb puts "What's your name ?" user_name = gets.chomp puts "Hello " + user_name <file_sep>/Ruby/exo_10.rb puts "En quelle année es-tu né ?" year = gets.chomp.to_i puts "En 2017 tu avais #{2017 - year} ans" <file_sep>/Ruby/exo_18.rb email = [ ] 50.times do |i| if i < 9 email.append("<EMAIL>") else email.append("<EMAIL>") end end puts email
5a138054038e07bc79d10b315127e89cb49d7908
[ "Ruby" ]
16
Ruby
Aviala7/Ruby-exercices
e4645c00ceab318b660031926a5a720e72cbb1c3
5630c2d6eb7b3c6369af368cbec68d0722e30473
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Numerics; namespace KthFactorial { public class Program { // Kth Factorial //In mathematics, the factorial of a non-negative integer n, denoted by n!, is the product of all positive integers less than or equal to n. For example: //5! = 5 * 4 * 3 * 2 * 1 = 120 //To make things more interesting, we want you to find the kth factorial of any number n. //kth_factorial = (n!) * (n!) * (n!) ... k times //The interface of the function is kth_factorial(k, n). Think about the constraints of the types of input k and n parameters and the output of the whole function. // SOLUTION: // By definition, the factorial of a non-negative integer n, denoted by n!, is the product of all positive integers less than or equal to n. So in our case, n should be of a non-negative type; I've chosen byte. // We're having a positive number of factorials to multiply, so k should also be a positive integer; again, we should be fine with type byte. // To be on the safe side, the result will be of a BigInteger type, thus allowing us not to worry about maximum value of the Factorial of n. // TODO: to work on abstracting repetitive code public static BigInteger Factorial(byte n) { BigInteger result = 1; for (int i = 1; i <= n; i++) { result *= i; } return result; } public static BigInteger kth_factorial(byte k, byte n) { BigInteger result = 1; for (int i = 1; i <= k; i++) { result *= Factorial(n); } return result; } static void Main(string[] args) { //Console.WriteLine(Factorial(5)); //Console.WriteLine(kth_factorial(0, 0)); //Console.WriteLine(kth_factorial(0, 1)); Console.WriteLine(kth_factorial(1, 6)); //Console.WriteLine(kth_factorial(255, 255)); if (Factorial(5) == 120) { Console.WriteLine("true"); } else Console.WriteLine("false"); if (kth_factorial(3, 5) == 1728000) { Console.WriteLine("true"); } else Console.WriteLine("false"); } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Numerics; namespace Quaternions { class Quaternion { //Quaternion (optional) //Quaternions are cool! They find uses in both theoretical and applied mathematics, in particular for calculations involving three-dimensional rotations such as in three-dimensional computer graphics and computer vision. //Choose an OOP language of your liking and design a Quaternion class implementing all of the properties by its definition. //Hint: you can name the component 1 as e. //The interface is up to you. How should you create a Quaternion? Should you override operators for Quaternion operations, if your language of choice supports it? Should you have any static properties? Why? //Please, answer all those question in a comment above the class definition. //Optional task //You can apply without solving this problem. But if you manage to solve it, this will help you in the interview process :) // QUESTION: How should you create a Quaternion? // ANSWER: A quaternion can be represented as follows: // H = a.1 + b.i + c.j + d.k, where a, b, c, d are explicit real numbers // The "a.1" part of the quaternion is its scalar part, and the "b.i + c.j + d.k" part is its vector part. // Programmatically a quaternion could be defined by two parameters - a scalar parameter and a vector parameter, which could be an object of a Vector3 class. Here, I choose not to use a Vector3 class, but to let the user define the vector part components b, c, and d. // Quaternion (float a, float b, float c, float d) // TODO: a better alternative might be using a Complex structure // QUESTION: to override operators for operations? // ANSWER: Yes, because we're dealing with complex numbers, which have a real and an imaginary values. So, for example, addition of complex numbers will require first the real components to be added and then the imaginary values to be added. Finally the result will be another complex number, with its special representation, for example: (a + bi) + (c + di) = (a + c) + (b + d)i. So, we won't be able to get such a result with the usual + operator. // QUESTION: Should you have any static properties? Why? // ANSWER: The i, j, k imaginary units could be static. // To implement: // Constructor - done // Conjugate - done // Sum - done // Product - done // Norm - done // Division // Matrix representations // Fields private float _a; private float _b; private float _c; private float _d; // Properties public float A { get { return _a; } set { _a = value; } } public float B { get { return _b; } set { _b = value; } } public float C { get { return _c; } set { _c = value; } } public float D { get { return _d; } set { _d = value; } } // Constructor public Quaternion() { } public Quaternion(float a, float b, float c, float d) { this._a = a; this._b = b; this._c = c; this._d = d; } // Overriden methods public override string ToString() { return String.Format("{0} + {1}i + {2}j + {3}k", this.A, this.B, this.C, this.D); } public static Quaternion operator +(Quaternion p, Quaternion q) { Quaternion result = new Quaternion(); result.A = p.A + q.A; result.B = p.B + q.B; result.C = p.C + q.C; result.D = p.D + q.D; return result; } public static Quaternion operator *(Quaternion p, Quaternion q) { Quaternion result = new Quaternion(); result.A = p.A * q.A - p.B * q.B - p.C * q.C - p.D * q.D; result.B = p.A * q.B + p.B * q.A + p.C * q.D - p.D * q.C; result.C = p.A * q.C - p.B * q.D + p.C * q.A + p.D * q.B; result.D = p.A * q.D + p.B * q.C - p.C * q.B + p.D * q.A; return result; } // Methods public static string Conjugate(Quaternion q) { return String.Format("{0} - {1}i - {2}j - {3}k", q.A, q.B, q.C, q.D); } public static float Norm(Quaternion q) { float n = (float)Math.Sqrt(q.A * q.A + q.B * q.B + q.C * q.C + q.D * q.D); return n; } static void Main(string[] args) { Quaternion h = new Quaternion(2.3f, 4.5f, 5.3f, 4.3f); Console.WriteLine(h); Quaternion q = new Quaternion(1.5f, 6.2f, 6.4f, 4.3f); Console.WriteLine("\nSum of quaternions: \n{0} \n{1} \nequals \n{2}", h, q, h + q); Console.WriteLine("\nProduct of quaternions: \n{0} \n{1} \nequals \n{2}", h, q, h * q); Console.WriteLine("\nConjugate of quaternion: \n{0} is \n{1}", h, Conjugate(h)); Console.WriteLine("\nNorm of quaternion: \n{0} is \n{1}", h, Norm(h)); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Numerics; namespace Taylor { public class Calculate { // Taylor Series //Because we know you love your calculus classes, we present you the final of our Y U GIVE US SOME MUCH MATH series with the, ahem, Taylor series. //In mathematics, a Taylor series is a representation of a function as an infinite sum of terms that are calculated from the values of the function's derivatives at a single point. It is common practice to approximate a function by using a finite number of terms of its Taylor series. //In particular, you can easily calculate common trigonometric functions. And that's want we want you to do. Calculate Sine and Cosine using their respective Taylor series. You can find them here. //The interface for the Sine and Cosine functions should be sine(x, precision) and cosine(x, precision), where precision is the upper limit of n. The higher the precision is, the better the approximation. public static long Factorial(int n) { long result = 1; for (int i = 1; i <= n; i++) { result *= i; } return result; } // calculating input degrees to radians public static double ToRadians(int degrees) { double radians = Math.PI * degrees / 180; return radians; } public static double Sine(int x, int precision) { double result = 0; for (int i = 0; i <= precision; i++) { double a = Math.Pow(-1, i); double b = Math.Pow(ToRadians(x), 2 * i + 1); double c = Factorial(2 * i + 1); result += a * b / c; } return result; } public static double Cosine(int x, int precision) { double result = 0; for (int i = 0; i <= precision; i++) { double a = Math.Pow(-1, i); double b = Math.Pow(ToRadians(x), 2 * i); double c = Factorial(2 * i); result += (a * b) / c; } return result; } static void Main(string[] args) { // some tests Console.WriteLine("Sine of 60 degrees: {0:0.00000}", Sine(60, 3)); //Console.WriteLine("Sine of 60 degrees: {0:0.00000}", Sine(60, 15)); //Console.WriteLine("Cosine 30 degrees: {0:0.00000}", Cosine(30, 2)); //Console.WriteLine("Sine 90 degrees: {0:0.00000}", Sine(90, 10)); //Console.WriteLine("Cosine of 90 degrees: {0:0.00000}", Cosine(90, 3)); //Console.WriteLine("Cosine of 0 degrees: {0:0.00000}", Cosine(0, 3)); //Console.WriteLine("Sine of 0 degrees: {0:0.00000}", Sine(0, 3)); } } }
bb9f4d3b0d111539a58c2acd94269b4e860aa4db
[ "C#" ]
3
C#
svetlik/core-ruby-solutions
1787ea79286143e5f4124c48dcb286335c676a88
515ca72291e9fcd9780270fd9a67025087417ecd
refs/heads/master
<file_sep>#GitTest # Lizhuo Push # Lizhuo Push2 # Lizhuo Push3 # Lizhuo Push4 # Lizhuo Push5 #ryeagler edit
b99c6a845772404019ad73c8344f4b1166ab3cdd
[ "Markdown" ]
1
Markdown
Ryeagler/GitTest
aba6a79921c95a9307555bb60e631b77277ba213
a5c616b637c67c80a2f47af1e0f95656ac6a2f3d
refs/heads/master
<file_sep>/* * DO NOT EDIT THIS FILE - it is generated by Glade. */ GtkWidget* create_fenetre_ajout (void); GtkWidget* create_fenetre_afficher (void); GtkWidget* create_fenetre_modifier (void); GtkWidget* create_window1 (void); <file_sep>#include<stdio.h> #include<string.h> #include "equipement.h" enum { TYPE, MARQUE, PUISSANCE, ANNEE, MATRICULE, COLUMNS, }; //ajouter equipement int ajouter_equipement(equipement e) { FILE *f; f=fopen("equipement.txt","a+"); if(f!=NULL) { fprintf(f,"%s %s %s %s %s \n",e.type,e.marque,e.puissance,e.annee,e.matricule); fclose(f); return 0; } } //afficher equipement void afficher_equipement(GtkWidget *liste) { GtkCellRenderer *renderer; GtkTreeViewColumn *column; GtkTreeIter iter; GtkListStore *store; char type[30]; char marque[30]; char puissance[30]; char annee[30]; char matricule[30]; store=NULL; FILE *f; store=gtk_tree_view_get_model(liste); if(store==NULL) { renderer =gtk_cell_renderer_text_new(); column = gtk_tree_view_column_new_with_attributes("type",renderer, "text",TYPE,NULL); gtk_tree_view_append_column (GTK_TREE_VIEW (liste),column); renderer = gtk_cell_renderer_text_new(); column = gtk_tree_view_column_new_with_attributes(" marque",renderer, "text",MARQUE,NULL); gtk_tree_view_append_column (GTK_TREE_VIEW (liste),column); renderer = gtk_cell_renderer_text_new(); column = gtk_tree_view_column_new_with_attributes("puissance",renderer, "text",PUISSANCE,NULL); gtk_tree_view_append_column (GTK_TREE_VIEW (liste),column); renderer = gtk_cell_renderer_text_new(); column = gtk_tree_view_column_new_with_attributes("annee",renderer, "text",ANNEE,NULL); gtk_tree_view_append_column (GTK_TREE_VIEW (liste),column); renderer = gtk_cell_renderer_text_new(); column = gtk_tree_view_column_new_with_attributes("matricule",renderer,"text",MATRICULE,NULL); gtk_tree_view_append_column (GTK_TREE_VIEW (liste),column); } store=gtk_list_store_new(5,G_TYPE_STRING,G_TYPE_STRING,G_TYPE_STRING,G_TYPE_STRING,G_TYPE_STRING); f = fopen("equipement.txt","r"); if(f==NULL) { return; } else { f=fopen("equipement.txt","a+"); while(fscanf(f,"%s %s %s %s %s \n",type,marque,puissance,annee,matricule )!=EOF) { gtk_list_store_append (store,&iter); gtk_list_store_set(store,&iter,TYPE,type,MARQUE,marque,PUISSANCE,puissance,ANNEE,annee,MATRICULE,matricule,-1); } fclose(f);} gtk_tree_view_set_model(GTK_TREE_VIEW(liste), GTK_TREE_MODEL(store)); g_object_unref(store); } // supprimer equipement void supprimer_equipement(char matricule[30]) { FILE *f,*f1; f=fopen("equipement.txt","r"); f1=fopen("equipement_tmp.txt","w"); if ((f!=NULL) && (f1!=NULL)) { while(fscanf(f,"%s %s %s %s %s\n",e.type,e.marque,e.puissance,e.annee,e.matricule )!=EOF) { if(strcmp(matricule,e.matricule)!=0) { fprintf(f1,"%s %s %s %s %s\n",e.type,e.marque,e.puissance,e.annee,e.matricule); } } fclose(f) ; fclose(f1); remove("equipement.txt"); rename("equipement_tmp.txt","equipement.txt"); } } //modifier equipement void modifier_equipement (equipement e) { { FILE *f; FILE *f2; f=fopen("equipement.txt","r"); f2=fopen("equipement.txt.tmp","w"); if ((f!=NULL) && (f2!=NULL)) { while (fscanf(f,"%s %s %s %s %s\n",m.type,m.marque,m.puissance,m.annee,m.matricule)!=EOF) { if (strcmp(e.matricule,m.matricule)==0){ fprintf(f2," %s %s %s %s %s\n",e.type,e.marque,e.puissance,e.annee,e.matricule ); } else { fprintf(f2,"%s %s %s %s %s\n",m.type,m.marque,m.puissance,m.annee,m.matricule); } }} fclose(f2); fclose(f); remove("equipement.txt"); rename("equipement.txt.tmp","equipement.txt"); } } <file_sep>#include <gtk/gtk.h> typedef struct { char type[30]; char marque[30]; char puissance[30]; char annee[30]; char matricule[30]; }equipement; equipement e,m; int ajouter_equipement(equipement e); void supprimer_equipement(char matricule[30]); void modifier_equipement(equipement e); void afficher_equipement(GtkWidget *treeview);
171204a89acd3a0dba1ecb7b1b1f026ef965bdbe
[ "C" ]
3
C
saberherbegue/SmartFarm
4292f6f517421e4fc1b31decfd2012830e21ac44
947dbe3e98bf17805bac371f3d2e2491e1259f6f
refs/heads/master
<repo_name>kumavis/meltdown-spectre-javascript<file_sep>/README.md # Meltdown & Spectre JavaScript checker This is a meltdown & spectre checker found online: https://xlab.tencent.com/special/spectre/spectre_check.html https://kumavis.github.io/meltdown-spectre-javascript/meltdown-checker.html
1039393815d91800f2f943e6dadd705e1dd94911
[ "Markdown" ]
1
Markdown
kumavis/meltdown-spectre-javascript
84b40ff57a384387de68d07c56e4891b6b4184dd
8004f47a912d531de0f790564243bd1f3e354073
refs/heads/master
<repo_name>VanceLongwill/gomonsters<file_sep>/monster.go package main import ( "errors" "strings" ) const ( monsterNameLength = 8 // Assumption: 8 characters is long enough to ensure uniqueness per game ) var ( // ErrMonsterNotFound is returned when attempting to access a monster which doesn't exist in the collection ErrMonsterNotFound = errors.New("Monster not found") // ErrMonsterDuplicateID is returned when attempting to add a monster with an id already present in the collection ErrMonsterDuplicateID = errors.New("Monster with this id already exists") ) // MonsterID is the identifier for monsters type MonsterID uint // Monster represents a monster in the game type Monster struct { ID MonsterID name string location CityName } // SetLocation changes the monster's location func (m *Monster) SetLocation(city CityName) { m.location = city } // Location returns the current location of the monster func (m *Monster) Location() CityName { return m.location } // Name return the name of the monster func (m *Monster) Name() string { return m.name } // NewMonster creates a monster with a randomly generated name func NewMonster(id uint) *Monster { return &Monster{ ID: MonsterID(id), name: strings.Title(GenerateIdentifier(monsterNameLength)), } } // MonsterCollection is a store of monsters type MonsterCollection struct { monsters map[MonsterID]*Monster } // Add adds a monster to the store if it is not already present func (mc *MonsterCollection) Add(monster *Monster) error { if _, ok := mc.monsters[monster.ID]; ok { return ErrMonsterDuplicateID } mc.monsters[monster.ID] = monster return nil } // Remove removes a monster from the store if it is present func (mc *MonsterCollection) Remove(monster *Monster) error { if _, ok := mc.monsters[monster.ID]; !ok { return ErrMonsterNotFound } delete(mc.monsters, monster.ID) return nil } // Length returns the number of monsters in the store func (mc *MonsterCollection) Length() int { return len(mc.monsters) } // IsEmpty checks whether there are are monsters in the store func (mc *MonsterCollection) IsEmpty() bool { return mc.Length() == 0 } // GetAll returns a map of monsters by id func (mc *MonsterCollection) GetAll() map[MonsterID]*Monster { return mc.monsters } // NewMonsterCollection creates a new monster store func NewMonsterCollection() *MonsterCollection { return &MonsterCollection{ monsters: make(map[MonsterID]*Monster), } } <file_sep>/csv_io_test.go package main import ( "bufio" "bytes" "strings" "testing" ) func TestCSVReaderAndWriter(t *testing.T) { csvData := ` Denalmo north=Agixo-A south=Amolusnisnu east=Elolesme west=Migina Asnu north=Ago-Mo south=Emexisno east=Dinexe west=Amiximine Esmosno north=Emexege south=Anegu east=Axesminilmo west=Dosmolixo ` reader := strings.NewReader(csvData) csvReader := NewCSVReader(reader) testChannel := csvReader.ReadAll() var b bytes.Buffer output := bufio.NewWriter(&b) csvWriter := NewCSVWriter(output) csvWriter.WriteAll(testChannel) if strings.TrimSpace(b.String()) != strings.TrimSpace(csvData) { t.Errorf("Expected input and output csv to match") } } <file_sep>/game_test.go package main import ( "bufio" "bytes" "os" "testing" ) // @TODO: add more tests func TestMoveMonster(t *testing.T) { file, _ := os.Open("assets/world_map_small.txt") defer file.Close() r := NewCSVReader(file) inputChannel := r.ReadAll() world, _ := BuildWorldFromRecords(inputChannel) var b bytes.Buffer output := bufio.NewWriter(&b) game := NewMonsterGame(world, 100, 20, output) game.Start() output.Flush() t.Logf(b.String()) } <file_sep>/worldstate_io.go package main // WorldRecord is generic representation of a city and roads which lead out of it useful in managing data from different formats type WorldRecord struct { City CityName Roads []*Road } // WorldStateReader is an generic interface for reading in the state of a World type WorldStateReader interface { // ReadAll: Reads CSV data and returns a channel which it feeds records // All world map data input sources should be handled using this interface ReadAll() (ch chan *WorldRecord) } // WorldStateWriter is an generic interface for writing the state of a World type WorldStateWriter interface { // WriteAll: Writes CSV data from a channel of records // All world map data output sources should be handled using this interface WriteAll(ch <-chan *WorldRecord) } // BuildWorldFromRecords generates a World graph from records passed through a channel (in order to not be specific to a particular input method/source) func BuildWorldFromRecords(records <-chan *WorldRecord) (*World, error) { world := NewWorld() maxMonstersPerCity := 2 for { if record, ok := <-records; ok { city := NewCity(record.City, maxMonstersPerCity) world.AddCity(city) for _, road := range record.Roads { // Check if destination city exists, if not then create it if world.GetCity(road.Destination) == nil { world.AddCity(NewCity(road.Destination, maxMonstersPerCity)) } world.AddRoad(road) } } else { break } } return world, nil } // GetRemainingWorldRecords finds the remaining cities which are reachable and output's their respective records to the channel func GetRemainingWorldRecords(w *World) (ch chan *WorldRecord) { ch = make(chan *WorldRecord) go func() { defer close(ch) for _, city := range w.GetUndestroyedCities() { record := &WorldRecord{City: city.Name} possibleDestinations := w.GetRoads(city.Name) if len(possibleDestinations) == 0 { continue } var roads []*Road for _, dest := range possibleDestinations { // Assumption: don't include roads leading to destroyed cities if !w.GetCity(dest.Destination).Destroyed { roads = append(roads, dest) } } if len(roads) == 0 { continue } record.Roads = roads ch <- record } }() return } <file_sep>/csv_io.go package main import ( "encoding/csv" "fmt" "io" "strings" ) // CSVReader reads CSV records in the specified format type CSVReader struct{ reader io.Reader } // ReadAll reads CSV records one by one, converts them to a WorldRecord and sends them to an ouput channer func (csvReader *CSVReader) ReadAll() (ch chan *WorldRecord) { ch = make(chan *WorldRecord) go func() { defer close(ch) r := csv.NewReader(csvReader.reader) // Space separates values r.Comma = ' ' // Allow variable number of fields per record r.FieldsPerRecord = -1 for { rec, err := r.Read() if err != nil { if err == io.EOF { break } panic(err) } cityName := CityName(rec[0]) record := &WorldRecord{City: cityName} roads := make([]*Road, len(rec)-1) for i, edge := range rec[1:] { // Directions and their respective destinations are separated by '=' // e.g. North=Edinburgh roadTuple := strings.Split(edge, "=") direction := roadTuple[0] destCityName := CityName(roadTuple[1]) roads[i] = NewRoad(direction, cityName, destCityName) } record.Roads = roads ch <- record } }() return } // NewCSVReader creates a new CSVReader which will read from the reader param func NewCSVReader(r io.Reader) *CSVReader { return &CSVReader{reader: r} } // CSVWriter writes CSV records in the specified format type CSVWriter struct{ writer io.Writer } // WriteAll converts WorldRecord records one by one from the input channel to a row of CSV in the specified format and writes them func (csvWriter *CSVWriter) WriteAll(ch <-chan *WorldRecord) { writer := csv.NewWriter(csvWriter.writer) writer.Comma = ' ' defer writer.Flush() for { if record, ok := <-ch; ok { csvRecord := make([]string, len(record.Roads)+1) // CityName is the first column csvRecord[0] = string(record.City) // Following columns are the roads leading out of the city in the format "north=Edinburgh" for i, road := range record.Roads { csvRecord[i+1] = fmt.Sprintf("%s=%s", road.Direction, road.Destination) } writer.Write(csvRecord) } else { break } } } // NewCSVWriter creates a new CSVWriter which will write WorldRecord records to CSV format func NewCSVWriter(w io.Writer) *CSVWriter { return &CSVWriter{writer: w} } <file_sep>/README.md ## Monster Game #### Rules of the game - See `description.txt` #### Installation (requires golang) - Clone this repo - Build the project `go build` #### Usage - Run the generated executable with no args to see usage options `./monsters` - A small (default) and medium map are provided in `/assets` e.g. `./monsters -n 100 -d assets/world_map_medium.txt` - Results are directed to stdout as default, though they can also be written to a file e.g. `./monsters -n 100 -d assets/world_map_medium.txt -o results_file.txt` #### Testing - Run tests with `go test -v` #### Stack - Golang standard library (no external packages used) #### About my solution - [x] Easily flexible/extendible/configurable/transformable into a larger game/simulator by use of generic interfaces and separation of concerns - [x] Golang best practices - [x] Linted with [Golint](https://github.com/golang/lint) - [x] Formatted with [Gofmt](https://golang.org/cmd/gofmt) #### TODO: - [ ] Expand test coverage - [ ] Improve error handling - [ ] Introduce concurrency - [ ] Create a frontend/visualisation/graphic representation for the world map <file_sep>/city_test.go package main import "testing" func TestAddMonsterToCity(t *testing.T) { monsters := NewMonsterCollection() unlimitedCity := &City{Name: "a", maxMonsters: -1, Monsters: monsters} firstMonster := NewMonster(0) if destroyed, err := unlimitedCity.AddMonster(firstMonster); destroyed || err != nil { t.Errorf("City with unlimited monster capacity should not be destroyed or full") } monsters = NewMonsterCollection() city := &City{Name: "a", maxMonsters: 2, Monsters: monsters} secondMonster := NewMonster(1) if destroyed, err := city.AddMonster(firstMonster); destroyed || err != nil { t.Errorf("City should not be destroyed when monsters are under capacity") } if destroyed, err := city.AddMonster(secondMonster); !destroyed || err != nil { t.Errorf("City should be destroyed when monsters reach capacity") } if monsters.Length() != 2 { t.Errorf("City should add the correct number of monsters") } } func TestDestroyCity(t *testing.T) { city := NewCity("asd", 2) city.Destroy() if !city.Destroyed { t.Errorf("City.Destroy() should destroy city") } if err := city.Destroy(); err != ErrCityDestroyed { t.Errorf("Should throw error when trying to destroy a destroyed city") } } <file_sep>/world.go package main import "fmt" // Road represents an unidirectional edge in the world graph type Road struct { Direction string Source CityName Destination CityName } // NewRoad returns a Road type edge func NewRoad(dir string, src, dest CityName) *Road { return &Road{Direction: dir, Destination: dest, Source: src} } // World is the game's map represented by a directed graph type World struct { Cities map[CityName]*City // Nodes in the graph Roads map[CityName][]*Road // Edges in the graph } // NewWorld Create world map func NewWorld() *World { return &World{ Cities: make(map[CityName]*City), Roads: make(map[CityName][]*Road), } } // AddCity Add city to world map, return true if added (CityName's are unique). func (w *World) AddCity(city *City) bool { if _, ok := w.Cities[city.Name]; ok { return false } w.Cities[city.Name] = city return true } // AddRoad Add an edge to the world map // Note this method does NOT validate that source & destination cities of the road exist func (w *World) AddRoad(road *Road) { // Assumption: roads don't need to be bidirectional because the // - input data takes care of this // - it's not a requirement in this world // i.e. we're using a directed graph w.Roads[road.Source] = append(w.Roads[road.Source], road) } // GetUndestroyedCities returns a list of cities which haven't been destroyed func (w *World) GetUndestroyedCities() []*City { var undestroyed []*City for _, city := range w.Cities { if !city.Destroyed { undestroyed = append(undestroyed, city) } } return undestroyed } // FindPossibleDestinations returns a list of possible destinations from a given city func (w *World) FindPossibleDestinations(cityName CityName) ([]*City, error) { var possibleDestinations []*City for _, road := range w.GetRoads(cityName) { if _, ok := w.Cities[road.Destination]; !ok { return nil, fmt.Errorf("Error finding destination city %s: doesn't exist", road.Destination) } if !w.Cities[road.Destination].Destroyed { possibleDestinations = append(possibleDestinations, w.Cities[road.Destination]) } } return possibleDestinations, nil } // GetCity returns a pointer to a City by its name func (w *World) GetCity(cityName CityName) *City { return w.Cities[cityName] } // GetRoads returns a list of Roads leading out of a given city func (w *World) GetRoads(cityName CityName) []*Road { return w.Roads[cityName] } <file_sep>/main.go package main import ( "flag" "io" "log" "os" ) func main() { defaultMapDataFn := "assets/world_map_small.txt" // Get cli flags initialMonsterCount := flag.Uint("n", 0, "specify the number of monsters you want to start with (n > 0)") mapDataFn := flag.String("d", defaultMapDataFn, "input file path containing data used to build the game map") outputDataFn := flag.String("o", "", "output file path to write the world state after the game, writes to stdout as default") flag.Parse() // Print usage info if no cli arg is provided if *initialMonsterCount == 0 { flag.Usage() return } // Open the map data file file, err := os.Open(*mapDataFn) defer file.Close() if err != nil { log.Fatal(err) } // WorldStateReader interface keeps the process of getting input data generic var r WorldStateReader // currently only CSV is used r = NewCSVReader(file) // Read records in the map data file inputChannel := r.ReadAll() // Build world graph/map based on map data records worldOfX, err := BuildWorldFromRecords(inputChannel) if err != nil { log.Fatal(err) } // Create a new game instance using map, redirecting output to stdout game := NewMonsterGame(worldOfX, 10000, *initialMonsterCount, os.Stdout) // Run the game to completion game.Start() os.Stdout.WriteString("\n") // WorldStateWriter interface keeps the process of getting input data generic var w WorldStateWriter // output writer var target io.Writer if *outputDataFn != "" { // Create the map data output file // Contents will be overwritten! file, err := os.Create(*outputDataFn) defer file.Close() if err != nil { log.Fatal(err) } target = file } else { // writing the results to stdout as default target = os.Stdout } // currently only CSV format is used w = NewCSVWriter(target) // Output what's left of the world outputChannel := GetRemainingWorldRecords(worldOfX) // Store the records somewhere w.WriteAll(outputChannel) } <file_sep>/city.go package main import "errors" // CityName is a string used to identify a city type CityName string // City is an stateful location in the world map type City struct { // Name of the city (assumed to be unique) Name CityName // Monsters currently present in the city Monsters *MonsterCollection // Whether the city has been destroyed or not Destroyed bool // The number of monsters which causes the city to be destroyed and unreachable, -1 for never destroyed maxMonsters int } var ( // ErrCityFull is returned when an operation requiring free space is performed on a city with no free space ErrCityFull = errors.New("City has already reached capacity") // ErrCityDestroyed is return when attempting to destroy a city which has already been destroyed ErrCityDestroyed = errors.New("City is already destroyed") ) // AddMonster adds a monster to the city's holdings and causes the city to be destoyed if it has subsequently reached capacity func (c *City) AddMonster(monster *Monster) (bool, error) { if c.maxMonsters == -1 { c.Monsters.Add(monster) return c.Destroyed, nil } if c.Monsters.Length() > c.maxMonsters-1 { if !c.Destroyed { c.Destroy() } return c.Destroyed, ErrCityFull } c.Monsters.Add(monster) // If the maximum number of monsters has been reached, destroy the city if c.Monsters.Length() == c.maxMonsters { if err := c.Destroy(); err != nil { return c.Destroyed, err } } return c.Destroyed, nil } // RemoveMonster removes a monster from the city's holdings func (c *City) RemoveMonster(monster *Monster) { c.Monsters.Remove(monster) } // Destroy marks the city as destroyed func (c *City) Destroy() error { if c.Destroyed { return ErrCityDestroyed } c.Destroyed = true return nil } // NewCity creates a new city instance func NewCity(cityName CityName, maxMonsters int) *City { return &City{Name: cityName, maxMonsters: maxMonsters, Monsters: NewMonsterCollection()} } <file_sep>/game.go package main import ( "bytes" "fmt" "io" "math/rand" "time" ) // MonsterGame represents the game state type MonsterGame struct { world *World // World map to navigate ActiveMonsters *MonsterCollection // Keep track of monsters which are not dead or trapped in a location done bool // Is the game finished maxIterations int // Maximum number of steps before the game finishes logger io.Writer // Log for output rand *rand.Rand // Random number generator } // Start runs the game until completion func (g *MonsterGame) Start() { for i := 0; i < g.maxIterations; i++ { if g.done { break } // @TODO: introduce concurrency with mutexes on stateful struct fields g.step() } g.done = true } // MoveMonsterRandomly transports a monster from its previous location (if any) to another random location func (g *MonsterGame) MoveMonsterRandomly(monster *Monster) error { var possibleDestinations []*City if monster.Location() != "" { destinations, err := g.world.FindPossibleDestinations(monster.Location()) if err != nil { return err } if len(destinations) == 0 { // Trapped monsters are not active if err := g.ActiveMonsters.Remove(monster); err != nil { return err } return nil } possibleDestinations = destinations } else { // possibleDestinations are all remaining cities if there is no previous location possibleDestinations = g.world.GetUndestroyedCities() if len(possibleDestinations) == 0 { // The game is finished if all cities are destroyed g.done = true return nil } } // Remove the monster from the source city (if one has been set) if monster.Location() != "" { g.world.GetCity(monster.Location()). RemoveMonster(monster) } // Random index with which to choose the destination i := g.rand.Intn(len(possibleDestinations)) // Random destination city destCity := possibleDestinations[i] // Try to add the monster to the destination destCity destroyed, err := destCity.AddMonster(monster) // Check if the destCity unexpectedly ran out of space if err != nil { return err } monster.SetLocation(destCity.Name) if destroyed { count := 0 var msg bytes.Buffer msg.WriteString(fmt.Sprintf("%s has been destroyed by ", destCity.Name)) for _, deadMonster := range destCity.Monsters.GetAll() { // Dead monsters are not active g.ActiveMonsters.Remove(deadMonster) // Pretty print the monsters list // E.g. monster 0, monster 1 and monster 2 etc if count < destCity.Monsters.Length()-1 { msg.WriteString(fmt.Sprintf("monster %s", deadMonster.Name())) if count != destCity.Monsters.Length()-2 { msg.WriteString(", ") } } else { msg.WriteString(fmt.Sprintf(" and monster %s!\n", deadMonster.Name())) } count++ } // Write the message to the game logger g.logger.Write(msg.Bytes()) } return nil } // step: runs one iteration of the game func (g *MonsterGame) step() { // Game is done when no active monsters are left if g.ActiveMonsters.Length() == 0 { g.done = true return } for _, monster := range g.ActiveMonsters.GetAll() { if err := g.MoveMonsterRandomly(monster); err != nil { panic(err) } } } // NewMonsterGame sets up a monster game, adding a number of monsters to the provided world in randomly selected locations func NewMonsterGame(w *World, maxIterations int, initialMonsterCount uint, logger io.Writer) *MonsterGame { seededRand := rand.New( rand.NewSource(time.Now().UnixNano())) game := &MonsterGame{ ActiveMonsters: NewMonsterCollection(), world: w, maxIterations: maxIterations, logger: logger, rand: seededRand, } for monsterID := uint(0); monsterID < initialMonsterCount; monsterID++ { if game.done { break } // Create a monster m := NewMonster(monsterID) // Add it to the active monsters game.ActiveMonsters.Add(m) // Place it on the map at random if err := game.MoveMonsterRandomly(m); err != nil { panic(err) } } return game }
df0476bffcc0a2cd575d60ced5960771da86e661
[ "Markdown", "Go" ]
11
Markdown
VanceLongwill/gomonsters
fe123a343dac5c37c81e372ffc35fe9882f97709
c4c264aa2bf4304986a00025844e5d384fb005bd
refs/heads/master
<repo_name>kaizadp/fticrrr<file_sep>/reports/fticrrr_report.Rmd --- title: "fticrrr report" output: github_document --- ```{r setup, include=FALSE} knitr::opts_chunk$set(echo = TRUE, collapse = TRUE, warning = FALSE, message = FALSE, comment = "#>", fig.path = ("markdown-figs/fticrrr/")) library(drake) ``` --- ## FTICR domains ### compound classes ```{r domains_classes, fig.height=4} readd(gg_vankrevelen_domains)$gg_vk_domains+theme(legend.position = "right") ``` ### NOSC ```{r domains_nosc, fig.asp=1, fig.height=2} readd(gg_vankrevelen_domains)$gg_vk_domains_nosc ``` --- ## Van Krevelen plots option 1 ```{r gg_vk1, fig.width=9, fig.height=4} readd(gg_vankrevelens)$gg_vk1 ``` option 2, with marginal plots ```{r gg_vk2, fig.asp=1, fig.height=3} readd(gg_vankrevelens)$gg_vk2 ``` --- ## PCA ```{r PCA, fig.width=5, fig.height=8} readd(gg_pca)+theme_kp()+xlim(-3.5,3.5)+ylim(-3,3) ``` --- ## Relative abundance ```{r relabund} readd(gg_relabund_bar)+theme(legend.position = "right") ``` <file_sep>/code/2-fticr_abundance.R # HYSTERESIS AND SOIL CARBON # # <NAME> # April 2020 source("code/0-packages.R") # ------------------------------------------------------- ---- # I. LOAD FILES ---- fticr_data = read.csv(FTICR_LONG) fticr_meta = read.csv(FTICR_META) meta_hcoc = read.csv(FTICR_META_HCOC) # II. RELATIVE ABUNDANCE ---- ## IIa. calculate relative abundance of classes in each core relabund_cores = fticr_data %>% # add the Class column to the data left_join(dplyr::select(fticr_meta, formula, Class), by = "formula") %>% # calculate abundance of each Class as the sum of all counts group_by(CoreID, sat_level, Class) %>% #$$$$# dplyr::summarise(abund = sum(presence)) %>% ungroup %>% # create a new column for total counts per core assignment # and then calculate relative abundance group_by(CoreID, sat_level) %>% #$$$$# dplyr::mutate(total = sum(abund), relabund = round((abund/total)*100,2)) ## IIb. calculate mean relative abundance across all replicates of the treatments relabund_trt = relabund_cores %>% group_by(sat_level, Class) %>% #$$$$# dplyr::summarize(rel_abund = round(mean(relabund),2), se = round((sd(relabund/sqrt(n()))),2), relative_abundance = paste(rel_abund, "\u00b1",se)) # IV. OUTPUT ---- write.csv(relabund_cores, FTICR_RELABUND_CORES, row.names=FALSE) write.csv(relabund_trt, FTICR_RELABUND_TRT, row.names=FALSE) <file_sep>/code/functions.R mean_mpg = function(data, group_col) { data %>% group_by_(.dots = lazyeval::lazy(group_col)) %>% summarize(mean_mpg = mean(mpg)) } relativeabundancebycores = function(dat, treatments){ dat %>% # add the Class column to the data left_join(dplyr::select(fticr_meta, formula, Class), by = "formula") %>% # calculate abundance of each Class as the sum of all counts group_by(.dots = lazyeval::lazy(treatments)) %>% #$$$$# dplyr::summarise(abund = sum(presence)) %>% ungroup %>% # create a new column for total counts per core assignment # and then calculate relative abundance group_by(treatments) %>% #$$$$# dplyr::mutate(total = sum(abund), relabund = round((abund/total)*100,2)) } treatments = "sat_level" fticr_data %>% relativeabundancebycores(sat_level) mean_mpg = function(data, group_col) { data %>% group_by(.dots = lazyeval::lazy(group_col)) %>% summarize(mean_mpg = mean(mpg)) } mtcars %>% mean_mpg(cyl) mtcars %>% mean_mpg(gear) nopeaks = fticr_data %>% group_by(CoreID) %>% dplyr::summarise(count = n()) peakcount = function(dat, ...){ dat %>% group_by(.dots = lazyeval::lazy_dots(...)) %>% dplyr::summarise(count = n()) } fticr_data %>% peakcount(sat_level, treatment) mean_mpg = function(data, ...) { data %>% group_by_(.dots = lazyeval::lazy_dots(...)) %>% summarize(mean_mpg = mean(mpg)) } mtcars %>% mean_mpg(cyl, gear) relativeabundancebycores = function(dat, ...){ dat %>% # add the Class column to the data left_join(dplyr::select(fticr_meta, formula, Class), by = "formula") %>% # calculate abundance of each Class as the sum of all counts # group_by(CoreID, Class) %>% #$$$$# group_by_(.dots = lazyeval::lazy_dots(CoreID, Class, ...)) %>% dplyr::summarise(abund = sum(presence)) %>% ungroup %>% # create a new column for total counts per core assignment # and then calculate relative abundance # group_by(CoreID, sat_level) %>% #$$$$# group_by_(.dots = lazyeval::lazy_dots(CoreID, ...)) %>% dplyr::mutate(total = sum(abund), relabund = round((abund/total)*100,2)) } fticr_data %>% relativeabundancebycores(sat_level, treatment) <file_sep>/code/0-packages.R ## Functions # <NAME> ## packages #### library(readxl) library(readr) library(data.table) library(stringr) # 1.1.0 library(tidyr) library(readr) library(Rmisc) library(ggplot2) library(ggExtra) library(stringi) library(tidyr) library(ggbiplot) library(dplyr) library(drake) pkgconfig::set_config("drake::strings_in_dots" = "literals") # custom ggplot theme theme_kp <- function() { # this for all the elements common across plots theme_bw() %+replace% theme(legend.position = "top", legend.key=element_blank(), legend.title = element_blank(), legend.text = element_text(size = 12), legend.key.size = unit(1.5, 'lines'), legend.background = element_rect(colour = NA), panel.border = element_rect(color="black",size=1.5, fill = NA), plot.title = element_text(hjust = 0.05, size = 14), axis.text = element_text(size = 14, color = "black"), axis.title = element_text(size = 14, face = "bold", color = "black"), # formatting for facets panel.background = element_blank(), strip.background = element_rect(colour="white", fill="white"), #facet formatting panel.spacing.x = unit(1.5, "lines"), #facet spacing for x axis panel.spacing.y = unit(1.5, "lines"), #facet spacing for x axis strip.text.x = element_text(size=12, face="bold"), #facet labels strip.text.y = element_text(size=12, face="bold", angle = 270) #facet labels ) } # custom ggplot function for Van Krevelen plots gg_vankrev <- function(data,mapping){ ggplot(data,mapping) + # plot points geom_point(size=2, alpha = 0.2) + # set size and transparency # axis labels ylab("H/C") + xlab("O/C") + # axis limits xlim(0,1.25) + ylim(0,2.5) + # add boundary lines for Van Krevelen regions geom_segment(x = 0.0, y = 1.5, xend = 1.2, yend = 1.5,color="black",linetype="longdash") + #geom_segment(x = 0.0, y = 2, xend = 1.2, yend = 2,color="black",linetype="longdash") + #geom_segment(x = 0.0, y = 1, xend = 1.2, yend = 0.75,color="black",linetype="longdash") + geom_segment(x = 0.0, y = 0.8, xend = 1.2, yend = 0.8,color="black",linetype="longdash")+ guides(colour = guide_legend(override.aes = list(alpha=1))) } ## to make the Van Krevelen plot: # replace the initial `ggplot` function with `gg_vankrev` and use as normal ## CREATE INPUT FILES COREKEY = "data/corekey.csv" ## CREATE OUTPUT FILES FTICR_LONG = "processed/fticr_longform.csv" FTICR_META = "processed/fticr_meta.csv" FTICR_META_HCOC = "processed/fticr_meta_hcoc.csv" FTICR_RELABUND_CORES = "processed/fticr_relabund_cores.csv" FTICR_RELABUND_TRT = "processed/fticr_relabund.csv" FTICR_RELABUND_SUMMARY = "processed/fticr_relabund_summary.csv" <file_sep>/code/a-functions_processing.R # 1. PROCESSING FUNCTIONS ------------------------------------------------- ## LEVEL I FUNCTIONS ------------------------------------------------------- ## for metadata file apply_filter_report = function(report){ report %>% # filter appropriate mass range filter(Mass>200 & Mass<900) %>% # remove isotopes filter(C13==0) %>% # remove peaks without C assignment filter(C>0) } compute_indices = function(dat){ dat %>% dplyr::select(Mass, C:P) %>% dplyr::mutate(AImod = round((1+C-(0.5*O)-S-(0.5*(N+P+H)))/(C-(0.5*O)-S-N-P),4), NOSC = round(4-(((4*C)+H-(3*N)-(2*O)-(2*S))/C),4), HC = round(H/C,2), OC = round(O/C,2), DBE_AI = 1+C-O-S-0.5*(N+P+H), DBE = 1 + ((2*C-H + N + P))/2, DBE_C = round(DBE_AI/C,4)) %>% dplyr::select(-c(C:P)) } compute_mol_formula = function(dat){ dat %>% dplyr::select(Mass, C:P) %>% dplyr::mutate(formula_c = if_else(C>0,paste0("C",C),as.character(NA)), formula_h = if_else(H>0,paste0("H",H),as.character(NA)), formula_o = if_else(O>0,paste0("O",O),as.character(NA)), formula_n = if_else(N>0,paste0("N",N),as.character(NA)), formula_s = if_else(S>0,paste0("S",S),as.character(NA)), formula_p = if_else(P>0,paste0("P",P),as.character(NA)), formula = paste0(formula_c,formula_h, formula_o, formula_n, formula_s, formula_p), formula = str_replace_all(formula,"NA","")) %>% dplyr::select(Mass, formula) } assign_class_seidel = function(meta_clean, meta_indices){ meta_clean %>% left_join(meta_indices, by = "Mass") %>% mutate(Class = case_when(AImod>0.66 ~ "condensed aromatic", AImod<=0.66 & AImod > 0.50 ~ "aromatic", AImod <= 0.50 & HC < 1.5 ~ "unsaturated/lignin", HC >= 1.5 ~ "aliphatic"), Class = replace_na(Class, "other"), Class_detailed = case_when(AImod>0.66 ~ "condensed aromatic", AImod<=0.66 & AImod > 0.50 ~ "aromatic", AImod <= 0.50 & HC < 1.5 ~ "unsaturated/lignin", HC >= 2.0 & OC >= 0.9 ~ "carbohydrate", HC >= 2.0 & OC < 0.9 ~ "lipid", HC < 2.0 & HC >= 1.5 & N==0 ~ "aliphatic", HC < 2.0 & HC >= 1.5 & N > 0 ~ "aliphatic+N")) %>% dplyr::select(Mass, EMSL_class, Class, Class_detailed) } ## for data file compute_presence = function(dat){ dat %>% pivot_longer(-("Mass"), values_to = "presence", names_to = "CoreID") %>% # convert intensities to presence==1/absence==0 dplyr::mutate(presence = if_else(presence>0,1,0)) %>% # keep only peaks present filter(presence>0) } apply_replication_filter = function(data_long_key, ...){ max_replicates = data_long_key %>% ungroup() %>% group_by(...) %>% distinct(CoreID) %>% dplyr::summarise(reps = n()) # second, join the `reps` file to the long_key file # and then use the replication filter data_long_key %>% group_by(formula, ...) %>% dplyr::mutate(n = n()) %>% left_join(max_replicates) %>% ungroup() %>% mutate(keep = n >= (2/3)*reps) %>% filter(keep) %>% dplyr::select(-keep, -reps) } ## LEVEL II FUNCTIONS ------------------------------------------------------ make_fticr_meta = function(report){ fticr_report = (apply_filter_report(report)) meta_clean = fticr_report %>% # select only the relevant columns for the formula assignments dplyr::select(Mass, C, H, O, N, S, P, El_comp, Class) %>% rename(EMSL_class = Class) meta_indices = compute_indices(meta_clean) meta_formula = compute_mol_formula(meta_clean) meta_class = assign_class_seidel(meta_clean, meta_indices) # output meta2 = meta_formula %>% left_join(meta_class, by = "Mass") %>% left_join(meta_indices, by = "Mass") %>% dplyr::select(-Mass) %>% distinct(.) list(meta2 = meta2, meta_formula = meta_formula) } make_fticr_data = function(report, ...){ fticr_report = (apply_filter_report(report)) mass_to_formula = make_fticr_meta(report)$meta_formula data_columns = fticr_report %>% dplyr::select(-c(C:Candidates)) data_presence = compute_presence(data_columns) %>% left_join(mass_to_formula, by = "Mass") %>% dplyr::select(formula, CoreID, presence) data_long_key = data_presence %>% left_join(corekey, by = "CoreID") data_long_key_repfiltered = apply_replication_filter(data_long_key, ...) data_long_trt = data_long_key_repfiltered %>% distinct(formula, ...) list(data_long_trt = data_long_trt, data_long_key_repfiltered = data_long_key_repfiltered) } <file_sep>/4-fticr_markdown.Rmd --- title: "fticr_markdown" output: github_document --- ```{r setup, include=FALSE} knitr::opts_chunk$set(echo=FALSE,message=FALSE,warning=FALSE, collapse = TRUE, comment = "#>", fig.path = "images/fticr_markdown/" ) ``` ```{r} source("0-packages.R") fticr_data = read.csv(FTICR_LONG) fticr_meta = read.csv(FTICR_META) meta_hcoc = read.csv(FTICR_META_HCOC) relabund_cores = read.csv(FTICR_RELABUND_CORES) relabund_trt = read.csv(FTICR_RELABUND_TRT) relabund_summary = read.csv(FTICR_RELABUND_SUMMARY) ``` ## VAN KREVELEN DOMAINS ```{r vk_domains, fig.height=5, fig.width=5} gg_vankrev(fticr_meta, aes(x = OC, y = HC, color = Class))+ scale_color_viridis_d(option = "inferno")+ theme_kp() ``` ## VAN KREVELEN PLOTS {.tabset} ### simple VK plots ```{r vk, fig.height=6, fig.width=16} fticr_hcoc = fticr_data %>% left_join(meta_hcoc, by = "formula") gg_vankrev(fticr_hcoc, aes(x = OC, y = HC, color = sat_level))+ facet_grid(.~sat_level)+ theme_kp() ``` ### VK plots with marginal plots ```{r vk_marginal, fig.height = 6, fig.width=6} gg_fm = gg_vankrev(fticr_hcoc, aes(x = OC, y = HC, color = sat_level))+ stat_ellipse()+ annotate("text", label = "aliphatic", x = 1.2, y = 1.9, hjust="right")+ annotate("text", label = "polyphenolic", x = 1.2, y = 1.2, hjust="right")+ annotate("text", label = "condensed \n aromatic", x = 1.2, y = 0.2, hjust="right")+ theme_kp() ggMarginal(gg_fm,groupColour = TRUE,groupFill = TRUE) ``` ## RELATIVE ABUNDANCE FIGURES ```{r relabund_bar} relabund_trt %>% dplyr::mutate(Class = factor(Class, levels = c("AminoSugar", "Carb","Lipid","Protein","UnsatHC", "ConHC","Lignin","Tannin","Other"))) %>% ggplot(aes(x = sat_level, y = rel_abund, fill = Class))+ geom_bar(stat = "identity")+ scale_fill_viridis_d(option = "inferno")+ labs(x = "percent saturation", y = "relative abundance (%)")+ theme_kp() ``` ## RELATIVE ABUNDANCE TABLES Different letters denote significant differences among saturation levels at alpha = 0.05. ```{r} relabund_summary %>% dplyr::select(sat_level, Class, relative_abundance) %>% dplyr::mutate(Class = factor(Class, levels = c("AminoSugar", "Carb","Lipid","Protein","UnsatHC", "ConHC","Lignin","Tannin","Other"))) %>% spread(sat_level, relative_abundance) %>% knitr::kable(align = "c") ``` <file_sep>/code/1-fticr_processing.R # HYSTERESIS AND SOIL CARBON # 3-fticr_initial processing # <NAME> # March 2020 ## this script will process the input data and metadata files and ## generate clean files that can be used for subsequent analysis. ## each dataset will generate longform files of (a) all cores, (b) summarized data for each treatment (i.e. cores combined) source("code/0-packages.R") # ------------------------------------------------------- ---- ## step 1: load the files ---- report = read.csv("data/Report.csv") corekey = read.csv(COREKEY) fticr_report = report %>% # filter appropriate mass range filter(Mass>200 & Mass<900) %>% # remove isotopes filter(C13==0) %>% # remove peaks without C assignment filter(C>0) # this has metadata as well as sample data # split them # 1a. create meta file ---- fticr_meta = fticr_report %>% # select only the relevant columns for the formula assignments dplyr::select(Mass:Candidates) %>% # alternatively, use `starts_with()` if all your sample names start with the same prefix # dplyr::select(-starts_with("FT")) %>% # select only necessary columns dplyr::select(Mass, C, H, O, N, S, P, El_comp, Class) %>% # create columns for indices dplyr::mutate(AImod = round((1+C-(0.5*O)-S-(0.5*(N+P+H)))/(C-(0.5*O)-S-N-P),4), NOSC = round(4-(((4*C)+H-(3*N)-(2*O)-(2*S))/C),4), HC = round(H/C,2), OC = round(O/C,2)) %>% # create column/s for formula # first, create columns for individual elements # then, combine dplyr::mutate(formula_c = if_else(C>0,paste0("C",C),as.character(NA)), formula_h = if_else(H>0,paste0("H",H),as.character(NA)), formula_o = if_else(O>0,paste0("O",O),as.character(NA)), formula_n = if_else(N>0,paste0("N",N),as.character(NA)), formula_s = if_else(S>0,paste0("S",S),as.character(NA)), formula_p = if_else(P>0,paste0("P",P),as.character(NA)), formula = paste0(formula_c,formula_h, formula_o, formula_n, formula_s, formula_p), formula = str_replace_all(formula,"NA","")) %>% dplyr::select(Mass, formula, El_comp, Class, HC, OC, AImod, NOSC, C:P) # subset of meta for HC/OC only, for Van Krevelen diagrams meta_hcoc = fticr_meta %>% dplyr::select(Mass, formula, HC, OC) # # 1b. create data file ---- fticr_data = fticr_report %>% # select only the relevant columns for the formula assignments dplyr::select(-c(C:Candidates)) %>% # alternatively, use `starts_with()` if all your sample names start with the same prefix # dplyr::select(Mass,starts_with("FT")) %>% melt(id = c("Mass"), value.name = "presence", variable.name = "CoreID") %>% # convert intensities to presence==1/absence==0 dplyr::mutate(presence = if_else(presence>0,1,0)) %>% # keep only peaks present filter(presence>0) %>% left_join(dplyr::select(fticr_meta, Mass,formula), by = "Mass") %>% left_join(corekey, by = "CoreID") %>% # rearrange columns dplyr::select(-Mass,-formula, -presence,Mass,formula,presence) %>% # now we want only peaks that are in 3 of the 5 replicates # group by the treatment levels group_by(treatment, sat_level,formula) %>% dplyr::mutate(n = n(), presence = mean(presence)) %>% filter(n>2) ## OUTPUTS write.csv(fticr_data,FTICR_LONG, row.names = FALSE) write.csv(fticr_meta,FTICR_META, row.names = FALSE) write.csv(meta_hcoc,FTICR_META_HCOC, row.names = FALSE) <file_sep>/reports/fticrrr_report.md fticrrr report ================ ----- ## FTICR domains ### compound classes ``` r readd(gg_vankrevelen_domains)$gg_vk_domains+theme(legend.position = "right") ``` ![](markdown-figs/fticrrr/domains_classes-1.png)<!-- --> ### NOSC ``` r readd(gg_vankrevelen_domains)$gg_vk_domains_nosc ``` ![](markdown-figs/fticrrr/domains_nosc-1.png)<!-- --> ----- ## Van Krevelen plots option 1 ``` r readd(gg_vankrevelens)$gg_vk1 ``` ![](markdown-figs/fticrrr/gg_vk1-1.png)<!-- --> option 2, with marginal plots ``` r readd(gg_vankrevelens)$gg_vk2 ``` ![](markdown-figs/fticrrr/gg_vk2-1.png)<!-- --> ----- ## PCA ``` r readd(gg_pca)+theme_kp()+xlim(-3.5,3.5)+ylim(-3,3) ``` ![](markdown-figs/fticrrr/PCA-1.png)<!-- --> ----- ## Relative abundance ``` r readd(gg_relabund_bar)+theme(legend.position = "right") ``` ![](markdown-figs/fticrrr/relabund-1.png)<!-- --> <file_sep>/code/3-fticr_stats.R # HYSTERESIS AND <NAME> # 3-fticr_initial processing # <NAME> # June 2020 ## this script will perform statistical analyses on processed FTICR-MS data ## use relative abundances for statistical analyses source("code/0-packages.R") # ------------------------------------------------------- ---- # I. Load files ----------------------------------------------------------- relabund_cores = read.csv(FTICR_RELABUND_CORES) relabund_trt = read.csv(FTICR_RELABUND_TRT) # # II. MANOVA: overall treatment effect --------------------------------------------------------------- # perform a Multivariate ANOVA with relative abundances of groups as the response variables and # moisture level as an explanatory variable. # to perform MANOVA, each group must be a column relabund_wide = relabund_cores %>% dplyr::select(CoreID, sat_level, Class, relabund) %>% spread(Class, relabund) %>% replace(is.na(.),0) # create a matrix of all the group columns relabund_wide$DV = as.matrix(relabund_wide[,3:11]) # since the relative abundances are not strictly independent and all add to 100 %, # use the isometric log ratio transformation # http://www.sthda.com/english/wiki/manova-test-in-r-multivariate-analysis-of-variance#import-your-data-into-r library(compositions) man = manova(ilr(clo(DV)) ~ sat_level, data = relabund_wide) summary(man) # # III. PCA --------------------------------------------------------------------- # IV. Pairwise statistics ------------------------------------------------- # testing the treatment effect for each group # fit an ANOVA+HSD function and then apply it to each FTICR group fit_hsd <- function(dat) { a <-aov(relabund ~ sat_level, data = dat) h <-agricolae::HSD.test(a,"sat_level") #create a tibble with one column for each treatment #the hsd results are row1 = drought, row2 = saturation, row3 = time zero saturation, row4 = field moist. hsd letters are in column 2 tibble(`100` = h$groups["100",2], `50` = h$groups["50",2], `FM` = h$groups["FM",2]) } fticr_hsd = relabund_cores %>% group_by(Class) %>% do(fit_hsd(.)) %>% pivot_longer(-Class, names_to = "sat_level", values_to = "hsd") relabund_summary = relabund_trt %>% left_join(fticr_hsd, by = c("sat_level", "Class")) %>% dplyr::mutate(relative_abundance = paste(relative_abundance, hsd)) # for a simple ANOVA (no HSD), use this code instead: # fit_aov_ <- function(dat) { # a <-aov(relabund ~ sat_level, data = dat) # tibble(`p` = summary(a)[[1]][[1,"Pr(>F)"]]) # } # fticr_aov = # relabund_cores %>% # group_by(Class) %>% # do(fit_aov(.)) %>% # dplyr::mutate(p = round(p,4), # asterisk = if_else(p<0.05,"*",as.character(NA))) %>% # dplyr::select(-p) # # V. SHANNON DIVERSITY ---- # Shannon diversity, H = - sum [p*ln(p)], where n = no. of individuals per species/total number of individuals shannon = relabund %>% dplyr::mutate( p = abund/total, log = log(p), p_logp = p*log) %>% group_by(Core_assignment) %>% dplyr::summarize(H1 = sum(p_logp), H = round(-1*H1, 2)) %>% dplyr::select(-H1) # # VI. OUTPUT ---- write.csv(shannon, "data/processed/fticr_shannon.csv", row.names = FALSE) write.csv(relabund, "data/processed/fticr_relabund.csv", row.names=FALSE) write.csv(relabund_summary, FTICR_RELABUND_SUMMARY, row.names = F) <file_sep>/code/d-fticr_drake_plan.R ## FTICR-MS DRAKE PLAN ## USE THIS SCRIPT/PLAN TO PROCESS, ANALYZE, AND GRAPH FTICR-MS DATA ## <NAME> ## OCT-06-2020 ############################## ############################## ## SOURCE THE FUNCTION FILES FIRST, AND THEN RUN THE DRAKE PLAN ## DON'T RUN THE PROCESSING PLAN MULTIPLE TIMES. ONCE IS ENOUGH. ############################## ############################## # 1. SET input file paths ------------------------------- COREKEY = "data/corekey.csv" REPORT = "data/Report.csv" ## SET the treatment variables TREATMENTS = quos(sat_level) ## this will work with multiple variables too. just add all the variable names in the parentheses. # 2. load packages and source the functions -------------------------------------------------------- library(drake) library(tidyverse) source("code/a-functions_processing.R") source("code/b-functions_relabund.R") source("code/c-functions_vankrevelen.R") #source("code/d-functions_statistics.R") # 3. load drake plans ----------------------------------------------------- fticr_processing_plan = drake_plan( # a. PROCESSING datareport = read.csv(file_in(REPORT)), fticr_meta = make_fticr_meta(datareport)$meta2, fticr_data_longform = make_fticr_data(datareport, sat_level, treatment)$data_long_key_repfiltered, fticr_data_trt = make_fticr_data(datareport, sat_level, treatment)$data_long_trt, ## OUTPUT # fticr_meta %>% write.csv(), # fticr_data_trt %>% write.csv(), # fticr_data_longform %>% write.csv() # b. relative abundance relabund_cores = fticr_data_longform %>% compute_relabund_cores(fticr_meta, sat_level, treatment), gg_relabund_bar = relabund_cores %>% plot_relabund(TREATMENTS)+ scale_fill_manual(values = PNWColors::pnw_palette("Sailboat")), ## create relabund table ## OUTPUT ? # c. van krevelen plots gg_vankrevelen_domains = plot_vankrevelen_domains(fticr_meta), gg_vankrevelens = plot_vankrevelens(fticr_data_longform, fticr_meta), # d. stats ## PERMANOVA ## PCA gg_pca = compute_fticr_pca(relabund_cores), # e. REPORT outputreport = rmarkdown::render( knitr_in("reports/fticrrr_report.Rmd"), output_format = rmarkdown::github_document()) ) # 4. make plans ------------------------------------------------------------------------- corekey = read.csv(file_in(COREKEY)) make(fticr_processing_plan) <file_sep>/code/d-functions_statistics.R # pca functions ----------------------------------------------------------- library(ggbiplot) compute_fticr_pca = function(relabund_cores){ relabund_pca= relabund_cores %>% ungroup %>% dplyr::select(-c(abund, total)) %>% spread(Class, relabund) %>% replace(.,is.na(.),0) %>% dplyr::select(-1) relabund_pca_num = relabund_pca %>% dplyr::select(c(aliphatic, aromatic, `condensed aromatic`, `unsaturated/lignin`)) relabund_pca_grp = relabund_pca %>% dplyr::select(-c(aliphatic, aromatic, `condensed aromatic`, `unsaturated/lignin`)) %>% dplyr::mutate(row = row_number()) pca = prcomp(relabund_pca_num, scale. = T) summary(pca) ggbiplot(pca, obs.scale = 1, var.scale = 1, groups = relabund_pca_grp$treatment, ellipse = TRUE, circle = F, var.axes = TRUE)+ geom_point(size=2,stroke=2, aes(color = groups, shape = as.factor(relabund_pca_grp$sat_level))) } compute_permanova = function(relabund_cores, indepvar){ relabund_wide = relabund_cores %>% ungroup() %>% mutate(Class = factor(Class, levels = c("aliphatic", "unsaturated/lignin", "aromatic", "condensed aromatic"))) %>% dplyr::select(-c(abund, total)) %>% spread(Class, relabund) %>% replace(is.na(.), 0) permanova_fticr_all = adonis(relabund_wide %>% dplyr::select(aliphatic:`condensed aromatic`) ~ indepvar, data = relabund_wide) broom::tidy(permanova_fticr_all$aov.tab) } variables = c("sat_level", "treatment") indepvar = paste(variables, collapse = " + ") compute_permanova(indepvar) <file_sep>/code/c-functions_vankrevelen.R # FTICRRR: fticr results in R # <NAME> # October 2020 ################################################## # ## `functions_vankrevelens.R` ## this script will load functions for plotting Van Krevelen diagrams ## source this file in the `fticr_drake_plan.R` file, do not run the script here. ################################################## # ################################################## # theme_kp <- function() { # this for all the elements common across plots theme_bw() %+replace% theme(legend.position = "top", legend.key=element_blank(), legend.title = element_blank(), legend.text = element_text(size = 12), legend.key.size = unit(1.5, 'lines'), legend.background = element_rect(colour = NA), panel.border = element_rect(color="black",size=1.5, fill = NA), plot.title = element_text(hjust = 0.05, size = 14), axis.text = element_text(size = 14, color = "black"), axis.title = element_text(size = 14, face = "bold", color = "black"), # formatting for facets panel.background = element_blank(), strip.background = element_rect(colour="white", fill="white"), #facet formatting panel.spacing.x = unit(1.5, "lines"), #facet spacing for x axis panel.spacing.y = unit(1.5, "lines"), #facet spacing for x axis strip.text.x = element_text(size=12, face="bold"), #facet labels strip.text.y = element_text(size=12, face="bold", angle = 270) #facet labels ) } gg_vankrev <- function(data,mapping){ ggplot(data,mapping) + # plot points geom_point(size=2, alpha = 0.2) + # set size and transparency # axis labels ylab("H/C") + xlab("O/C") + # axis limits xlim(0,1.25) + ylim(0,2.5) + # add boundary lines for Van Krevelen regions geom_segment(x = 0.0, y = 1.5, xend = 1.2, yend = 1.5,color="black",linetype="longdash") + geom_segment(x = 0.0, y = 0.7, xend = 1.2, yend = 0.4,color="black",linetype="longdash") + geom_segment(x = 0.0, y = 1.06, xend = 1.2, yend = 0.51,color="black",linetype="longdash") + guides(colour = guide_legend(override.aes = list(alpha=1))) } # van krevelen plots ------------------------------------------------------ plot_vankrevelen_domains = function(fticr_meta){ gg_vk_domains = gg_vankrev(fticr_meta, aes(x = OC, y = HC, color = Class))+ scale_color_manual(values = PNWColors::pnw_palette("Sunset2"))+ theme_kp() gg_vk_domains_nosc = gg_vankrev(fticr_meta, aes(x = OC, y = HC, color = as.numeric(NOSC)))+ scale_color_gradientn(colors = PNWColors::pnw_palette("Bay"))+ theme_kp() list(gg_vk_domains = gg_vk_domains, gg_vk_domains_nosc = gg_vk_domains_nosc) } plot_vankrevelens = function(fticr_data_longform, fticr_meta){ fticr_hcoc = fticr_data_longform %>% left_join(dplyr::select(fticr_meta, formula, HC, OC), by = "formula") gg_vk1 = gg_vankrev(fticr_hcoc, aes(x = OC, y = HC, color = sat_level))+ facet_grid(.~sat_level)+ theme_kp() gg_fm = gg_vankrev(fticr_hcoc, aes(x = OC, y = HC, color = sat_level))+ stat_ellipse()+ theme_kp() gg_vk2 = ggExtra::ggMarginal(gg_fm,groupColour = TRUE,groupFill = TRUE) list(gg_vk1 = gg_vk1, gg_vk2 = gg_vk2) } <file_sep>/README.md <img align="right" heignt = "250" width = "250" src="images/fticr_hex.png"> # fticrrr [![DOI](https://zenodo.org/badge/259772882.svg)](https://zenodo.org/badge/latestdoi/259772882) This script is designed for batch processing and analysis of **FTICR r**esults in **R** (fticrrr). Use this script for: (a) cleaning and processing data (b) plotting Van Krevelen diagrams (c) calculating relative abundance of functional classes (d) statistical analyses ----- <file_sep>/4-fticr_markdown.md fticr\_markdown ================ ## VAN KREVELEN DOMAINS ![](images/fticr_markdown/vk_domains-1.png)<!-- --> ## VAN KREVELEN PLOTS ### simple VK plots ![](images/fticr_markdown/vk-1.png)<!-- --> ### VK plots with marginal plots ![](images/fticr_markdown/vk_marginal-1.png)<!-- --> ## RELATIVE ABUNDANCE FIGURES ![](images/fticr_markdown/relabund_bar-1.png)<!-- --> ## RELATIVE ABUNDANCE TABLES Different letters denote significant differences among saturation levels at alpha = 0.05. | Class | 100 | 50 | FM | | :--------: | :-------------: | :------------: | :------------: | | AminoSugar | 0.71 ± 0.11 b | 1.15 ± 0.07 a | 0.83 ± 0.07 b | | Carb | 0.35 ± 0.06 b | 0.72 ± 0.04 a | 0.7 ± 0.06 a | | Lipid | 4.75 ± 1.28 a | 2.85 ± 0.06 a | 3.37 ± 0.07 a | | Protein | 15.93 ± 2.87 a | 13.27 ± 0.18 a | 12.99 ± 0.13 a | | UnsatHC | 0.25 ± 0.08 a | 0.23 ± 0.03 a | 0.29 ± 0.04 a | | ConHC | 14.12 ± 2.56 a | 16.77 ± 0.2 a | 17.48 ± 0.18 a | | Lignin | 52.39 ± 1.06 ab | 50.64 ± 0.3 b | 53.09 ± 0.1 a | | Tannin | 10.85 ± 2.65 a | 13.51 ± 0.19 a | 10.69 ± 0.09 a | | Other | 0.65 ± 0.11 ab | 0.84 ± 0.03 a | 0.56 ± 0.03 b |
1d5dfd2bf8d155121693044d4b67d0a8e3318533
[ "RMarkdown", "Markdown", "R" ]
14
RMarkdown
kaizadp/fticrrr
7d746b31379a6251cc8f74e8d299ed8ce125baf7
2ac0730e33cc1bed62d6f8b1461670595492212e
refs/heads/master
<repo_name>Nastasia8/n-g<file_sep>/NewTest.py string = 'Python is an interpreted, ' \ 'high-level and general-purpose programming language. ' \ 'Python\'s design philosophy emphasizes code readability with ' \ 'its notable use of significant whitespace. Its language ' \ 'constructs and object-oriented approach aim to help programmers ' \ 'write clear, logical code for small and large-scale projects. ' \ 'Python is dynamically-typed and garbage-collected.'.lower()<file_sep>/README.md # n-g ## <NAME>
56a52312c5bcd965efd29ebd6c135e3b472e9235
[ "Markdown", "Python" ]
2
Markdown
Nastasia8/n-g
4cc916230c1f8f00babf85b911f15968e3fa698d
c1aa3f835013764ef1c558cb33c6bcabb2a2bb6b
refs/heads/master
<file_sep># Laradock guide Welcome to the Laradock guide,<br> Here you will learn how to deploy laravel in a docker container.<br/> Everything is nicely explained, some of the line-numbers may have changed, since we keep pulling the latest version of laradock into our new projects, if you experience errors and can't fix them,<br/>don't forget to check for the latest versions of laradock on it's github repository and look if there are any posted issues there,<br/> if the current build is failing, than take the last passing build. ## Table of Content 1. Create the folder structure 1. Setting up Laradock 1. Spinning up Laradock 1. Setting up Laravel 1. Important docker commando`s ## 1. Creating the folder structure Create folder on your harddrive to hold the laradock and laravel projects. <br>Use the following commands in a terminal: ```` mkdir Your-folder-name ```` Enter this folder and initialise a local Git repository. ```` cd Your-folder-name git init ```` ***(optional)*** Link the project to your remote repository ```` // Dont forget to change username and repository git remote add origin <EMAIL>:username/repository.git ```` Now add Laradock and Laravel as a submodule to your repository like so ```` git submodule add https://github.com/Laradock/laradock.git git submodule add https://github.com/laravel/laravel.git ```` Your folder structure should now look like this: ```` + laradock + laravel .gitignore .gitmodules ```` Our folder structure should be all set for now. <br>We have our basic components to spin up our laravel project with Docker. If you want to you could add/commit/push this to Github repository to save your current status.<br> ## 2. Setting up Laradock Its now time to set up nginx, mariadb and phpmyadmin. <br>This way our workspace should be all set to start our development. ### Create a .env file Enter the laradock folder and copy ``env-example`` to ``.env`` ```` cd laradock // for Linux cp env-example .env // for Windows copy env-example .env ```` We need to edit the ``.env`` file to choose which software’s we want to be installed in your environment. We can always refer to the ``docker-compose.yml`` file to see how those variables are being used. All we need to know for now are these following steps: ### Change the settings inside the .env file 1. Open the .env file with any installed editor 1. Change line 8 to the following: ``APP_CODE_PATH_HOST=../laravel/`` 1. Change on line 36 the variable ``COMPOSE_PROJECT_NAME`` to something unique like your project name. 1. Starting from line 250, Change the settings of the Mariadb Server. Database, Username, Password and root password. 1. Change line 314 to the following: ``PMA_DB_ENGINE=mariadb`` and change the credentials below. 1. Save the changes into this file and close it.</li></ol> ### Change the settings inside the docker-compose.yml file (Optional) At the time of writing this column, laradock has a known bug into its settings.. <br>If we now try to load up our mariadb container, it will give us a error. <br>In order to solve this we need to open the ``docker-compose.yml`` file and change the settings on line 370: ```` - mariadb:/var/lib/mysql ```` I am well aware that i remove the dynamic part of the mariadb container and by doing this we are making a recursive container.. But it is a fix we are grown custom to and laradock hasn't removed the bug for a while now. <br>Hopefully, by the time you read this, this bug is resolved. ## 3. Spinning up Laradock for the first time Now that all our settings are in order its time to start our engine`s and see what this baby is made off.. <br><br>In order to start our containers, enter the following commands: ```` docker-compose up -d nginx mariadb phpmyadmin ```` This might take a while, depending on whether you have the images installed locally. <br>If you do need to wait, I advice you to get yourself a coffee.. this might take a while depending on your internet speed After the installation is done, make sure all the containers are up and running by the following command: ```` docker ps -a ```` This should give you something like this: ```` CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES fe3b8b8a83d2 michelpietersbe_phpmyadmin "/run.sh supervisord…" 4 minutes ago Up 3 minutes 9000/tcp, 0.0.0.0:8080-&gt;80/tcp michelpietersbe_phpmyadmin_1 8b10a517699a michelpietersbe_nginx "/bin/bash /opt/star…" 4 minutes ago Up 4 minutes 0.0.0.0:80-&gt;80/tcp, 0.0.0.0:443-&gt;443/tcp michelpietersbe_nginx_1 8399cb008b36 michelpietersbe_php-fpm "docker-php-entrypoi…" 4 minutes ago Up 4 minutes 9000/tcp michelpietersbe_php-fpm_1 f0712df65f3a michelpietersbe_workspace "/sbin/my_init" 4 minutes ago Up 4 minutes 0.0.0.0:2222-&gt;22/tcp michelpietersbe_workspace_1 035549ab5ec3 michelpietersbe_mariadb "docker-entrypoint.s…" 4 minutes ago Up 4 minutes 0.0.0.0:3306-&gt;3306/tcp michelpietersbe_mariadb_1 8c2cd6bdf46c docker:dind "dockerd-entrypoint.…" 4 minutes ago Up 4 minutes 2375/tcp michelpietersbe_docker-in-docker_1 ```` In total we should have 6 containers up and running. <br>If we open up our browser and visit the url: ``localhost`` <br>we dont see anything going on, and we get an error: <br>**HTTP ERROR 500!** In order to fix this we have to install Laravel to our docker container. Luckily our Laradock has all the tools already installed for us. ## 4. Setting up Laravel Before we can install laravel we need to enter our docker container. In order to do so we need to execute the following command into our teminal: ```` docker exec -it 'YOUR_COMPOSE_PROJECT_NAME'_workspace_1 bash ```` We can install Laravel using composer: ```` composer install ```` Next we need to copy the ``.env-example`` to a ``.env`` file: ```` // for Linux cp .env.example .env // for Windows copy .env.example .env ```` Open the ``.env`` file in a editor and change the following: - on line 1: ``APP_NAME`` - on line 10: ``DB_HOST=mariadb`` - on line 12: ``DB_DATABASE=default`` - on line 13: ``DB_USERNAME=YOUR_SQL_USERNAME`` - on line 14: ``DB_PASSWORD=<PASSWORD>`` Save the changes and close the file. <br>Generate a laravel key and prepaire the DB: ```` php artisan key:generate php artisan migrate ```` All set! Visit with your browser the website by the following url: [http://localhost](http://localhost) ## 5. Important docker commando`s In order to keep control over your containers you'll need to know a list of important commands. So study them closely. These commands will only work if your located inside the laradock folder. ```` // Starting laradock containers docker-compose up -d nginx mariadb phpmyadmin // Checking if containers are running docker ps -a // Enter your workspace docker exec -it 'YOUR_COMPOSE_PROJECT_NAME'_workspace_1 bash // Leave your workspace exit // Stopping docker containers docker-compose down ```` Yaay! You finished setting up laravel - laradock container, this is entry level docker usage, if you want to know more about docker itself, go look up the official documentation on the website.
088a2fdda7b3af9da893bcee9bfd322f64faca97
[ "Markdown" ]
1
Markdown
rafaello104/laradock
9f3b57bf4b25f018e5a3f0d54508427cbb4eeada
4b8a1b94d3f819b8cb38b408a725b8854c8ca1e7
refs/heads/master
<repo_name>yansixing/blog<file_sep>/README.md # blog Powered by Hexo. http://floatingmuseum.net/
820bae1d52c747f8ac1b743454cccdf9ea25395a
[ "Markdown" ]
1
Markdown
yansixing/blog
19aa9e8ef9147bc8d816dc061df4452ed561a49a
ba421d4159bb87530c88bd96625ab06028938e7c
refs/heads/master
<repo_name>averybroderick/ruby-music-library-cli-v-000<file_sep>/lib/Artist.rb class Artist extend Concerns::Findable attr_accessor :name, :songs @@all = [] #Instance Methods def initialize(name) @name = name @songs = [] end def save @@all << self end def add_song(song) new_song = song self.songs.include?(new_song) ? nil : self.songs << new_song new_song.artist == nil ? new_song.artist = self : nil end def genres genre_collection = [] self.songs.each do |song| genre_collection.include?(song.genre) ? nil : genre_collection << song.genre end genre_collection end #Class Methods def self.all @@all end def self.create(name) artist = self.new(name) artist.save artist end def self.destroy_all @@all = [] end end <file_sep>/lib/Genre.rb class Genre extend Concerns::Findable attr_accessor :name, :songs @@all = [] #Instance Methods def initialize(name) @name = name @songs = [] end def save @@all << self end def artists artist_collection = [] self.songs.each do |song| artist_collection.include?(song.artist) ? nil : artist_collection << song.artist end artist_collection end #Class Methods def self.all @@all end def self.create(name) genre = self.new(name) genre.save genre end def self.destroy_all @@all = [] end end <file_sep>/lib/MusicImporter.rb require 'pry' class MusicImporter attr_accessor :path def initialize(path) @path = path end def files @files = Dir.entries(self.path).select{|mp3| mp3.end_with?("mp3")} end def import self.files.each{|file| Song.create_from_filename(file)} end end <file_sep>/lib/Song.rb class Song extend Concerns::Findable attr_accessor :name attr_reader :artist, :genre @@all = [] #Instance Methods def initialize(name, artist=nil, genre=nil) @name = name if artist self.artist=(artist) end if genre self.genre=(genre) end end def save @@all << self end def artist=(artist) @artist = artist self.artist.add_song(self) end def genre=(genre) @genre = genre if self.genre.songs.include?(self) == false self.genre.songs << self end end #Class Methods def self.all @@all end def self.create(name) song = self.new(name) song.save song end def self.destroy_all @@all = [] end def self.find_by_name(name) self.all.detect{|instance| instance.name == name} end def self.find_or_create_by_name(name) self.find_by_name(name) ? self.find_by_name(name) : self.create(name) end def self.new_from_filename(filename) file = filename.split(" - ") name = file[1] artist = Artist.find_or_create_by_name(file[0]) genre = Genre.find_or_create_by_name(file[2][0...-4]) self.new(name, artist, genre) end def self.create_from_filename(filename) self.new_from_filename(filename).save end end
f689c9f2e296033e51af25dbcc2676b828899fe4
[ "Ruby" ]
4
Ruby
averybroderick/ruby-music-library-cli-v-000
1b8731802b93efffbd3099bcaf5abb56ad96b189
a31b8734f2020648f1017e60a104d78cbe60fe3c
refs/heads/master
<repo_name>GubarSerg/fabrics<file_sep>/src/scss/layout/footer.scss .footer__contact-block { background-color: color(secondary-grey); } .contacts { @media screen and (max-width: 320px) { text-align: center; margin-bottom: 20px; } @media screen and (min-width: 1200px) { width: 240px; } } .contacts__title { @extend %title-sett; font-family: "CormorantUnicase"; font-weight: 500; font-size: 28px; @media screen and (min-width: 1200px) { margin-bottom: 30px; } } .contacts__text { @extend %base-text-sett; @media screen and (min-width: 1200px) { font-size: 12px; margin-bottom: 10px; } } .contacts__address { @extend %base-text-sett; display: flex; flex-direction: column; font-style: normal; @media screen and (min-width: 1200px) { font-size: 12px; } } .contacts__link { text-decoration: none; color: color(semi-grey); } .about-us { display: flex; flex-direction: column; align-items: center; @media screen and (max-width: 320px) { margin-bottom: 20px; } @media screen and (min-width: 1200px) { width: 74px; align-items: flex-start; } } .about-us__title { @extend %title-sett; font-family: "Roboto"; font-weight: 300; font-size: 22px; @media screen and (min-width: 1200px) { font-size: 18px; margin-bottom: 34px; } } .about-us__link { @extend %link-sett; } .questions { display: flex; flex-direction: column; align-items: center; @media screen and (max-width: 320px) { margin-bottom: 20px; } @media screen and (min-width: 1200px) { width: 174px; align-items: flex-start; } } .questions__title { @extend %title-sett; font-family: "Roboto"; font-weight: 300; font-size: 22px; @media screen and (min-width: 1200px) { font-size: 18px; margin-bottom: 34px; } } .questions__link { @extend %link-sett; } .join { margin-bottom: 20px; @media screen and (min-width: 1200px) { width: 194px; } } .join__title { @extend %title-sett; text-align: center; font-family: "Roboto"; font-weight: 300; font-size: 22px; @media screen and (min-width: 1200px) { font-size: 18px; margin-bottom: 34px; } } .join__inner { display: flex; justify-content: center; @media screen and (min-width: 1200px) { justify-content: left; padding-left: 12px; } } .join__icon { cursor: pointer; width: 30px; height: 30px; &:nth-child(1) { margin-right: 18px; } } .news { @media screen and (max-width: 320px) { text-align: center; } @media screen and (min-width: 1200px) { width: 212px; } } .news__title { @extend %title-sett; font-family: "Roboto"; font-weight: 300; font-size: 22px; @media screen and (min-width: 1200px) { font-size: 18px; margin-bottom: 34px; } } .news__text { @extend %base-text-sett; margin-bottom: 10px; @media screen and (min-width: 1200px) { font-size: 12px; margin-bottom: 18px; } } .news__btn { background-color: transparent; border: none; cursor: pointer; font-family: "Roboto"; font-weight: 500; font-size: 16px; color: color(primary-white); padding: 14px 47px; @media screen and (min-width: 1200px) { font-size: 12px; } } .news__icon { cursor: pointer; width: 18px; padding: 12px; border-right: 0.1px solid color(secondary-grey); } .news__box { display: flex; align-items: center; background-color: color(semi-grey); @media screen and (max-width: 320px) { width: 235px; margin: 0 auto; } } .footer__block { background-color: color(semi-grey); color: color(primary-grey); } .footer__copyright { font-family: "Roboto"; font-weight: 500; font-size: 16px; display: flex; justify-content: center; @media screen and (max-width: 320px) { text-align: center; } @media screen and (min-width: 1200px) { font-size: 12px; } } .copyright-icon { margin-right: 5px; } .pdb-10 { padding-bottom: 10px; @media screen and (min-width: 1200px) { padding: 18px 0; } } .inner-block { @media screen and (min-width: 1200px) { display: flex; justify-content: space-between; align-items: baseline; padding: 96px 0 72px; } } <file_sep>/src/scss/helpers/placeholders.scss %wrapper-sett { margin: 0 auto; width: 320px; box-sizing: border-box; padding: 10px 10px 20px 10px; } %title-sett { text-transform: uppercase; color: color(semi-grey); margin-bottom: 10px; } %base-text-sett { font-family: "Roboto"; font-weight: 300; font-size: 16px; line-height: 1.75; color: color(semi-grey); } %link-sett { font-family: "Roboto"; font-weight: 300; font-size: 16px; line-height: 1.5; height: 24px; text-decoration: none; color: color(semi-grey); &::after { content: ""; display: none; width: 100%; height: 1px; background-color: color(semi-grey); } &:hover::after { display: block; } @media screen and (min-width: 1200px) { font-size: 12px; line-height: 1.2; height: 22px; } }<file_sep>/src/scss/layout/header.scss .header { background-color: color(dark-grey); &__wrapper { padding: 0; text-align: center; @media screen and (min-width: 1200px) { @include flex_block(flex, space-between, center); width: 1200px; } @media screen and (min-width: 1600px) { width: 1600px; } } &__btn { width: 0px; height: 0px; position: absolute; z-index: 20; top: 36px; left: 20px; border: none; cursor: pointer; outline: none; @media screen and (min-width: 1200px) { display: none; } &::before, &::after { display: block; content: ""; width: 17px; height: 3px; } &::before { border-top: 1px solid color(light-grey); } &::after { border-bottom: 1px solid color(light-grey); } &:checked::after { transform: rotate(45deg) translate(-1.5px, -3px); } &:checked::before { transform: rotate(-45deg) translate(-1.5px, 3px); } &~nav { @media screen and (max-width: 1199px) { transition: height 600ms ease; height: 0; top: 90px; overflow: hidden; } } &:checked~nav { transition: height 600ms ease; height: 300px; } } &__logo { @include font_style('CormorantUnicase', 28px, 500, 80px, uppercase, map-get($map: $colors, $key: light-grey)); text-decoration: none; @media screen and (min-width: 1200px) { padding: 0; } } &__nav { @media screen and (min-width: 1200px) { @include flex_block(flex, space-between); width: 800px; } @media screen and (min-width: 1600px) { width: 1200px; } } } .menu { padding: 20px 0px; margin: 0 auto; width: 85%; border-top: 1px solid color(semi-grey); border-bottom: 1px solid color(semi-grey); margin-bottom: 30px; @media screen and (min-width: 1200px) { @include flex_block(flex, space-between); padding: 0px; width: 474px; margin: 0; border: 0; } &__link { @include font_style('Roboto', 16px, 300, 36px, uppercase, map-get($map: $colors, $key: light-grey)); position: relative; text-decoration: none; @media screen and (min-width: 1200px) { font-size: 12px; } &:not(:last-child) { margin-right: 10px; } &::after { position: absolute; left: 0; top: 20px; content: ""; opacity: 0; height: 1px; width: 100%; background-color: color(light-grey); } &:hover::after { opacity: 1; } } } .caret_down { padding: 0; border: none; width: 8px; height: 8px; background-color: transparent; cursor: pointer; } .registration { @include flex_block(flex, center, center); margin: auto; width: 270px; @media screen and (min-width: 1200px) { margin: 0; justify-content: flex-end; } &__account { display: flex; margin-right: 20px; } &__shop { @include flex_block(flex, space-between); position: relative; width: 60px; } &__icons { position: relative; width: 18px; height: 18px; } &__active { display: none; padding-left: 7px; & a { @include font_style('Roboto', 16px, 300, 20px, none, map-get($map: $colors, $key: light-grey)); text-decoration: none; @media screen and (min-width: 1200px) { font-size: 12px; line-height: 14px; } } } &__active-signin { margin-right: 10px; } &__active-signup { padding-left: 14px; border-left: 1px solid color(section-text); } } .heart-icon { display: none; } .shop-icon:first-child:hover .heart-icon { display: block; position: absolute; bottom: 0px; } .shop-icon::after { position: absolute; bottom: 12px; padding-left: 5px; content: "0"; width: 14px; height: 14px; @include font_style('Roboto', 10px, 300, 12px, none, map-get($map: $colors, $key: light-grey)); } .registration__account:hover .registration__active { display: block; } <file_sep>/src/scss/styles.scss @import 'normalize'; @import 'helpers/colors'; @import 'helpers/mixins'; @import 'helpers/placeholders'; @import 'helpers/variables'; @import 'helpers/fonts'; @import 'base/custom-reset'; @import 'base/wrappers'; @import 'layout/footer'; @import 'layout/second-section'; @import 'layout/third-section'; @import 'layout/header'; @import 'layout/first-section'; @import 'layout/fourth-section'; <file_sep>/src/scss/layout/first-section.scss .first-section { text-align: center; padding: 50px 0px 40px; @media screen and (min-width: 1200px) { @include flex_block(flex, space-between, center); padding-bottom: 230px; } &__title { @include font_style('Roboto', 14px, 400, 16px, uppercase, map-get($map: $colors, $key: semi-grey)); @media screen and (min-width: 1200px) { font-size: 12px; line-height: 14px; } } &__subtitle { @include font_style('Roboto', 23px, 300, 60px, map-get($map: $colors, $key: semi-grey)); margin-bottom: 30px; @media screen and (min-width: 1200px) { margin-bottom: 0; } } &__img { width: 290px; margin: 0 auto; @media screen and (min-width: 1200px) { @include flex_block(flex, space-between); width: 900px; margin: 0; } } &__img-item { margin-bottom: 10px; @media screen and (min-width: 1200px) { margin-bottom: 0; &:not(:last-child) { margin-right: 20px; } } } } <file_sep>/src/scss/layout/fourth-section.scss .fourth-section { @media screen and (min-width: 1200px) { width: 1040px; padding-bottom: 175px; margin: 100px auto 0; display: flex; } } .box-information { @media screen and (min-width: 1200px) { flex-basis: 50%; } } .sec-img-box { display: inline-block; text-align: center; padding: 0 50px 0 50px; margin-bottom: 15px; @media screen and (min-width: 1200px) { padding: 0; margin: 35px 0 52px; } } .text-box-info { text-align: center; @media screen and (min-width: 1200px) { text-align: left; width: 360px; } } .title-name { @include font_style('Roboto', 12px, 500, 14px , uppercase, map-get($map: $colors, $key: semi-grey)); margin-bottom: 9px; @media screen and (min-width: 1200px) { margin-bottom: 40px; } } .information-box { @include font_style('Roboto', 18px, 300, 30px , none, map-get($map: $colors, $key: section-text)); } .textblock_link { @include font_style('Roboto', 12px, 500, 15px , none, map-get($map: $colors, $key: semi-grey)); padding-top: 28px; padding-bottom: 8px; text-decoration: none; display: inline-block; cursor: pointer; &::after { content: ""; display: block; width: 100%; height: 2px; background-color: transparent; } &:hover::after { background-color: color(semi-grey); } } .box-list-img { @media screen and (max-width: 400px) { width:267px; margin: 0 auto; } @media screen and (min-width: 1200px) { flex-basis: 50%; } } .img-box-list { @media screen and (min-width: 1200px) { position: relative; } } .photo-list { margin-bottom: 9px; @media screen and (min-width: 1200px) { position: absolute; margin-bottom: 0px; } } .picture1 { @media screen and (min-width: 1200px) { width: 313px; position: absolute; top: 20px; left: 0; } } .picture2 { @media screen and (min-width: 1200px) { width: 267px; position: absolute; top: 0px; left: 200px; } } .picture3 { @media screen and (min-width: 1200px) { width: 271px; top: 379px; left: 250px; } } <file_sep>/src/scss/helpers/colors.scss $colors: ( primary-black: #000000, primary-grey: #717171, semi-grey: #333333, dark-grey: #222222, light-grey: #dddddd, secondary-grey: #efefef, primary-white: #ffffff, section-text: #444444 ); @function color($key) { @if map-has-key($map: $colors, $key: $key) { @return map-get($map: $colors, $key: $key); } @return null; }
b3897e43d5da47bb6f25b29444cd58022180f64c
[ "SCSS" ]
7
SCSS
GubarSerg/fabrics
4101d61c5c4786a44ba31f9da3ab4f97c9c3d237
7e9832cd42f49c29f5c086b44c9734ed555aa021
refs/heads/master
<repo_name>les113/gttwo_mob<file_sep>/index.php <?php require_once('../connections/cardealer.php'); ?> <?php /* page content */ $colname_rs_pagecontent = "-1"; if (isset($_GET['pageid'])) { $colname_rs_pagecontent = (get_magic_quotes_gpc()) ? $_GET['pageid'] : addslashes($_GET['pageid']); } mysql_select_db($database_cardealer, $cardealer); $query_rs_pagecontent = sprintf("SELECT * FROM pagecontent WHERE pageid = %s", $colname_rs_pagecontent); $rs_pagecontent = mysql_query($query_rs_pagecontent, $cardealer) or die(mysql_error()); $row_rs_pagecontent = mysql_fetch_assoc($rs_pagecontent); $totalRows_rs_pagecontent = mysql_num_rows($rs_pagecontent); ?> <?php // stocklist page $maxRows_rs_stocklist = 8; $pageNum_rs_stocklist = 0; if (isset($_GET['pageNum_rs_stocklist'])) { $pageNum_rs_stocklist = $_GET['pageNum_rs_stocklist']; } $startRow_rs_stocklist = $pageNum_rs_stocklist * $maxRows_rs_stocklist; mysql_select_db($database_cardealer, $cardealer); // latest stock $query_rs_stocklist = "SELECT * FROM vehicledata, fuel, registration, transmission, manufacturer WHERE vehicledata.fuel = fuel.fuelID AND vehicledata.registration = registration.RegistrationID AND vehicledata.transmission = transmission.transmissionID AND vehicledata.manufacturer = manufacturer.manufacturerID ORDER BY price DESC"; $query_limit_rs_stocklist = sprintf("%s LIMIT %d, %d", $query_rs_stocklist, $startRow_rs_stocklist, $maxRows_rs_stocklist); $rs_stocklist = mysql_query($query_limit_rs_stocklist, $cardealer) or die(mysql_error()); $row_rs_stocklist = mysql_fetch_assoc($rs_stocklist); if (isset($_GET['totalRows_rs_stocklist'])) { $totalRows_rs_stocklist = $_GET['totalRows_rs_stocklist']; } else { $all_rs_stocklist = mysql_query($query_rs_stocklist); $totalRows_rs_stocklist = mysql_num_rows($all_rs_stocklist); } $totalPages_rs_stocklist = ceil($totalRows_rs_stocklist/$maxRows_rs_stocklist)-1; ?> <?php // detail page $colname_rs_vehicledetails = "-1"; if (isset($_GET['vehicleID'])) { $colname_rs_vehicledetails = (get_magic_quotes_gpc()) ? $_GET['vehicleID'] : addslashes($_GET['vehicleID']); } mysql_select_db($database_cardealer, $cardealer); $query_rs_vehicledetails = sprintf("SELECT * FROM vehicledata, fuel, registration, manufacturer, transmission, bodytype WHERE vehicleID = %s AND vehicledata.fuel = fuel.fuelID AND vehicledata.registration = registration.RegistrationID AND vehicledata.manufacturer = manufacturer.manufacturerID AND vehicledata.transmission = transmission.transmissionID AND vehicledata.bodytype = bodytype.bodytypeID", $colname_rs_vehicledetails); $rs_vehicledetails = mysql_query($query_rs_vehicledetails, $cardealer) or die(mysql_error()); $row_rs_vehicledetails = mysql_fetch_assoc($rs_vehicledetails); //$totalRows_rs_vehicledetails = mysql_num_rows($rs_vehicledetails); ?> <?php //Truncate description function myTruncate($string, $limit, $break=".", $pad="...") { // return with no change if string is shorter than $limit if(strlen($string) <= $limit) return $string; // is $break present between $limit and the end of the string? if(false !== ($breakpoint = strpos($string, $break, $limit))) { if($breakpoint < strlen($string) - 1) { $string = substr($string, 0, $breakpoint) . $pad; } } return $string; } ?> <?php // Gallery mysql_select_db($database_cardealer, $cardealer); $query_rs_gallery = "SELECT * FROM gallery"; $rs_gallery = mysql_query($query_rs_gallery, $cardealer) or die(mysql_error()); $row_rs_gallery = mysql_fetch_assoc($rs_gallery); $totalRows_rs_gallery = mysql_num_rows($rs_gallery); /* recordset paging */ $rs_gallery = mysql_query($query_rs_gallery, $cardealer) or die(mysql_error()); $row_rs_gallery = mysql_fetch_assoc($rs_gallery); $totalRows_rs_gallery = mysql_num_rows($rs_gallery); $maxRows_rs_gallery = 15; $pageNum_rs_gallery = 0; if (isset($_GET['pageNum_rs_gallery'])) { $pageNum_rs_gallery = $_GET['pageNum_rs_gallery']; } $startRow_rs_gallery = $pageNum_rs_gallery * $maxRows_rs_gallery; $colname_rs_gallery = "-1"; if (isset($_POST['price'])) { $colname_rs_gallery = (get_magic_quotes_gpc()) ? $_POST['price'] : addslashes($_POST['price']); } mysql_select_db($database_cardealer, $cardealer); $query_limit_rs_gallery = sprintf("%s LIMIT %d, %d", $query_rs_gallery, $startRow_rs_gallery, $maxRows_rs_gallery); $rs_gallery = mysql_query($query_limit_rs_gallery, $cardealer) or die(mysql_error()); $row_rs_gallery = mysql_fetch_assoc($rs_gallery); if (isset($_GET['totalRows_rs_gallery'])) { $totalRows_rs_gallery = $_GET['totalRows_rs_gallery']; } else { $all_rs_gallery = mysql_query($query_rs_gallery); $totalRows_rs_gallery = mysql_num_rows($all_rs_gallery); } $totalPages_rs_gallery = ceil($totalRows_rs_gallery/$maxRows_rs_gallery)-1; $queryString_rs_gallery = ""; if (!empty($_SERVER['QUERY_STRING'])) { $params = explode("&", $_SERVER['QUERY_STRING']); $newParams = array(); foreach ($params as $param) { if (stristr($param, "pageNum_rs_gallery") == false && stristr($param, "totalRows_rs_gallery") == false) { array_push($newParams, $param); } } if (count($newParams) != 0) { $queryString_rs_gallery = "&" . htmlentities(implode("&", $newParams)); } } $queryString_rs_gallery = sprintf("&totalRows_rs_gallery=%d%s", $totalRows_rs_gallery, $queryString_rs_gallery); ?> <!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <meta name="viewport" content="initial-scale=1.0, width=device-width"/> <!-- for iphone --> <title>GT Two</title> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script> <script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script> <link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" /> <link rel="stylesheet" href="style.css" /> </head> <body> <!--- home page --> <div data-role="page" data-url="index.php" data-theme="a"> <div data-role="header"> <h1>GT Two - Prestige Cars<br/>Cranleigh, Surrey</h1> </div> <div data-role="content"> <a href="index.php"> <img src="images/logo.png" width="300" alt="GT Two Logo" style="padding-left:0px;" /> </a> <div id="home_mainimage" > <div> <div class="mainimage"> <img src="http://www.gttwo.com/images/mainimage1.jpg" alt="main image"/> </div> <div class="transbg"> <h1>Welcome to GT Two. Established in 2001 we have 35 years experience in the high performance and prestige car sectors.</h1> </div> </div> </div> <ul data-role="listview" data-inset="true"> <li><a href="index.php?pageid=2#Content" rel="external">About Us</a></li> <li><a href="#Stocklist">Current Stock</a></li> <li><a href="index.php?pageid=3#Content" rel="external">Finance</a></li> <li><a href="index.php?pageid=4#Content" rel="external">Car Finder</a></li> <li><a href="#Gallery">Gallery</a></li> <li><a href="#Contact">Contact Us</a></li> </ul> </div> <?php include('footer.php') ?> </div> <!-- content pages --> <div data-role="page" data-theme="a" id="Content"> <div data-role="header"> <h1><?php echo $row_rs_pagecontent['pagetitle']; ?></h1> </div> <div data-role="content"> <?php echo $row_rs_pagecontent['pagecontent']; ?> <h3><a href="#Contact">If you have any questions please contact us.</a></h3> </div> <?php include('footer.php') ?> </div> <!-- stocklist page --> <div data-role="page" data-url="index.php" data-theme="a" id="Stocklist"> <div data-role="header"> <h1>Stocklist</h1> </div> <div data-role="content"> <ul data-role="listview" data-inset="true" data-dividertheme="a"> <li data-role="list-divider">Our Used Cars</li> <?php $rs_stocklist_endRow = 8; $rs_stocklist_columns = 1; // number of columns $rs_stocklist_hloopRow1 = 0; // first row flag do { if($rs_stocklist_endRow == 0 && $rs_stocklist_hloopRow1++ != 0) echo ""; ?> <li> <a href="index.php?vehicleID=<?php echo $row_rs_stocklist['vehicleID']; ?>#Detail" rel="external" > <img src="http://www.gttwo.com/vehicledata/<?php echo $row_rs_stocklist['image1']; ?>" alt="<?php echo $row_rs_stocklist['title']; ?>" /> </a> <h3><a href="index.php?vehicleID=<?php echo $row_rs_stocklist['vehicleID']; ?>#Detail" rel="external" ><?php echo $row_rs_stocklist['title']; ?></a></h3> <p><strong>Registration: </strong><?php echo $row_rs_stocklist['regYear']; ?></p> <p><strong>Mileage: </strong><?php echo $row_rs_stocklist['mileage']; ?> Miles</p> <p><strong>Transmission: </strong><?php echo $row_rs_stocklist['transmission']; ?></p> <p><strong>Fuel: </strong><?php echo $row_rs_stocklist['fuel']; ?></p> <h5>Price: &pound;<?php echo number_format($row_rs_stocklist['price'],0); ?></h5> <p><a href="index.php?vehicleID=<?php echo $row_rs_stocklist['vehicleID']; ?>#Detail" rel="external" >More details..</a></p> <p>&nbsp;</p> </li> <?php $rs_stocklist_endRow++; if($rs_stocklist_endRow >= $rs_stocklist_columns) { ?> <?php $rs_stocklist_endRow = 0; } } while ($row_rs_stocklist = mysql_fetch_assoc($rs_stocklist)); if($rs_stocklist_endRow != 0) { while ($rs_stocklist_endRow < $rs_stocklist_columns) { echo("&nbsp;"); $rs_stocklist_endRow++; } echo(""); }?> </ul> </div> <?php include('footer.php') ?> </div> <!-- detail page --> <div data-role="page" data-theme="a" id="Detail"> <div data-role="header"> <h1>Vehicle Details</h1> </div> <div data-role="content"> <ul data-role="listview" data-inset="true" data-dividertheme="a"> <li data-role="list-divider"><?php echo $row_rs_vehicledetails['title']; ?></li> <p>&nbsp;</p> <?php $i = 1; while ($i <= 6) { if ($row_rs_vehicledetails['image'.$i] != NULL) {?> <div style="margin-bottom:10px"> <img src="http://www.gttwo.com/vehicledata/<?php echo $row_rs_vehicledetails['image'.$i]; ?>" alt="<?php echo $row_rs_vehicledetails['title'];?> thumbnail image" title="<?php echo $row_rs_vehicledetails['title']; ?>" class="detailimage"/> </div> <?php } $i++; }; ?> <h3><?php echo $row_rs_vehicledetails['title']; ?></h3> <p><strong>Registration: </strong><?php echo $row_rs_vehicledetails['regYear']; ?></p> <p><strong>Mileage: </strong><?php echo $row_rs_vehicledetails['mileage']; ?> Miles</p> <p><strong>Transmission: </strong><?php echo $row_rs_vehicledetails['transmission']; ?></p> <p><strong>Fuel: </strong><?php echo $row_rs_vehicledetails['fuel']; ?></p> <p><?php $shortdesc = myTruncate($row_rs_vehicledetails['description'], 100);echo "$shortdesc"; ?></p> <h4><strong>Price: </strong>&pound;<?php echo number_format($row_rs_vehicledetails['price'],0); ?></h4> <h3><a href="#Contact">contact us for further details of this vehicle.</a></h3> </ul> </div> <?php include('footer.php') ?> </div> <!-- gallery page --> <div data-role="page" data-theme="a" id="Gallery"> <div data-role="header"> <h1>Gallery</h1> </div> <div data-role="content"> <h1>Recently sold vehicles</h1> <?php do { ?> <div class="gallery"> <img src="http://www.gttwo.com/gallery/<?php echo $row_rs_gallery['image']; ?>" alt="<?php echo $row_rs_gallery['description']; ?>" /> <div class="cardesc"><h3><?php echo $row_rs_gallery['description']; ?></h3></div> </div> <?php } while ($row_rs_gallery = mysql_fetch_assoc($rs_gallery)); ?> </div> <?php include('footer.php') ?> </div> <!-- contact page --> <div data-role="page" data-theme="a" id="Contact"> <div data-role="header"> <h1>Contact Us</h1> </div> <div data-role="content"> <h1>Contact GT Two at:</h1> <p><strong>email: </strong><a href="mailto:<EMAIL>"><EMAIL></a><br/><br/> <strong>tel: </strong><a href="tel:01483548991"> 01483 548991</a><br/><br/> <strong>mob: </strong><a href="tel:07764460891"> 07764 460891</a></p> <p>GT TWO<br/> Stable Cottage<br/> Horsham Road<br/> Cranleigh<br/> Surrey<br/> GU6 8EJ</p> <p><strong>map: </strong><a href="https://www.google.co.uk/maps/place/Cranleigh,+Surrey+GU6+8EJ/@51.1292198,-0.471183,15z/data=!3m1!4b1!4m2!3m1!1s0x4875c47b8eb33e85:0x80d8f736f51db38?hl=en">click here</a></p> </div> <?php include('footer.php') ?> </div> <?php include('statcounter.php') ?> </body> </html> <?php mysql_free_result($rs_pagecontent); mysql_free_result($rs_stocklist); mysql_free_result($rs_vehicledetails); mysql_free_result($rs_gallery); ?><file_sep>/footer.php <div data-role="footer"> <h4>&copy; <?php echo date("Y"); ?></h4> <!--<h5><a href="http://www.gttwo.com">Desktop Site</a></h5>--> </div>
9ccd8e9acaf6f0638b8bd8810a6656ee5603c468
[ "PHP" ]
2
PHP
les113/gttwo_mob
e40eea5f13d8552bc8ad4b94bd74af42276b1a86
43f459176feabdeb24dad7976d32d69d9898e20e
refs/heads/master
<file_sep><?php session_start(); ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <!--added favicon --> <link rel="apple-touch-icon" sizes="180x180" href="favicon/apple-touch-icon.png"> <link rel="icon" type="image/png" href="favicon/favicon-32x32.png" sizes="32x32"> <link rel="icon" type="image/png" href="favicon/favicon-16x16.png" sizes="16x16"> <link rel="manifest" href="favicon/manifest.json"> <link rel="mask-icon" href="favicon/safari-pinned-tab.svg" color="#5bbad5"> <meta name="theme-color" content="#ffffff"> <title> Park It App </title> <link rel="stylesheet" href="css/normalize.css"> <link rel="stylesheet" href="css/bootstrap.min.css"> <link rel="stylesheet" href="css/bootstrap-theme.css"> <link rel="stylesheet" href="css/font-awesome.min.css"> <link rel="stylesheet" href="css/custom.css"> <style> body { background-image: url("images/NYCracks.jpg"), url("images/NYCracks.jpg"); } </style> </head> <body> <div class="container"> <div class="row" id="row"> <div class="jumbotron" id="jumbotron"> <h1>For Fun Play Video Below!!</h1> <iframe src="https://player.vimeo.com/video/85770708" width="1100" height="360" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe> <p><a href="https://vimeo.com/85770708">Bicycle.mp4</a> from <a href="https://vimeo.com/markedphotography"><NAME></a> on <a href="https://vimeo.com">Vimeo</a>.</p> <p><a class="btn btn-primary btn-lg" href="index.php" role="button">Return to LogIn</a></p> </div> </div> </div> <div class="container"> <div class="row" id="row"> <div class="jumbotron" id="jumbotron"> <p><a class="btn btn-primary btn-lg" href="https://www.google.com/maps/search/bike+racks+maps/@40.6834452,-74.0268973,13z/data=!3m1!4b1" role="button">LOGOUT & RIDE SAFELY</a></p> <h1>PARK IT APP!!</h1> <img src="images/pic1.jpg" class="img-rounded" alt="pic1" width="404" height="236"> </div> </div> </div> <div class="container"> <div class="row"> <footer class="col-sm-12"> <p class="text-center">&copy; Copyright 2016</p> </footer> </div> </div> <script src="js/jquery.2.2.4.min.js"></script> <script src="js/bootstrap.js"></script> <script src="js/custom.js"></script> </body> </html><file_sep><?php session_start(); ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <!--added favicon --> <link rel="apple-touch-icon" sizes="180x180" href="favicon/apple-touch-icon.png"> <link rel="icon" type="image/png" href="favicon/favicon-32x32.png" sizes="32x32"> <link rel="icon" type="image/png" href="favicon/favicon-16x16.png" sizes="16x16"> <link rel="manifest" href="favicon/manifest.json"> <link rel="mask-icon" href="favicon/safari-pinned-tab.svg" color="#5bbad5"> <meta name="theme-color" content="#ffffff"> <title> Park It App </title> <link rel="stylesheet" href="css/normalize.css"> <link rel="stylesheet" href="css/bootstrap.min.css"> <link rel="stylesheet" href="css/bootstrap-theme.css"> <link rel="stylesheet" href="css/font-awesome.min.css"> <link rel="stylesheet" href="css/custom.css"> <style> body { background-image: url("images/NYCracks.jpg"), url("images/NYCracks.jpg"); } </style> </head> <body> <div class="container"> <div class="row" id="row"> <div class="jumbotron" id="jumbotron"> <h1>PARK IT APP!!</h1> <p>Use Park It App to find a bicycle rack anywhere on the map BUT PLEASE do not park your bike on Jack's house!! </p> <p>Park It App To Find A Bike Rack Near You.:</p> <img src="images/pic1.jpg" class="img-rounded" alt="pic1" width="404" height="236"> <p><a class="btn btn-primary btn-lg" href="index2.php" role="button">Log In and Map</a></p> </div> </div> </div> <div class="container"> <div class="row"> <footer class="col-sm-12"> <p class="text-center">&copy; Copyright 2016</p> </footer> </div> </div> <script src="js/jquery.2.2.4.min.js"></script> <script src="js/bootstrap.js"></script> <script src="js/custom.js"></script> </body> </html>
bf598661587f8d7716b86abafe529940856bc5a9
[ "PHP" ]
2
PHP
eju105/Park_It_app
5e90d81c7582130622aeccdf7945f7057dbfa36a
00575d793279a77799536c9998d84ebea4c30335
refs/heads/master
<repo_name>ZohaibS/NBA-Lineup-Optimization<file_sep>/README.md # NBA-Lineup-Optimization A short paper describing a method of optimizing roster rotations.
81f4b23110295edb85a97517328a2b09aa5fd2f7
[ "Markdown" ]
1
Markdown
ZohaibS/NBA-Lineup-Optimization
cbc680b1e5426eb418d785ce25ceaab1ed8482f9
d9a71a023f6299815fe1fc31cec3f0b719aa8e20
refs/heads/master
<repo_name>sparta-prog/iConnect<file_sep>/README.md ## how to use ``` npm install -> install all dependencies from package.json npm run dev Go to localhost:3000 ```
4080a0fa7c9f88c19b64d8a0ec45c6806e0871b9
[ "Markdown" ]
1
Markdown
sparta-prog/iConnect
c964bd6cc69e37f6eed9ea73accbdc2b00824dbe
642aa8cff61f15afa402c070af9a06da0bdabfa6
refs/heads/master
<file_sep>FROM node:10.15.1-alpine RUN mkdir -p /usr/src/app WORKDIR /usr/src/app COPY package*.json ./ RUN npm install --prod COPY . . EXPOSE 3050 CMD ["npm", "start"]
4a2b002cfeaf1833c63ac05d5fd5d467405f7af7
[ "Dockerfile" ]
1
Dockerfile
felipechagas/simple-nodejs-api
4d983b8ca5045ce3de443193a2aaa1550b2176b9
6bb9e55fd6125ff8840f7c5ca0eb6bc561fce6db
refs/heads/master
<repo_name>faathirmashar/ViewBindingBase<file_sep>/app/src/main/java/id/sharekom/materialdesign/LatihanFragment.kt package id.sharekom.materialdesign import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import id.sharekom.materialdesign.databinding.FragmentLatihanBinding class LatihanFragment : Fragment() { private var _binding: FragmentLatihanBinding? = null private val binding get() = _binding override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { _binding = FragmentLatihanBinding.inflate(inflater, container, false) return binding?.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) with(binding){ } } override fun onDestroy() { super.onDestroy() _binding = null } }
671bc42c7a8d461a80cfe2cd9677bea366bd6cf1
[ "Kotlin" ]
1
Kotlin
faathirmashar/ViewBindingBase
ec3e49116e2a2349fff43b3e5208f5285c0fd00d
4c5b9f076ae4512df4ab17d9c57437e90f870727
refs/heads/master
<repo_name>moophlo/MufloCoin<file_sep>/build/build.h // No build information available #define BUILD_DATE "2013-12-23 12:00:37 -0500"
ec4389c2d5d191ae5b127526d549aa4a359aa9aa
[ "C" ]
1
C
moophlo/MufloCoin
a4dc662afaf848e2ed1c26f2c1a0941b8ae98b2f
51a23224a79721ea413e59235f233077e04be374
refs/heads/master
<repo_name>1600383075/REMD-MWNN<file_sep>/README.md # IEMD-MWNN #利用改进EMD与记忆性WNN来预测单维数据 #WNN单隐含层是只有单隐含层的WNN网络,WNN5是再WNN4的基础上进行改进,使其变成多隐含层WNN #EMD数据分解是将单维高频数据分解为多个低频数据
4dd69d30a2aff4b80df9d471f73f7133e64e93a1
[ "Markdown" ]
1
Markdown
1600383075/REMD-MWNN
0929614ab2d5e9c4964a5e3297f98cf75918c0e4
e86444a1d3820ffe2ee472dd7236e351671ac624
refs/heads/master
<file_sep># Basic Jest Tests ## About This repository contains some basic tests using Jest. This has served as an introduction for me to Jest and automated testing in general. From here on I plan on getting more comfortable with Jest and including testing in all future projects. <file_sep>// Format and compare two strings. If true then they are anagrams. const isAnagram = (str1, str2) => formatString(str1) === formatString(str2); // Prepare string for comparison by removing white space, making characters lowercase and sorting the characters. const formatString = str => str .replace(/[^\w]/g, '') .toLowerCase() .split('') .sort() .join(''); module.exports = isAnagram;
61cf87ccb18d8fcf41d4d0a3db99623e70438c8a
[ "Markdown", "JavaScript" ]
2
Markdown
Pingrash/jest-tests
c4cd7a736d6a7dbe860ca09d090d7ecd1ca62563
a2b612f1105266692ea0959d4939cc1fffeaad0a
refs/heads/master
<repo_name>botalov/WeatherGDG2<file_sep>/app/src/main/java/com/example/botalovns/weathergdg/helpers/WebHelper.java package com.example.botalovns.weathergdg.helpers; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; public class WebHelper { public static String GoToURL(String url, String request) { String outtext1=""; url = url.replaceFirst("https", "http"); HttpURLConnection urlConnection = null; try { urlConnection = (HttpURLConnection) new URL(url).openConnection(); urlConnection.setDoOutput(true); urlConnection.setDoInput(true); PrintWriter out = new PrintWriter(urlConnection.getOutputStream()); out.println(request); out.close(); InputStream tmptmp = urlConnection.getInputStream(); InputStream in = new BufferedInputStream(tmptmp); outtext1 = IStoString(in); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { urlConnection.disconnect(); } return outtext1; } private static String IStoString(InputStream in) { BufferedReader br = new BufferedReader(new InputStreamReader(in)); StringBuilder sb = new StringBuilder(); String line; try { while ((line = br.readLine()) != null) { sb.append(line); } } catch (IOException e) { e.printStackTrace(); } return sb.toString(); } public static boolean isNetworkAvailable(Context context) { try { ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo(); return activeNetworkInfo != null && activeNetworkInfo.isConnected(); } catch (Exception exc){ return false; } } } <file_sep>/app/src/main/java/com/example/botalovns/weathergdg/common/DefinitionLocationAsync.java package com.example.botalovns.weathergdg.common; import android.app.ProgressDialog; import android.content.Context; import android.os.AsyncTask; import android.util.Log; import android.widget.Toast; import com.example.botalovns.weathergdg.R; import com.example.botalovns.weathergdg.helpers.LocationHelper; import com.example.botalovns.weathergdg.models.CityModel; import com.example.botalovns.weathergdg.models.WeatherModel; public class DefinitionLocationAsync extends AsyncTask { public AsyncResponseLocation delegate; public void setDelegate(AsyncResponseLocation delegate){ this.delegate = delegate; } private ProgressDialog dialogGetLocation; private Context context; public DefinitionLocationAsync(Context context){ this.context = context; } @Override protected void onPreExecute() { try { if(dialogGetLocation==null && context!=null) { dialogGetLocation = new ProgressDialog(context); dialogGetLocation.setMessage(context.getString(R.string.message_dialog_get_location)); dialogGetLocation.setIndeterminate(true); dialogGetLocation.setCancelable(false); dialogGetLocation.setCanceledOnTouchOutside(false); dialogGetLocation.show(); } } catch (Exception exc){ Log.println(1, "", exc.toString()); } } @Override protected Object doInBackground(Object[] objects) { return LocationHelper.getCurrentLocation(context); } @Override protected void onPostExecute(final Object result) { if(dialogGetLocation!=null){ dialogGetLocation.dismiss(); } if(result==null){ Toast.makeText( context, context.getString(R.string.error_get_location), Toast.LENGTH_LONG ).show(); }else{ final CityModel city = (CityModel)result; DefinitionWeatherAsync definitionWeatherAsync = new DefinitionWeatherAsync(city, context); definitionWeatherAsync.setDelegate(new DefinitionWeatherAsync.AsyncResponseWeather() { @Override public void processFinish(WeatherModel output) { city.setWeather(output); delegate.processFinish(city); } }); definitionWeatherAsync.execute(); } } public interface AsyncResponseLocation { void processFinish(CityModel output); } }<file_sep>/app/src/main/java/com/example/botalovns/weathergdg/common/AsyncResponse.java package com.example.botalovns.weathergdg.common; import com.example.botalovns.weathergdg.models.CityModel; import java.util.ArrayList; public interface AsyncResponse { void processFinish(ArrayList<CityModel> output); } <file_sep>/app/src/main/java/com/example/botalovns/weathergdg/common/SearchCityListAdapter.java package com.example.botalovns.weathergdg.common; import android.content.Context; import android.content.Intent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import com.example.botalovns.weathergdg.ListCitiesActivity; import com.example.botalovns.weathergdg.R; import com.example.botalovns.weathergdg.helpers.DatabaseHelper; import com.example.botalovns.weathergdg.models.CityModel; import com.example.botalovns.weathergdg.models.WeatherModel; import java.util.ArrayList; public class SearchCityListAdapter extends BaseAdapter { Context ctx; LayoutInflater lInflater; ArrayList<CityModel> objects; DatabaseHelper databaseHelper; public SearchCityListAdapter(Context context, ArrayList<CityModel> products) { ctx = context; objects = products; lInflater = (LayoutInflater) ctx .getSystemService(Context.LAYOUT_INFLATER_SERVICE); databaseHelper = new DatabaseHelper(context); } // кол-во элементов @Override public int getCount() { return objects.size(); } // элемент по позиции @Override public Object getItem(int position) { return objects.get(position); } // id по позиции @Override public long getItemId(int position) { return position; } // пункт списка @Override public View getView(int position, View convertView, ViewGroup parent) { // View view = convertView; if (view == null) { view = lInflater.inflate(R.layout.item_city_search, parent, false); } final CityModel city = getCity(position); ((TextView) view.findViewById(R.id.nameCity)).setText(city.getName()); view.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if(!databaseHelper.existsCity(city.getName())) { DefinitionWeatherAsync definitionWeatherAsync = new DefinitionWeatherAsync(city, ctx); definitionWeatherAsync.setDelegate(new DefinitionWeatherAsync.AsyncResponseWeather() { @Override public void processFinish(WeatherModel output) { city.setWeather(output); databaseHelper.addCity(city); Intent intent = new Intent(ctx, ListCitiesActivity.class); ctx.startActivity(intent); } }); definitionWeatherAsync.execute(); } } }); return view; } CityModel getCity(int position) { return ((CityModel) getItem(position)); } }<file_sep>/app/src/main/java/com/example/botalovns/weathergdg/ListCitiesActivity.java package com.example.botalovns.weathergdg; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.ContextMenu; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import android.widget.TextView; import com.example.botalovns.weathergdg.common.CityListAdapter; import com.example.botalovns.weathergdg.helpers.DatabaseHelper; import com.example.botalovns.weathergdg.models.CityModel; import java.util.ArrayList; public class ListCitiesActivity extends AppCompatActivity { DatabaseHelper databaseHelper; ListView listView = null; TextView messageNotCities = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_list_cities); messageNotCities = (TextView)findViewById(R.id.notCitiesMessage); listView = (ListView)findViewById(R.id.listCities); registerForContextMenu(listView); //updateWeather(); } @Override public void onResume(){ super.onResume(); databaseHelper = new DatabaseHelper(this); ArrayList<CityModel> cities = databaseHelper.getCities(); updateListView(cities); } @Override public void onBackPressed() { super.onBackPressed(); Intent intent = new Intent(this, MainActivity.class); startActivity(intent); } //Выхов активити для поиска нового города public void onAddNewCity(View view){ Intent intent = new Intent(this, SearchCityActivity.class); startActivity(intent); } private void updateListView(ArrayList<CityModel> cities){ CityListAdapter cityListAdapter = new CityListAdapter(this, cities); if(listView!=null && cityListAdapter!=null && cities.size()>0){ listView.setAdapter(cityListAdapter); listView.setVisibility(View.VISIBLE); messageNotCities.setVisibility(View.GONE); } else{ listView.setVisibility(View.GONE); messageNotCities.setVisibility(View.VISIBLE); } } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) { if (v.getId()==R.id.listCities) { AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)menuInfo; menu.setHeaderTitle(((CityModel)listView.getAdapter().getItem(info.position)).getName()); String[] menuItems = {"Удалить"};//getResources().getStringArray(R.array.menu); for (int i = 0; i<menuItems.length; i++) { menu.add(Menu.NONE, i, i, menuItems[i]); } } } @Override public boolean onContextItemSelected(MenuItem item) { AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo(); int menuItemIndex = item.getItemId(); String[] menuItems = {"Удалить"};// getResources().getStringArray(R.array.menu); String menuItemName = menuItems[menuItemIndex]; //String listItemName = Countries[info.position]; CityModel city = (CityModel)listView.getAdapter().getItem(info.position); switch (menuItemIndex){ case 0:{ if(databaseHelper==null){ databaseHelper=new DatabaseHelper(this); } databaseHelper.deleteCity(city); updateListView(databaseHelper.getCities()); break; } } /*TextView text = (TextView)findViewById(R.id.footer); text.setText(String.format("Selected %s for item %s", menuItemName, listItemName));*/ return true; } } <file_sep>/app/src/main/java/com/example/botalovns/weathergdg/helpers/WeatherHelper.java package com.example.botalovns.weathergdg.helpers; import android.content.Context; import com.example.botalovns.weathergdg.R; import com.example.botalovns.weathergdg.common.DefinitionWeatherAsync; import com.example.botalovns.weathergdg.enums.CloudinessEnum; import com.example.botalovns.weathergdg.enums.DirectionOfTheWindEnum; import com.example.botalovns.weathergdg.models.CityModel; import com.example.botalovns.weathergdg.models.CoordinatesModel; import com.example.botalovns.weathergdg.models.WeatherModel; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; public class WeatherHelper { public static WeatherModel getWeather(CityModel city, Context context) { WeatherModel resultWeather = new WeatherModel(); // получаем данные с внешнего ресурса try { URL url = new URL(createAddress(city.getCoordinates(), context)); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.connect(); InputStream inputStream = urlConnection.getInputStream(); StringBuffer buffer = new StringBuffer(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); String line = ""; while ((line = reader.readLine()) != null) { buffer.append(line); } String resultJson = buffer.toString(); int temp = -273; int pressure = 0; int powerWind = 0; DirectionOfTheWindEnum windDirection = DirectionOfTheWindEnum.NONE; CloudinessEnum cloudinessEnum = CloudinessEnum.NONE; try { JSONObject jsonObject = new JSONObject(resultJson); try { JSONObject mainJsonObject = jsonObject.getJSONObject("main"); temp = (int) mainJsonObject.getDouble("temp"); pressure = (int) mainJsonObject.getDouble("pressure"); pressure = ConvertHelper.hPaTOmmHg(pressure); } catch (JSONException je) { je.printStackTrace(); } try{ JSONObject weatherJsonObject = jsonObject.getJSONArray("weather").getJSONObject(0); int cloudiness = weatherJsonObject.getInt("id"); cloudinessEnum = ConvertHelper.getCloudinessEnum(cloudiness); } catch (JSONException je){ je.printStackTrace(); } try { JSONObject windObject = jsonObject.getJSONObject("wind"); powerWind = (int) windObject.getDouble("speed"); windDirection = ConvertHelper.degTOdirectionWind(windObject.getDouble("deg")); } catch (JSONException je) { je.printStackTrace(); } } catch (Exception e) { e.printStackTrace(); } resultWeather.setTemp(temp); resultWeather.setPressure(pressure); resultWeather.setPowerWind(powerWind); resultWeather.setDirectionOfTheWind(windDirection); resultWeather.setCloudiness(cloudinessEnum); } catch (Exception exc) { exc.printStackTrace(); return null; } return resultWeather; } private static String createAddress(CoordinatesModel coordinates, Context context) { String result = ""; result += context.getString(R.string.weather_address); result += ("lat=" + coordinates.getLatitude()); result += ("&lon=" + coordinates.getLongitude()); result += ("&appid=" + context.getString(R.string.weather_key)); result += "&units=metric"; return result; } public static void updateWeatherInAllCities(Context context) { final DatabaseHelper databaseHelper = new DatabaseHelper(context); ArrayList<CityModel> cities = databaseHelper.getCities(); for (final CityModel city : cities) { final DefinitionWeatherAsync definitionWeatherAsync = new DefinitionWeatherAsync(city, context); definitionWeatherAsync.setDelegate(new DefinitionWeatherAsync.AsyncResponseWeather() { @Override public void processFinish(WeatherModel output) { city.setWeather(output); databaseHelper.updateCity(city); //listView.invalidateViews(); } }); definitionWeatherAsync.execute(); } } public static void updateWeather(Context context, final CityModel city) { final DatabaseHelper databaseHelper = new DatabaseHelper(context); ArrayList<CityModel> cities = databaseHelper.getCities(); final DefinitionWeatherAsync definitionWeatherAsync = new DefinitionWeatherAsync(city, context); definitionWeatherAsync.setDelegate(new DefinitionWeatherAsync.AsyncResponseWeather() { @Override public void processFinish(WeatherModel output) { city.setWeather(output); databaseHelper.updateCity(city); } }); definitionWeatherAsync.execute(); } } <file_sep>/app/src/main/java/com/example/botalovns/weathergdg/MainActivity.java package com.example.botalovns.weathergdg; import android.Manifest; import android.content.Intent; import android.content.pm.PackageManager; import android.content.res.Configuration; import android.os.Bundle; import android.os.Handler; import android.support.v4.app.ActivityCompat; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.Gravity; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.example.botalovns.weathergdg.common.DefinitionLocationAsync; import com.example.botalovns.weathergdg.enums.CloudinessEnum; import com.example.botalovns.weathergdg.helpers.ConvertHelper; import com.example.botalovns.weathergdg.helpers.DatabaseHelper; import com.example.botalovns.weathergdg.helpers.WeatherHelper; import com.example.botalovns.weathergdg.helpers.WebHelper; import com.example.botalovns.weathergdg.models.CityModel; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { private static final int REQUEST_LOCALE = 1; private static String[] PERMISSIONS_LOCALE = { Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.INTERNET, Manifest.permission.ACCESS_NETWORK_STATE }; @Override public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) { Intent intent = getIntent(); finish(); startActivity(intent); } boolean changeOrientation = false; String cityName = ""; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); changeOrientation = false; try { cityName = getIntent().getStringExtra("city_name"); } catch (Exception e){ e.printStackTrace(); } } @Override public void onResume(){ super.onResume(); if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions( this, PERMISSIONS_LOCALE, REQUEST_LOCALE ); } if(!changeOrientation) { try { if (cityName == null || cityName.equals("")) { if (WebHelper.isNetworkAvailable(this)) { DefinitionLocationAsync definitionLocationAsync = new DefinitionLocationAsync(this); definitionLocationAsync.setDelegate(new DefinitionLocationAsync.AsyncResponseLocation() { @Override public void processFinish(CityModel output) { setDataToInterface(output); WeatherHelper.updateWeatherInAllCities(getApplicationContext()); } }); definitionLocationAsync.execute(); } else { ArrayList<CityModel> cities = DatabaseHelper.getInstance(this).getCities(); if (cities != null && cities.size() > 0) { CityModel cityModel = cities.get(0); if (cityModel != null) { setDataToInterface(cityModel); } Toast.makeText( this, getString(R.string.not_internet), Toast.LENGTH_LONG ).show(); } else { Toast.makeText( this, getString(R.string.not_cities_and_connection), Toast.LENGTH_LONG ).show(); } } } else{ ArrayList<CityModel> cities = DatabaseHelper.getInstance(this).getCities(); CityModel cityModel = null; if(cities!=null && cities.size()>0){ for(CityModel city : cities){ if(city.getName().equals(cityName)){ cityModel = city; } } } if(cityModel!=null) { setDataToInterface(cityModel); } } } catch (Exception exc) { exc.printStackTrace(); } } } @Override public void onConfigurationChanged(Configuration newConfig){ super.onConfigurationChanged(newConfig); changeOrientation = true; } // Переход на активити с выбором города public void onChangeCityButton(View view){ Intent intent = new Intent(this, ListCitiesActivity.class); startActivity(intent); overridePendingTransition(R.anim.right_in, R.anim.empty_anim); } private void setDataToInterface(CityModel output){ TextView cityText = (TextView)findViewById(R.id.cityTextView); cityText.setText(output.getName()); TextView tempText = (TextView)findViewById(R.id.tempTextView); String temp = "-"; try{ temp = Integer.toString(output.getWeather().getTemp()); tempText.setText(temp); } catch (Exception ex){ ex.printStackTrace(); } TextView pressureText = (TextView)findViewById(R.id.pressureTextView); String pressure = "-"; try{ pressure = Integer.toString(output.getWeather().getPressure()); pressureText.setText(pressure); } catch (Exception ex){ ex.printStackTrace(); } TextView powerWindText = (TextView)findViewById(R.id.windPowerTextView); String powerWind = "-"; try{ powerWind = Integer.toString(output.getWeather().getPowerWind()); powerWindText.setText(powerWind); } catch (Exception ex){ ex.printStackTrace(); } TextView directionWindText = (TextView)findViewById(R.id.windTextView); String directionWind = "-"; try{ directionWind = ConvertHelper.getNameOfDirectionWind(output.getWeather().getDirectionOfTheWind(), getApplicationContext()); directionWindText.setText(directionWind); } catch (Exception ex){ ex.printStackTrace(); } ImageView imageView = (ImageView)findViewById(R.id.sunImageView); try{ CloudinessEnum cloudinessEnum = output.getWeather().getCloudiness(); if(cloudinessEnum == CloudinessEnum.SUN){ imageView.setImageResource(R.drawable.sun); } else if(cloudinessEnum == CloudinessEnum.CLODY){ imageView.setImageResource(R.drawable.clouds); } else if(cloudinessEnum == CloudinessEnum.SUN_CLOUDY){ imageView.setImageResource(R.drawable.sunclouds); } else if(cloudinessEnum == CloudinessEnum.RAIN){ imageView.setImageResource(R.drawable.cloudsrain); } } catch (Exception e){ e.printStackTrace(); } } boolean doubleBackToExitPressedOnce = false; @Override public void onBackPressed() { if (doubleBackToExitPressedOnce) { finish(); } this.doubleBackToExitPressedOnce = true; Toast.makeText(this, getString(R.string.double_back_press), Toast.LENGTH_SHORT).show(); new Handler().postDelayed(new Runnable() { @Override public void run() { doubleBackToExitPressedOnce=false; } }, 2000); } } <file_sep>/app/src/main/java/com/example/botalovns/weathergdg/common/DefinitionWeatherAsync.java package com.example.botalovns.weathergdg.common; import android.app.ProgressDialog; import android.content.Context; import android.os.AsyncTask; import android.util.Log; import android.widget.Toast; import com.example.botalovns.weathergdg.R; import com.example.botalovns.weathergdg.helpers.WeatherHelper; import com.example.botalovns.weathergdg.models.CityModel; import com.example.botalovns.weathergdg.models.WeatherModel; public class DefinitionWeatherAsync extends AsyncTask { public AsyncResponseWeather delegate = null; public void setDelegate(AsyncResponseWeather delegate){ this.delegate = delegate; } private ProgressDialog dialogGetWeather; private CityModel city; private Context context; public DefinitionWeatherAsync(CityModel city, Context context){ this.city=city; this.context=context; } @Override protected void onPreExecute() { try { if(dialogGetWeather==null && context!=null) { dialogGetWeather = new ProgressDialog(context); dialogGetWeather.setMessage(context.getString(R.string.message_dialog_get_weather)); dialogGetWeather.setIndeterminate(true); dialogGetWeather.setCancelable(false); dialogGetWeather.setCanceledOnTouchOutside(false); dialogGetWeather.show(); } } catch (Exception exc){ Log.println(1, "", exc.toString()); } } @Override protected Object doInBackground(Object[] objects) { return WeatherHelper.getWeather(city, context); } @Override protected void onPostExecute(Object result) { if (dialogGetWeather != null) { dialogGetWeather.dismiss(); } if(result==null){ Toast.makeText( context, context.getString(R.string.error_get_weather), Toast.LENGTH_LONG ).show(); } else{ try { WeatherModel weatherModel = (WeatherModel) result; delegate.processFinish(weatherModel); } catch (Exception exc){ exc.printStackTrace(); } } } public interface AsyncResponseWeather { void processFinish(WeatherModel output); } }<file_sep>/app/src/main/java/com/example/botalovns/weathergdg/enums/CloudinessEnum.java package com.example.botalovns.weathergdg.enums; public enum CloudinessEnum { SUN, // Солнечно CLODY, // Пасмурно SUN_CLOUDY, // Переменная облачность RAIN, // Дождь NONE // Не определенно } <file_sep>/app/src/main/java/com/example/botalovns/weathergdg/common/CustomLocationListener.java package com.example.botalovns.weathergdg.common; import android.Manifest; import android.app.Activity; import android.content.Context; import android.content.pm.PackageManager; import android.location.Address; import android.location.Geocoder; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.app.ActivityCompat; import android.util.Log; import android.widget.Toast; import java.io.IOException; import java.util.List; import java.util.Locale; public class CustomLocationListener{ private Context context; public CustomLocationListener(Context context) { this.context = context; } private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute private static final int REQUEST_LOCALE = 1; private static String[] PERMISSIONS_LOCALE = { Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION }; public Location getLocation() { Location location = null; try { LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE); // boolean isGPSEnabled = locationManager .isProviderEnabled(LocationManager.GPS_PROVIDER); // boolean isNetworkEnabled = locationManager .isProviderEnabled(LocationManager.NETWORK_PROVIDER); if (!isGPSEnabled && !isNetworkEnabled) { } else { if (isNetworkEnabled) { if (locationManager != null) { if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions( (Activity)context, PERMISSIONS_LOCALE, REQUEST_LOCALE ); } location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); } } if (isGPSEnabled) { if (location == null) { if (locationManager != null) { location = locationManager .getLastKnownLocation(LocationManager.GPS_PROVIDER); } } } } } catch (Exception e) { e.printStackTrace(); } return location; } }<file_sep>/app/src/main/java/com/example/botalovns/weathergdg/helpers/SearchHelper.java package com.example.botalovns.weathergdg.helpers; import android.content.Context; import android.os.AsyncTask; import com.example.botalovns.weathergdg.common.AsyncResponse; import com.example.botalovns.weathergdg.models.CityModel; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; public class SearchHelper extends AsyncTask { public AsyncResponse delegate = null; private Context context; private String url; public SearchHelper(Context context, String url){ this.context = context; this.url = url; } public SearchHelper(){ } public void setDelegate(AsyncResponse delegate){ this.delegate = delegate; } public void setContext(Context context){ this.context = context; } public void setUrl(String url){ this.url = url; } @Override protected void onPreExecute() { } @Override protected ArrayList<CityModel> doInBackground(Object[] objects) { //return null; ArrayList<CityModel> result = new ArrayList<>(); JSONObject jsonObject = null; try { jsonObject = new JSONObject(WebHelper.GoToURL(url, "")); } catch (JSONException e) { e.printStackTrace(); } JSONArray gNames = new JSONArray(); try { if (jsonObject!=null) gNames = jsonObject.getJSONArray("geonames"); } catch (JSONException e) { e.printStackTrace(); } if (gNames.length() > 0) { result.clear(); } for (int i = 0; i < gNames.length(); i++) { JSONObject c = new JSONObject(); String cName = ""; long population = 0L; double lat = 0.0; double lng = 0.0; String tzStr = "GMT+00:00"; try { c = gNames.getJSONObject(i); population = c.getLong("population"); if (population > 0L) { cName = c.getString("name"); lat = c.getDouble("lat"); lng = c.getDouble("lng"); JSONArray names = null; try{ names = c.getJSONArray("alternateNames"); } catch (JSONException e){ e.printStackTrace(); } if(names!=null && names.length()>0){ for(int j=0; j<names.length(); j++){ JSONObject nameObject = names.getJSONObject(j); if(nameObject!=null){ try{ if(nameObject.getString("lang").equals("ru")){ cName = nameObject.getString("name"); } } catch (JSONException exc){ exc.printStackTrace(); } } } } CityModel city = new CityModel(); city.setName(cName); city.setCoordinates(lat, lng); result.add(city); } } catch (JSONException e) { e.printStackTrace(); } } return result; } @Override protected void onPostExecute(Object result) { try { delegate.processFinish((ArrayList<CityModel>) result); } catch (Exception e){ e.printStackTrace(); } } } <file_sep>/app/src/main/java/com/example/botalovns/weathergdg/enums/DirectionOfTheWindEnum.java package com.example.botalovns.weathergdg.enums; public enum DirectionOfTheWindEnum { SOUTH, //Юг EAST, // Восток NORTH, // Север WEST, // Запад SOUTHWEST, // юго-запад SOUTHEAST, // юго-восток NORTHWEST, // северо-запад NORTHEAST, // северо-восток NONE // Не определенно }
cde971e695a862796c2e189d570df6c51295afa3
[ "Java" ]
12
Java
botalov/WeatherGDG2
536484f07ce80616560bb92d8021516a692d744c
f6ed254f17fb3112a887c1af638480817a581a76
refs/heads/master
<file_sep>{{!-- {{#each places as |place|}} <div> <form action="/edit-place?placeid={{place._id}}" method="POST"> <div> <label for="">{{place.name}}</label> <input type="text" name="name" placeholder="Name" /><br><br> <label for="">{{place.type}}</label><br><br> <select name="type" id=""> <option value="coffee shop">coffee shop</option> <option value="bookstore">bookstore</option> </select> </div> <button type="submit">Edita place</button> </form> </div> {{/each}} --}} <h2>Edit Place</h2> <form action="/update-place/{{place._id}}" method="POST"> <div class="form-group"> <label for="name">Name</label> <input value="{{place.name}}" name="name" type="text" class="form-control" id="name" placeholder="Enter name"> </div> <div class="form-group"> <label for="type">Type</label> <select name="type" id="type" class="form-control"> <option selected>Choose...</option> <option value="coffee shop">Coffee Shop</option> <option value="bookstore">Bookstore</option> </select> </div> <div class="form-group"> <label for="lng">Longitude</label> <input value="{{place.location.coordinates.[0]}}" id="lng" class="form-control" type="text" name="lng" placeholder="Longitude" /> </div> <div class="form-group"> <label for="lat">Latitude</label> <input value="{{place.location.coordinates.[1]}}" id="lat" class="form-control" type="text" name="lat" placeholder="Latitude" /> </div> <button type="submit" class="btn btn-primary">Edit</button> </form> <file_sep><div> <form action="/create" method="POST"> <div class="form-group"> <label for="">Name</label> <input type="text" name="name" placeholder="Name" /><br><br> <label for="">Type</label> <select name="type" id=""> <option value="coffee shop">coffee shop</option> <option value="bookstore">bookstore</option> </select> </div> <div class="form-group"> <label for="longitude">Longitude</label> <input id="lng" class="form-control" type="text" name="lng" placeholder="Longitude" /> </div> <div class="form-group"> <label for="latitude">Latitude</label> <input id="lat" class="form-control" type="text" name="lat" placeholder="Latitude" /> </div> <button type="submit" class="btn btn-primary">Create place</button> </form> <br> <a href="/lugares"><button type="submit" class="btn btn-primary">Go to places</button></a> </div> <file_sep><h1>Places</h1> <a href="/">Inicio</a> <ul class="list-group"></ul>{{#each places as |place|}} <li class="list-group-item"> <p>Name: {{place.name}}</p> <p>Type: {{place.type}}</p> <form action="/lugares" method="POST"> <a href="/delete/{{place._id}}"> <button type="button" class="btn btn-primary">Delete Lugar</button> </a><br><br> <a href="/update-place/{{place._id}}"> <button type="button" class="btn btn-primary">Update Lugar</button> </a> </form> </li> {{/each}} </ul> <div> <div> <div id='map' style='display: inline-flex;width: 800px; height: 500px;'></div> </div> <script> mapboxgl.accessToken="<KEY>" let map2 = new mapboxgl.Map({ container: "map", style: "mapbox://styles/mapbox/streets-v10", }); //añadir controladores map2.addControl(new MapboxDirections({accessToken:mapboxgl.accessToken}),'top-left') map2.addControl(new mapboxgl.NavigationControl()); {{!-- const marker = new mapboxgl.Marker() .setLngLat([-99.1711, 19.399]) .addTo(map2); --}} if (navigator.geolocation) { // Get current position // The permissions dialog will pop up navigator.geolocation.getCurrentPosition(function (position) { // Create an object to match Mapbox's Lat-Lng array format const center = [ position.coords.longitude, position.coords.latitude, ]; map2.setZoom(12).setCenter(center); new mapboxgl.Marker({color:"red"}) .setLngLat(center) .addTo(map2) .setPopup(new mapboxgl.Popup().setHTML("<p>Usted està aquì </p>")) }); } let locations=[]; let names=[]; {{#each places as |place|}} locations.push({{{place.location}}}) names.push("{{place.name}}") {{/each}} console.log(locations) locations.forEach((place,i)=>{ console.log(i+1,location[i]) let [lng,lat]=place.coordinates let place_position=[lng,lat]; let popup =new mapboxgl.Popup().setText(names[i]); let marker =new mapboxgl.Marker().setLngLat(place_position).setPopup(popup).addTo(map); }) </script>
807404a55369c1841d6eecdaa13c7caaa357a908
[ "Handlebars" ]
3
Handlebars
Giseliux/lab-coffee-and-books
f819444b61fd912925905f30d2db743d1bb5de60
f875115c28f58c5c3cf7821b338c926db3d96081
refs/heads/master
<repo_name>DataCollectApp/twitch-data-feed<file_sep>/src/main/resources/application.properties spring.application.name=twitch-data-feed spring.main.banner-mode=off server.forward-headers-strategy=framework server.servlet.context-path=/${spring.application.name}/v1 info.app.title=${spring.application.name} info.app.description=Application to expose data collected from Twitch info.app.version=0.1.0-SNAPSHOT spring.security.user.name=${SPRING_SECURITY_USER_NAME} spring.security.user.password=${<PASSWORD>PASSWORD} management.endpoints.web.exposure.include=* management.endpoint.health.show-details=when_authorized management.metrics.export.prometheus.enabled=true management.metrics.tags.application=${spring.application.name} management.metrics.tags.system=DataCollectApp management.info.git.mode=full spring.datasource.url=${SPRING_DATASOURCE_URL} spring.datasource.username=${SPRING_DATASOURCE_USERNAME} spring.datasource.password=${SPRING_DATASOURCE_PASSWORD} spring.datasource.driver-class-name=org.postgresql.Driver spring.datasource.tomcat.test-while-idle=true spring.datasource.tomcat.validation-query=SELECT 1 twitch-data-feed.config.chat-message.name=${TWITCH_DATA_FEED_CONFIG_CHAT_MESSAGE_NAME} twitch-data-feed.config.chat-message.description=${TWITCH_DATA_FEED_CONFIG_CHAT_MESSAGE_DESCRIPTION} twitch-data-feed.config.chat-message.author=${TWITCH_DATA_FEED_CONFIG_CHAT_MESSAGE_AUTHOR} twitch-data-feed.config.chat-message.table-name=${TWITCH_DATA_FEED_CONFIG_CHAT_MESSAGE_TABLE_NAME} twitch-data-feed.config.connection.name=${TWITCH_DATA_FEED_CONFIG_CONNECTION_NAME} twitch-data-feed.config.connection.description=${TWITCH_DATA_FEED_CONFIG_CONNECTION_DESCRIPTION} twitch-data-feed.config.connection.author=${TWITCH_DATA_FEED_CONFIG_CONNECTION_AUTHOR} twitch-data-feed.config.connection.table-name=${TWITCH_DATA_FEED_CONFIG_CONNECTION_TABLE_NAME} twitch-data-feed.config.host.name=${TWITCH_DATA_FEED_CONFIG_HOST_NAME} twitch-data-feed.config.host.description=${TWITCH_DATA_FEED_CONFIG_HOST_DESCRIPTION} twitch-data-feed.config.host.author=${TWITCH_DATA_FEED_CONFIG_HOST_AUTHOR} twitch-data-feed.config.host.table-name=${TWITCH_DATA_FEED_CONFIG_HOST_TABLE_NAME} twitch-data-feed.config.punishment.name=${TWITCH_DATA_FEED_CONFIG_PUNISHMENT_NAME} twitch-data-feed.config.punishment.description=${TWITCH_DATA_FEED_CONFIG_PUNISHMENT_DESCRIPTION} twitch-data-feed.config.punishment.author=${TWITCH_DATA_FEED_CONFIG_PUNISHMENT_AUTHOR} twitch-data-feed.config.punishment.table-name=${TWITCH_DATA_FEED_CONFIG_PUNISHMENT_TABLE_NAME}<file_sep>/src/main/java/app/datacollect/twitchdata/feed/feed/service/SyndFeedService.java package app.datacollect.twitchdata.feed.feed.service; import app.datacollect.twitchdata.feed.config.FeedConfigProperties; import app.datacollect.twitchdata.feed.feed.domain.FeedEntry; import com.rometools.rome.feed.synd.SyndCategory; import com.rometools.rome.feed.synd.SyndCategoryImpl; import com.rometools.rome.feed.synd.SyndContent; import com.rometools.rome.feed.synd.SyndContentImpl; import com.rometools.rome.feed.synd.SyndEntry; import com.rometools.rome.feed.synd.SyndEntryImpl; import com.rometools.rome.feed.synd.SyndFeed; import com.rometools.rome.feed.synd.SyndFeedImpl; import java.util.Date; import java.util.List; import java.util.stream.Collectors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; @Service public class SyndFeedService { private static final Logger logger = LoggerFactory.getLogger(SyndFeedService.class); public SyndFeed createFeed( List<FeedEntry> feedEntries, FeedConfigProperties feedConfigProperties) { logger.debug("Creating feed with '{}' entries", feedEntries.size()); SyndFeed syndFeed = new SyndFeedImpl(); syndFeed.setTitle(feedConfigProperties.getName()); syndFeed.setDescription(feedConfigProperties.getDescription()); syndFeed.setAuthor(feedConfigProperties.getAuthor()); syndFeed.setFeedType("atom_1.0"); syndFeed.setEntries(feedEntries.stream().map(this::createEntry).collect(Collectors.toList())); logger.info("Created feed with '{}' entries", feedEntries.size()); return syndFeed; } private SyndEntry createEntry(FeedEntry feedEntry) { SyndContent content = new SyndContentImpl(); content.setType(feedEntry.getContentType()); content.setValue(feedEntry.getContent()); SyndEntry syndEntry = new SyndEntryImpl(); syndEntry.setUri(feedEntry.getId().toString()); syndEntry.setAuthor(feedEntry.getAuthor()); syndEntry.setPublishedDate(Date.from(feedEntry.getPublishedDate().getInstant())); syndEntry.setUpdatedDate(Date.from(feedEntry.getUpdatedDate().getInstant())); syndEntry.setContents(List.of(content)); syndEntry.setCategories( List.of( createCategory(feedEntry.getEventType().name(), "eventType"), createCategory(feedEntry.getObjectType().name(), "objectType"), createCategory(feedEntry.getVersion().name(), "version"))); return syndEntry; } private SyndCategory createCategory(String name, String taxonomyUri) { final SyndCategory category = new SyndCategoryImpl(); category.setName(name); category.setTaxonomyUri(taxonomyUri); return category; } } <file_sep>/src/main/java/app/datacollect/twitchdata/feed/feed/domain/FeedEntry.java package app.datacollect.twitchdata.feed.feed.domain; import app.datacollect.time.UTCDateTime; import app.datacollect.twitchdata.feed.events.EventType; import app.datacollect.twitchdata.feed.events.ObjectType; import app.datacollect.twitchdata.feed.events.Version; import java.util.UUID; public class FeedEntry { private final UUID id; private final String author; private final EventType eventType; private final ObjectType objectType; private final Version version; private final UTCDateTime publishedDate; private final UTCDateTime updatedDate; private final String contentType; private final String content; public FeedEntry( UUID id, String author, EventType eventType, ObjectType objectType, Version version, UTCDateTime publishedDate, UTCDateTime updatedDate, String contentType, String content) { this.id = id; this.author = author; this.eventType = eventType; this.objectType = objectType; this.version = version; this.publishedDate = publishedDate; this.updatedDate = updatedDate; this.contentType = contentType; this.content = content; } public UUID getId() { return id; } public String getAuthor() { return author; } public EventType getEventType() { return eventType; } public ObjectType getObjectType() { return objectType; } public Version getVersion() { return version; } public UTCDateTime getPublishedDate() { return publishedDate; } public UTCDateTime getUpdatedDate() { return updatedDate; } public String getContentType() { return contentType; } public String getContent() { return content; } } <file_sep>/src/main/resources/db/migration/V001_02__CREATE_CONNECTION_FEED_TABLE.sql CREATE TABLE connection_feed ( id UUID PRIMARY KEY, author VARCHAR(32) NOT NULL, event_type VARCHAR(32) NOT NULL, object_type VARCHAR(32) NOT NULL, version VARCHAR(8) NOT NULL, published_date VARCHAR(64) NOT NULL, updated_date VARCHAR(64) NOT NULL, content_type VARCHAR(32) NOT NULL, content TEXT NOT NULL );<file_sep>/src/main/java/app/datacollect/twitchdata/feed/feed/connection/controller/ConnectionFeedController.java package app.datacollect.twitchdata.feed.feed.connection.controller; import static app.datacollect.twitchdata.feed.common.Resource.CONNECTION; import static app.datacollect.twitchdata.feed.common.Resource.FEED; import static org.springframework.http.MediaType.APPLICATION_ATOM_XML_VALUE; import app.datacollect.twitchdata.feed.common.error.ErrorMessage; import app.datacollect.twitchdata.feed.config.FeedConfigProperties; import app.datacollect.twitchdata.feed.feed.domain.FeedEntry; import app.datacollect.twitchdata.feed.feed.service.FeedService; import app.datacollect.twitchdata.feed.feed.service.FeedValidator; import app.datacollect.twitchdata.feed.feed.service.SyndFeedService; import com.rometools.rome.feed.WireFeed; import java.util.List; import java.util.Optional; import java.util.UUID; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; @Controller @RequestMapping(FEED) public class ConnectionFeedController { private final FeedService service; private final SyndFeedService syndFeedService; private final FeedConfigProperties feedConfigProperties; private final FeedValidator feedValidator; public ConnectionFeedController( FeedService service, SyndFeedService syndFeedService, @Qualifier("connectionFeedConfigProperties") FeedConfigProperties feedConfigProperties, FeedValidator feedValidator) { this.service = service; this.syndFeedService = syndFeedService; this.feedConfigProperties = feedConfigProperties; this.feedValidator = feedValidator; } @GetMapping(value = CONNECTION, produces = APPLICATION_ATOM_XML_VALUE) public ResponseEntity<?> getConnectionFeed( @RequestParam("marker") Optional<String> marker, @RequestParam(value = "limit", defaultValue = "1000") int limit) { final Optional<ErrorMessage> errorMessage = feedValidator.validateLimit(limit); if (errorMessage.isPresent()) { return ResponseEntity.badRequest().body(errorMessage.get()); } final List<FeedEntry> feedEntries = service.getEntries(feedConfigProperties.getTableName(), marker, limit); return ResponseEntity.ok( syndFeedService.createFeed(feedEntries, feedConfigProperties).createWireFeed()); } @GetMapping(value = CONNECTION + "/{id}", produces = APPLICATION_ATOM_XML_VALUE) public ResponseEntity<WireFeed> getConnectionFeedEntry(@PathVariable("id") UUID id) { return service .getEntry(feedConfigProperties.getTableName(), id) .map( feedEntry -> ResponseEntity.ok( syndFeedService .createFeed(List.of(feedEntry), feedConfigProperties) .createWireFeed())) .orElse(ResponseEntity.notFound().build()); } } <file_sep>/src/main/java/app/datacollect/twitchdata/feed/common/repository/Tables.java package app.datacollect.twitchdata.feed.common.repository; public final class Tables { public static class FEED { public static final String ID = "id"; public static final String AUTHOR = "author"; public static final String EVENT_TYPE = "event_type"; public static final String OBJECT_TYPE = "object_type"; public static final String VERSION = "version"; public static final String PUBLISHED_DATE = "published_date"; public static final String UPDATED_DATE = "updated_date"; public static final String CONTENT_TYPE = "content_type"; public static final String CONTENT = "content"; } } <file_sep>/src/main/java/app/datacollect/twitchdata/feed/common/repository/FeedEntryRowMapper.java package app.datacollect.twitchdata.feed.common.repository; import static app.datacollect.twitchdata.feed.common.repository.Tables.FEED.AUTHOR; import static app.datacollect.twitchdata.feed.common.repository.Tables.FEED.CONTENT; import static app.datacollect.twitchdata.feed.common.repository.Tables.FEED.CONTENT_TYPE; import static app.datacollect.twitchdata.feed.common.repository.Tables.FEED.EVENT_TYPE; import static app.datacollect.twitchdata.feed.common.repository.Tables.FEED.ID; import static app.datacollect.twitchdata.feed.common.repository.Tables.FEED.OBJECT_TYPE; import static app.datacollect.twitchdata.feed.common.repository.Tables.FEED.PUBLISHED_DATE; import static app.datacollect.twitchdata.feed.common.repository.Tables.FEED.UPDATED_DATE; import static app.datacollect.twitchdata.feed.common.repository.Tables.FEED.VERSION; import app.datacollect.time.UTCDateTime; import app.datacollect.twitchdata.feed.events.EventType; import app.datacollect.twitchdata.feed.events.ObjectType; import app.datacollect.twitchdata.feed.events.Version; import app.datacollect.twitchdata.feed.feed.domain.FeedEntry; import java.sql.ResultSet; import java.sql.SQLException; import java.util.UUID; public final class FeedEntryRowMapper { public static FeedEntry mapRow(ResultSet resultSet, int rowNum) throws SQLException { return new FeedEntry( UUID.fromString(resultSet.getString(ID)), resultSet.getString(AUTHOR), EventType.valueOf(resultSet.getString(EVENT_TYPE)), ObjectType.valueOf(resultSet.getString(OBJECT_TYPE)), Version.valueOf(resultSet.getString(VERSION)), UTCDateTime.of(resultSet.getString(PUBLISHED_DATE)), UTCDateTime.of(resultSet.getString(UPDATED_DATE)), resultSet.getString(CONTENT_TYPE), resultSet.getString(CONTENT)); } } <file_sep>/README.md # twitch-data-feed Application to expose data collected from Twitch ### Environment variables The following properties are required to run the application: | Name | Description | | ------------- | ------------- | | SPRING_SECURITY_USER_NAME | Username for accessing endpoints | | SPRING_SECURITY_USER_PASSWORD | <PASSWORD> for accessing endpoints | | SPRING_DATASOURCE_URL | Database URL (Postgres supported) | | SPRING_DATASOURCE_USERNAME | Database username | | SPRING_DATASOURCE_PASSWORD | Database password | | TWITCH_DATA_FEED_CONFIG_CHAT_MESSAGE_NAME | Name of the chat message feed | | TWITCH_DATA_FEED_CONFIG_CHAT_MESSAGE_DESCRIPTION | Description of the chat message feed | | TWITCH_DATA_FEED_CONFIG_CHAT_MESSAGE_AUTHOR | Author of the chat message feed | | TWITCH_DATA_FEED_CONFIG_CHAT_MESSAGE_TABLE_NAME | Table name for the chat message feed | | TWITCH_DATA_FEED_CONFIG_CONNECTION_NAME | Name of the connection feed | | TWITCH_DATA_FEED_CONFIG_CONNECTION_DESCRIPTION | Description of the connection feed | | TWITCH_DATA_FEED_CONFIG_CONNECTION_AUTHOR | Author of the connection feed | | TWITCH_DATA_FEED_CONFIG_CONNECTION_TABLE_NAME | Table name for the connection feed | | TWITCH_DATA_FEED_CONFIG_HOST_NAME | Name of the host feed | | TWITCH_DATA_FEED_CONFIG_HOST_DESCRIPTION | Description of the host feed | | TWITCH_DATA_FEED_CONFIG_HOST_AUTHOR | Author of the host feed | | TWITCH_DATA_FEED_CONFIG_HOST_TABLE_NAME | Table name for the host feed | | TWITCH_DATA_FEED_CONFIG_PUNISHMENT_NAME | Name of the punishment feed | | TWITCH_DATA_FEED_CONFIG_PUNISHMENT_DESCRIPTION | Description of the punishment feed | | TWITCH_DATA_FEED_CONFIG_PUNISHMENT_AUTHOR | Author of the punishment feed | | TWITCH_DATA_FEED_CONFIG_PUNISHMENT_TABLE_NAME | Table name for the punishment feed | ### Database migration The application manages the database schema with Flyway.
254624e57e60000f10f8c7414395a62498e14835
[ "Java", "Markdown", "SQL", "INI" ]
8
Java
DataCollectApp/twitch-data-feed
cd328ba48272ce0ed970e74ad039c664b189a4db
f09186118dcba5b808debe9e1272c48935786999
refs/heads/master
<repo_name>zthab/ECON203Replication<file_sep>/README.txt Download census data through IPUMS USA: https://usa.ipums.org/usa/index.shtml Reference codebook for sample selection. Each figure and table can be constructed in its namesake program. rep_clean_vars must be run before any other program is run; it only has to be run once. Any data cleaning or limitations that only apply to part of the following analysis will be conducted in those specific programs. All figure and table programs are built to be independent of one another, and thus can be run in any combination. Observation Specifications: Data specification references: 1960: "The Integrated Public Use Microdata Series (IPUMS) provides a 1 percent sample for 1960 (Ruggles et al. 2004)" (Almond 683). 1970: "For 1970, Form 1 data are used since they contain disability measures, welfare payments, and so forth. The state, neighborhood, and metro samples are combined, yielding a 3 percent sample" (684). 1980: "The IPUMS provides its largest samples, 5 percent, beginning with the 1980 Census" (684). Birth Cohorts: The analysis performed in this paper has the widest set of birth cohorts in figure 8 (b. 1911-1924). (685, 687). Quality Flags: —“All persons born in the United States whose age was not allocated are included in the cohorts analysis sample of Section V" (683-684). This includes Tables 2, 3, 4, and Figures 3, 4, 5, 6, 8 analyzed below. It does not include Table 1, so this quality flag is specified within each of the programs to which it pertains. Coding of Income Variables: In analyzing wage income, Almond says that he dropped observations with no wages, "so work-preventing disabilities per se cannot account for this effect" (694). The syntax leaves it unclear if those with no wages are dropped from the dataset as a whole, or if they are excluded from wage analysis. The situational context for this information suggests that these men are only excluded from wage analysis. I then coded $0 wages as null wages. The author's consistency of coding for income variables is questionable. It is unclear if they drop people whose total income is 0 or not, as they indicate that they do to wage income. I chose to keep observations where total income is 0 coded as 0 because total income being 0 do not necessarily causally relate to wage income being 0. In order to use the justification that we are excluding wage income = 0, so we should exclude total income = 0, this causal relationship would have to stand. total income being 0 is less meaningful because while this could be caused by no income, it can also be a result of debt etc. So excluding it, to some extent, is a bit arbitrary. Almond's measurement of welfare and social security income clearly included observations where incwelfr = 0. However, I do not necessarily agree with this analysis as it leaves unknown if a change in welfare or social security income is attributable to the proportion of the population receiving these payments changing or the size of those payments themselves changing. I will include indicator variables indicating if an observation receives wages, welfare, and social security income in further regressions wherever wages, welfare, or social security is considered. Almond fails to apply inflation measures to social security and welfare statistics and wage income collected in the 1970 census. I made the decision to uniformly adjust welfare and social security income for inflation throughout my analysis, as below Table 1, Almond indicates "All income figures are given in 2005 dollars" (685). Coding of Disability Variables: I do not incorporate new data as Almond does for the 1980 census. The data that he references, "The Econometrics Laboratory at the University of California, Berkeley maintains a 5 percent extract of the 1980 Census micro data without the questionable IPUMS recoding" is accompanied by a broken link (684). Therefore, I don't recode disability limiting work as Almond does, leading to a systematic underestimation of disability limiting work in any summary statistics or regression using data from the 1980 census. Almond's for disability duration is unclear. As a result, I code each value at the midpoint of the range of durations that it represents. For disabdur == 6, the disability lasts for more than 10 years, I code this as 15 years. I chose this value because it brings disability duration most in line with the summary statistics pertaining to disability duration. Table 1 Notes (in excel spreadsheet titled analysis): Standard deviation instead of the noted standard error are shown in the original article's table (685). I then calculated standard deviation instead of standard error in my replication. The standard deviation for the 1919 male cohort and the surrounding cohorts are switched for the age variable throughout all census years. I fixed this in my replication. Almond uses different, unspecified methods for inflation than I do. This leads to a 2-3% variation in my outputs in 2005 dollars and his. I implement my inflation methods in rep_clean_vars using the Consumer Price Index: Total All Items for the United States (Organization for Economic Co-operation and Development). Almond does not seem to apply his own measure to removing those who don't receive wage income from the cohort mean wage income. This causes a considerable difference between our means in 1980, when many people in the birth cohorts do not receive wages (31% in both cohorts). Table 2 Notes (in xml file titled table2): outreg2 takes an astonishingly long time to run. per the paper's own instructions, I estimated the cohort trend for all income related variables in 1980 using a cubic function. However, it seems as though Almond used a squared trend estimation. 1980 income variables Variable | Thab | Almond ------------------------------ Mean totinc_adj |-600.096 |-1,065 SD |(174.147) |[191] P-Value |0.001 |<0.01 Mean incss_adj |-301.301 |83 SD |(17.720) |[19] P-Value |<0.001 |<0.01 Mean incwelf_adj|7.405 |17 SD |(6.764) |[7] P-Value |0.274 |<0.05 Significant results from new binary variables (receives wage, welfare, or social security payments) — in the 1970 census, members of the male cohort b. 1919 were 0.5% more likely to not receive wages than their surrounding year of birth cohorts (P-Value = 0.057). — in the 1970 census, members of the male cohort b. 1919 were 0.2% more likely to receive welfare payments than their surrounding yob cohorts (P-Value = 0.040). — in the 1980 census, members of the male cohort b. 1919 were 0.57% less likely to receive social security benefits than their surrounding yob cohorts (P-Value < 0.001). Almond unfortunately does not compute departure from trend in welfare and social security for the i1919 male cohort in inflated terms. Since I don't know what inflation measure he used, direct comparison isn't entirely possible. Table 3 Notes: Summary Statistics (in excel spreadsheet titled analysis): — in 1980, Almond's mean wage income dramatically departs from my computation. This is mostly likely because of one of two factors : 1) Almond did not incorporate inflation into his calculation or 2) Almond includes observations where wage income is $0. The latter seems most plausible because 1) the standard deviation reported is much closer to my standard deviation, indicating that these values are adjusted for inflation. Departure from Sample Mean (in xml titled table3): — My departure from trend for total income in 1980 differs significantly from Almond’s. Similarly my wage departure from the sample mean in 1980 was significantly lower than Almond’s. This difference does not disappear when I calculate the trend as a squared rather than a cubed function of year of birth. Significant results from new binary variables (receives wage, welfare, or social security payments) — in the 1980 census, the members of the female cohort born in 1919 were 0.8% more likely to receive wages than those in the surrounding cohorts (P=0.001). — in the 1980 census, the members of the female cohort born in 1919 were 10.5% less likely to receive social security payments than their surrounding cohorts (P<0.01). — in the 1970 and 1980 census, the members of the female cohort born in 1919 were 0.3% more likely than their surrounding cohorts to receive welfare payments (P=0.005 and P=0.004 respectively). Table 4 Notes: Summary Statistics (in analysis excel sheet): —Almond reports median neighbor income in 1970 as 0 with a standard deviation of 0. This does not make sense logically, and my findings are consistent with this intuition (38583.48 [13979.30]). Departure from Sample Mean (in table4 xml): Significant results from new binary variables: — the nonwhite cohort born in 1919 was 1.1% less likely to be employed in 1970 than surrounding nonwhite cohorts (P = 0.075). — the nonwhite cohort born in 1919 was 5.3% less likely than the surrounding nonwhite cohorts to receive social security in 1980 (P<0.001). — the nonwhite cohort born in 1919 was 0.7% more likely to receive welfare that nonwhite cohorts born in the years surrounding 1919 (P = 0.059). Table 5 Notes: — Almond’s y-axis is not in percentage terms although it is labeled as such. I fixed this discrepancy in my results by scaling the high school graduation variable to out of 100. — I believe that Almond is only graphing the male cohort, as the resultant graphs with this constraint are much more similar than when sex is not limited. Table 6 Notes: — Almond’s y-axis is not in percentage terms although it is labeled as such. I fixed this discrepancy in my results by scaling the disability rates to out of 100. Table 8 notes: I made two graphs for figure 8. One showing the mean welfare payment, and one showing the percent of observations receiving welfare. This is the beginning of an attempt to show the confounding nature of Almond's methodology. While welfare payments plateaus after 1916 as year of births progress, the percent of people receiving welfare continues to trend downwards. It’s also worth noting that another troubling aspect of this graph is that the categories that Almond groups by are non-exclusive. So, this is another source of how the variables tend to not be clear. Citations <NAME>. “Is the 1918 Influenza Pandemic Over? Long‐Term Effects of In Utero Influenza Exposure in the Post‐1940 U.S. Population.” Journal of Political Economy, vol. 114, no. 4, Aug. 2006, pp. 672–712. DOI.org (Crossref), doi:10.1086/507154. Organization for Economic Co-operation and Development, Consumer Price Index: Total All Items for the United States [CPALTT01USA657N], retrieved from FRED, Federal Reserve Bank of St. Louis; https://fred.stlouisfed.org/series/CPALTT01USA657N, April 30, 2020. <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME> and <NAME>. IPUMS USA: Version 10.0 [dataset]. Minneapolis, MN: IPUMS, 2020. https://doi.org/10.18128/D010.V10.0 <file_sep>/replication_v0.do #delimit ; cd "/Users/zahrathabet/Desktop/replication/"; *run below line if program fails; *ssc install outreg2, replace; capture log close; log using replication.log, replace; use census.dta, clear; /* Samples selected: 1960 1% 1970 Form 1 State 1% 1970 Form 1 Metro 1% 1970 Form 1 Neighborhood 1% 1980 5% In each of these samples, age and birthplace were restricted to these specifications: AGE: 038-068 Note: contains the desired 1911-1924 birth cohort for all census years. BPL: 001-120 Note: limits selection of birthplace to the U.S. More information available in codebook.cbk file */ capture program drop rep_clean_vars; program define rep_clean_vars; /* cleans variables to be used in rest of analysis. */ *generating age-related statistics; qui gen yob = year - age; la var yob "year of birth"; qui replace yob = year - age - 1 if inlist(birthqtr, 2, 3, 4); /* " year of birth = : census year-age-1 if born April to December census year-age if born January to March "(Almond 683) */ qui keep if ((yob <= 1924) & (yob >= 1911)); *keeps observations that were born 1911-1924; qui gen i1919 = (yob == 1919); la var i1919 "born in 1919"; *generating education-related statistics; qui replace higrade = 21 if ((higrade == 22) | (higrade == 23)); *high school graduation indicator. codes >=7 years of post-secondary *education (higrade = 22-23) as >=6 years of P-S education (higrade = 21) *because the data for 7-8 years of p-s education is unavailable in the 1960 and *1970 censuses; qui gen yrsofeduc = . ; la var yrsofeduc "years of education"; qui replace yrsofeduc = 0 if inlist(higrade, 0, 1, 2, 3); *codes pre 1st-grade education as 0 years of education; qui replace yrsofeduc = higrade - 3 if ((higrade >= 4) & (higrade <= 99)); *transforms yrsofeduc so that 1st grade is coded as one year of education; *high school graduate stats; qui gen hsgrad = (yrsofeduc >= 12); la var hsgrad "graduated high school"; qui replace hsgrad = . if (yrsofeduc == .); *when years of education is not available, codes hsgrad as unavailable rather *than as 0; *generating wage and income statistics; *imports CPI data to inflate USD to 2005 dollar levels; preserve; *keeps census data set; qui import delimited using CPI.csv, clear; /* Consumer Price Index: Total All Items for the United States Units: Growth Rate Previous Period, Not Seasonally Adjusted Frequency: Annual Source: Organization for Economic Co-operation and Development, Consumer Price Index: Total All Items for the United States [CPALTT01USA657N], retrieved from FRED, Federal Reserve Bank of St. Louis; https://fred.stlouisfed.org/series/CPALTT01USA657N, April 30, 2020. */ qui su cpi if (year == 2005); qui gen adj_factor = r(mean) / cpi; *adj factor that can be multiplied by dollar amt to give it in 2005 terms; la var adj_factor "2005 inflation factor"; qui save cpi.dta, replace; restore; sort year; *sorts the census data by year, makes it marginally faster to merge; qui merge m:1 year using cpi.dta; *adds inflation factor to census data; qui keep if _merge == 3; *keeps data that is matched, and gets rid of cpi data that isn't from 1960; *1970, 1980; qui gen incwage_adj = incwage * adj_factor; la var incwage_adj "wage and salary income (2005 dollars)"; qui replace incwage_adj = . if (incwage == 0); *codes wage income as null if it is 0, explained in readme; qui gen iemp = (incwage_adj != .); *there are no negative values of wage in this dataset, so this indicates if the *observation receives a wage or not (proxy for employment); la var iemp "receives wages"; qui gen inctot_adj = inctot * adj_factor; la var inctot_adj "total personal income (2005 dollars)"; qui gen nmedinc_adj = nmedinc * adj_factor * 1000; *originally in thousands of dollars, multiplying by 1000 gets rid of adjustment; la var nmedinc_adj "median family income (2005 dollars)"; qui gen incwelfr_adj = incwelfr * adj_factor; la var incwelfr_adj "welfare (public assistance) income (2005 dollars)"; qui gen irecwelf = (incwelfr_adj != 0 & incwelfr_adj !=.); la var irecwelf "receives welfare (public assistance) income"; qui gen incss_adj = incss * adj_factor; la var incss_adj "social security income (2005 dollars)"; qui gen irecss = (incss_adj != 0 & incss_adj != .); la var irecss "receives social security income"; qui gen ipoverty = (poverty < 150); * `poor' is defined by Almond as "below 150% of the poverty level" (688); la var ipoverty "below 150% of the poverty level"; *generating disability statistics; qui gen idislimwrk = (disabwrk == 2); la var idislimwrk "disability limits but does not prevent work"; qui gen idisprevwrk = (disabwrk == 3); la var idisprevwrk "disability prevents work"; qui gen idisaffwrk = (idislimwrk | idisprevwrk); la var idisaffwrk "disability limits or prevents work"; gen disabduradj = 0; la var disabduradj "duration of work disability in years"; qui replace disabduradj = 0.25 if (disabdur == 1); qui replace disabduradj = 0.75 if (disabdur == 2); qui replace disabduradj = 2 if (disabdur == 3); qui replace disabduradj = 4 if (disabdur == 4); qui replace disabduradj = 7.5 if (disabdur == 5); qui replace disabduradj = 15 if (disabdur == 6); qui replace idislimwrk = . if (disabwrk == .); qui replace idisprevwrk = . if (disabwrk == .); qui replace idisaffwrk = . if (disabwrk == .); qui replace disabduradj = . if ((disabwrk == .) | (year == 1980)); *codes disability variables as null in census years when it does not exist; end; rep_clean_vars; capture program drop table_1; program define table_1; /* Table 1: male outcome means replication; */ putexcel set analysis.xlsx, sheet(table 1) modify; foreach y in 1 0{; *loops through born in 1919 status; tabstat age hsgrad yrsofeduc inctot_adj incwage_adj iemp ipoverty nmedinc_adj sei idislimwrk idisprevwrk disabduradj incss_adj irecss incwelfr_adj irecwelf if (i1919 == `y') & (sex == 1) & (yob >= 1918) & (yob <= 1920), by(year) stat(mean sd co) nototal save; *summary statistics for 1919 and surrounding cohort of males born 1918-1920; mat table1_`y' = [r(Stat1)\r(Stat2)\r(Stat3)]; *matrix of summary statistics; if `y'{; *if cohort of men born in 1919; qui putexcel A1 = "1919 Male Cohort"; qui putexcel A3 = 1960; qui putexcel A6 = 1970; qui putexcel A9 = 1980; qui putexcel B2 = matrix(table1_`y'), names nformat(number_d2); }; else{; *if cohort of men born 1918 and 1920; qui putexcel A12 = "Surrounding Male Cohort"; qui putexcel A14 = 1960; qui putexcel A17 = 1970; qui putexcel A20 = 1980; qui putexcel B13 = matrix(table1_`y'), names nformat(number_d2); }; *transfers summary statistics to excel spreadsheet titled "analysis"; }; end; *table_1; capture program drop figure_2; program define figure_2; *Figure 2: percent of cohort disabled by birth quarter replication; preserve; *observation limitation for regression; qui keep if ((yob <= 1920 & yob >= 1918) | (yob == 1917 & birthqtr == 4 )) & (sex == 1) & (qage == 0 | qage == .) & (qage2 == 0 | qage2 == .); *keeps men born 1918-1920 and men born in the last quarter of 1917. All *observations with allocated ages are removed from the following analysis; *program variable creation; qui egen time = group(yob birthqtr); la var time "birth quarter, year of birth cohorts"; qui bys time: gen f_time = (_n == 1); la var f_time "first observation in each birth quarter, year of birth cohort"; qui su time; local max_time = r(max); qui gen dis80 = .; la var dis80 "proportion of birth qtr, yob cohort disabled in 1980 census"; *regression and coefficient assignment; qui reg idisprevwrk ibn.time if year == 1980, noconstant; *coefficients are mean disability rates for each birth quarter cohort in 1980 *census; forv i = 1 / `max_time' {; *loops through each cohort; qui replace dis80 = _b[`i'.time] if time == `i'; *locates disability rate coefficients for each cohort from *regression, assigns value to every observation in the same cohort; }; *graphing of regression coefficients; set graphics off; *disables graphics from popping up; scatter dis80 time if f_time == 1, scheme(s1color) mcolor(black) ytitle("Percent of Cohort Disabled") xtitle("Quarter of Birth") xlabel( 1 " " 2 "1918 Q1" 3 " " 4 "1918 Q3" 5 " " 6 "1919 Q1" 7 " " 8 "1919 Q3" 9 " " 10 "1920 Q1" 11 " " 12 "1920 Q3" 13 " ") xline(6, lcolor(black) lwidth(thin) lpattern(dash)) note(Fig. 2. — 1980 male disability rates by quarter of birth: prevented from work by a physical disability.); *scatter plot of percent disabled by quarter of birth and year of birth; qui gr save Figure2, replace; *saves scatter plot as a gph; qui gr export Figure2.pdf, replace; *saves scatter plot as a pdf; restore; end; *figure_2; capture program drop table_2; program define table_2; /* Table 2: Departure of 1919 Male Birth Cohort Outcomes from 1912–22 Trend replication. */ preserve; *observation limitation implementation for summary statistics; qui keep if sex == 1 & (qage == 0 | qage == .) & (qage2 == 0 | qage2 == .) & yob >= 1912 & yob <= 1922; *keeps male observations with non allocated ages born 1912-1922; *program variable creation; *terms for regression to be performed that involve income; qui gen yob_square = c.yob^2; la var yob_square "year of birth squared"; qui gen yob_cube = c.yob^3; la var yob_cube "year of birth cubed"; *regression and coefficient output; qui reg hsgrad i1919 c.yob##c.yob if year == 1960 & sex == 1, depname("hsgrad 1960") nocons vce(robust); *first result from regression to export to xml titled table2 (notice, the *dependent variable is the first variable in the following foreach loop); qui outreg2 using table2, se replace excel bdec(3) noaster keep(i1919) stat(coef se pval); *export of first result; foreach y in hsgrad yrsofeduc inctot_adj incwage_adj iemp ipoverty nmedinc_adj sei idislimwrk idisprevwrk disabduradj incss_adj irecss incwelfr_adj irecwelf {; foreach t in 1960 1970 1980{; qui cou if year ==`t' & `y' != .; *counts number of variables that arent null in the census year; if (!("`y'" == "hsgrad" & `t' == 1960)) & (r(N) != 0) {; *skipping what is already done outside of loop; *if there are any non null values, continues to perform regression *will output error if regression performed on variable with only nulls; if `t' == 1980 & (`y' == inctot_adj | `y' == incwage_adj | `y' == iemp | `y' == incss_adj | `y' == irecss | `y' == incwelfr_adj | `y' == irecwelf) {; /* "For 1980 income measures only, the cohort trend is estimated as a cubic function to attempt to account for retirement at age 62" (696) */ qui reg `y' i1919 c.yob yob_square yob_cube if year == `t' & sex == 1, depname("`y' `t'") vce(robust); * use of robust se: "Robust standard errors are in brackets" *(688). coefficient of i1919 measures departure from trend of *variable `y' for men born in 1919; }; else {; qui reg `y' i1919 c.yob##c.yob if year == `t' & sex == 1, depname("`y' `t'") vce(robust); /* Model specifications outlined on p.687. Coefficient of i1919 measures departure from trend of variable `y' for men born in 1919. Variable name changed so as to easily identify census year of variable in output. */ }; qui outreg2 using table2, se append excel bdec(3) keep(i1919) stat(coef se pval) nocons noaster; *outputs i1919 coefficient to xml named table 2; }; }; }; restore; end; *table_2; capture program drop table_3; program define table_3; /* Table 3: 1912–22 Census Outcomes among Women (Census Years 1960, 1970, and 1980) Replication */ preserve; *observation limitation implementation for summary statistics; keep if yob >= 1912 & yob <= 1922; *keeps observations born 1912-1922; putexcel set analysis.xlsx, sheet(table 3) modify; *summary statistics and summary statistics outputs; tabstat hsgrad yrsofeduc inctot_adj incwage_adj iemp ipoverty nmedinc_adj sei idislimwrk idisprevwrk disabduradj incss_adj irecss incwelfr_adj irecwelf if i1919 == 0 & sex == 2, by (year) stat(mean sd co) nototal save; *summary statistics for women not born in 1919; mat table3_0 = [r(Stat1)\r(Stat2)\r(Stat3)]; putexcel A1 = "Female Sample Mean"; putexcel A3 = 1960; putexcel A6 = 1970; putexcel A9 = 1980; putexcel B2 = matrix(table3_0), names nformat(number_d2); *puts summary statistics in analysis.xlsx in a sheet labeled table 4; *observation limitation for departure from mean regression; keep if ((qage == 0) | (qage == .)) & ((qage2 == 0) | (qage2 == .)); *keeps observations with non-allocated ages; *departure from mean regression variable creation; *terms for regression to be performed that involve income; qui gen yob_square = c.yob^2; la var yob_square "year of birth squared"; qui gen yob_cube = c.yob^3; la var yob_cube "year of birth cubed"; *regression and coefficient output; qui reg hsgrad i1919 c.yob##c.yob if year == 1960 & sex == 2, vce(robust) depname("hsgrad 1960"); *first result from regression to start exporting to xml titled table2; qui outreg2 using table3, se replace excel bdec(3) keep(i1919) nocons noaster stat(coef se pval); foreach y in hsgrad yrsofeduc inctot_adj incwage_adj iemp ipoverty nmedinc_adj sei idislimwrk idisprevwrk disabduradj incss_adj irecss incwelfr_adj irecwelf {; foreach t in 1960 1970 1980 {; qui cou if year == `t' & `y' != .; *counts number of variables that arent null in the census year; if (!("`y'" == "hsgrad" & `t' == 1960)) & r(N){; *skipping what is already done outside of loop; *if there are any non null values, continues to perform regression *will output error if regression performed on variable with only nulls; if `t' == 1980 & ("`y'" == "inctot_adj" | "`y'" == "incwage_adj" | "`y'" == "iemp" | "`y'" == "incss_adj" | "`y'" == "irecss" | "`y'" == "incwelfr_adj" | "`y'" == "irecwelf") {; /* "For 1980 income measures only, the cohort trend is estimated as a cubic function to attempt to account for retirement at age 62" (696) */ qui reg `y' i1919 c.yob yob_square yob_cube if year == `t' & sex == 2, depname("`y' `t'") vce(robust); *use of robust se: "Robust standard errors are in brackets" *(688). coefficient of i1919 measures departure from trend of *variable `y' for women born in 1919.; }; else {; qui reg `y' i1919 c.yob##c.yob if year == `t' & sex == 2, vce(robust) depname("`y' `t'"); /* Model specifications outlined on p.687. Coefficient of i1919 measures departure from trend of variable `y' for those born in 1919. Name is changed in output to easily identify census year of variable in output. */ }; qui outreg2 using table3, se append excel bdec(3) keep(i1919) stat(coef se pval) nocons noaster; *outputs i1919 coefficient to xml file titled table3; }; }; }; restore; end; table_3; capture program drop table_4; program define table_4; *Table 4: 1912–22 Census Outcomes among Nonwhites (Census Years 1960, 1970, and; *1980) Replication; preserve; *observation limitation implementation for summary statistics and regression; keep if (qage == 0 | qage == .) & (qage2 == 0 | qage2 == .) & yob >= 1912 & yob <= 1922; *keeps observations with non-allocated ages born 1912-1922; *summary statistics and summary statistics outputs: putexcel set analysis.xlsx, sheet(table 4) modify; tabstat hsgrad yrsofeduc inctot_adj incwage_adj iemp ipoverty nmedinc_adj sei idislimwrk idisprevwrk disabduradj incss_adj irecss incwelfr_adj irecwelf if i1919 == 0 & race != 1, by (year) stat(mean sd co) nototal save; *summary statistics for nonwhite observations not born in 1919; mat table4_0 = [r(Stat1)\r(Stat2)\r(Stat3)]; putexcel A1 = "Nonwhite Sample Mean"; putexcel A3 = 1960; putexcel A6 = 1970; putexcel A9 = 1980; putexcel B2 = matrix(table4_0), names nformat(number_d2); *puts summary statistics in analysis.xlsx in a sheet labeled table 4; *regression variable creation; *terms for regression to be performed that involve income; qui gen yob_square = c.yob^2; la var yob_square "year of birth squared"; qui gen yob_cube = c.yob^3; la var yob_cube "year of birth cubed"; *regression and coefficient output; qui reg hsgrad i1919 c.yob##c.yob if year == 1960 & race != 1, vce(robust) depname("hsgrad 1960"); *first result from regression to start exporting to xml titled table2; qui outreg2 using table4, se replace excel bdec(3) noaster nocons keep(i1919) stat(coef se pval); foreach y in hsgrad yrsofeduc inctot_adj incwage_adj iemp ipoverty nmedinc_adj sei idislimwrk idisprevwrk disabduradj incss_adj irecss incwelfr_adj irecwelf {; foreach t in 1960 1970 1980 {; qui cou if year == `t' & `y' != .; *counts number of variables that arent null in the census year; if ((!("`y'" == "hsgrad" & `t' == 1960)) & r(N)){; *skipping what is already done outside of loop; *if there are any non null values, continues to perform regression *will output error if regression performed on variable with only nulls; if `t' == 1980 & ("`y'" == "inctot_adj" | "`y'" == "incwage_adj" | "`y'" == "iemp" | "`y'" == "incss_adj" | "`y'" == "irecss" | "`y'" == "incwelfr_adj" | "`y'" == "irecwelf") {; /* "For 1980 income measures only, the cohort trend is estimated as a cubic function to attempt to account for retirement at age 62" (696) */ qui reg `y' i1919 c.yob yob_square yob_cube if year == `t' & race != 1, depname("`y' `t'") vce(robust); *robust se: "Robust standard errors are in brackets"(688); }; else {; qui reg `y' i1919 c.yob##c.yob if year == `t' & race != 1, vce(robust) depname("`y' `t'"); *Model specifications outlined on p.687; }; qui outreg2 using table4, se append excel bdec(3) keep(i1919) stat(coef se pval) nocons noaster; *outputs i1919 coefficient to xml file titled table4; }; }; }; restore; end; table_4; capture program drop figure_3; program define figure_3; /* Figure 3: 1960 average years of schooling: men and women born in the United States Replication */ preserve; *observation limitation for regression; qui keep if (qage == 0 | qage == .) & (qage2 == 0 | qage2 == .) & yob >= 1912 & yob <= 1922; *keeps observations where age is not allocated; *variable creation for regression; qui egen time3 = group(yob); la var time3 "year of birth cohorts"; qui bys time3: gen f_time3 = (_n == 1); la var f_time3 "first observation in each time3 cohort"; qui su time3; local max_time3 = r(max); *counts number of years of birth; qui gen avgeduc = .; la var avgeduc "average years of education for each time3 cohort"; *regression and coefficient output; qui reg yrsofeduc ibn.time3 if year == 1960, noconstant; *coefficients are mean years of education for each yob cohort in 1960 census; forv i = 1 / `max_time3' {; *loops through each cohort; qui replace avgeduc = _b[`i'.time3] if time3 == `i'; *locates mean years of education coefficient for each cohort from; *regression, assigns this value to every observation in the same cohort; }; *graphing of regression coefficients; set graphics off; *disables graphics from popping up; scatter avgeduc time3 if f_time3 == 1, scheme(s1color) mcolor(black) ytitle("Years of Schooling") xtitle("Year of Birth") xlabel( 1 "1912" 2 " " 3 "1914" 4 " " 5 "1916" 6 " " 7 "1918" 8 " " 9 "1920" 10 " " 11 "1922") xline(8, lcolor(black) lwidth(thin) lpattern(dash)) note(Fig. 3. — 1960 average years of schooling: men and women born in the United States); *scatter plot of years of education by year of birth in 1960 census; qui gr save Figure3, replace; *saves scatter plot as a gph; qui gr export Figure3.pdf, replace; *saves scatter plot as a pdf; restore; end; figure_3; capture program drop figure_4; program define figure_4; *Figure 4: 1970 high school graduation: by year of birth replication; preserve; *observation limitations for regression; qui keep if (qage == 0 | qage == .) & (qage2 == 0 | qage2 == .) & yob >= 1912 & yob <= 1922; *keeps observations if their age is not allocated and they are born 1912-1922; *variable creation for regression; qui egen time4 = group(yob); la var time4 "year of birth cohorts"; qui egen time41 = group(yob sex); la var time41 "year of birth by sex cohorts"; qui bys time41: gen f_time4 = (_n == 1); la var f_time4 "first observation in time41 cohorts"; qui su time4; local max_time4 = r(max); *counts number of years of birth; qui gen pergrad = .; la var pergrad "Percent of Men Graduating"; qui gen pergradb = .; la var pergradb "Percent of Women Graduating"; *regression and coefficient output; qui replace hsgrad = hsgrad * 100; *puts hsgrad in percent terms; qui reg hsgrad ibn.time4 if year == 1970 & sex == 1, noconstant; *coeffs are mean graduation rate for men by year of birth in the 1970 census; forv i = 1 / `max_time4' {; qui replace pergrad = _b[`i'.time4] if time4 == `i' & sex == 1; *assigns mean graduation rate for the part of the `i'th time4 cohort that is *men to each of the male observations in that cohort; }; qui reg hsgrad ibn.time4 if year == 1970 & sex == 2, noconstant; *coeffs are mean graduation rate for women by year of birth in the 1970 census; forv i = 1 / `max_time4' {; qui replace pergradb = _b[`i'.time4] if time4 == `i' & sex == 2; *assigns mean graduation rate for the part of the `i'th time4 cohort that is *women to each of the female observations in that cohort; }; *graphing of regression coefficients; set graphics off; *disables gr from popping up; scatter pergrad pergradb time4 if f_time4 == 1, sort(sex) legend() scheme(s1color) mcolor(black) ytitle("Percent Graduating") xtitle("Year of Birth") msymbol(O D) xlabel( 1 "1912" 2 " " 3 "1914" 4 " " 5 "1916" 6 " " 7 "1918" 8 " " 9 "1920" 10 " " 11 "1922") xline(8, lcolor(black) lwidth(thin) lpattern(dash)) note(Fig. 4. — 1970 high school graduation: by year of birth); *scatter plots mean graduation rate for each time41 cohort (year of birth and *sex cohorts) by year of birth; qui gr save Figure4, replace; *saves scatter plot as a gph; qui gr export Figure4.pdf, replace; *saves scatter plot as a pdf; restore; end; figure_4; capture program drop figure_5; program define figure_5; /* Figure 5: a) 1980 high school graduation rate by quarter of birth. b) Regression -adjusted 1980 high school graduation rate by quarter of birth replication. */ preserve; *observation limitations for regression; qui keep if (qage == 0 | qage == .) & (qage2 == 0 | qage2 == .) & yob >= 1916 & yob <= 1920 & sex == 1; *keeps male observations that do not have allocated ages and are born 1916-1920; *regression variable creation; qui egen yobqtrc = group(yob birthqtr); la var yobqtrc "birth quarter by year of birth cohorts"; qui bys yobqtrc: gen f_yobqtrc = (_n == 1); la var f_yobqtrc "first observation in time5 cohorts"; qui su yobqtrc; local max_yobqtrc = r(max); *counts number of years of birth; qui gen pergrad5a = .; la var pergrad5a "high school graduation rate of each birth quarter"; replace hsgrad = hsgrad * 100; *replaced to be in percentage points; *regression and coefficient output; qui reg hsgrad ibn.yobqtrc if year == 1980, noconstant; *coefficients are mean high school graduation rate by birth quarter and year of; *birth as reported in the 1980 census; forv i = 1 / `max_yobqtrc' {; qui replace pergrad5a = _b[`i'.yobqtrc] if yobqtrc == `i'; *assigns mean graduation rate for the part of the `i'th time5 cohort to; *each of the in that cohort; }; *graphing of regression coefficients; scatter pergrad5a yobqtrc if f_yobqtrc == 1, scheme(s1color) mcolor(black) ytitle("Percent Graduating") xtitle("Quarter of Birth") xlabel( 1 "1916 Q1" 2 " " 3 " " 4 " " 5 "1917 Q1" 6 " " 7 " " 8 " " 9 "1918 Q1" 10 " " 11 " " 12 " " 13 "1919 Q1" 14 " " 15 " " 16 " " 17 "1920 Q1" 18 " " 19 " " 20 " ") xline(13, lcolor(black) lwidth(thin) lpattern(dash)) note(Fig. 5a - 1980 high school graduation rate by quarter of birth); *scatter plots mean graduation rate for each time5 cohort (year of birth and *birth quarter cohorts) by their birth quarter and year of birth; qui gr save Figure5a, replace; *saves scatter plot as a gph; qui gr export Figure5a.pdf, replace; *saves scatter plot as a pdf; *regression variable creation; qui gen pergrad5b = .; la var pergrad5b "high school graduation rates of each birth quarter cohort (regression adjusted)"; *regression and coefficient output; qui reg hsgrad c.yobqtrc ibn.birthqtr if year == 1980, nocons; *regression of high school graduation rates from the 1980 census on the *continuous years and quarters of birth 1916-1920 and binary birth quarter; *variables; predict rhsgrad, r; *extracts the residual of high school graduation rates - the change in high; *school graduation rates that is not explained by the linear trend of time nor; *seasonality of birth quarter; qui reg rhsgrad ibn.yobqtrc if year == 1980, nocons; *regression of the residual of the high school graduation rate on the birth; forv i = 1 / `max_yobqtrc' {; qui replace pergrad5b = _b[`i'.yobqtrc] if yobqtrc == `i'; *assigns mean graduation rate for the part of the `i'th time5 cohort to; *each of the in that cohort; }; *graphing of regression coefficients; set graphics off; *disables graphics from popping up; scatter pergrad5b yobqtrc if f_yobqtrc == 1, scheme(s1color) mcolor(black) ytitle("Percent Graduating") xtitle("Quarter of Birth") xlabel( 1 "1916 Q1" 2 " " 3 " " 4 " " 5 "1917 Q1" 6 " " 7 " " 8 " " 9 "1918 Q1" 10 " " 11 " " 12 " " 13 "1919 Q1" 14 " " 15 " " 16 " " 17 "1920 Q1" 18 " " 19 " " 20 " ") xline(13, lcolor(black) lwidth(thin) lpattern(dash)) note(Fig. 5b - Regression-adjusted 1980 high school graduation rate by quarter of birth); *scatter plot of percent disabled by quarter of birth; *reg take out trend and control seasonality ; qui gr save Figure5b, replace; *saves scatter plot as a gph; qui gr export Figure5b.pdf, replace; *saves scatter plot as a pdf; restore; end; figure_5; capture program drop figure_6; program define figure_6; *Figure 6: 1970 male disability rate: physical disability limits or prevents *work replication.; preserve; *observation limitations for regression; qui keep if sex == 1 & (qage == 0 | qage == .) & (qage2 == 0 | qage2 ==.) & yob >= 1912 & yob <= 1922; *keeps male observations that do not have their age allocated born 1912-1922; *variable creation for regression; qui egen time6 = group(yob); la var time6 "male year of birth cohorts"; qui bys time6: gen f_time6 = (_n == 1); la var f_time6 "first observation of each time6 cohort"; qui su time6; local max_time6 = r(max); *counts birth quarters; qui gen perdis = .; la var perdis "percent of observations that have a disability that affects their work"; qui replace idisaffwrk = idisaffwrk * 100; *scales it as percentage points; *regression and coefficient output; qui reg idisaffwrk ibn.time6 if year == 1970, noconstant; *coefficients are the time6 cohort's proportion disabled in the 1970 census; forv i = 1 / `max_time6' {; qui replace perdis = _b[`i'.time6] if time6 == `i'; *assigns the cohort's proportion disabled to perdis for that cohort; }; *graphing regression coefficients; set graphics off; *disables graph from popping up; scatter perdis time6 if f_time6 ==1, scheme(s1color) mcolor(black) ytitle("Percent with a Disability") xtitle("Year of Birth") xlabel( 1 "1912" 2 " " 3 "1914" 4 " " 5 "1916" 6 " " 7 "1918" 8 " " 9 "1920" 10 " " 11 "1922") xline(8, lcolor(black) lwidth(thin) lpattern(dash)) note(Fig. 6. — 1970 male disability rate: physical disability limits or prevents work); *scatter plot of percent disabled by year of birth; qui gr save Figure6, replace; *saves scatter plot as a gph; qui gr export Figure6.pdf, replace; *saves scatter plot as a pdf; restore; end; figure_6; capture program drop figure_8; program define figure_8; *Figure 8: Average welfare payments for women and nonwhites: by year of birth *replication.; preserve; *observation limitation for regression; keep if (qage == 0 | qage == .) & (qage2 == 0 | qage2 == .); *keeps observations with unallocated ages; *variable creation for regressions; *replace incwelfr_adj = 0 if incwelfr_adj == .; qui egen yobc = group(yob); la var yobc "year of birth cohorts"; qui egen yobsexc = group(yob sex);*year of birth and sex cohorts; la var yobsexc "year of birth and sex cohorts"; gen nonwhite = race != 1; la var nonwhite "non-white race"; qui egen yobracec = group(yob nonwhite); la var yobracec "year of birth and white/nonwhite cohorts"; qui egen yobracesexc = group(yob nonwhite sex); la var yobracesexc "year of birth, sex, and white/nonwhite cohorts"; qui bys yobracesexc: gen f_nonwhiteman = (_n == 1) if nonwhite & sex == 1; la var f_nonwhiteman "first observation from each cohort of nonwhite men out of all cohorts of observations grouped by year of birth, sex, and race"; qui bys yobracesexc: gen f_whitewomn = (_n == 1) if (!nonwhite) & sex == 2; la var f_whitewomn "first observation from each cohort of white women out of all cohorts of observations grouped by year of birth, sex, and race"; qui su yobsexc; local max_yobsexc = r(max); *number of year of birth, sex cohorts; *calculations for mean welfare for women and non-white people; qui gen meanwelfsex = .; la var meanwelfsex "Payments to Women"; qui su yobracec; local max_yobracec = r(max); *number of year of birth, race cohorts; qui gen meanwelfrace = .; la var meanwelfrace "Payements to Non-White Persons"; *calculations for percent of women and nonwhite people receiving welfare; qui gen perwelfsex = .; la var perwelfsex "Payments to Women"; replace irecwelf = irecwelf *100 ; *scales indicator variable for if someone receives welfare to out of 100; qui gen perwelfrace = .; la var perwelfrace "Payments to Non-White Persons"; *regression and coefficient output; qui reg incwelfr_adj ibn.yobsexc, noconstant; *coefficients are mean welfare by year of birth and sex; forv i = 1 / `max_yobsexc' {; qui replace meanwelfsex = _b[`i'.yobsexc] if yobsexc == `i' & sex == 2; *assigns coefficients to mean welfare variable for women; *(if assigned to both women and men, all cohorts would be graphed); }; qui reg incwelfr_adj ibn.yobracec, noconstant; *coefficients are mean welfare by year of birth and race; forv i = 1 / `max_yobracec' {; qui replace meanwelfrace = _b[`i'.yobracec] if yobracec == `i' & nonwhite; *assigns coefficients to mean welfare variable for nonwhite people *(if assigned to both nonwhite and white, all cohorts would be graphed); }; qui reg irecwelf ibn.yobsexc, noconstant; *coefficients are percent of cohort receiving welfare by year of birth and sex; forv i = 1 / `max_yobsexc' {; qui replace perwelfsex = _b[`i'.yobsexc] if yobsexc == `i' & sex == 2; *assigns coefficients to the percent of cohort that receives welfare *variable for women cohorts. *(if assigned to both women and men, all cohorts would be graphed); }; qui reg irecwelf ibn.yobracec, noconstant; *coefficients are percent of cohort receiving welfare by year of birth and race; forv i = 1 / `max_yobracec' {; qui replace perwelfrace = _b[`i'.yobracec] if yobracec == `i' & nonwhite; *assigns coefficients to the percent of cohort that receives welfare *variable for nonwhite cohorts; *(if assigned to both nonwhite and white, all cohorts would be graphed); }; *graphing of coefficients; scatter meanwelfsex meanwelfrace yobc if (f_whitewomn == 1 | f_nonwhiteman == 1), scheme(s1color) mcolor(black) ytitle("Mean Welfare Payement (2005 Dollars)") xtitle("Year of Birth") xlabel( 1 "1911" 2 " " 3 "1913" 4 " " 5 "1915" 6 " " 7 "1917" 8 " " 9 "1919" 10 " " 11 "1921" 12 " " 13 "1923" 14 " ") xline(9, lcolor(black) lwidth(thin) lpattern(dash)) note(Fig. 8a. - Average welfare payments for women and non-white persons: by year of birth); *scatter plot of mean welfare for women and nonwhite people by year of birth; qui gr save Figure8a, replace; *saves scatter plot as a gph; qui gr export Figure8a.pdf, replace; *saves scatter plot as a pdf; scatter perwelfsex perwelfrace yobc if (f_whitewomn == 1 | f_nonwhiteman == 1), scheme(s1color) mcolor(black) ytitle("Percent Receiving Welfare") xtitle("Year of Birth") xlabel( 1 "1911" 2 " " 3 "1913" 4 " " 5 "1915" 6 " " 7 "1917" 8 " " 9 "1919" 10 " " 11 "1921" 12 " " 13 "1923" 14 " ") xline(9, lcolor(black) lwidth(thin) lpattern(dash)) note(Fig. 8b. - Percent of women and non-white persons who receive welfare payments: by year of birth); *scatter plot of percent of women and non-white people who receive welfare by *year of birth; qui gr save Figure8b, replace; *saves scatter plot as a gph; qui gr export Figure8b.pdf, replace; *saves scatter plot as a pdf; restore; end; figure_8;
4b81e230a7b45d8124d777dfe9d5ed6fd45b9e75
[ "Text", "Stata" ]
2
Text
zthab/ECON203Replication
6b44d578ada89b43526eb8db426fe865ca12d68b
1540be73accb1148495e69c7d673910937b9e129
refs/heads/master
<file_sep>import sys from PyQt5 import QtWidgets from includes.gui import interface class ChatWindow(QtWidgets.QMainWindow, interface.Ui_MainWindow): def __init__(self): super().__init__() self.setupUi(self) self.init_handlers() def init_handlers(self): self.MessageSubmit.clicked.connect(self.send_message) def send_message(self): message = self.MessageInput.text() self.MessagesView.appendPlainText(message) self.MessageInput.clear() app = QtWidgets.QApplication(sys.argv) window = ChatWindow() window.show() app.exec_() <file_sep>class User: first_name: str last_name: str def __init__(self, first_name, last_name): self.first_name = first_name self.last_name = last_name def full_name(self): return f"Fullname: {self.first_name} {self.last_name}" class AgedUser(User): __age: int def __init__(self, first_name, last_name, age): super().__init__(first_name, last_name) self.__age = age def full_name_age(self): return f"Fullname: {self.first_name} {self.last_name} {self.__age}" john = AgedUser("John", "Doe", 30) print(john.full_name_age()) <file_sep># -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'interface.ui' # # Created by: PyQt5 UI code generator 5.13.1 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.resize(314, 425) MainWindow.setCursor(QtGui.QCursor(QtCore.Qt.ArrowCursor)) self.centralwidget = QtWidgets.QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget") self.verticalLayout = QtWidgets.QVBoxLayout(self.centralwidget) self.verticalLayout.setObjectName("verticalLayout") self.MessagesView = QtWidgets.QPlainTextEdit(self.centralwidget) self.MessagesView.setStyleSheet("") self.MessagesView.setReadOnly(True) self.MessagesView.setObjectName("MessagesView") self.verticalLayout.addWidget(self.MessagesView) self.MessageInput = QtWidgets.QLineEdit(self.centralwidget) self.MessageInput.setStyleSheet("") self.MessageInput.setObjectName("MessageInput") self.verticalLayout.addWidget(self.MessageInput) self.MessageSubmit = QtWidgets.QPushButton(self.centralwidget) self.MessageSubmit.setEnabled(True) self.MessageSubmit.setObjectName("MessageSubmit") self.verticalLayout.addWidget(self.MessageSubmit) MainWindow.setCentralWidget(self.centralwidget) self.retranslateUi(MainWindow) QtCore.QMetaObject.connectSlotsByName(MainWindow) def retranslateUi(self, MainWindow): _translate = QtCore.QCoreApplication.translate MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow")) self.MessagesView.setPlaceholderText(_translate("MainWindow", "Your memories will be here...")) self.MessageInput.setPlaceholderText(_translate("MainWindow", "Message")) self.MessageSubmit.setText(_translate("MainWindow", "Send your message"))
44387d16986a1d467e45b99deb5d69fa13f646c7
[ "Python" ]
3
Python
mrcowboy007/Messenger-from-skilbox
6ce968126e73095dff58f5e652a3d7b9365a870d
e414f4805c9b216f2949c0bfa925ccd9efcae141
refs/heads/master
<repo_name>freifunkh/ansible-configs<file_sep>/supernodes.yml --- - hosts: supernodes roles: # General - { name: ffh.devname, tags: devname } - { name: ferm, tags: ferm } - { name: supernode, tags: supernode } - { name: cli_tools, tags: cli_tools } - { name: networkd, tags: networkd } - { name: reboot, tags: reboot } # Enable reboot role on initial roleout. - { name: babeld, tags: babeld } - { name: simple_mail, tags: simple_mail } - { name: admin, tags: admin } - { name: cron-apt, tags: cron-apt } # Batman - { name: mesh_batman, tags: mesh_batman } - { name: mesh_fastd, tags: mesh_fastd } - { name: mesh_fastd_remotes_backbone, tags: mesh_fastd_remotes_backbone } - { name: mesh_fastd_remotes_peers_git, tags: mesh_fastd_remotes_peers_git } - { name: mesh_announce, tags: mesh_announce } # Stats, Monitoring, Logging - { name: radv_server, tags: radv_server } - { name: dns_recursive, tags: dns_recursive } - { name: dhcp_server, tags: dhcp_server } - { name: gateway_announcement, tags: gateway_announcement } - { name: node_exporter, tags: node_exporter } - { name: iperf3, tags: iperf3 } - { name: journald, tags: journald } - { name: ffh.zabbix-agent, tags: zabbix-agent } - { name: reboot, tags: reboot } # Enable reboot role on initial roleout. vars_files: - vars/all_hosts.yml - vars/domains.yml - vars/secrets.yml <file_sep>/host_vars/sn02.yml --- servername: sn02 sn: 2 mail_fqdn: "sn02.s.ffh.zone" admin_authorized: [lemoer, cawi, luk, manawyrm, aiyion, jue, okrueger, raute, tobby, sush, codefetch, DarkAMD] networkd_configures: - iface: eth0 addresses: - fc00:e968:6179::de52:7100/64 dhcp: true gateway6: fe80::1 no_radv_accept: true dns_server: [192.168.127.12, 8.8.8.8] babeld_interfaces: ['gre-steintor', 'gre-leintor', 'gre-clevertor', 'gre-listertor', 'gre-aegidientor', 'gre-bruehltor'] babeld_interface_penalty: gre-aegidientor: 666 gre-steintor: 666 gre-leintor: 110 gre-clevertor: 120 gre-listertor: 666 gre-bruehltor: 100 legacy_dom0: true radv_announce_default: false <file_sep>/harvester.yml --- - hosts: harvester roles: # General - { name: networkd, tags: networkd } - { name: ferm, tags: ferm } - { name: simple_mail, tags: simple_mail } - { name: admin, tags: admin } - { name: cli_tools, tags: cli_tools } - { name: cron-apt, tags: cron-apt } - { name: journald, tags: journald } # Batman - { name: mesh_batman, tags: mesh_batman } - { name: mesh_fastd, tags: mesh_fastd } - { name: mesh_fastd_remotes_backbone, tags: mesh_fastd_remotes_backbone } # Harvester - { name: influxdb, tags: influxdb } - { name: prometheus, tags: prometheus } - { name: node_exporter, tags: node_exporter } - { name: grafana, tags: grafana } - { name: yanic, tags: yanic } - { name: nginx, tags: nginx } - { name: ffh.zabbix-agent, tags: zabbix-agent } vars_files: - vars/all_hosts.yml - vars/domains.yml - vars/secrets.yml vars: - servername: harvester - mail_fqdn: "harvester.ffh.zone" - admin_authorized: [lemoer, cawi, luk, manawyrm, aiyion, jue, okrueger, raute, bschelm, tobby, sush, codefetch, DarkAMD, s_2] - networkd_configures: - iface: eth0 addresses: - 192.168.127.12/27 - fdf8:f53e:61e4::18/64 gateway4: 192.168.3.11 gateway6: fc00:e968:6179::de52:7100 dns_server: [172.16.58.3, 172.16.17.32, 213.133.100.100] - legacy_dom0: true - mesh_ula_address_suffix: 1231 - yanic_port: 10002 - yanic_nodes_enabled: true - yanic_nodes_path: /var/www/harvester.ffh.zone - yanic_influxdb_enabled: true - yanic_influx_database: yanic_harvester - yanic_influx_hostname: http://localhost:8086/ # yanic_influx_password in var/secrets.yml - influxdb_meta_path: "/media/data/influxdb/meta" - influxdb_data_path: "/media/data/influxdb/data" - influxdb_wal_path: "/media/data/influxdb/wal" - influxdb_bind_address: ":8086" - influxdb_clients: - "192.168.127.12/32" # temp stats.ffh.zone - "fc00:db20:35b:7399::5/128" # temp stats.ffh.zone - prometheus_storage_path: "/media/data/prometheus" - prometheus_storage_retention: "8760h0m0s" - prometheus_clients: - "192.168.127.12/32" # temp stats.ffh.zone - "fc00:db20:35b:7399::5/128" # temp stats.ffh.zone - prometheus_scrapes: - name: prometheus interval: 60 timeout: 60 targets: ['localhost:9090'] - name: node_exporter interval: 60 timeout: 30 targets: - sn01.s.ffh.zone:9100 - sn02.s.ffh.zone:9100 - sn03.s.ffh.zone:9100 - sn04.s.ffh.zone:9100 - sn05.s.ffh.zone:9100 - sn06.s.ffh.zone:9100 - sn07.s.ffh.zone:9100 - sn08.s.ffh.zone:9100 - sn09.s.ffh.zone:9100 - sn10.s.ffh.zone:9100 - bruehltor.e.ffh.zone:9100 - listertor.e.ffh.zone:9100 - clevertor.e.ffh.zone:9100 - leintor.e.ffh.zone:9100 - aegidientor.e.ffh.zone:9100 - harvester.ffh.zone:9100 - grafana_datadir: "/media/data/grafana" - grafana_allow_signup: true - grafana_anonymous_access: true - grafana_smtp_host: "mail.ffh.zone:25" - grafana_smtp_from: "<EMAIL>" - nginx_sites: - domain: harvester.ffh.zone root: /var/www/harvester.ffh.zone locations: - location: / allow_cors: true directory_index: true gzip: true tls: true tls_redirect_to_https: true - domain: opkg.ffh.zone tls: false locations: - location: /openwrt/ type: proxy proxy_pass_host: false proxy_forward_url: http://downloads.openwrt.org/ - location: /lede/ type: proxy proxy_pass_host: false proxy_forward_url: http://archive.openwrt.org/ - location: /modules/ type: proxy proxy_pass_host: false proxy_forward_url: http://build.ffh.zone/job/gluon-beta/ws/beta/packages/ - domain: prometheus.ffh.zone tls: true locations: - location: / type: proxy proxy_forward_url: http://[::1]:9090/ - domain: stats.ffh.zone tls: true tls_redirect_to_https: true locations: - location: / type: proxy proxy_forward_url: http://localhost:3000/ <file_sep>/README.md # ansible config for freifunkh ## how to use: **suggested directory layout:** --- inventory/ | \-- ff | |-- roles/ | |-- ff/ | | |-- docs/ | | | \-- ... | | \-- roles/ | | |-- cli_tools/ | | |-- dhcp_server/ | | \-- ... | | | \-- galaxy | \-- ... | | |-- ff/ | |-- sn01.yml | |-- sn02.yml | |-- webserver.yml | \-- ... | \-- ansible.cfg **setup:** ``` shell mkdir roles git clone <EMAIL>:freifunkh/ansible.git roles/ff mkdir roles/galaxy git clone <EMAIL>:freifunkh/ansible-configs.git ff mkdir inventory ln -s ../ff/inventory inventory/ff # ansible.cfg cat > ansible.cfg <<EOF [defaults] inventory = inventory roles_path = /etc/ansible/roles:roles/ff/roles:roles/galaxy EOF ``` **deploy a host:** ``` shell ansible-playbook ff/sn03.yml ``` <file_sep>/ns1.yml --- - hosts: ns1 roles: - { name: networkd, tags: networkd } - { name: ferm, tags: ferm } - { role: dns_authoritative, tags: dns_authoritative } - { role: dns_zonenodes, tags: dns_zonenodes } - { name: simple_mail, tags: simple_mail } - { name: journald, tags: journald } - { name: admin, tags: admin } - { name: cli_tools, tags: cli_tools } - { name: cron-apt, tags: cron-apt } - { name: postfix, tags: postfix } - { name: ntp, tags: ntp } - { name: ffh.zabbix-agent, tags: zabbix-agent } vars_files: - vars/dns-external.yml - vars/dns-internal.yml - vars/all_hosts.yml vars: - servername: ns1 - mail_fqdn: "ns1.fnorden.net" - admin_authorized: [lemoer, cawi, luk, manawyrm, aiyion, jue, okrueger, raute, bschelm, tobby, sush, codefetch, DarkAMD] - networkd_configures: - iface: eth0 addresses: - 172.16.58.3/22 - 2a03:fdf8:f53e:61e4::18/64 gateway4: 172.16.31.10 gateway6: fe80::1 dns_server: [8.8.8.8, 8.8.4.4] - dns_authoritative_nameserver: - nameserver: "ns1.fnorden.net." - nameserver: "ns2.fnorden.net." - nameserver: "ns3.fnorden.net." - dns_authoritative_allowAXFR: - nameserver: "fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b" - nameserver: "172.16.31.10" - dns_authoritative_notify: - nameserver: "172.16.58.3" - dns_authoritative_listen_on: - "127.0.0.1" - "::1" - "172.16.58.3" - "fc00:e968:6179::de52:7100" - dns_authoritative_external: - domain: "n.ffh.zone" zonefile: "n.ffh.zone.zone" - domain: "f.f.0.0.0.9.7.0.2.0.a.2.ip6.arpa" zonefile: "f.f.0.0.0.9.7.0.2.0.a.2.ip6.arpa.zone" - domain: "ffh" zonefile: "ffh.zone" - domain: "hannover.freifunk.net" zonefile: "hannover.freifunk.net.zone" - dns_authoritative_SOAmail: "zonemaster.ffh.zone" - dns_zonenodes_toplevel: "ffh.zone." - dns_zonenodes_nodedomain: "n.ffh.zone" - dns_zonenodes_rdnsdomain: "f.f.0.0.0.9.7.0.2.0.a.2.ip6.arpa" - dns_zonenodes_matchIP: "/^2a02/" - dns_zonenodes_nodeurl: "https://harvester.ffh.zone/nodes.json" - postfix_myhostname: "mail.ffh.zone" - postfix_virtual_alias_domains: "hannover.freifunk.net, freifunk-hannover.de" - postfix_mynetworks: - "127.0.0.0/8" - "[::ffff:127.0.0.0]/104" - "[::1]/128" - "{{ lookup('dig', 'web.ffh.zone./A') }}/32" - "[{{ lookup('dig', 'web.ffh.zone./AAAA') }}]/128" # - "{{ lookup('dig', 'sn01.s.ffh.zone./A') }}/32" # - "[{{ lookup('dig', 'sn01.s.ffh.zone./AAAA') }}]/128" - "{{ lookup('dig', 'sn02.s.ffh.zone./A') }}/32" - "[{{ lookup('dig', 'sn02.s.ffh.zone./AAAA') }}]/128" - "{{ lookup('dig', 'sn03.s.ffh.zone./A') }}/32" # - "[{{ lookup('dig', 'sn03.s.ffh.zone./AAAA') }}]/128" - "{{ lookup('dig', 'sn04.s.ffh.zone./A') }}/32" - "[{{ lookup('dig', 'sn04.s.ffh.zone./AAAA') }}]/128" - "{{ lookup('dig', 'sn05.s.ffh.zone./A') }}/32" - "[{{ lookup('dig', 'sn05.s.ffh.zone./AAAA') }}]/128" - "{{ lookup('dig', 'sn06.s.ffh.zone./A') }}/32" - "[{{ lookup('dig', 'sn06.s.ffh.zone./AAAA') }}]/128" - "{{ lookup('dig', 'sn07.s.ffh.zone./A') }}/32" - "[{{ lookup('dig', 'sn07.s.ffh.zone./AAAA') }}]/128" - "{{ lookup('dig', 'sn08.s.ffh.zone./A') }}/32" - "[{{ lookup('dig', 'sn08.s.ffh.zone./AAAA') }}]/128" - "{{ lookup('dig', 'sn09.s.ffh.zone./A') }}/32" - "[{{ lookup('dig', 'sn09.s.ffh.zone./AAAA') }}]/128" - "{{ lookup('dig', 'sn10.s.ffh.zone./A') }}/32" - "[{{ lookup('dig', 'sn10.s.ffh.zone./AAAA') }}]/128" # - "{{ lookup('dig', 'steintor.e.ffh.zone./A') }}/32" # - "[{{ lookup('dig', 'steintor.e.ffh.zone./AAAA') }}]/128" - "{{ lookup('dig', 'leintor.e.ffh.zone./A') }}/32" - "[{{ lookup('dig', 'leintor.e.ffh.zone./AAAA') }}]/128" - "{{ lookup('dig', 'bruehltor.e.ffh.zone./A') }}/32" - "[{{ lookup('dig', 'bruehltor.e.ffh.zone./AAAA') }}]/128" # - "{{ lookup('dig', 'listertor.e.ffh.zone./A') }}/32" # - "[{{ lookup('dig', 'listertor.e.ffh.zone./AAAA') }}]/128" - "{{ lookup('dig', 'aegidientor.e.ffh.zone./A') }}/32" - "[{{ lookup('dig', 'aegidientor.e.ffh.zone./AAAA') }}]/128" - "{{ lookup('dig', 'ns1.fnorden.net./A') }}/32" - "[{{ lookup('dig', 'ns1.fnorden.net./AAAA') }}]/128" - "{{ lookup('dig', 'log.ffh.zone./A') }}/32" - "[{{ lookup('dig', 'log.ffh.zone./AAAA') }}]/128" - "{{ lookup('dig', 'stats.ffh.zone./A') }}/32" - "[{{ lookup('dig', 'stats.ffh.zone./AAAA') }}]/128" - "{{ lookup('dig', 'harvester.ffh.zone./A') }}/32" - "[{{ lookup('dig', 'harvester.ffh.zone./AAAA') }}]/128" - "{{ lookup('dig', 'observer.ffh.zone./A') }}/32" - "[{{ lookup('dig', 'observer.ffh.zone./AAAA') }}]/128" - zabbix_agent_server: "zabbix.ffh.zone" - zabbix_agent_server_active: "zabbix.ffh.zone" <file_sep>/build.yml --- - hosts: build roles: # General - { name: ferm, tags: ferm } - { name: ffh.zabbix-agent, tags: zabbix-agent } vars_files: - vars/all_hosts.yml - vars/secrets.yml vars: - servername: build - mail_fqdn: "build.ffh.zone" - admin_authorized: [lemoer, cawi, luk, manawyrm, aiyion, jue, okrueger, raute, bschelm, tobby, sush, codefetch, DarkAMD] <file_sep>/host_vars/sn01.yml --- servername: sn01 sn: 1 mail_fqdn: "sn01.s.ffh.zone" admin_authorized: [lemoer, cawi, luk, manawyrm, aiyion, jue, okrueger, raute, tobby, sush, codefetch, DarkAMD] networkd_configures: - iface: eth0 addresses: - 192.168.127.12/24 - fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b/64 gateway4: 192.168.3.11 gateway6: fe80::1 no_radv_accept: true dns_server: [1.1.1.1, 8.8.8.8] babeld_interfaces: ['gre-steintor', 'gre-leintor', 'gre-clevertor', 'gre-listertor', 'gre-aegidientor', 'gre-bruehltor'] babeld_interface_penalty: gre-aegidientor: 666 gre-steintor: 666 gre-leintor: 110 gre-clevertor: 120 gre-listertor: 666 gre-bruehltor: 100 legacy_dom0: true radv_announce_default: false fix_netifnames: true <file_sep>/host_vars/sn06.yml --- servername: sn06 sn: 6 mail_fqdn: "sn06.s.ffh.zone" admin_authorized: [lemoer, cawi, luk, manawyrm, aiyion, jue, okrueger, raute, tobby, sush, codefetch, DarkAMD] networkd_configures: - iface: eth0 addresses: - 192.168.127.12/24 - fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b/64 gateway4: 192.168.3.11 gateway6: fe80::1 no_radv_accept: true dns_server: [172.16.31.10, 192.168.127.12] babeld_interfaces: ['gre-steintor', 'gre-leintor', 'gre-clevertor', 'gre-listertor', 'gre-aegidientor', 'gre-bruehltor'] babeld_interface_penalty: gre-aegidientor: 666 gre-steintor: 130 gre-leintor: 110 gre-clevertor: 100 gre-listertor: 120 gre-bruehltor: 666 legacy_dom0: true radv_announce_default: false
b5ae80aa4a2b7bd8781fb09962b180f229b6cc96
[ "Markdown", "YAML" ]
8
Markdown
freifunkh/ansible-configs
3183b79b81d98ca4c9042d2d2636cbce74088c31
fc9e9d69e4fe713f1f33ab2c2955cfc6de2da4a3