text
stringlengths
27
775k
require 'httparty' require 'builder' require 'openssl' require 'cgi' module FreshBooks API_VERSION = '2.1' # provides a Hash-like response object with structure # isomorphic to actual xml response, slightly tidied. class Response < Hash attr_reader :status def initialize(data) super nil response = data["response"] response.delete "xmlns" @status = response.delete "status" update response end def success? status == "ok" end end class Connection # :nodoc: # <b>DEPRECATED:</b> Please use <tt>FreshBooks::Client.new</tt> instead. def self.new(*args) warn "[DEPRECATED] `FreshBooks::Connection` is deprecated. Please use `FreshBooks::Client` instead." Client.new(*args) end end # FreshBooks API client. instances are FreshBooks account # specific so you can, e.g. setup two clients and copy/ # sync data between them module Client include HTTParty # :call-seq: # new(domain, api_token) => FreshBooks::TokenClient # new(domain, consumer_key, consumer_secret, token, token_secret) => FreshBooks::OAuthClient # # creates a new FreshBooks API client. returns the appropriate client # type based on the authorization arguments provided def self.new(*args) case args.size when 2 then TokenClient.new(*args) when 5 then OAuthClient.new(*args) else raise ArgumentError end end def api_url # :nodoc: "https://#{@domain}/api/#{API_VERSION}/xml-in" end # HTTParty (sort of) assumes global connections to services # but we can easily avoid that by making an instance method # that knows account-specific details that calls its # coresponding class method. # note: we only need to provide a #post method because the # FreshBooks API is POST only def post(method, params={}) # :nodoc: Response.new Client.post(api_url, :headers => auth, :body => Client.xml_body(method, params)) end # takes nested Hash/Array combos and generates isomorphic # XML bodies to be POSTed to FreshBooks API def self.xml_body(method, params) xml = Builder::XmlMarkup.new(:indent => 2) xml.instruct! :xml, :version=>"1.0", :encoding=>"utf-8" xml.tag!("request", :method => method) do build_xml(params, xml) end xml.target! end # helper method to xml_body def self.build_xml(obj, xml=Builder::XmlMarkup.new) # ZOMG! haven't you ever heard of polymorphism?!? # of course. I'm simply electing not to pollute the # method space of two of the most common Ruby classes. # besides, what are the chances this library will ever # be used in a context where some other library hasn't # already defined #to_xml on Hash... case obj when Hash obj.each do |k,v| if [Hash, Array].include?(v.class) xml.tag!(k) { build_xml(v, xml) } else xml.__send__(k, v) end end when Array then obj.each { |e| build_xml(e, xml) } end xml.target! end # infer API methods based on 2-(and sometimes 3) deep method # chains sent to clients. this allows us to provide a simple # interface without actually knowing anything about the supported # API methods (and hence trusting users to read the official # FreshBooks API documentation) def method_missing(sym, *args) # :nodoc: NamespaceProxy.new self, sym end # nothing to see here... class NamespaceProxy < Struct.new(:client, :namespace) # :nodoc: def method_missing(sym, *args) # check for subordinate resources if [:invoice, :recurring].include?(namespace) and sym == :lines NamespaceProxy.new client, "#{namespace}.#{sym}" else client.post "#{namespace}.#{sym}", *args end end end class FreshBooksAPIRequest < HTTParty::Request private # HACK # FreshBooks' API unfortunately redirects to a login search # html page if you specify an endpoint that doesn't exist # (i.e. typo in subdomain) instead of returning a 404 def handle_response if loc = last_response['location'] and loc.match /loginSearch\.php$/ resp = Net::HTTPNotFound.new(1.1, 404, "Not Found") resp.instance_variable_set :@read, true resp.instance_variable_set :@body, <<EOS <?xml version="1.0" encoding="utf-8"?> <response xmlns="http://www.freshbooks.com/api/" status="fail"> <error>Not Found. Verify FreshBooks API endpoint</error> </response> EOS self.last_response = resp end super end end def self.post(path, options={}) # :nodoc: perform_freshbooks_api_request Net::HTTP::Post, path, options end private def self.perform_freshbooks_api_request(http_method, path, options) #:nodoc: options = default_options.dup.merge(options) process_cookies(options) FreshBooksAPIRequest.new(http_method, path, options).perform end end # Basic Auth client. uses an account's API token. class TokenClient include Client def initialize(domain, api_token) @domain = domain @username = api_token @password = 'X' end def auth { 'Authorization' => # taken from lib/net/http.rb 'Basic ' + ["#{@username}:#{@password}"].pack('m').delete("\r\n") } end end # OAuth 1.0 client. access token and secret must be obtained elsewhere. # cf. the {oauth gem}[http://oauth.rubyforge.org/] class OAuthClient include Client def initialize(domain, consumer_key, consumer_secret, token, token_secret) @domain = domain @consumer_key = consumer_key @consumer_secret = consumer_secret @token = token @token_secret = token_secret end def auth data = { :realm => '', :oauth_version => '1.0', :oauth_consumer_key => @consumer_key, :oauth_token => @token, :oauth_timestamp => timestamp, :oauth_nonce => nonce, :oauth_signature_method => 'PLAINTEXT', :oauth_signature => signature, }.map { |k,v| %Q[#{k}="#{v}"] }.join(',') { 'Authorization' => "OAuth #{data}" } end def signature CGI.escape("#{@consumer_secret}&#{@token_secret}") end def nonce [OpenSSL::Random.random_bytes(10)].pack('m').gsub(/\W/, '') end def timestamp Time.now.to_i end end end
#!/bin/bash # Use unofficial Bash Strict Mode set -euo pipefail IFS=$'\n\t' # LOG NC='\033[0m' # No Color RED='\033[0;31m' YELLOW='\033[0;33m' GREEN='\033[0;32m' function error() { typeset message message=$1 printf "${RED}[ERROR]${NC} - $message\n" } function warning() { typeset message message=$1 printf "${YELLOW}[WARNING]${NC} - $message\n" } function info() { typeset message message=$1 printf "${GREEN}[INFO]${NC} - $message\n" } # Homebrew install function brewInstall() { typeset appName appName=$1 # check whether Homebrew is installed if ! hash brew 2>/dev/null then echo "Homebrew isn't installed. Please install it first." return 1 fi if ! brew list $appName 1> /dev/null 2> /dev/null then info "start install $appName " brew install $appName else info "$appName is already installed" fi return 0 } # Homebrew upgrade function brewUpgrade() { typeset appName appName=$1 # check whether Homebrew is installed if ! hash brew 2>/dev/null then echo "Homebrew isn't installed. Please install it first." return 1 fi if brew list $appName 1> /dev/null 2> /dev/null then info "start upgrade $appName, make sure execute \"brew update\" first" echo $(brew upgrade $appName) else warning "$appName is not installed" fi return 0 } # Register config in shell startup script function registerInZshrc() { typeset filePath typeset comments filePath=$1 comments=$2 if [ ! -e $filePath ] then warning "$filePath not exists" return 0 fi if grep -p "$filePath" ~/.zshrc 1> /dev/null then warning "$filePath is already registered" return 0 fi info "start register $filePath" echo "" >> ~/.zshrc echo "# $comments" >> ~/.zshrc echo "source $filePath" >> ~/.zshrc return 0 } # create directory function createDir() { typeset dirPath dirPath=$1 if [ ! -d $dirPath ] then info "create folder \"$dirPath\"" mkdir -p "$dirPath" else warning "folder \"$dirPath\" already exists" fi } # install golang.org/x/pkg function installGoXPkg() { typeset pkgName typeset pkgURL pkgName=$1 pkgURL=$2 pkgPath="$GOPATH/src/$pkgName" createDir "$(dirname "$pkgPath")" # create parent directory of pkgPath if [ -d "$pkgPath" ] then info "update $pkgName" pushd "$pkgPath" 1 > /dev/null git pull popd 1 > /dev/null else info "download $pkgName" git clone "$pkgURL" "$pkgPath" 2> /dev/null || info "$pkgName is already installed" fi }
#!/usr/bin/perl use DBI; use strict; use Data::UUID; my $driver = "SQLite"; my $database = "db/cablix.db"; my $dsn = "DBI:$driver:dbname=$database"; my $userid = ""; my $password = ""; my $dbh = DBI->connect($dsn, $userid, $password, { RaiseError => 1 }) or die $DBI::errstr; print "Opened database successfully\n"; my $stmt = qq(SELECT max(id) from adder;); my $sth = $dbh->prepare( $stmt ); my $rv = $sth->execute() or die $DBI::errstr; if($rv < 0) { print $DBI::errstr; } my $max; while(my @row = $sth->fetchrow_array()) { $max = $row[0]; print "Max ID = ". $row[0] . "\n"; } print "Operation done successfully\n"; my ($size, $number) = @ARGV; if (not defined $size) { die "ciao! la prossima $0 <size> <number>\n"; } if (not defined $number) { die "Need number\n"; } print "Start create $number adder of $size racks each\n"; my $ug = Data::UUID->new; my $istr=qq[insert into adder (id,uuid,size) values(?,?,?)]; $sth = $dbh->prepare($istr); for (my $i=$max;$i<($number+$max);$i++){ my $uuid1 = $ug->create(); my $tuuid=$ug->to_string( $uuid1 ); $sth->execute($i+1,$tuuid,$size); print "$i - $tuuid \n"; } $dbh->disconnect();
package com.system.po; import java.util.List; /** * Student的扩展类 */ public class StudentCustom extends Student { //所属院系名 private String collegeName; //选课列表 private List<SelectedCourseCustom> selectedCourseList; public void setcollegeName(String collegeName) { this.collegeName = collegeName; } public String getcollegeName() { return collegeName; } public void setSelectedCourseList(List<SelectedCourseCustom> selectedCourseList) { this.selectedCourseList = selectedCourseList; } public List<SelectedCourseCustom> getSelectedCourseList() { return selectedCourseList; } }
use std::fs; use std::fs::File; use std::path::PathBuf; use serde::{Deserialize, Serialize}; #[derive(Debug, Serialize, Deserialize)] pub struct Config { /// The port to host the daemon on. pub port: u16, /// The volume of the played songs. Normal volume is `1.0`. pub volume: f32, /// Whether to loop the last song of the queue. pub loop_last: bool, // Last.fm username for scrobbling. pub lastfm_username: String, // Last.fm password. pub lastfm_password: String, // Duration before scrobbling a track to Last.fm. pub lastfm_threshold_seconds: u64, } impl Default for Config { fn default() -> Self { Self { port: 9999, volume: 0.2, loop_last: false, lastfm_username: "".into(), lastfm_password: "".into(), lastfm_threshold_seconds: 110, } } } pub fn directory() -> PathBuf { let dir = dirs::config_dir().unwrap(); dir.join("pmu") } pub fn load() -> crate::Result<Config> { let directory = directory(); let path = &directory.join("config.json"); if !path.exists() { fs::create_dir_all(directory)?; let file = File::create(path)?; let default = Config::default(); serde_json::to_writer_pretty(file, &default)?; } let file = File::open(path)?; Ok(serde_json::from_reader(file)?) }
package es.upm.fi.dia.oeg.morph.base.path import org.junit.Assert.assertEquals import org.junit.Assert.assertTrue import org.junit.Test class JSONPath_PathExpressionTest { @Test def TestEvaluate() { println("------------------ TestEvaluate ------------------") val json: String = """[ { "name" : "john", "gender" : "male", "age": 28}, [ 10, "ben" ], { "name" : "lucie", "gender": "female"}, ]""" var path = new JSONPath_PathExpression("$[*]['gender']") val gender = path.evaluate(json) println(gender) assertEquals("male", gender(0)) assertEquals("female", gender(1)) path = new JSONPath_PathExpression("$[*].age") val age = path.evaluate(json) println(age) assertEquals(28, age(0)) path = new JSONPath_PathExpression("$[0]") val dic = path.evaluate(json) assertEquals(1, dic.length) assertEquals("""{"name":"john","gender":"male","age":28}""", dic(0)) println(dic) path = new JSONPath_PathExpression("$[1]") val arr = path.evaluate(json) assertEquals(1, arr.length) assertEquals("""[10,"ben"]""", arr(0)) println(arr) path = new JSONPath_PathExpression("$[0") val lst = path.evaluate(json) println(lst) assertEquals(lst, List(json)) } @Test def TestEvaluate2() { println("------------------ TestEvaluate2 ------------------") val json: String = """[ { "name" : "john", "gender" : "male", "age": 28}, [ 10, "ben" ], { "name" : "lucie", "gender": "female"}, ]""" var path = new JSONPath_PathExpression("$[?(@.gender == 'male')].age") val result = path.evaluate(json) println(result) } @Test def TestEvaluate3() { println("------------------ TestEvaluate3 ------------------") val json: String = """ {"p": { "name" : "john", "gender" : "male", "age": 28}}, """ var path = new JSONPath_PathExpression("$.p[?(@.gender == 'male')][?(@.name == 'john')].age") var result = path.evaluate(json) println(result) path = new JSONPath_PathExpression("$.p[?(@.gender == 'male' && @.name == 'john')].age") result = path.evaluate(json) println(result) } @Test def TestEvaluate4() { println("------------------ TestEvaluate4 ------------------") val json: String = """ { "dept":"Sales", "code":"sa", "manager":"F. Underwood", "members":[{"name":"mark", "gender":"male", "age":40}, {"name":"sophie", "gender":"female", "age":23}]} """ var path = new JSONPath_PathExpression("$.members[?(@.age >= 40)].name") var result = path.evaluate(json) println(result) } }
#!/bin/bash -e export NAME=udp # shellcheck source=examples/verify-common.sh . "$(dirname "${BASH_SOURCE[0]}")/../verify-common.sh" run_log "Send some UDP packets" echo -n HELO | nc -4u -w1 127.0.0.1 10000 echo -n OLEH | nc -4u -w1 127.0.0.1 10000 run_log "Check backend log" docker-compose logs service-udp | grep HELO docker-compose logs service-udp | grep OLEH run_log "Check admin stats" curl -s http://127.0.0.1:10001/stats | grep udp | grep -v "\: 0"
using System.CommandLine; using System.Threading.Tasks; using Miru.Consolables; using Miru.Core; namespace Miru.Makers; public class MakeJobConsolable : Consolable { public MakeJobConsolable() : base("make.job", "Make a new Job") { Add(new Argument<string>("in")); Add(new Argument<string>("name")); Add(new Argument<string>("action")); Add(new Option<bool>("--no-tests", "--no-test")); Add(new Option<bool>("--only-tests", "--only-test")); } public class ConsolableHandler : IConsolableHandler { private readonly MiruSolution _solution; public ConsolableHandler(MiruSolution solution) { _solution = solution; } public string In { get; set; } public string Name { get; set; } public string Action { get; set; } public bool NoTests { get; set; } public bool OnlyTests { get; set; } public async Task Execute() { var make = new Maker(_solution); Console2.BreakLine(); make.Job(In, Name, Action, OnlyTests, NoTests); Console2.BreakLine(); await Task.CompletedTask; } } }
AccountSettings = new Mongo.Collection('accountSettings'); AccountSettings.attachSchema(new SimpleSchema({ _id: { type: String, }, booleanValue: { type: Boolean, optional: true, }, sort: { type: Number, decimal: true, }, })); AccountSettings.allow({ update(userId) { const user = Users.findOne(userId); return user && user.isAdmin; }, }); if (Meteor.isServer) { Meteor.startup(() => { AccountSettings.upsert({ _id: 'accounts-allowEmailChange' }, { $setOnInsert: { booleanValue: false, sort: 0, }, }); }); }
package com.HBuilder.integrate; import java.util.Random; import android.app.ListActivity; import android.content.Intent; import android.os.Bundle; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ListView; import android.widget.TextView; public class ActivityEntry extends ListActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setListAdapter(new MyListViewAdapter()); getListView().setTextFilterEnabled(true); } @Override protected void onListItemClick(ListView l, View v, int position, long id) { // TODO Auto-generated method stub super.onListItemClick(l, v, position, id); onListItemClick(position); } void onListItemClick(int index) { Intent intent = null; intent = new Intent(ActivityEntry.this, acts[index].cls); this.startActivity(intent); } AcitivtyInfo[] acts = new AcitivtyInfo[]{ new AcitivtyInfo("webapp集成方式", SDK_WebApp.class), new AcitivtyInfo("webview集成方式", SDK_WebView.class) }; class AcitivtyInfo{ String title; Class<? extends android.app.Activity> cls; AcitivtyInfo(String title,Class cls){ this.title = title; this.cls = cls; } } private static int randomColor(){ int count = 8; int ret = 0; // StringBuffer sb = new StringBuffer("0X"); for(int i = count - 1 ; i >= 0 ; i--){ ret += (new Random().nextInt(16) << (i*4)); } return ret; } private static String getHexChar(int i){ if(i >= 0 && i < 10){ return "" + i; }else if(i == 10){ return "a"; }else if(i == 11){ return "b"; }else if(i == 12){ return "c"; }else if(i == 13){ return "d"; }else if(i == 14){ return "e"; }else if(i == 15){ return "f"; } return "f"; } class MyListViewAdapter extends BaseAdapter{ @Override public int getCount() { // TODO Auto-generated method stub return acts.length; } @Override public Object getItem(int position) { // TODO Auto-generated method stub return acts[position]; } @Override public long getItemId(int position) { // TODO Auto-generated method stub return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { TextView tv = new TextView(parent.getContext()); tv.setHeight(100); tv.setGravity(Gravity.CENTER); tv.setText(acts[position].title); convertView = tv; return convertView; } } }
use super::{FileInfo, HeadInfo, MabiError, HEADER_SIZE}; use byteorder::{LittleEndian, WriteBytesExt}; use libflate::zlib; use mersenne_twister::MT19937; use rand::{Rng, SeedableRng}; use std::fs::{metadata, File, OpenOptions}; use std::io::{BufWriter, Read, Seek, SeekFrom, Write}; use std::path::{Path, MAIN_SEPARATOR}; use std::time::{SystemTime, UNIX_EPOCH}; use walkdir::WalkDir; fn pack_file(root_dir: &str, rel_path: &str, key: u32) -> Result<(FileInfo, Vec<u8>), MabiError> { let mut stm = vec![]; { let mut fs = File::open(Path::new(root_dir).join(rel_path))?; fs.read_to_end(&mut stm)?; } let mut encoder = zlib::Encoder::new(vec![]).unwrap(); encoder .write_all(&stm) .map_err(|e| MabiError::CompressError(e.to_string()))?; let mut encoded_buff = encoder .finish() .into_result() .map_err(|e| MabiError::CompressError(e.to_string()))?; let mut rng: MT19937 = SeedableRng::from_seed((key << 7) ^ 0xA9C36DE1); for i in 0..encoded_buff.len() { encoded_buff[i] ^= rng.next_u32() as u8; } Ok(( FileInfo { name: rel_path.to_string(), version: key, off: 0, raw_size: encoded_buff.len() as u32, uncompr_size: stm.len() as u32, }, encoded_buff, )) } fn calc_str_size(l: usize) -> (usize, u8) { match l { 0..=14 => (16, 0), 15..=30 => (32, 1), 31..=46 => (48, 2), 47..=62 => (64, 3), 63..=94 => (96, 4), x => ((x + 21) / 16 * 16, 5), } } fn get_rel_path(root_dir: &str, full_path: &str) -> Result<String, MabiError> { let full_path = Path::new(full_path); let rel_name = full_path .strip_prefix(root_dir) .map_err(|_| MabiError::InternalError)?; Ok(rel_name.to_string_lossy().into_owned()) } fn write_str_block(stm: &mut impl Write, s: &str) -> Result<u64, MabiError> { let (all_len, lead_byte) = calc_str_size(s.as_bytes().len()); stm.write_u8(lead_byte)?; let mut wrote_bytes = 1; if lead_byte == 5 { stm.write_u32::<LittleEndian>(all_len as u32 - 5)?; wrote_bytes += 4; } stm.write_all(s.replace(MAIN_SEPARATOR, "\\").as_bytes())?; wrote_bytes += s.as_bytes().len(); for _ in 0..all_len - wrote_bytes { stm.write_u8(0)?; } Ok(all_len as u64) } fn time_to_filetime(t: SystemTime) -> Result<u64, MabiError> { let t = t .duration_since(UNIX_EPOCH) .map_err(|_| MabiError::TimeError)? .as_millis(); Ok(((t * 10000) + 116444736000000000) as u64) } fn write_file_time(stm: &mut impl Write, root_dir: &str, rel_path: &str) -> Result<(), MabiError> { let meta = metadata(Path::new(root_dir).join(rel_path))?; // As creation time is not supported in WSL, replace it with modified time //let c_time = time_to_filetime(meta.created()?)?; let a_time = time_to_filetime(meta.accessed()?)?; let m_time = time_to_filetime(meta.modified()?)?; stm.write_u64::<LittleEndian>(m_time)?; stm.write_u64::<LittleEndian>(m_time)?; stm.write_u64::<LittleEndian>(a_time)?; stm.write_u64::<LittleEndian>(m_time)?; stm.write_u64::<LittleEndian>(m_time)?; Ok(()) } fn write_file_entry( stm: &mut impl Write, ent: &FileInfo, root_dir: &str, ) -> Result<u64, MabiError> { let str_block_size = write_str_block(stm, &ent.name)?; stm.write_u32::<LittleEndian>(ent.version)?; stm.write_u32::<LittleEndian>(0)?; stm.write_u32::<LittleEndian>(ent.off)?; stm.write_u32::<LittleEndian>(ent.raw_size)?; stm.write_u32::<LittleEndian>(ent.uncompr_size)?; stm.write_u32::<LittleEndian>(1)?; write_file_time(stm, root_dir, &ent.name)?; Ok(str_block_size + 0x40) } fn write_header_time(stm: &mut impl Write) -> Result<(), MabiError> { let cur = time_to_filetime(SystemTime::now())?; stm.write_u64::<LittleEndian>(cur)?; stm.write_u64::<LittleEndian>(cur)?; Ok(()) } fn write_header(stm: &mut impl Write, head_info: &HeadInfo) -> Result<(), MabiError> { stm.write_u32::<LittleEndian>(0x4b434150)?; stm.write_u32::<LittleEndian>(0x102)?; stm.write_u32::<LittleEndian>(head_info.file_ver)?; stm.write_u32::<LittleEndian>(head_info.file_cnt)?; write_header_time(stm)?; stm.write("data\\".as_bytes())?; stm.write(&[0; 0x1e0 - 5])?; stm.write_u32::<LittleEndian>(head_info.file_cnt)?; stm.write_u32::<LittleEndian>(head_info.index_size)?; stm.write_u32::<LittleEndian>(0)?; stm.write_u32::<LittleEndian>(head_info.content_size)?; stm.write_all(&[0; 16])?; Ok(()) } pub fn run_pack(input_folder: &str, output_fname: &str, version: &str) -> Result<(), MabiError> { let version = version .parse::<u32>() .map_err(|_| MabiError::InvalidVersion)?; let file_names: Vec<String> = WalkDir::new(input_folder) .into_iter() .filter_map(|e| e.ok()) .filter(|e| !e.file_type().is_dir()) .map(|e| get_rel_path(input_folder, e.into_path().to_str().unwrap())) .collect::<Result<Vec<String>, MabiError>>() .map_err(|e| MabiError::TraversingFail(e.to_string()))?; let index_size: u64 = file_names .iter() .map(|s| calc_str_size(s.as_bytes().len()).0 + 0x40) .sum::<usize>() as u64; let fs = OpenOptions::new() .create(true) .write(true) .open(output_fname)?; let mut stm = BufWriter::new(fs); stm.write_all(&[0; HEADER_SIZE as usize])?; let content_start_off = HEADER_SIZE + index_size; let mut content_off = 0; let mut index_off = HEADER_SIZE; for name in &file_names { let (mut fi, packed_file) = pack_file(input_folder, &name, version) .map_err(|e| MabiError::PackingFail(name.clone(), e.to_string()))?; fi.off = content_off; stm.seek(SeekFrom::Start(index_off))?; index_off += write_file_entry(&mut stm, &fi, input_folder)?; stm.seek(SeekFrom::Start(content_start_off + content_off as u64))?; stm.write_all(&packed_file)?; content_off += fi.raw_size; } let file_size = stm.seek(SeekFrom::Current(0))?; stm.seek(SeekFrom::Start(0))?; write_header( &mut stm, &HeadInfo { file_ver: version, file_cnt: file_names.len() as u32, index_size: index_size as u32, content_size: (file_size - content_start_off) as u32, }, )?; Ok(()) }
package com.android.inputmethodcommon; import android.content.Context; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.preference.PreferenceFragment; /** * This is a helper class for an IME's settings preference fragment. It's recommended for every * IME to have its own settings preference fragment which inherits this class. */ public abstract class InputMethodSettingsFragment extends PreferenceFragment implements InputMethodSettingsInterface { private final InputMethodSettingsImpl mSettings = new InputMethodSettingsImpl(); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); final Context context = getActivity(); setPreferenceScreen(getPreferenceManager().createPreferenceScreen(context)); mSettings.init(context, getPreferenceScreen()); } /** * {@inheritDoc} */ @Override public void setInputMethodSettingsCategoryTitle(int resId) { mSettings.setInputMethodSettingsCategoryTitle(resId); } /** * {@inheritDoc} */ @Override public void setInputMethodSettingsCategoryTitle(CharSequence title) { mSettings.setInputMethodSettingsCategoryTitle(title); } /** * {@inheritDoc} */ @Override public void setSubtypeEnablerTitle(int resId) { mSettings.setSubtypeEnablerTitle(resId); } /** * {@inheritDoc} */ @Override public void setSubtypeEnablerTitle(CharSequence title) { mSettings.setSubtypeEnablerTitle(title); } /** * {@inheritDoc} */ @Override public void setSubtypeEnablerIcon(int resId) { mSettings.setSubtypeEnablerIcon(resId); } /** * {@inheritDoc} */ @Override public void setSubtypeEnablerIcon(Drawable drawable) { mSettings.setSubtypeEnablerIcon(drawable); } /** * {@inheritDoc} */ @Override public void onResume() { super.onResume(); mSettings.updateSubtypeEnabler(); } }
// import * as Vts from 'vue-property-decorator' import { mixins as Mixins } from 'vue-class-component' import Vue from 'vue' import VMixin from '../../mixins/v.mixin' import RHMixin from '../../mixins/robinhood.mixin' import * as _ from '../../../common/lodash' import * as core from '../../../common/core' import * as pretty from '../../../common/pretty' import * as rkeys from '../../../common/rkeys' import * as robinhood from '../../adapters/robinhood' import * as security from '../../adapters/security' import * as http from '../../../common/http' import store from '../../store' import socket from '../../adapters/socket' @Vts.Component({ beforeRouteEnter(to, from, next) { // if (process.env.DEVELOPMENT) return next(); store.state.security.rhusername ? next() : next({ name: 'login' }) }, }) export default class extends Mixins(VMixin, RHMixin) { get routes() { return this.$router.options.routes.find((v) => v.name == 'robinhood').children } }
<?php namespace app\modules\swagger\actions; use OpenApi\Annotations\OpenApi; use Yii; use yii\base\Action; use yii\base\InvalidConfigException; use yii\base\Response; use yii\caching\Cache; use yii\di\Instance; use function OpenApi\scan; /** * Class OpenAPIRenderer is responsible for generating the JSON spec. */ class SwaggerSchemaRender extends Action { /** @var string|array */ public $scanDir; /** @var array */ public $scanOptions = []; /** @var Cache|array|string */ public $cache = 'cache'; /** @var int */ public $cacheDuration = 86400; /** @var string */ public $cacheKey = 'api-swagger-cache'; /** * @inheritdoc * @throws InvalidConfigException */ public function init(): void { parent::init(); if($this->cache !== null) { $this->cache = Instance::ensure($this->cache, Cache::class); } } /** * @inheritdoc */ public function run(): Response { $this->enableCORS(); return $this->controller->asJson($this->getSwaggerDocumentation()); } /** * @return OpenApi */ protected function getSwaggerDocumentation(): OpenApi { if(!$this->cache instanceof Cache) { return scan($this->scanDir, $this->scanOptions); } return $this->cache->getOrSet( $this->cacheKey, function() { return scan($this->scanDir, $this->scanOptions); }, $this->cacheDuration ); } /** * Enable CORS */ protected function enableCORS(): void { $headers = Yii::$app->getResponse()->getHeaders(); $headers->set('Access-Control-Allow-Headers', 'Content-Type, api_key, Authorization'); $headers->set('Access-Control-Allow-Methods', 'GET, POST, DELETE, PUT'); $headers->set('Access-Control-Allow-Origin', '*'); } }
# newfile-cli `newfile folder/file.js then cd` 👈 newfile can do more like this! --- 🌞🌈 Create a file or folder recursively then do something at once ~ ![render.gif](https://i.loli.net/2020/05/31/1MNheGR9oVYk6J4.gif) ## Quick Use ``` $ npx newfile-cli src/index.js then cd ``` Will create index.js in src folder, and cd in src direcory. ## Install `yarn global add newfile-cli` `npm -g i newfile-cli` ## Use ``` $ newfile app/src/index.js then cd ``` ## Do More ``` $ newfile somefile.js then ls -a ```
{-# LANGUAGE OverloadedStrings #-} -- | -- Module : Parsing -- Description : Handle parsing data -- License : MIT -- Maintainer : The Lusitanian King <alexlusitanian@gmail.com> module Parsing where import Input import Data.Text (Text) import qualified Data.Text as T -- | Parsing a CSV file parseCSVFile :: Text -- ^ content of the CSV file -> Int -- ^ index of the class/variable to predict -> Input -- ^ parsed input parseCSVFile content i = parse . map (map T.strip . T.splitOn ",") . T.lines $ content where parse :: [[Text]] -> Input parse ((_:columns):ws:os) = if i >= length columns then error "Could not find the class/variable to predict in the CSV." else -- to make it easier, we suppose the class will always have a - indicating a missing value Input { _weighs = map (read . T.unpack) (filter (/="-") ws) , _objects = map (parseObject i) os } parse _ = error "Missing data in the parsed CSV." -- | Parsing a single object parseObject :: Int -- the index where the class is -> [Text] -- the list of variables -> Object -- the constructed object parseObject i (n:values) = let v = values !! i -- retrieving class value vs = let (a, _:b) = splitAt i values in a ++ b -- removing class from the variables in Object { _name = T.strip n , _features = map (read . T.unpack) vs , _label = if v == "-" then Nothing else return $ (read . T.unpack) v , _reliable = v /= "-" , _neighbours = Nothing } parseObject _ _ = error "Malformed entity value..." -- | Parsing an evaluating set parseEvaluatingCSVFile :: Text -> Int -> [Object] parseEvaluatingCSVFile content i = map (parseObject i . map T.strip . T.splitOn ",") . T.lines $ content
#[doc = r" Value read from the register"] pub struct R { bits: u32, } #[doc = r" Value to write to the register"] pub struct W { bits: u32, } impl super::C2 { #[doc = r" Modifies the contents of the register"] #[inline] pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W, { let bits = self.register.get(); let r = R { bits: bits }; let mut w = W { bits: bits }; f(&r, &mut w); self.register.set(w.bits); } #[doc = r" Reads the contents of the register"] #[inline] pub fn read(&self) -> R { R { bits: self.register.get() } } #[doc = r" Writes to the register"] #[inline] pub fn write<F>(&self, f: F) where F: FnOnce(&mut W) -> &mut W, { let mut w = W::reset_value(); f(&mut w); self.register.set(w.bits); } #[doc = r" Writes the reset value to the register"] #[inline] pub fn reset(&self) { self.write(|w| w) } } #[doc = r" Value of the field"] pub struct ACONR { bits: u8, } impl ACONR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bits(&self) -> u8 { self.bits } } #[doc = "Possible values of the field `INITMOD`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum INITMODR { #[doc = "The modulus is set to 64(same with 111111)."] _000000, #[doc = r" Reserved"] _Reserved(u8), } impl INITMODR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bits(&self) -> u8 { match *self { INITMODR::_000000 => 0, INITMODR::_Reserved(bits) => bits, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: u8) -> INITMODR { match value { 0 => INITMODR::_000000, i => INITMODR::_Reserved(i), } } #[doc = "Checks if the value of the field is `_000000`"] #[inline] pub fn is_000000(&self) -> bool { *self == INITMODR::_000000 } } #[doc = "Possible values of the field `NSAM`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum NSAMR { #[doc = "The comparison result is sampled as soon as the active channel is scanned in one round-robin clock."] _00, #[doc = "The sampling takes place 1 round-robin clock cycle after the next cycle of the round-robin clock."] _01, #[doc = "The sampling takes place 2 round-robin clock cycles after the next cycle of the round-robin clock."] _10, #[doc = "The sampling takes place 3 round-robin clock cycles after the next cycle of the round-robin clock."] _11, } impl NSAMR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bits(&self) -> u8 { match *self { NSAMR::_00 => 0, NSAMR::_01 => 1, NSAMR::_10 => 2, NSAMR::_11 => 3, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: u8) -> NSAMR { match value { 0 => NSAMR::_00, 1 => NSAMR::_01, 2 => NSAMR::_10, 3 => NSAMR::_11, _ => unreachable!(), } } #[doc = "Checks if the value of the field is `_00`"] #[inline] pub fn is_00(&self) -> bool { *self == NSAMR::_00 } #[doc = "Checks if the value of the field is `_01`"] #[inline] pub fn is_01(&self) -> bool { *self == NSAMR::_01 } #[doc = "Checks if the value of the field is `_10`"] #[inline] pub fn is_10(&self) -> bool { *self == NSAMR::_10 } #[doc = "Checks if the value of the field is `_11`"] #[inline] pub fn is_11(&self) -> bool { *self == NSAMR::_11 } } #[doc = r" Value of the field"] pub struct CH0FR { bits: bool, } impl CH0FR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { self.bits } #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r" Value of the field"] pub struct CH1FR { bits: bool, } impl CH1FR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { self.bits } #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r" Value of the field"] pub struct CH2FR { bits: bool, } impl CH2FR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { self.bits } #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r" Value of the field"] pub struct CH3FR { bits: bool, } impl CH3FR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { self.bits } #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r" Value of the field"] pub struct CH4FR { bits: bool, } impl CH4FR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { self.bits } #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r" Value of the field"] pub struct CH5FR { bits: bool, } impl CH5FR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { self.bits } #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r" Value of the field"] pub struct CH6FR { bits: bool, } impl CH6FR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { self.bits } #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r" Value of the field"] pub struct CH7FR { bits: bool, } impl CH7FR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { self.bits } #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = "Possible values of the field `FXMXCH`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum FXMXCHR { #[doc = "Channel 0 is selected as the fixed reference input for the fixed mux port."] _000, #[doc = "Channel 1 is selected as the fixed reference input for the fixed mux port."] _001, #[doc = "Channel 2 is selected as the fixed reference input for the fixed mux port."] _010, #[doc = "Channel 3 is selected as the fixed reference input for the fixed mux port."] _011, #[doc = "Channel 4 is selected as the fixed reference input for the fixed mux port."] _100, #[doc = "Channel 5 is selected as the fixed reference input for the fixed mux port."] _101, #[doc = "Channel 6 is selected as the fixed reference input for the fixed mux port."] _110, #[doc = "Channel 7 is selected as the fixed reference input for the fixed mux port."] _111, } impl FXMXCHR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bits(&self) -> u8 { match *self { FXMXCHR::_000 => 0, FXMXCHR::_001 => 1, FXMXCHR::_010 => 2, FXMXCHR::_011 => 3, FXMXCHR::_100 => 4, FXMXCHR::_101 => 5, FXMXCHR::_110 => 6, FXMXCHR::_111 => 7, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: u8) -> FXMXCHR { match value { 0 => FXMXCHR::_000, 1 => FXMXCHR::_001, 2 => FXMXCHR::_010, 3 => FXMXCHR::_011, 4 => FXMXCHR::_100, 5 => FXMXCHR::_101, 6 => FXMXCHR::_110, 7 => FXMXCHR::_111, _ => unreachable!(), } } #[doc = "Checks if the value of the field is `_000`"] #[inline] pub fn is_000(&self) -> bool { *self == FXMXCHR::_000 } #[doc = "Checks if the value of the field is `_001`"] #[inline] pub fn is_001(&self) -> bool { *self == FXMXCHR::_001 } #[doc = "Checks if the value of the field is `_010`"] #[inline] pub fn is_010(&self) -> bool { *self == FXMXCHR::_010 } #[doc = "Checks if the value of the field is `_011`"] #[inline] pub fn is_011(&self) -> bool { *self == FXMXCHR::_011 } #[doc = "Checks if the value of the field is `_100`"] #[inline] pub fn is_100(&self) -> bool { *self == FXMXCHR::_100 } #[doc = "Checks if the value of the field is `_101`"] #[inline] pub fn is_101(&self) -> bool { *self == FXMXCHR::_101 } #[doc = "Checks if the value of the field is `_110`"] #[inline] pub fn is_110(&self) -> bool { *self == FXMXCHR::_110 } #[doc = "Checks if the value of the field is `_111`"] #[inline] pub fn is_111(&self) -> bool { *self == FXMXCHR::_111 } } #[doc = "Possible values of the field `FXMP`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum FXMPR { #[doc = "The Plus port is fixed. Only the inputs to the Minus port are swept in each round."] _0, #[doc = "The Minus port is fixed. Only the inputs to the Plus port are swept in each round."] _1, } impl FXMPR { #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { match *self { FXMPR::_0 => false, FXMPR::_1 => true, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> FXMPR { match value { false => FXMPR::_0, true => FXMPR::_1, } } #[doc = "Checks if the value of the field is `_0`"] #[inline] pub fn is_0(&self) -> bool { *self == FXMPR::_0 } #[doc = "Checks if the value of the field is `_1`"] #[inline] pub fn is_1(&self) -> bool { *self == FXMPR::_1 } } #[doc = "Possible values of the field `RRIE`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum RRIER { #[doc = "The round-robin interrupt is disabled."] _0, #[doc = "The round-robin interrupt is enabled when a comparison result changes from the last sample."] _1, } impl RRIER { #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { match *self { RRIER::_0 => false, RRIER::_1 => true, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> RRIER { match value { false => RRIER::_0, true => RRIER::_1, } } #[doc = "Checks if the value of the field is `_0`"] #[inline] pub fn is_0(&self) -> bool { *self == RRIER::_0 } #[doc = "Checks if the value of the field is `_1`"] #[inline] pub fn is_1(&self) -> bool { *self == RRIER::_1 } } #[doc = "Possible values of the field `RRE`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum RRER { #[doc = "Round-robin operation is disabled."] _0, #[doc = "Round-robin operation is enabled."] _1, } impl RRER { #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { match *self { RRER::_0 => false, RRER::_1 => true, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> RRER { match value { false => RRER::_0, true => RRER::_1, } } #[doc = "Checks if the value of the field is `_0`"] #[inline] pub fn is_0(&self) -> bool { *self == RRER::_0 } #[doc = "Checks if the value of the field is `_1`"] #[inline] pub fn is_1(&self) -> bool { *self == RRER::_1 } } #[doc = r" Proxy"] pub struct _ACONW<'a> { w: &'a mut W, } impl<'a> _ACONW<'a> { #[doc = r" Writes raw bits to the field"] #[inline] pub unsafe fn bits(self, value: u8) -> &'a mut W { const MASK: u8 = 255; const OFFSET: u8 = 0; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = "Values that can be written to the field `INITMOD`"] pub enum INITMODW { #[doc = "The modulus is set to 64(same with 111111)."] _000000, } impl INITMODW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> u8 { match *self { INITMODW::_000000 => 0, } } } #[doc = r" Proxy"] pub struct _INITMODW<'a> { w: &'a mut W, } impl<'a> _INITMODW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: INITMODW) -> &'a mut W { unsafe { self.bits(variant._bits()) } } #[doc = "The modulus is set to 64(same with 111111)."] #[inline] pub fn _000000(self) -> &'a mut W { self.variant(INITMODW::_000000) } #[doc = r" Writes raw bits to the field"] #[inline] pub unsafe fn bits(self, value: u8) -> &'a mut W { const MASK: u8 = 63; const OFFSET: u8 = 8; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = "Values that can be written to the field `NSAM`"] pub enum NSAMW { #[doc = "The comparison result is sampled as soon as the active channel is scanned in one round-robin clock."] _00, #[doc = "The sampling takes place 1 round-robin clock cycle after the next cycle of the round-robin clock."] _01, #[doc = "The sampling takes place 2 round-robin clock cycles after the next cycle of the round-robin clock."] _10, #[doc = "The sampling takes place 3 round-robin clock cycles after the next cycle of the round-robin clock."] _11, } impl NSAMW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> u8 { match *self { NSAMW::_00 => 0, NSAMW::_01 => 1, NSAMW::_10 => 2, NSAMW::_11 => 3, } } } #[doc = r" Proxy"] pub struct _NSAMW<'a> { w: &'a mut W, } impl<'a> _NSAMW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: NSAMW) -> &'a mut W { { self.bits(variant._bits()) } } #[doc = "The comparison result is sampled as soon as the active channel is scanned in one round-robin clock."] #[inline] pub fn _00(self) -> &'a mut W { self.variant(NSAMW::_00) } #[doc = "The sampling takes place 1 round-robin clock cycle after the next cycle of the round-robin clock."] #[inline] pub fn _01(self) -> &'a mut W { self.variant(NSAMW::_01) } #[doc = "The sampling takes place 2 round-robin clock cycles after the next cycle of the round-robin clock."] #[inline] pub fn _10(self) -> &'a mut W { self.variant(NSAMW::_10) } #[doc = "The sampling takes place 3 round-robin clock cycles after the next cycle of the round-robin clock."] #[inline] pub fn _11(self) -> &'a mut W { self.variant(NSAMW::_11) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bits(self, value: u8) -> &'a mut W { const MASK: u8 = 3; const OFFSET: u8 = 14; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _CH0FW<'a> { w: &'a mut W, } impl<'a> _CH0FW<'a> { #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 16; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _CH1FW<'a> { w: &'a mut W, } impl<'a> _CH1FW<'a> { #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 17; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _CH2FW<'a> { w: &'a mut W, } impl<'a> _CH2FW<'a> { #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 18; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _CH3FW<'a> { w: &'a mut W, } impl<'a> _CH3FW<'a> { #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 19; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _CH4FW<'a> { w: &'a mut W, } impl<'a> _CH4FW<'a> { #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 20; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _CH5FW<'a> { w: &'a mut W, } impl<'a> _CH5FW<'a> { #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 21; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _CH6FW<'a> { w: &'a mut W, } impl<'a> _CH6FW<'a> { #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 22; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _CH7FW<'a> { w: &'a mut W, } impl<'a> _CH7FW<'a> { #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 23; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = "Values that can be written to the field `FXMXCH`"] pub enum FXMXCHW { #[doc = "Channel 0 is selected as the fixed reference input for the fixed mux port."] _000, #[doc = "Channel 1 is selected as the fixed reference input for the fixed mux port."] _001, #[doc = "Channel 2 is selected as the fixed reference input for the fixed mux port."] _010, #[doc = "Channel 3 is selected as the fixed reference input for the fixed mux port."] _011, #[doc = "Channel 4 is selected as the fixed reference input for the fixed mux port."] _100, #[doc = "Channel 5 is selected as the fixed reference input for the fixed mux port."] _101, #[doc = "Channel 6 is selected as the fixed reference input for the fixed mux port."] _110, #[doc = "Channel 7 is selected as the fixed reference input for the fixed mux port."] _111, } impl FXMXCHW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> u8 { match *self { FXMXCHW::_000 => 0, FXMXCHW::_001 => 1, FXMXCHW::_010 => 2, FXMXCHW::_011 => 3, FXMXCHW::_100 => 4, FXMXCHW::_101 => 5, FXMXCHW::_110 => 6, FXMXCHW::_111 => 7, } } } #[doc = r" Proxy"] pub struct _FXMXCHW<'a> { w: &'a mut W, } impl<'a> _FXMXCHW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: FXMXCHW) -> &'a mut W { { self.bits(variant._bits()) } } #[doc = "Channel 0 is selected as the fixed reference input for the fixed mux port."] #[inline] pub fn _000(self) -> &'a mut W { self.variant(FXMXCHW::_000) } #[doc = "Channel 1 is selected as the fixed reference input for the fixed mux port."] #[inline] pub fn _001(self) -> &'a mut W { self.variant(FXMXCHW::_001) } #[doc = "Channel 2 is selected as the fixed reference input for the fixed mux port."] #[inline] pub fn _010(self) -> &'a mut W { self.variant(FXMXCHW::_010) } #[doc = "Channel 3 is selected as the fixed reference input for the fixed mux port."] #[inline] pub fn _011(self) -> &'a mut W { self.variant(FXMXCHW::_011) } #[doc = "Channel 4 is selected as the fixed reference input for the fixed mux port."] #[inline] pub fn _100(self) -> &'a mut W { self.variant(FXMXCHW::_100) } #[doc = "Channel 5 is selected as the fixed reference input for the fixed mux port."] #[inline] pub fn _101(self) -> &'a mut W { self.variant(FXMXCHW::_101) } #[doc = "Channel 6 is selected as the fixed reference input for the fixed mux port."] #[inline] pub fn _110(self) -> &'a mut W { self.variant(FXMXCHW::_110) } #[doc = "Channel 7 is selected as the fixed reference input for the fixed mux port."] #[inline] pub fn _111(self) -> &'a mut W { self.variant(FXMXCHW::_111) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bits(self, value: u8) -> &'a mut W { const MASK: u8 = 7; const OFFSET: u8 = 25; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = "Values that can be written to the field `FXMP`"] pub enum FXMPW { #[doc = "The Plus port is fixed. Only the inputs to the Minus port are swept in each round."] _0, #[doc = "The Minus port is fixed. Only the inputs to the Plus port are swept in each round."] _1, } impl FXMPW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { FXMPW::_0 => false, FXMPW::_1 => true, } } } #[doc = r" Proxy"] pub struct _FXMPW<'a> { w: &'a mut W, } impl<'a> _FXMPW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: FXMPW) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = "The Plus port is fixed. Only the inputs to the Minus port are swept in each round."] #[inline] pub fn _0(self) -> &'a mut W { self.variant(FXMPW::_0) } #[doc = "The Minus port is fixed. Only the inputs to the Plus port are swept in each round."] #[inline] pub fn _1(self) -> &'a mut W { self.variant(FXMPW::_1) } #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 29; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = "Values that can be written to the field `RRIE`"] pub enum RRIEW { #[doc = "The round-robin interrupt is disabled."] _0, #[doc = "The round-robin interrupt is enabled when a comparison result changes from the last sample."] _1, } impl RRIEW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { RRIEW::_0 => false, RRIEW::_1 => true, } } } #[doc = r" Proxy"] pub struct _RRIEW<'a> { w: &'a mut W, } impl<'a> _RRIEW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: RRIEW) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = "The round-robin interrupt is disabled."] #[inline] pub fn _0(self) -> &'a mut W { self.variant(RRIEW::_0) } #[doc = "The round-robin interrupt is enabled when a comparison result changes from the last sample."] #[inline] pub fn _1(self) -> &'a mut W { self.variant(RRIEW::_1) } #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 30; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = "Values that can be written to the field `RRE`"] pub enum RREW { #[doc = "Round-robin operation is disabled."] _0, #[doc = "Round-robin operation is enabled."] _1, } impl RREW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { RREW::_0 => false, RREW::_1 => true, } } } #[doc = r" Proxy"] pub struct _RREW<'a> { w: &'a mut W, } impl<'a> _RREW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: RREW) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = "Round-robin operation is disabled."] #[inline] pub fn _0(self) -> &'a mut W { self.variant(RREW::_0) } #[doc = "Round-robin operation is enabled."] #[inline] pub fn _1(self) -> &'a mut W { self.variant(RREW::_1) } #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 31; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } impl R { #[doc = r" Value of the register as raw bits"] #[inline] pub fn bits(&self) -> u32 { self.bits } #[doc = "Bits 0:7 - The result of the input comparison for channel n"] #[inline] pub fn acon(&self) -> ACONR { let bits = { const MASK: u8 = 255; const OFFSET: u8 = 0; ((self.bits >> OFFSET) & MASK as u32) as u8 }; ACONR { bits } } #[doc = "Bits 8:13 - Comparator and DAC initialization delay modulus."] #[inline] pub fn initmod(&self) -> INITMODR { INITMODR::_from({ const MASK: u8 = 63; const OFFSET: u8 = 8; ((self.bits >> OFFSET) & MASK as u32) as u8 }) } #[doc = "Bits 14:15 - Number of sample clocks"] #[inline] pub fn nsam(&self) -> NSAMR { NSAMR::_from({ const MASK: u8 = 3; const OFFSET: u8 = 14; ((self.bits >> OFFSET) & MASK as u32) as u8 }) } #[doc = "Bit 16 - Channel 0 input changed flag"] #[inline] pub fn ch0f(&self) -> CH0FR { let bits = { const MASK: bool = true; const OFFSET: u8 = 16; ((self.bits >> OFFSET) & MASK as u32) != 0 }; CH0FR { bits } } #[doc = "Bit 17 - Channel 1 input changed flag"] #[inline] pub fn ch1f(&self) -> CH1FR { let bits = { const MASK: bool = true; const OFFSET: u8 = 17; ((self.bits >> OFFSET) & MASK as u32) != 0 }; CH1FR { bits } } #[doc = "Bit 18 - Channel 2 input changed flag"] #[inline] pub fn ch2f(&self) -> CH2FR { let bits = { const MASK: bool = true; const OFFSET: u8 = 18; ((self.bits >> OFFSET) & MASK as u32) != 0 }; CH2FR { bits } } #[doc = "Bit 19 - Channel 3 input changed flag"] #[inline] pub fn ch3f(&self) -> CH3FR { let bits = { const MASK: bool = true; const OFFSET: u8 = 19; ((self.bits >> OFFSET) & MASK as u32) != 0 }; CH3FR { bits } } #[doc = "Bit 20 - Channel 4 input changed flag"] #[inline] pub fn ch4f(&self) -> CH4FR { let bits = { const MASK: bool = true; const OFFSET: u8 = 20; ((self.bits >> OFFSET) & MASK as u32) != 0 }; CH4FR { bits } } #[doc = "Bit 21 - Channel 5 input changed flag"] #[inline] pub fn ch5f(&self) -> CH5FR { let bits = { const MASK: bool = true; const OFFSET: u8 = 21; ((self.bits >> OFFSET) & MASK as u32) != 0 }; CH5FR { bits } } #[doc = "Bit 22 - Channel 6 input changed flag"] #[inline] pub fn ch6f(&self) -> CH6FR { let bits = { const MASK: bool = true; const OFFSET: u8 = 22; ((self.bits >> OFFSET) & MASK as u32) != 0 }; CH6FR { bits } } #[doc = "Bit 23 - Channel 7 input changed flag"] #[inline] pub fn ch7f(&self) -> CH7FR { let bits = { const MASK: bool = true; const OFFSET: u8 = 23; ((self.bits >> OFFSET) & MASK as u32) != 0 }; CH7FR { bits } } #[doc = "Bits 25:27 - Fixed channel selection"] #[inline] pub fn fxmxch(&self) -> FXMXCHR { FXMXCHR::_from({ const MASK: u8 = 7; const OFFSET: u8 = 25; ((self.bits >> OFFSET) & MASK as u32) as u8 }) } #[doc = "Bit 29 - Fixed MUX Port"] #[inline] pub fn fxmp(&self) -> FXMPR { FXMPR::_from({ const MASK: bool = true; const OFFSET: u8 = 29; ((self.bits >> OFFSET) & MASK as u32) != 0 }) } #[doc = "Bit 30 - Round-Robin interrupt enable"] #[inline] pub fn rrie(&self) -> RRIER { RRIER::_from({ const MASK: bool = true; const OFFSET: u8 = 30; ((self.bits >> OFFSET) & MASK as u32) != 0 }) } #[doc = "Bit 31 - Round-Robin Enable"] #[inline] pub fn rre(&self) -> RRER { RRER::_from({ const MASK: bool = true; const OFFSET: u8 = 31; ((self.bits >> OFFSET) & MASK as u32) != 0 }) } } impl W { #[doc = r" Reset value of the register"] #[inline] pub fn reset_value() -> W { W { bits: 0 } } #[doc = r" Writes raw bits to the register"] #[inline] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } #[doc = "Bits 0:7 - The result of the input comparison for channel n"] #[inline] pub fn acon(&mut self) -> _ACONW { _ACONW { w: self } } #[doc = "Bits 8:13 - Comparator and DAC initialization delay modulus."] #[inline] pub fn initmod(&mut self) -> _INITMODW { _INITMODW { w: self } } #[doc = "Bits 14:15 - Number of sample clocks"] #[inline] pub fn nsam(&mut self) -> _NSAMW { _NSAMW { w: self } } #[doc = "Bit 16 - Channel 0 input changed flag"] #[inline] pub fn ch0f(&mut self) -> _CH0FW { _CH0FW { w: self } } #[doc = "Bit 17 - Channel 1 input changed flag"] #[inline] pub fn ch1f(&mut self) -> _CH1FW { _CH1FW { w: self } } #[doc = "Bit 18 - Channel 2 input changed flag"] #[inline] pub fn ch2f(&mut self) -> _CH2FW { _CH2FW { w: self } } #[doc = "Bit 19 - Channel 3 input changed flag"] #[inline] pub fn ch3f(&mut self) -> _CH3FW { _CH3FW { w: self } } #[doc = "Bit 20 - Channel 4 input changed flag"] #[inline] pub fn ch4f(&mut self) -> _CH4FW { _CH4FW { w: self } } #[doc = "Bit 21 - Channel 5 input changed flag"] #[inline] pub fn ch5f(&mut self) -> _CH5FW { _CH5FW { w: self } } #[doc = "Bit 22 - Channel 6 input changed flag"] #[inline] pub fn ch6f(&mut self) -> _CH6FW { _CH6FW { w: self } } #[doc = "Bit 23 - Channel 7 input changed flag"] #[inline] pub fn ch7f(&mut self) -> _CH7FW { _CH7FW { w: self } } #[doc = "Bits 25:27 - Fixed channel selection"] #[inline] pub fn fxmxch(&mut self) -> _FXMXCHW { _FXMXCHW { w: self } } #[doc = "Bit 29 - Fixed MUX Port"] #[inline] pub fn fxmp(&mut self) -> _FXMPW { _FXMPW { w: self } } #[doc = "Bit 30 - Round-Robin interrupt enable"] #[inline] pub fn rrie(&mut self) -> _RRIEW { _RRIEW { w: self } } #[doc = "Bit 31 - Round-Robin Enable"] #[inline] pub fn rre(&mut self) -> _RREW { _RREW { w: self } } }
# Overview ## Packages `BuffettCode` ソリューションは下記の package を含みます 1. BuffettCodeAddinRibbon and Test 2. BuffettCodeAPIAdapter and Test 3. BuffettCodeExcelFunctions and Test 4. BuffettCodeInstaller ここでは、各 package の役割について簡単に説明します ### 1. BuffettCodeAddinRibbon バフェット・コードアドインの、Excel の「リボン」部分の実装です。 - CSV出力やTokenの入力フォームを提供します - VSTO(Visual Studio Tools for Office)を利用しており、リリースビルドにはデジタル署名が必要です ### 2. BuffettCodeIO - [BuffettCode API](https://docs.buffett-code.com/)のclient, Formatter などデータの入出力を管理します - Registryの読み書きもここにあります ### 3. BuffetCodeExcelFunctions - [Excel-DNA](https://excel-dna.net/) を利用して、ExcelのUDFを作成しています - [Excel-XLL](https://docs.microsoft.com/ja-jp/office/client-developer/excel/developing-excel-xlls) が Build されます ### BuffettCodeInstaller BuffettCode Excel Addin は、上記の通り - VSTOで作られたExcelリボン - Excel-DNAで作られたUDF という、2つの異なる2つの成果物で成り立っています。 インストーラは、この2つをそれぞれRegistryに配置します。
import React, { useEffect } from 'react'; const WSClient: React.FC = () => { useEffect(() => { document.title = 'WebSockets Client'; }); return ( <article className="w-full mx-auto px-5 pt-5 sm:pt-10 md:pt-15 lg:pt-20 xl:pt-25 font-sans text-center"> <h1 className="text-2xl sm:text-3xl md:text-4xl lg:text-5xl xl:text-6xl font-medium text-gray-900"> WebSockets Client </h1> <h2 className="text-base sm:text-lg md:text-xl lg:text-2xl xl:text-3xl text-gray-700"> Simple WebSockets Client for development purposes. </h2> </article> ); }; export default WSClient;
/* * Copyright (C) 2021 Rick Busarow * 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. */ plugins { id("com.rickbusarow.gradle-dependency-sync") version "0.11.4" } dependencies { dependencySync("com.android.tools.build:gradle:7.0.3") dependencySync("com.github.javaparser:javaparser-symbol-solver-core:3.23.1") dependencySync("com.rickbusarow.hermit:hermit-core:0.9.5") dependencySync("com.rickbusarow.hermit:hermit-coroutines:0.9.5") dependencySync("com.rickbusarow.hermit:hermit-junit4:0.9.5") dependencySync("com.rickbusarow.hermit:hermit-junit5:0.9.5") dependencySync("com.rickbusarow.hermit:hermit-mockk:0.9.5") dependencySync("com.squareup.anvil:gradle-plugin:2.3.10-1-6-0") dependencySync("com.squareup:kotlinpoet:1.10.2") dependencySync("com.vanniktech:gradle-maven-publish-plugin:0.18.0") dependencySync("io.kotest:kotest-assertions-core-jvm:5.0.0") dependencySync("io.kotest:kotest-property-jvm:5.0.0") dependencySync("io.kotest:kotest-runner-junit5-jvm:5.0.0") dependencySync("javax.inject:javax.inject:1") dependencySync("net.swiftzer.semver:semver:1.1.2") dependencySync("org.codehaus.groovy:groovy-xml:3.0.9") dependencySync("org.codehaus.groovy:groovy:3.0.9") dependencySync("org.jetbrains.kotlin:kotlin-compiler-embeddable:1.6.0") dependencySync("org.jetbrains.kotlin:kotlin-gradle-plugin:1.6.0") dependencySync("org.jetbrains.kotlin:kotlin-reflect:1.6.0") dependencySync("org.jetbrains.kotlinx:kotlinx-knit:0.3.0") dependencySync("org.jlleitschuh.gradle:ktlint-gradle:10.2.0") dependencySync("org.junit.jupiter:junit-jupiter-api:5.8.2") dependencySync("org.junit.jupiter:junit-jupiter-engine:5.8.2") dependencySync("org.junit.jupiter:junit-jupiter-params:5.8.2") }
package com.unimicron.chapter06 object CatDemo { def main(args: Array[String]): Unit = { // 創建一個Cat類 val cat = new Cat // 屬性賦值 // 1. 賦值時cat.name = "Lucky"其實不是直接訪問屬性,而是cat.name_$eq("Lucky") cat.name = "Lucky" cat.age = 5 cat.color = "black" cat.height = "120" // 可以給String cat.weight = null // 只能給null // 2. 使用時cat.name等價於cat.name() println("貓的命字: " + cat.name) } } // 定義一個類,底層對應public class Cat class Cat { // 定義三個屬性 // 1. 聲明了var name: String時,在底層對應private name // 2. 同時會生成兩個方法: public name() -> 類似於getter 與 public name_$eq() -> 類似於setter var name: String = "" // 必須給初始值 var age: Int = _ // _表示默認值,如果是Int,默認值是0 var color: String = _ // _表示默認值,如果是String,默認值是null var height: String = null // 給一個null值,但類型是String var weight = null // 給一個null值,類型是Null // 如果賦值為null,一定要加類型,否則該署性的類型就是Null,但兩種情況都不會報錯 } // 注意事項 // 1. Scala中,類不額外聲明為public,所有這些類都具有公有可見性(即所有類都默認為public) // 2. 一個Scala源文件可以包含多個類 class Dog2 {} class Fish {} class Test{ var var1: String = _ // null,引用類型也是null var var2: Byte = _ var var3: Double = _ // 0.0 var var4: Boolean = _ // false } //public class Cat { // private String name; // private int age; // private String color; // // public String name(){return this.name;} // public void name_$eq(String x$1){this.name = x$1;} // public int age(){return this.age;} // public void age_$eq(int x$1){this.age = x$1;} // public String color(){return this.color;} // public void color_$eq(String x$1){this.color = x$1;} //}
--- title: All Things New- Week 2 date: 2016-01-10 00:00:00 Z link: https://s3.amazonaws.com/podcast.lifestonechurch.net/2016-01-10.mp3 podcastLength: '00:40:41' size: 79228898 image: speaker: Pastor Ben Helton description: All Things New vimeoId: 151858663 verse: Hebrews 11:23-27 --- ## Sermon Notes **Life-Shaping Choices** 1. *Refuse to be defined by others*{: class="sermon-answer"}. Hebrews 11:24 Romans 12:2 Exodus 23:2 1 Thessalonians 2:4 John 17:16 2. Choose *short term pain for long-term gain*{: class="sermon-answer"}. Hebrews 11:25 Romans 5:3-4 2 Corinthians 4:17 3. Choose *God's values, not ours*{: class="sermon-answer"}. Hebrews 11:26 1 John 2:17 **What does God value?** 1. God's purpose is more valuable than *popularity*{: class="sermon-answer"}. (Verse 24) 2. People are more valuable than *pleasure*{: class="sermon-answer"}. (Verse 26) 3. Peace of mind is more valuable than *possessions*{: class="sermon-answer"}. (Verse 26) 4. Choose *to live by faith, not by fear*{: class="sermon-answer"}. Hebrews 11:27 Galatians 2:16 **How do you keep you resolutions?** 1. Get support from a *LifeGroup*{: class="sermon-answer"}. Hebrews 10:24-25 2. *Ask*{: class="sermon-answer"} & *expect*{: class="sermon-answer"} God to help. Isaiah 50:7
<?php use Illuminate\Support\Facades\DB; /*return [ 'List' => 'DB::table('notifications') ->where('created_at', '=', Carbon::today()->subDays(30)->toDateString())->get()' return ['List']; ];*/ ?>
'use strict'; (function () { var dependencies = ['gettext', 'ionic', 'ui.router', 'DrugDoseFrameworkControllers']; var app = angular.module('DrugDoseFrameworkApp', dependencies).run(function ($ionicPlatform, gettextCatalog) { var language = 'en_EN'; if (window.localStorage.getItem('language')) { language = window.localStorage.getItem('language'); } else { switch (window.navigator.language.substr(0, 2)) { case 'pl': language = 'pl_PL'; break; case 'de': language = 'de_DE'; break; } localStorage.setItem('language', language); } gettextCatalog.setCurrentLanguage(language); $ionicPlatform.ready(function () { if (window.cordova && window.cordova.plugins.Keyboard) { // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard // for form inputs) cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true); // Don't remove this line unless you know what you are doing. It stops the viewport // from snapping when text inputs are focused. Ionic handles this internally for // a much nicer keyboard experience. cordova.plugins.Keyboard.disableScroll(true); } if (window.StatusBar) { StatusBar.styleDefault(); } setTimeout(function() { navigator.splashscreen.hide(); }, 100); }); }); app.directive('placeholder', ['gettextCatalog', function (gettextCatalog) { return { restrict: 'A', link: function (scope, element, attrs) { element.attr('placeholder', gettextCatalog.getString(attrs.placeholder)); } }; }]); app.config(function ($stateProvider, $urlRouterProvider) { $stateProvider.state('drugs', { cache: false, url: '/drugs/', templateUrl: 'partials/drug-list.html', controller: 'DrugListCtrl' }).state('drug-details', { cache: false, url: '/drugs/:drugId', templateUrl: 'partials/drug-details.html', controller: 'DrugDetailsCtrl' }).state('language', { cache: false, url: '/drugs/language/', templateUrl: 'partials/language.html', controller: 'LanguageCtrl' }).state('drug-dose', { cache: false, url: '/drugs/dose/:drugId', templateUrl: 'partials/drug-dose.html', controller: 'DrugDoseCtrl' }); $urlRouterProvider.otherwise('/drugs/'); }); })();
<?php namespace App\Http\Controllers\Backend; use App\Http\Controllers\BackendController; use App\Http\Controllers\Controller; use App\User; use App\Role; use Illuminate\Http\Request; use Throwable; use Illuminate\Support\Facades\Hash; class UserController extends BackendController { // public function userProfile() { return view($this->_mainpages . 'user.profile'); } public function userList() { $users = User::with('roles')->orderBy('id', 'DESC')->get(); return view($this->_mainpages . 'user.index', compact('users')); } public function adminList() { $users = User::whereRoleIs(['admin'])->get(); return view($this->_mainpages . 'user.adminlist', compact('users')); } public function vendorList() { $users = User::whereRoleIs(['vendor'])->get(); return view($this->_mainpages . 'user.vendorlist', compact('users')); } public function edit($id) { $users = User::with('roles')->orderBy('id', 'DESC')->get(); $user = User::findOrFail($id); return view($this->_mainpages . 'user.index', compact('user', 'users')); } public function customerList() { $users = User::whereRoleIs(['user'])->get(); return view($this->_mainpages . 'user.adminlist', compact('users')); } public function userAdd(Request $request) { $data=$request->validate([ 'email' => 'required|email', 'name' => 'required', 'role' => 'required', 'user_type'=>'', 'password' => 'required|confirmed|min:6', 'password_confirmation' => 'required| min:6' ] ); try { $user=new User(); $user->user_type=$request->role; $user->fill($data); $user->password=bcrypt($request->password); $success=$user->save(); $user->attachRole($request->role); if ($user) { return redirect()->back()->with('status', 'User Successfully Created'); } } catch (Throwable $e) { dd($e->getMessage()); } } public function updateUser(Request $request, $id) { $request->validate([ 'email' => 'required|email', 'name' => 'required', 'role' => 'required', 'password' => 'confirmed', 'password_confirmation' => '' ] ); try { $user = User::findOrFail($id); $user->update([ 'name' => $request->name, 'email' => $request->email, ]); $user->syncRoles([$request->role]); if ($user) { return redirect()->back()->with('status', 'User Succesfully Updated'); } } catch (Throwable $e) { dd($e->getMessage()); } } public function deleteUser($id) { $user = User::findOrFail($id); $user->detachRole($user); $user->detachPermission($user); $delete = $user->delete(); if ($delete) { return redirect()->back()->with('status', 'Successfully Deleted'); } return redirect()->back()->with('error', 'Something went wrong'); } }
package com.upseil.gdx.artemis; import com.badlogic.gdx.utils.JsonValue; import com.upseil.gdx.properties.EnumerizedJsonBasedProperties; public final class ArtemisConfigs { public static enum SaveConfigValues { SaveStoreName, AutoSaveInterval, AutoSaveSlot, SaveSlots, SlotPrefix, TimeSuffix, NameSuffix } public static class SaveConfig extends EnumerizedJsonBasedProperties<SaveConfigValues> { public SaveConfig(JsonValue json) { super(json, SaveConfigValues.class); } } private ArtemisConfigs() { } }
gnuplot << EOF set term pngcairo size 1920,1080 enhanced set datafile separator "," set output 'output.png' set title 'Balsa FPS' set xlabel 'Time (s)' set ylabel 'FPS' set yrange [0:100] set key off plot 'FrameTimePlot.csv' using 1:3 with lines EOF okular output.png
using System.Collections.Generic; using System.Threading.Tasks; using UniversalDownloaderPlatform.Common.Interfaces.Models; namespace UniversalDownloaderPlatform.Common.Interfaces { public interface ICrawlResultsExporter { /// <summary> /// Generate file with crawl results inside the download directory /// </summary> /// <param name="crawlTargetInfo">Crawl target information</param> /// <param name="crawledUrls">List of crawled urls</param> /// <returns></returns> Task ExportCrawlResults(ICrawlTargetInfo crawlTargetInfo, List<ICrawledUrl> crawledUrls); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using DG.Tweening; using UniRx; using Summer; using System.Linq; public class PanelTextController : MonoBehaviour { public float speed = 1.0f; /// <summary> /// TextBoxに表示するテキストをバッファしておく /// </summary> public List<string> textBuffer = new List<string>(); List<string> defaultTextBuffer = new List<string> { "た~まや~", "さくしゃのTwitter → @john95206", "がんばって!", "リトライは R キー", "フィーバータイム後は いがいと チャンス", "なんどでもよみがえるさ", "て さえ にぎってしまえば こっちのもんよ", "なつだもの", "花火は 300発分 だよ" }; Vector2 initPos; float leftLimitPosX = 0; float RightLimitPosX = 0; /// <summary> /// チュートリアルの表示内容 /// </summary> List<string> TutorialTextList = new List<string> { "花火大会が おわる までに カノジョ の 手を にぎろう!", "← か A キーで カノジョ に 近づこう!", "明るい ときに うごくと にげられちゃうぞ!", }; List<string> GameOverTextList = new List<string> { "ざんねんでした  リトライは R キーだよ", "リトライは R キーです お足もとにお気をつけてお忘れ物のないようにおかえりください", "R キーでリトライ しばし花火を楽しむがいいさ", "R キーでリトライ この花火でも見て げんきだしなよ" }; /// <summary> /// エンディング中のテキスト /// </summary> List<string> EndingTextList = new List<string> { "Congraturation!", "- Credit -", "使用アセット:UniRx DOTween", "使用フォント:Pixel M Plus Regular10", "使用楽曲:エンディングテーマ「ピコピコ天国」from MusMus", "ヒューンの音 from Music is VFR", "パンの音 from ニコニ・コモンズ", "使用ツール:Edge", "Directed by Yuu from BIT-BAD COMPANY", "Thank you for playing!", "さくしゃのTwitter → @john95206", }; /// <summary> /// 表示するテキスト /// </summary> [SerializeField] private Text TextBox; FireWorksManager manager; Tweener moveTween; public void Initialize(FireWorksManager manager) { initPos = transform.localPosition; TextBox = GetComponent<Text>(); this.manager = manager; if (DataMaster.gameState <= GAME_STATE.Tutorial) { foreach (var text in TutorialTextList) { BufferText(text); } } SetTextBoxAndTween(); } void SetTextBoxAndTween() { AddDefaultTextIfBufferEmpty(); // リストの先頭を取り出す var nextText = textBuffer.FirstOrDefault(); // 先頭のテキストをリストからクリア if (textBuffer.Count > 0) { textBuffer.RemoveAt(0); } // テキストボックスに文字をセット TextBox.text = nextText; var textStartPosX = initPos.x; // 文字数に応じて位置をずらす transform.localPosition = new Vector2(TextBox.preferredWidth, transform.localPosition.y); RightLimitPosX = transform.localPosition.x; leftLimitPosX = -RightLimitPosX; moveTween = transform .DOLocalMoveX(leftLimitPosX, TextBox.text.Length * 0.4f) .SetEase(Ease.Linear) .OnComplete(() => { // チュートリアルの最後の文言の時はチュートリアルステート終了 if (nextText == TutorialTextList.Last()) { DataMaster.GameStart(); } // 非同期でテキストは追加され続けるので、再帰処理をして常に次のテキストを流し続ける SetTextBoxAndTween(); }); } /// <summary> /// もしバッファが空ならデフォルト分から補充 /// 表示されているものと被らないようにする /// </summary> void AddDefaultTextIfBufferEmpty() { if(textBuffer.Count < 1) { if(DataMaster.gameState == GAME_STATE.Ending) { // エンディングの全てのテキストが流れた後 return; } var index = (int)Random.Range(0, defaultTextBuffer.Count); textBuffer.Add(defaultTextBuffer.Where(text => text != TextBox.text).ElementAt(index)); } } /// <summary> /// 更新するテキストをバッファする /// </summary> void BufferText(string newText) { textBuffer.Add(newText); } /// <summary> /// FireWorksManagerから呼ぶ。 /// 更新するテキストを即座に流す /// </summary> /// <param name="newText"></param> public void ForceBufferText(string newText) { textBuffer.Insert(0, newText); moveTween.Kill(); SetTextBoxAndTween(); } /// <summary> /// 強制的に次のテキストを流す /// チュートリアルを想定 /// </summary> public void ForceUpdateText() { if(textBuffer.Count < 2) { return; } moveTween.Kill(); SetTextBoxAndTween(); } public void GameClear() { textBuffer.Clear(); textBuffer.AddRange(EndingTextList); moveTween.Kill(); SetTextBoxAndTween(); } public void GameOver(bool isFireRemain) { if (isFireRemain) { var index = (int)Random.Range(0, GameOverTextList.Count); textBuffer.Clear(); textBuffer.Add(GameOverTextList.ElementAt(index)); } else { textBuffer.Clear(); textBuffer.Add("これにて しゅうりょう またきてね リトライは Rだよ"); } moveTween.Kill(); SetTextBoxAndTween(); } }
<?php namespace App\Controller; use App\Api\AbstractController; use App\Attributes\UrlAttribute; use Psr\Http\Message\ResponseInterface; class WhoopsTest extends AbstractController { #[UrlAttribute('/whoops')] public function whoops(): ResponseInterface { throw new \Exception('whoops, i made a boo boo'); } }
package sttp.tapir.generic.internal import sttp.tapir.encodedName import scala.reflect.macros.blackbox private[generic] class CaseClassUtil[C <: blackbox.Context, T: C#WeakTypeTag](val c: C) { import c.universe._ val t: Type = weakTypeOf[T] if (!t.typeSymbol.isClass || !t.typeSymbol.asClass.isCaseClass) { c.error(c.enclosingPosition, s"Multipart codec can only be generated for a case class, but got: $t.") } lazy val fields: List[Symbol] = t.decls .collectFirst { case m: MethodSymbol if m.isPrimaryConstructor => m } .get .paramLists .head private lazy val companion: Ident = Ident(TermName(t.typeSymbol.name.decodedName.toString)) lazy val instanceFromValues: Tree = if (fields.size == 1) { q"$companion.apply(values.head.asInstanceOf[${fields.head.typeSignature}])" } else { q"$companion.tupled.asInstanceOf[Any => $t].apply(sttp.tapir.internal.SeqToParams(values))" } lazy val schema: Tree = c.typecheck(q"implicitly[sttp.tapir.Schema[$t]]") def getEncodedName(field: Symbol): Option[String] = { // https://stackoverflow.com/questions/20908671/scala-macros-how-to-read-an-annotation-object field.annotations.collectFirst { case a if a.tree.tpe <:< c.weakTypeOf[encodedName] => a.tree.children.tail match { case List(Literal(Constant(str: String))) => str } } } }
module ProxyEnforce module Errors class Base < ::Exception; end end end
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); // Dashboard adaptada de criative - tim // https://demos.creative-tim.com/now-ui-dashboard/docs/1.0/getting-started/introduction.html class Dashboard { function show($view, $data=array()){ $CI = & get_instance(); // carrega cabeçalho $CI->load->view('cabecalho',$data); // carrega menu lateral esquerdo $CI->load->view('menu-lateral',$data); //carrega main panel nav bar $CI->load->view('main-panel-nav-bar',$data); // carrega corpo da página $CI->load->view($view,$data); // carrega scripts $CI->load->view('scripts',$data); } }
import MdxCard from 'src/components/MdxCard'; <MdxCard> ## User (Avatar) Represents a component showing a user avatar (picture) with a user name on the right. [Size](demo://Size.tsx) ### Usage ```js import User from '@paljs/ui/User'; ``` You can hide unnecessary captions (name, title or both): [Hide](demo://Hide.tsx) You can set a custom avatar background-image, user image (as link or BASE64 string) and disable user initials: [Image](demo://Image.tsx) </MdxCard>
package codes.quine.labo.lite.crazy /** Tardis a state monad implementation holds both of backward and forward states. */ final case class Tardis[BW, FW, A](run: (Lazy[BW], Lazy[FW]) => (Lazy[BW], Lazy[FW], Lazy[A])) { /** Applies a result value to the given mapping, and returns a new tardis monad holds this result. */ def map[B](f: Lazy[A] => Lazy[B]): Tardis[BW, FW, B] = flatMap(lx => Tardis.pure(f(lx))) /** Applies a result value to the given mapping, and returns a new tardis monad holds flattened result. Hence the * mapping requires lazy cells as its arguments, we can write an action depends on both of future and past state. */ def flatMap[B](f: Lazy[A] => Tardis[BW, FW, B]): Tardis[BW, FW, B] = Tardis { case (lb0, lf0) => type Fix = ( Lazy[(Lazy[BW], Lazy[FW], Lazy[A])], Lazy[(Lazy[BW], Lazy[FW], Lazy[B])], Lazy[BW], Lazy[BW], Lazy[FW], Lazy[FW], Lazy[A], Lazy[B] ) val lfix = Lazy.fix[Fix] { lfix => val lb2f1x = Lazy(run(lfix.value._3, lf0)) val lb1f2y = Lazy(f(lfix.value._7).run(lb0, lfix.value._5)) val lb1 = Lazy(lb1f2y.value._1.value) val lb2 = Lazy(lb2f1x.value._1.value) val lf1 = Lazy(lb2f1x.value._2.value) val lf2 = Lazy(lb1f2y.value._2.value) val lx = Lazy(lb2f1x.value._3.value) val ly = Lazy(lb1f2y.value._3.value) (lb2f1x, lb1f2y, lb1, lb2, lf1, lf2, lx, ly) } val (_, _, _, lb2, _, lf2, _, ly) = lfix.value (lb2, lf2, ly) } } object Tardis { /** Returns a new tardis monad holds the specified value as its result. */ def pure[BW, FW, A](lx: Lazy[A]): Tardis[BW, FW, A] = Tardis((lb, lf) => (lb, lf, lx)) /** Returns a new tardis monad holds a backward state as its result. */ def getBackward[BW, FW]: Tardis[BW, FW, BW] = Tardis((lb, lf) => (lb, lf, lb)) /** Returns a new tardis monad for putting the specified value to a backward state. */ def putBackward[BW, FW](lb: Lazy[BW]): Tardis[BW, FW, Unit] = Tardis((_, lf) => (lb, lf, Lazy(()))) /** Returns a new tardis monad for modifying a backward state by the given mapping. */ def modifyBackward[BW, FW](f: Lazy[BW] => Lazy[BW]): Tardis[BW, FW, Unit] = Tardis((lb, lf) => (f(lb), lf, Lazy(()))) /** Returns a new tardis monad holds a forward state as its result. */ def getForward[BW, FW]: Tardis[BW, FW, FW] = Tardis((lb, lf) => (lb, lf, lf)) /** Returns a new tardis monad for putting the specified value to a forward state. */ def putForward[BW, FW](lf: Lazy[FW]): Tardis[BW, FW, Unit] = Tardis((lb, _) => (lb, lf, Lazy(()))) /** Returns a new tardis monad for modifying a forward state by the given mapping. */ def modifyForward[BW, FW](f: Lazy[FW] => Lazy[FW]): Tardis[BW, FW, Unit] = Tardis((lb, lf) => (lb, f(lf), Lazy(()))) }
package com.github.vickumar1981.stringdistance import com.github.vickumar1981.stringdistance.impl._ import com.github.vickumar1981.stringdistance.interfaces.NGramTokenizer /** * Main class to organize functionality of different string distance algorithms * * {{{ * import com.github.vickumar1981.stringdistance.StringDistance._ * import com.github.vickumar1981.stringdistance.impl.{ConstantGap, LinearGap} * * // Scores between strings * val cosSimilarity: Double = Cosine.score("hello", "chello") * val damerau: Double = Damerau.score("martha", "marhta") * val diceCoefficient: Double = DiceCoefficient.score("martha", "marhta") * val hamming: Double = Hamming.score("martha", "marhta") * val jaccard: Double = Jaccard.score("karolin", "kathrin", 1) * val jaro: Double = Jaro.score("martha", "marhta") * val jaroWinkler: Double = JaroWinkler.score("martha", "marhta", 0.1) * val levenshtein: Double = Levenshtein.score("martha", "marhta") * val needlemanWunsch: Double = NeedlemanWunsch.score("martha", "marhta", ConstantGap()) * val ngramSimilarity: Double = NGram.score("karolin", "kathrin", 1) * val bigramSimilarity: Double = NGram.score("karolin", "kathrin", 2) * val overlap: Double = Overlap.score("karolin", "kathrin", 1) * val smithWaterman: Double = SmithWaterman.score("martha", "marhta", (LinearGap(gapValue = -1), Integer.MAX_VALUE)) * val smithWatermanGotoh: Double = SmithWatermanGotoh.score("martha", "marhta", ConstantGap()) * val tversky: Double = Tversky.score("karolin", "kathrin", 0.5) * * // Distances between strings * val damerauDist: Int = Damerau.distance("martha", "marhta") * val hammingDist: Int = Hamming.distance("martha", "marhta") * val levenshteinDist: Int = Levenshtein.distance("martha", "marhta") * val longestCommonSubSeq: Int = LongestCommonSeq.distance("martha", "marhta") * val ngramDist: Int = NGram.distance("karolin", "kathrin", 1) * val bigramDist: Int = NGram.distance("karolin", "kathrin", 2) * * // return a List[String] of ngram tokens * val tokens = NGram.tokens("martha", 2) // List("ma", "ar", "rt", "th", "ha") * }}} */ object StringDistance { object Cosine extends StringMetric[CosineAlgorithm] object Damerau extends StringMetric[DamerauLevenshteinAlgorithm] object DiceCoefficient extends StringMetric[DiceCoefficientAlgorithm] object Hamming extends StringMetric[HammingAlgorithm] object Jaccard extends WeightedStringMetric[JaccardAlgorithm, Int] object Jaro extends StringMetric[JaroAlgorithm] object JaroWinkler extends WeightedStringMetric[JaroWinklerAlgorithm, Double] object Levenshtein extends StringMetric[LevenshteinAlgorithm] object LongestCommonSeq extends StringMetric[LongestCommonSeqAlorithm] object NeedlemanWunsch extends WeightedStringMetric[NeedlemanWunschAlgorithm, ConstantGap] object NGram extends WeightedStringMetric[NGramAlgorithm, Int] with NGramTokenizer { def tokens(s: String, n: Int): List[String] = tokenizeNGram(s.toCharArray, n).map(_.mkString) } object Overlap extends WeightedStringMetric[OverlapAlgorithm, Int] object SmithWaterman extends WeightedStringMetric[SmithWatermanAlgorithm, (Gap, Int)] object SmithWatermanGotoh extends WeightedStringMetric[SmithWatermanGotohAlgorithm, ConstantGap] object Tversky extends WeightedStringMetric[TverskyAlgorithm, Double] } private[stringdistance] class CosineSimilarityImplWrapper extends CosSimilarityImpl private[stringdistance] class DiceCoefficientImplWrapper extends DiceCoefficientImpl private[stringdistance] class HammingImplWrapper extends HammingImpl private[stringdistance] class JaccardImplWrapper extends JaccardImpl private[stringdistance] class JaroImplWrapper extends JaroImpl private[stringdistance] class LevenshteinDistanceImplWrapper extends LevenshteinDistanceImpl private[stringdistance] class LongestCommonSeqWrapper extends LongestCommonSeqImpl private[stringdistance] class NeedlemanWunschImplWrapper extends NeedlemanWunschImpl private[stringdistance] class NGramImplWrapper extends NGramImpl private[stringdistance] class OverlapImplWrapper extends OverlapImpl private[stringdistance] class SmithWatermanImplWrapper extends SmithWatermanImpl
// // CwCardDelegate.h // CwTest // // Created by CP Hsiao on 2014/12/8. // Copyright (c) 2014年 CP Hsiao. All rights reserved. // #ifndef CwTest_CwCardDelegate_h #define CwTest_CwCardDelegate_h #import <Foundation/Foundation.h> #import "CwCard.h" #import "CwAddress.h" @class CwCard; @protocol CwCardDelegate <NSObject> //@required @optional typedef NS_ENUM (NSInteger, CwCardRSSI) { CwCardRSSIStrong = 0x00, // > -80 CwCardRSSIWeak = 0x01, // > -95 CwCardRSSIFar = 0x02 // < -95 }; -(void) didWatchDogAlert: (NSInteger) scale; //0: strong, 1: weak, 2: far -(void) didPrepareService; -(void) didCwCardCommand; -(void) didCwCardCommandError:(NSInteger)cmdId ErrString:(NSString*)errString; -(void) didSyncFromCard; -(void) didSyncToCard; -(void) didGetModeState; -(void) didGetCwInfo; -(void) didReInitCw; -(void) didPinChlng; -(void) didPinAuth; -(void) didPinChange; -(void) didPinLogout; -(void) didRegisterHost: (NSString *)OTP; -(void) didRegisterHostError:(NSInteger)errorId; -(void) didConfirmHost; -(void) didConfirmHostError:(NSInteger)errId; -(void) didEraseCw; //erase wallet & hosts -(void) didEraseCwError:(NSInteger)errId; //fail to erase wallet & hosts -(void) didEraseWallet; //erase wallet, perserved hosts -(void) didLoginHost; -(void) didLogoutHost; -(void) didGenOTPWithError:(NSInteger)errId; -(void) didGetHosts; -(void) didApproveHost: (NSInteger) hostId; -(void) didRemoveHost: (NSInteger) hostId; -(void) didPersoSecurityPolicy; -(void) didGetSecurityPolicy; -(void) didSetSecurityPolicy; -(void) didGetCwCardName; //cardName -(void) didSetCwCardName; //cardName -(void) didGetCwCurrRate; //currRate -(void) didSetCwCurrRate; //currRate -(void) didGetCwCardId; -(void) didGetCwHdwStatus; //hdwStatus, -(void) didGetCwHdwName; //hdwName, -(void) didGetCwHdwAccountPointer; //hdwAccointPointer -(void) didSetCwHdwName; //hdwName -(void) didSetCwHdwAccointPointer; //hdwAccointPointer -(void) didInitHdwBySeed; -(void) didInitHdwByCard; -(void) didInitHdwConfirm; -(void) didNewAccount: (NSInteger) accId; -(void) didGetAccounts; -(void) didGetAccountInfo: (NSInteger) accId; -(void) didSetAccountName; -(void) didSetAccountBalance:(NSInteger) accId; -(void) didSetAccountExtKeyPtr:(NSInteger) accId keyPtr:(NSInteger)keyPtr; -(void) didSetAccountIntKeyPtr:(NSInteger) accId keyPtr:(NSInteger)keyPtr; -(void) didGenAddress: (CwAddress *) addr; -(void) didGenAddressError; -(void) didGetAccountAddresses: (NSInteger) accId; -(void) didGetAddressInfo; -(void) didGetAddressPublicKey:(CwAddress *)addr; -(void) didPrepareTransaction: (NSString *)OTP; -(void) didPrepareTransactionError: (NSString *)errMsg; -(void) didGetTapTapOtp: (NSString *)OTP; -(void) didGetButton; -(void) didVerifyOtp; -(void) didVerifyOtpError:(NSInteger)errId; -(void) didSignTransaction:(NSString *)txId; -(void) didSignTransactionError: (NSString *)errMsg; -(void) didCancelTransaction; -(void) didFinishTransaction; //Exchange Site Callbacks -(void) didExGetRegStatus: (NSInteger) status; -(void) didExGetOtp:(NSString *)exOtp type:(NSInteger)otpType; -(void) didExGetOtpError:(NSInteger)errId type:(NSInteger)otpType; -(void) didExSessionInit: (NSData *)seResp SeChlng: (NSData*)seChlng; -(void) didExSessionEstab; -(void) didExSessoinLogout; -(void) didMcuResetSe; -(void) didUpdateFirmwareProgress: (float)progress; -(void) didUpdateFirmwareDone: (NSInteger)status; //AuthError, DownloadError, MacError, DownloadSuccess -(void) didBackToSLE97Loader; -(void) didUpdateCurrencyDisplay; -(void) didUpdateCurrencyDisplayError:(NSInteger)errorCode; @end #endif
import { Controller, Get, UseGuards, Param } from '@nestjs/common'; import { ParticipantService } from './participant.service'; import { JwtAuthGuard } from 'src/auth/jwt-auth.guard'; import { GetUser } from 'src/user/user.decorator'; @UseGuards(JwtAuthGuard) @Controller('events/:event_id') export class ParticipantController { constructor(private readonly participantService: ParticipantService) {} @Get('attend-event') sendRequestToAttendEvent(@GetUser() user, @Param() params) { return this.participantService.sendRequestToAttendEvent(params.event_id, user); } @Get('cancel-attend-request') cancelRequesstToAttendEvent(@GetUser() user, @Param() params) { return this.participantService.cancelRequesstToAttendEvent(params.event_id, user); } @Get('confirm-attend-request') confirmAttendRequest(@GetUser() user, @Param() params) { return this.participantService.confirmAttendRequest(params.event_id, user); } @Get('reject-attend-request') rejectAttendRequest(@GetUser() user, @Param() params) { return this.participantService.rejectAttendRequest(params.event_id, user); } }
/** @babel */ import { CompositeDisposable } from 'atom' let RecentsView const VIEW_URI = 'atom://recents/view' export default class Recents { async activate() { this.subscriptions = new CompositeDisposable() this.subscriptions.add( atom.workspace.addOpener(uri => { if (uri === VIEW_URI) { return this.createView({ uri: VIEW_URI }) } }) ) this.subscriptions.add( atom.commands.add('atom-workspace', 'recents:view', async => { this.show() }) ) if (atom.config.get('recents.showOnStartup')) { if (atom.getLoadSettings().locationsToOpen.length == 1) { if (!atom.getLoadSettings().locationsToOpen[0].exists) { await this.show() } } } } deactivate() { this.subscriptions.dispose() } createView(state) { if (RecentsView == null) RecentsView = require('./view') return new RecentsView(state) } show() { return Promise.all([ atom.workspace.open(VIEW_URI, { searchAllPanes: true }) ]) } } export default new Recents();
module Data.TokenUsageLikelihood.Internal ( noTestOccurrences , totalFileCount , occurrenceCountByFileType , occursMoreThanOnce , oneTestOccurrence , occursInOneFile , matchesAutomaticLowLikelihood , oneApplicationOccurrence ) where import qualified Data.Text as T import Data.TokenUsageLikelihood.ProjectConfiguration import Data.TokenUsageLikelihood.TextPredicateMatch import Data.TokenUsageLikelihood.TokenOccurrences import Data.TokenUsageLikelihood.TokenOccurrences.Types import Numeric.Natural (Natural) noTestOccurrences :: Occurrences -> Bool noTestOccurrences output = occurrenceCountByFileType TestFile output == 0 oneTestOccurrence :: Occurrences -> Bool oneTestOccurrence output = occurrenceCountByFileType TestFile output == 1 oneApplicationOccurrence :: Occurrences -> Bool oneApplicationOccurrence output = occurrenceCountByFileType ApplicationFile output == 1 occursInOneFile :: Occurrences -> Bool occursInOneFile output = totalFileCount output == 1 occursMoreThanOnce :: Occurrences -> Bool occursMoreThanOnce output = totalOccurrenceCount output > 1 matchesAutomaticLowLikelihood :: [AutomaticLowLikelihood] -> Input -> Occurrences -> Maybe AutomaticLowLikelihood matchesAutomaticLowLikelihood lowLikelihoods input' occurrences' = safeHead $ filter (matchesAll input' occurrences') lowLikelihoods where safeHead [] = Nothing safeHead (x:_) = Just x matchesAll i o ll = all (matchesOutput i o) (automaticLowLikelihoodMatchers ll) matchesOutput :: Input -> Occurrences -> Matcher -> Bool matchesOutput input' occurrences' matcher = case matcher of TokenMatch pre -> any (`check` pre) $ inputTokenNames input' PathMatch pre -> any (\n -> check (T.pack n) pre) $ inputFilePaths input' FileTypeOccurrenceMatch ft count -> fromIntegral (fileCountByFileType ft occurrences') == count fileCountByFileType :: FileType -> Occurrences -> Natural fileCountByFileType ft = fileCount . tokenOccurrencesByFileType ft occurrenceCountByFileType :: FileType -> Occurrences -> Natural occurrenceCountByFileType ft = occurrenceCount . tokenOccurrencesByFileType ft totalFileCount :: Occurrences -> Natural totalFileCount = fileCount . totalOccurrences totalOccurrenceCount :: Occurrences -> Natural totalOccurrenceCount = occurrenceCount . totalOccurrences tokenOccurrencesByFileType :: FileType -> Occurrences -> TokenOccurrences tokenOccurrencesByFileType ApplicationFile = applicationDirectoryOccurrences tokenOccurrencesByFileType TestFile = testDirectoryOccurrences tokenOccurrencesByFileType ConfigFile = configDirectoryOccurrences tokenOccurrencesByFileType Unknown = unknownOccurrences
/* Generated from "toaster_base.dxf" on Aug-22-2014. Smoothed vertex normals. Normalized to unit bounding box. */ #include "gllist.h" static const float toaster_base_data[] = { -0.10666,0.994296,0,-0.242083,0.5,0.052679, 0.10666,0.994296,0,0.242083,0.5,-0.052679, -0.21332,0.976982,0,-0.242083,0.5,-0.052679, 0.10666,0.994296,0,0.242083,0.5,-0.052679, -0.10666,0.994296,0,-0.242083,0.5,0.052679, 0.213319,0.976983,0,0.242083,0.5,0.052679, 0.983679,0.17993,0,0.309535,0.432529,-0.052679, 0.999314,0.03703,0,0.357619,0,0.052679, 0.999314,-0.03703,0,0.357619,0,-0.052679, 0.999314,0.03703,0,0.357619,0,0.052679, 0.983679,0.17993,0,0.309535,0.432529,-0.052679, 0.968549,0.248824,0,0.309535,0.432529,0.052679, 0.10666,-0.994296,0,0.242083,-0.5,0.052679, -0.10666,-0.994296,0,-0.242083,-0.5,-0.052679, 0.213319,-0.976983,0,0.242083,-0.5,-0.052679, -0.10666,-0.994296,0,-0.242083,-0.5,-0.052679, 0.10666,-0.994296,0,0.242083,-0.5,0.052679, -0.21332,-0.976982,0,-0.242083,-0.5,0.052679, -0.983679,0.17993,0,-0.309535,0.432529,0.052679, -0.999314,0.03703,0,-0.357619,0,-0.052679, -0.999314,-0.03703,0,-0.357619,0,0.052679, -0.999314,0.03703,0,-0.357619,0,-0.052679, -0.983679,0.17993,0,-0.309535,0.432529,0.052679, -0.968549,0.248824,0,-0.309535,0.432529,-0.052679, 0,0,-1,-0.309535,0.432529,-0.052679, 0,0,-1,-0.309535,-0.432529,-0.052679, 0,0,-1,-0.357619,0,-0.052679, 0,0,-1,-0.309535,-0.432529,-0.052679, 0,0,-1,-0.309535,0.432529,-0.052679, 0,0,-1,-0.292672,0.483132,-0.052679, 0,0,-1,-0.309535,-0.432529,-0.052679, 0,0,-1,-0.292672,0.483132,-0.052679, 0,0,-1,-0.292672,-0.483132,-0.052679, 0,0,-1,-0.292672,-0.483132,-0.052679, 0,0,-1,-0.292672,0.483132,-0.052679, 0,0,-1,-0.242083,0.5,-0.052679, 0,0,-1,-0.292672,-0.483132,-0.052679, 0,0,-1,-0.242083,0.5,-0.052679, 0,0,-1,-0.242083,-0.5,-0.052679, 0,0,-1,-0.242083,-0.5,-0.052679, 0,0,-1,-0.242083,0.5,-0.052679, 0,0,-1,0.242083,0.5,-0.052679, 0,0,-1,-0.242083,-0.5,-0.052679, 0,0,-1,0.242083,0.5,-0.052679, 0,0,-1,0.242083,-0.5,-0.052679, 0,0,-1,0.242083,-0.5,-0.052679, 0,0,-1,0.242083,0.5,-0.052679, 0,0,-1,0.292672,-0.483132,-0.052679, 0,0,-1,0.292672,-0.483132,-0.052679, 0,0,-1,0.242083,0.5,-0.052679, 0,0,-1,0.292672,0.483132,-0.052679, 0,0,-1,0.292672,-0.483132,-0.052679, 0,0,-1,0.292672,0.483132,-0.052679, 0,0,-1,0.309535,-0.432529,-0.052679, 0,0,-1,0.309535,-0.432529,-0.052679, 0,0,-1,0.292672,0.483132,-0.052679, 0,0,-1,0.309535,0.432529,-0.052679, 0,0,-1,0.309535,-0.432529,-0.052679, 0,0,-1,0.309535,0.432529,-0.052679, 0,0,-1,0.357619,0,-0.052679, 0.999314,-0.03703,0,0.357619,0,-0.052679, 0.983679,-0.17993,0,0.309535,-0.432529,0.052679, 0.968549,-0.248824,0,0.309535,-0.432529,-0.052679, 0.983679,-0.17993,0,0.309535,-0.432529,0.052679, 0.999314,-0.03703,0,0.357619,0,-0.052679, 0.999314,0.03703,0,0.357619,0,0.052679, -0.999314,-0.03703,0,-0.357619,0,0.052679, -0.983679,-0.17993,0,-0.309535,-0.432529,-0.052679, -0.968549,-0.248824,0,-0.309535,-0.432529,0.052679, -0.983679,-0.17993,0,-0.309535,-0.432529,-0.052679, -0.999314,-0.03703,0,-0.357619,0,0.052679, -0.999314,0.03703,0,-0.357619,0,-0.052679, -0.968549,-0.248824,0,-0.309535,-0.432529,0.052679, -0.948709,-0.316149,0,-0.292672,-0.483132,-0.052679, -0.948709,-0.316149,0,-0.292672,-0.483132,0.052679, -0.948709,-0.316149,0,-0.292672,-0.483132,-0.052679, -0.968549,-0.248824,0,-0.309535,-0.432529,0.052679, -0.983679,-0.17993,0,-0.309535,-0.432529,-0.052679, -0.21332,-0.976982,0,-0.242083,-0.5,0.052679, -0.316307,-0.948657,0,-0.292672,-0.483132,-0.052679, -0.10666,-0.994296,0,-0.242083,-0.5,-0.052679, -0.316307,-0.948657,0,-0.292672,-0.483132,-0.052679, -0.21332,-0.976982,0,-0.242083,-0.5,0.052679, -0.316307,-0.948657,0,-0.292672,-0.483132,0.052679, 0.316307,-0.948657,0,0.292672,-0.483132,0.052679, 0.213319,-0.976983,0,0.242083,-0.5,-0.052679, 0.316307,-0.948657,0,0.292672,-0.483132,-0.052679, 0.213319,-0.976983,0,0.242083,-0.5,-0.052679, 0.316307,-0.948657,0,0.292672,-0.483132,0.052679, 0.10666,-0.994296,0,0.242083,-0.5,0.052679, 0.968549,-0.248824,0,0.309535,-0.432529,-0.052679, 0.948709,-0.316149,0,0.292672,-0.483132,0.052679, 0.948709,-0.316149,0,0.292672,-0.483132,-0.052679, 0.948709,-0.316149,0,0.292672,-0.483132,0.052679, 0.968549,-0.248824,0,0.309535,-0.432529,-0.052679, 0.983679,-0.17993,0,0.309535,-0.432529,0.052679, 0.213319,0.976983,0,0.242083,0.5,0.052679, 0.316307,0.948657,0,0.292672,0.483132,-0.052679, 0.10666,0.994296,0,0.242083,0.5,-0.052679, 0.316307,0.948657,0,0.292672,0.483132,-0.052679, 0.213319,0.976983,0,0.242083,0.5,0.052679, 0.316307,0.948657,0,0.292672,0.483132,0.052679, 0.948709,0.316149,0,0.292672,0.483132,-0.052679, 0.968549,0.248824,0,0.309535,0.432529,0.052679, 0.983679,0.17993,0,0.309535,0.432529,-0.052679, 0.968549,0.248824,0,0.309535,0.432529,0.052679, 0.948709,0.316149,0,0.292672,0.483132,-0.052679, 0.948709,0.316149,0,0.292672,0.483132,0.052679, -0.948709,0.316149,0,-0.292672,0.483132,0.052679, -0.968549,0.248824,0,-0.309535,0.432529,-0.052679, -0.983679,0.17993,0,-0.309535,0.432529,0.052679, -0.968549,0.248824,0,-0.309535,0.432529,-0.052679, -0.948709,0.316149,0,-0.292672,0.483132,0.052679, -0.948709,0.316149,0,-0.292672,0.483132,-0.052679, -0.316307,0.948657,0,-0.292672,0.483132,0.052679, -0.21332,0.976982,0,-0.242083,0.5,-0.052679, -0.316307,0.948657,0,-0.292672,0.483132,-0.052679, -0.21332,0.976982,0,-0.242083,0.5,-0.052679, -0.316307,0.948657,0,-0.292672,0.483132,0.052679, -0.10666,0.994296,0,-0.242083,0.5,0.052679 }; static const struct gllist toaster_base_frame = { GL_N3F_V3F, GL_TRIANGLES, 120, toaster_base_data, 0 }; const struct gllist *toaster_base = &toaster_base_frame;
--- title: test post date: 2019-08-27T07:00:00.000Z description: TEST POST --- asdasdfgghh
#!/usr/bin/env sh printf 'Building LESS files %s\n\n' $(date --iso=seconds) cp less/normalize.css css/normalize.css lessc less/index.less css/index.css --source-map --verbose printf 'Done\n'
**FNAMP笔记(FreeBSD 12.2 + Nginx 1.18 + Apache 2.4 + MariaDB 10.5 + PHP 8.0 + Tomcat 9.0 + Python 3.7)** ``` tzsetup freebsd-update fetch freebsd-update install freebsd-update upgrade -r 12.2-RELEASE freebsd-update install shutdown -r now freebsd-update install ``` /usr/local/etc/pkg/repos/FreeBSD.conf ``` FreeBSD: { url: "pkg+http://mirrors.ustc.edu.cn/freebsd-pkg/${ABI}/quarterly", } pkg update -f ``` ``` pkg-static install -f pkg pwd_mkdb -p /etc/master.passwd # user 'mysql' disappeared during update ``` ``` pkg install nginx apache24 mariadb105-server openjdk8 tomcat9 python3 py37-pip py37-certbot pkg install php80 mod_php80 php80-gd php80-json php80-mbstring php80-mysqli php80-pdo_mysql \ php80-session phpMyAdmin5-php80 ap24-mod_rpaf2 mysql-connector-java pkg install node14 npm-node14 ``` ``` sysrc mysql_enable="YES" service mysql-server start mysql_secure_installation sysrc mysql_args="--bind-address=127.0.0.1" service mysql-server restart ``` ``` mysql -u root -p MariaDB> grant select,insert,update,delete on *.* to 'user123'@'%' Identified by 'pass123'; MariaDB> flush privileges; ``` ``` curl -sS https://getcomposer.org/installer | php mv composer.phar /usr/local/bin/composer composer config -g repo.packagist composer https://mirrors.aliyun.com/composer/ pip3 install --upgrade pip cp /usr/local/share/java/class/mysql-connector-java.jar /usr/local/apache-tomcat-9/lib/ cp /usr/local/www/phpMyAdmin/config.sample.inc.php /usr/local/www/phpMyAdmin/config.inc.php ``` /usr/local/www/phpMyAdmin/config.inc.php ``` $cfg['blowfish_secret']='Fo1ec5u0n8lpG4hMCOICD8X8cUUTxOF1'; ``` ``` cp /usr/local/etc/php.ini-production /usr/local/etc/php.ini ``` /usr/local/etc/php.ini ``` expose_php = Off date.timezone = Asia/Shanghai ``` /usr/local/etc/apache24/httpd.conf ``` Listen 81 ServerAdmin xxx@live.cn ServerName localhost:81 DirectoryIndex index.php index.html <FilesMatch "\.php$"> SetHandler application/x-httpd-php </FilesMatch> Alias /phpmyadmin "/usr/local/www/phpMyAdmin" <Directory "/usr/local/www/phpMyAdmin"> Options None AllowOverride None Require all granted </Directory> ``` ``` LoadModule rewrite_module libexec/apache24/mod_rewrite.so LoadModule rpaf_module libexec/apache24/mod_rpaf.so RPAFenable On RPAFsethostname On RPAFproxy_ips 127.0.0.1 RPAFheader X-Forwarded-For ``` /etc/fstab ``` fdesc /dev/fd fdescfs rw 0 0 proc /proc procfs rw 0 0 ``` /usr/local/apache-tomcat-9.0/conf/tomcat-users.xml ``` <role rolename="admin-gui"/> <role rolename="manager-gui"/> <user username="admin" password="xxx" roles="admin-gui,manager-gui"/> ``` /usr/local/apache-tomcat-9.0/conf/server.xml ``` <Connector port="8080" address="127.0.0.1" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8443"/> <Context path="" docBase="ROOT" debug="0" reloadable="true"/> #在<Host>节点里面添加 ``` ``` sysrc apache24_enable="YES" service apache24 start sysrc nginx_enable="YES" service nginx start sysrc tomcat9_enable="YES" service tomcat9 start ``` ``` certbot certonly --webroot -w /usr/local/www/nginx -d xxx.net -m xxx@live.cn --agree-tos ``` /usr/local/etc/nginx/nginx.conf ``` http { upstream php { server 127.0.0.1:81; } upstream java { server 127.0.0.1:8080; } server { server_name _; return 404; } server { listen 80; server_name www.xxx.net; location / { index index.html; } } server { listen 443 ssl http2; server_name xxx.net; ssl_session_timeout 1d; ssl_session_cache shared:SSL:10m; ssl_session_tickets off; ssl_protocols TLSv1.2 TLSv1.3; ssl_ciphers HIGH:!aNULL:!MD5; ssl_prefer_server_ciphers on; ssl_certificate /usr/local/etc/letsencrypt/live/xxx.net/fullchain.pem; ssl_certificate_key /usr/local/etc/letsencrypt/live/xxx.net/privkey.pem; ssl_trusted_certificate /usr/local/etc/letsencrypt/live/xxx.net/chain.pem; ssl_stapling on; ssl_stapling_verify on; resolver 8.8.8.8 8.8.4.4 valid=300s; resolver_timeout 30s; location / { proxy_pass http://java; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } location /phpmyadmin/ { proxy_pass http://php; proxy_set_header Host $host:443; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; client_max_body_size 10m; client_body_buffer_size 128k; proxy_connect_timeout 90; proxy_send_timeout 90; proxy_read_timeout 90; proxy_buffer_size 4 32k; proxy_temp_file_write_size 64k; } } } ```
import os import unittest @unittest.skip('Skipping unittest for namespace') class TestNameSpace(unittest.TestCase): """ This test makes sure we don't remove anything from the pysal NameSpace that 1.0 users might expect to be there. 1.0 Namespace was taken from the 1.1 Code sprint wave, with special names removes (__all__, etc) """ def test_contents(self): namespace_v1_0 = ['Box_Plot', 'DistanceBand', 'Equal_Interval', 'Fisher_Jenks', 'Geary', 'Jenks_Caspall', 'Jenks_Caspall_Forced', 'Jenks_Caspall_Sampled', 'Join_Counts', 'K_classifiers', 'Kernel', 'LISA_Markov', 'Markov', 'Max_P_Classifier', 'Maximum_Breaks', 'Maxp', 'Maxp_LISA', 'Moran', 'Moran_BV', 'Moran_BV_matrix', 'Moran_Local', 'Natural_Breaks', 'Percentiles', 'Quantiles', 'SpatialTau', 'Spatial_Markov', 'Std_Mean', 'Theil', 'TheilD', 'TheilDSim', 'Theta', 'User_Defined', 'W', 'adaptive_kernelW', 'adaptive_kernelW_from_shapefile', 'bin', 'bin1d', 'binC', 'buildContiguity', 'cg', 'comb', 'common', 'core', 'directional', 'ergodic', 'esda', 'full', 'gadf', 'higher_order', 'inequality', 'kernelW', 'kernelW_from_shapefile', 'knnW', 'knnW_from_array', 'knnW_from_shapefile', 'lag_spatial', 'lat2W', 'min_threshold_dist_from_shapefile', 'open', 'order', 'quantile', 'queen_from_shapefile', 'block_weights', 'region', 'remap_ids', 'rook_from_shapefile', 'shimbel', 'spatial_dynamics', 'threshold_binaryW_from_array', 'threshold_binaryW_from_shapefile', 'threshold_continuousW_from_array', 'threshold_continuousW_from_shapefile', 'version', 'w_difference', 'w_intersection', 'w_subset', 'w_symmetric_difference', 'w_union', 'weights'] current_namespace = dir(pysal) for item in namespace_v1_0: self.assertTrue(item in current_namespace) for item in current_namespace: if item not in namespace_v1_0 and not item.startswith('__'): print(item, "added to name space") suite = unittest.TestLoader().loadTestsFromTestCase(TestNameSpace) if __name__ == '__main__': unittest.main() runner = unittest.TextTestRunner() runner.run(suite)
module Sailsify module Generators autoload :Model, 'sailsify/generators/model' autoload :Controller, 'sailsify/generators/controller' autoload :AbstractGenerator, 'sailsify/generators/abstract_generator' end mattr_accessor :destination_dir def self.config yield self end end require 'sailsify/main_generator' require 'sailsify/railtie' if defined?(Rails)
#include <llarp/encode.hpp> #include <stdexcept> namespace llarp { int char2int(char input) { if(input >= '0' && input <= '9') return input - '0'; if(input >= 'A' && input <= 'F') return input - 'A' + 10; if(input >= 'a' && input <= 'f') return input - 'a' + 10; throw std::invalid_argument("Invalid input string"); } void HexDecode(const char* src, uint8_t* target) { while(*src && src[1]) { *(target++) = char2int(*src) * 16 + char2int(src[1]); src += 2; } } } // namespace llarp
export function getRenderPanels() { return [ { id: 'layout-basic-actions', el: '#panel__layout-basic-actions', buttons: [ { id: 'visibility', active: true, // active by default className: 'btn-toggle-borders', label: '<i class="fas fa-border-none"></i>', command: 'sw-visibility', // Built-in command } ], },{ id: 'layout-show-actions', el: '#panel__render-show-actions', buttons: [ { id: 'preview', className: 'btn-preview', label: '<i class="fas fa-eye"></i>', command: 'custom-preview', // Built-in command } ], }, { id: 'layout-devices-actions', el: '#panel__layout-devices-actions', buttons: [ { id: 'desktop', active: true, // active by default className: 'btn-set-device-desktop', label: '<i class="fas fa-desktop"></i>', command: 'set-device-desktop' }, { id: 'tablet', active: false, // active by default className: 'btn-set-device-tablet', label: '<i class="fas fa-tablet-alt"></i>', command: 'set-device-tablet' }, { id: 'mobile landscape', active: false, // active by default className: 'btn-set-device-phone', label: '<i class="fas fa-mobile-alt"></i>', command: 'set-device-mobile-landscape' }, { id: 'mobile portrait', active: false, // active by default className: 'btn-set-device-phone', label: '<i class="fas fa-mobile-alt"></i>', command: 'set-device-mobile-portrait' } ], }, { id: 'layout-managers-actions', el: '#panel__render-panels-actions', buttons: [{ id: 'show-blocks', active: true, label: '<i class="fas fa-th-large"></i>', command: 'show-blocks', // Once activated disable the possibility to turn it off togglable: false, }, { id: 'show-style', active: false, label: '<i class="fas fa-palette"></i>', command: 'show-styles', togglable: false, }, { id: 'show-traits', active: false, className: 'fa fa-cog', command: 'show-traits', attributes: { title: 'Open Trait Manager' }, togglable: false, }, { id: 'show-layers', active: false, className: 'fa fa-bars', command: 'show-layers', attributes: { title: 'Open Layer Manager' }, togglable: false, }, { id: 'code', className: 'btn-preview', label: '<i class="fas fa-code"></i>', command: 'open-code', // Built-in command }] } ] /* editor.Panels.addPanel({ id: 'layers', el: '.panel__right', // Make the panel resizable resizable: { maxDim: 350, minDim: 200, tc: 0, // Top handler cl: 1, // Left handler cr: 0, // Right handler bc: 0, // Bottom handler // Being a flex child we need to change `flex-basis` property // instead of the `width` (default) keyWidth: 'flex-basis', }, })*/ }
from os import walk, remove def get_all_files(directory): """ Method for listing files within a directory """ f = [] for (_, _, filenames) in walk(directory): f.extend(filenames) return f def remove_file(filename, directory): """ Method for removing a file within a directory """ try: remove(directory + '/' + filename) except FileNotFoundError: pass
/* Composer.scala * * Copyright (c) 2021 wayfarerx (@thewayfarerx). * * 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. */ package net.wayfarerx.loremaster package service import zio.{Has, RIO, Task} import zio.random.Random import model.* /** * Definition of the composer service API. */ trait Composer: /** * Composes a story from the specified template. * * @param template The template that defines the shape of the story. * @return A story from the specified template. */ def compose(template: Composer.Template): Task[String] /** * Definitions associated with composer services. */ object Composer: val live: zio.RLayer[Has[Log.Factory] & Random & Has[Database], Has[Composer]] = zio.ZLayer fromEffect { for logFactory <- RIO.service[Log.Factory] log <- logFactory(classOf[Composer].getSimpleName) rng <- RIO.service[Random.Service] database <- RIO.service[Database] yield Live(log, rng, database) } /** * Creates a composer service bound to the specified database. * * @param log The log to append to. * @param rng The random number generator to use. * @param database The database to use. */ def apply(log: Log, rng: Random.Service, database: Database): Composer = Live(log, rng, database) /** * Composes a story from the specified template. * * @param template The template that defines the shape of the story. * @return A story from the specified template. */ inline def compose(template: Template): RIO[Has[Composer], String] = RIO.service flatMap (_.compose(template)) /** * A template that decribes the content to compose. * * @param paragraphs The descriptions of the paragraphs to create. * @param characterLimit The maximum number of characters to emit. */ case class Template(paragraphs: List[Template.Paragraph], characterLimit: Int) /** * Definitions associate with the template implementations. */ object Template extends ((List[Template.Paragraph], Int) => Template): /** * A template of a single paragraph. * * @param sentenceCount The number of sentences to include. */ case class Paragraph(sentenceCount: Int) /** * The live composer implementation. * * @param log The log to append to. * @param rng The random number generator to use. * @param database The database to use. */ private case class Live(log: Log, rng: Random.Service, database: Database) extends Composer : /* Compose a story from the specified template. */ override def compose(template: Template): Task[String] = ???
<?php namespace WordPress\V1\Rest\Taxonomies; use Zend\Paginator\Paginator; class TaxonomiesCollection extends Paginator { }
package grammar import grammar.model.CFGrammar interface GrammarParser { fun parse(filename: String): CFGrammar }
#include <bits/stdc++.h> #define ll long long #define ls id<<1 #define rs id<<1|1 #define mem(a,b) memset(a,b,sizeof(a)) #define pii pair<int,int> #define flush fflush(stdout) #define pb(x) push_back(x) using namespace std; const int inf=0x3f3f3f3f; const ll mod=1e9+7; const int N=1000050; int t[10]; int c; void solve() { sort(t+1,t+5); if(t[2]+t[3]+t[4]<=3*c) { puts("infinite"); return; } int x=3*c-t[2]-t[3]; if(x>=t[1]&&x<=t[4]) { printf("%.2lf\n",x/100.0); return; } puts("impossible"); } int main() { for(int i=1;i<=4;++i) { int x,y; scanf("%d.%d",&x,&y); t[i]=x*100+y; } int x,y; scanf("%d.%d",&x,&y); c=x*100+y; solve(); return 0; }
package info.smart_tools.smartactors.task.thread_pool; import info.smart_tools.smartactors.task.interfaces.itask.ITask; import info.smart_tools.smartactors.task.interfaces.itask.exception.TaskExecutionException; import org.junit.After; import org.junit.Before; import org.junit.Test; import static org.mockito.Mockito.*; /** * Test for {@link ThreadImpl}. */ public class ThreadImplTest { ThreadPool threadPoolMock; ThreadImpl thread; @Before public void setUp() throws Exception { threadPoolMock = mock(ThreadPool.class); thread = new ThreadImpl(threadPoolMock); } @After public void tearDown() throws Exception { if (null != thread) { thread.interrupt(); } } @Test public void Should_executeTaskInSeparateThread() throws Exception { ITask taskMock = mock(ITask.class); thread.execute(taskMock); verify(taskMock, timeout(1000)).execute(); } @Test(expected = TaskExecutionException.class) public void Should_throwWhenAnotherTaskIsBeingExecuted() throws Exception { thread.execute(() -> { try { Thread.sleep(100); } catch (InterruptedException e) { thread.interrupt(); } }); thread.execute(mock(ITask.class)); } @Test(expected = TaskExecutionException.class) public void Should_throwWhenThreadIsNotAlive() throws Exception { ITask taskMock = mock(ITask.class); thread.interrupt(); Thread.sleep(100); thread.execute(taskMock); verify(taskMock, timeout(100).times(0)).execute(); } @Test public void Should_ignoreExceptionsFromTask() throws Exception { ITask taskMock1 = mock(ITask.class), taskMock2 = mock(ITask.class); doThrow(new TaskExecutionException("Whoops!")).when(taskMock1).execute(); thread.execute(taskMock1); verify(taskMock1, timeout(100)).execute(); Thread.sleep(100); thread.execute(taskMock2); verify(taskMock2, timeout(100)).execute(); } }
module montecarlo use approx use conversion use energy use global use neighborhood use plot use transposition implicit none private interface vary module procedure vary_blind, vary_sighted end interface vary public :: vary, markov contains subroutine vary_blind(change) logical, intent(out) :: change integer :: from, to logical :: tmp if (todo%energy) call total_energy change = .false. if (s%nX .lt. 2 .or. s%nC - s%nX .lt. 2) return call jump(from, to) if (s%map(to) .le. s%nX) return change = .true. call swap(from, to) tmp = todo%correlations todo%energies = .true. todo%energy = .true. todo%penalty = .true. todo%correlations = .true. if (.not. accepted()) then call swap(from, to) change = .false. todo%correlations = tmp end if end subroutine vary_blind subroutine vary_sighted integer :: from, to logical :: tmp if (todo%energy) call total_energy if (s%nX .lt. 2 .or. s%nC - s%nX .lt. 2) return call transpose(from, to) call swap(from, to) tmp = todo%correlations todo%energies = .true. todo%energy = .true. todo%penalty = .true. todo%correlations = .true. if (.not. accepted()) then call swap(from, to) todo%correlations = tmp end if end subroutine vary_sighted function accepted() logical :: accepted real(dp) :: r accepted = .true. if (todo%energy) call total_energy if (s%E(s%i) .lt. s%E(3 - s%i)) return if (s%kT .na. 0.0_dp) then call random_number(r) if (r .lt. exp((s%E(3 - s%i) - s%E(s%i)) / s%kT)) return end if accepted = .false. end function accepted subroutine jump(from, to) integer, intent(out) :: from, to integer, save :: i = 0 real(dp) :: r, a, x, y i = modulo(i, s%nX) + 1 from = s%ls(i) call n2xy(from, x, y) call random_number(r) call random_number(a) r = 0.5_dp + (s%r - 0.5_dp) * r a = 2.0_dp * pi * a x = x + r * cos(a) y = y + r * sin(a) call xy2n(x, y, to) end subroutine jump subroutine transpose(from, to) integer, intent(out) :: from, to integer, save :: i = 0 real(dp) :: r i = modulo(i, s%nX) + 1 from = s%ls(i) call random_number(r) to = s%nX + int((s%nC - s%nX) * r) + 1 end subroutine transpose subroutine markov(change) logical, intent(out), optional :: change integer :: i real(dp) :: average, error if (todo%table) call table do i = 1, s%n if (present(change)) then call vary(change) else call vary end if if (todo%correlations) call correlations s%table(i, :) = s%chances if (.not. s%show) cycle if (present(change)) then if (.not. change) cycle end if call clear call show_lattice write (*, "(/, 'Neighborship probabilities & &(no correlation at ', I0, '%):')") nint(s%nX * 100.0_dp / s%nC) call show_correlations end do write (*, "(/, 'Averages and average absoulte deviations:')") do i = 1, size(s%table, 2) average = sum(s%table(:, i)) / s%n error = sum(abs(s%table(:, i) - average)) / s%n write (*, "('P(', A, ') = ', F5.3, ' +/- ', F5.3)") trim(adjustl(s%labels(i))), average, error end do end subroutine markov end module montecarlo
using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; namespace PiRhoSoft.Variables { public interface IVariableDictionary { IReadOnlyCollection<string> VariableNames { get; } Variable GetVariable(string name); SetVariableResult SetVariable(string name, Variable variable); SetVariableResult AddVariable(string name, Variable variable); SetVariableResult RemoveVariable(string name); SetVariableResult ClearVariables(); } public class VariableDictionary : IDictionary<string, Variable>, IVariableDictionary { private IDictionary<string, Variable> _variables; private IReadOnlyCollection<string> _names; public VariableDictionary() => SetVariables(new Dictionary<string, Variable>()); public VariableDictionary(IDictionary<string, Variable> variables) => SetVariables(variables); #region Saving/Loading public void LoadFrom(IVariableDictionary map) { foreach (var name in map.VariableNames) { var variable = map.GetVariable(name); SetVariable(name, variable); } } public void SaveTo(IVariableDictionary map) { foreach (var name in VariableNames) { var variable = GetVariable(name); map.SetVariable(name, variable); } } #endregion private void SetVariables(IDictionary<string, Variable> variables) { _variables = variables; _names = new ReadOnlyDictionary<string, Variable>(variables).Keys; } #region IVariableDictionary Implementation public IReadOnlyCollection<string> VariableNames => _names; public Variable GetVariable(string name) { return _variables.TryGetValue(name, out var variable) ? variable : Variable.Empty; } public SetVariableResult SetVariable(string name, Variable variable) { if (!_variables.ContainsKey(name)) return SetVariableResult.NotFound; _variables[name] = variable; return SetVariableResult.Success; } public SetVariableResult AddVariable(string name, Variable variable) { if (IsReadOnly || _variables.ContainsKey(name)) return SetVariableResult.ReadOnly; _variables.Add(name, variable); return SetVariableResult.Success; } public SetVariableResult RemoveVariable(string name) { if (IsReadOnly) return SetVariableResult.ReadOnly; return _variables.Remove(name) ? SetVariableResult.Success : SetVariableResult.NotFound; } public SetVariableResult ClearVariables() { if (IsReadOnly) return SetVariableResult.ReadOnly; _variables.Clear(); return SetVariableResult.Success; } #endregion #region IDictionary<string, Variable> Implementation public int Count => _variables.Count; public ICollection<string> Keys => _variables.Keys; public ICollection<Variable> Values => _variables.Values; public bool IsReadOnly => _variables.IsReadOnly; public Variable this[string key] { get => _variables[key]; set => _variables[key] = value; } public bool Contains(KeyValuePair<string, Variable> item) => _variables.Contains(item); public bool ContainsKey(string key) => _variables.ContainsKey(key); public bool TryGetValue(string key, out Variable value) => _variables.TryGetValue(key, out value); public void Add(string key, Variable value) => _variables.Add(key, value); public void Add(KeyValuePair<string, Variable> item) => _variables.Add(item); public bool Remove(string key) => _variables.Remove(key); public bool Remove(KeyValuePair<string, Variable> item) => _variables.Remove(item); public void Clear() => _variables.Clear(); public void CopyTo(KeyValuePair<string, Variable>[] array, int arrayIndex) => _variables.CopyTo(array, arrayIndex); public IEnumerator<KeyValuePair<string, Variable>> GetEnumerator() => _variables.GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => _variables.GetEnumerator(); #endregion } }
package cmd /* Onix Config Manager - Artisan Copyright (c) 2018-Present by www.gatblau.org Licensed under the Apache License, Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0 Contributors to this project, hereby assign copyright in this code to the project, to be licensed under the same terms as the rest of the code. */ import ( "github.com/gatblau/onix/artisan/core" "github.com/gatblau/onix/artisan/merge" "github.com/spf13/cobra" "os" ) // MergeCmd merges environment variables into one or more files type MergeCmd struct { cmd *cobra.Command envFilename string } func NewMergeCmd() *MergeCmd { c := &MergeCmd{ cmd: &cobra.Command{ Use: "merge [flags] [template1 template2 template3 ...]", Short: "merges environment variables in the specified template files", Long: ` merges environment variables in the specified template files merge merges variables stored in an .env file into one or more merge template files merge creates new merged files after the name of the templates without their extension`, }, } c.cmd.Run = c.Run c.cmd.Flags().StringVarP(&c.envFilename, "env", "e", ".env", "--env=.env or -e=.env") return c } func (c *MergeCmd) Run(cmd *cobra.Command, args []string) { env := merge.NewEnVarFromSlice(os.Environ()) env2, err := merge.NewEnVarFromFile(c.envFilename) core.CheckErr(err, "cannot load .env file") env.Merge(env2) m, _ := merge.NewTemplMerger() err = m.LoadTemplates(args) core.CheckErr(err, "cannot load templates") err = m.Merge(env) core.CheckErr(err, "cannot merge templates") err = m.Save() core.CheckErr(err, "cannot save templates") }
from pytest import raises from graphql.core.language.error import LanguageError from graphql.core.language.source import Source from graphql.core.language.parser import parse from graphql.core.language import ast from fixtures import KITCHEN_SINK def test_parse_provides_useful_errors(): with raises(LanguageError) as excinfo: parse("""{ ...MissingOn } fragment MissingOn Type """) assert 'Syntax Error GraphQL (2:20) Expected "on", found Name "Type"' in str(excinfo.value) with raises(LanguageError) as excinfo: parse('{ field: {} }') assert 'Syntax Error GraphQL (1:10) Expected Name, found {' in str(excinfo.value) with raises(LanguageError) as excinfo: parse('notanoperation Foo { field }') assert 'Syntax Error GraphQL (1:1) Unexpected Name "notanoperation"' in str(excinfo.value) with raises(LanguageError) as excinfo: parse('...') assert 'Syntax Error GraphQL (1:1) Unexpected ...' in str(excinfo.value) def test_parse_provides_useful_error_when_using_source(): with raises(LanguageError) as excinfo: parse(Source('query', 'MyQuery.graphql')) assert 'Syntax Error MyQuery.graphql (1:6) Expected Name, found EOF' in str(excinfo.value) def test_parses_variable_inline_values(): parse('{ field(complex: { a: { b: [ $var ] } }) }') def test_parses_constant_default_values(): with raises(LanguageError) as excinfo: parse('query Foo($x: Complex = { a: { b: [ $var ] } }) { field }') assert 'Syntax Error GraphQL (1:37) Unexpected $' in str(excinfo.value) def test_parses_kitchen_sink(): parse(KITCHEN_SINK) def test_parse_creates_ast(): source = Source("""{ node(id: 4) { id, name } } """) result = parse(source) assert result == \ ast.Document( loc={'start': 0, 'end': 41, 'source': source}, definitions= [ast.OperationDefinition( loc={'start': 0, 'end': 40, 'source': source}, operation='query', name=None, variable_definitions=None, directives=[], selection_set=ast.SelectionSet( loc={'start': 0, 'end': 40, 'source': source}, selections= [ast.Field( loc={'start': 4, 'end': 38, 'source': source}, alias=None, name=ast.Name( loc={'start': 4, 'end': 8, 'source': source}, value='node'), arguments=[ast.Argument( name=ast.Name(loc={'start': 9, 'end': 11, 'source': source}, value='id'), value=ast.IntValue( loc={'start': 13, 'end': 14, 'source': source}, value='4'), loc={'start': 9, 'end': 14, 'source': source})], directives=[], selection_set=ast.SelectionSet( loc={'start': 16, 'end': 38, 'source': source}, selections= [ast.Field( loc={'start': 22, 'end': 24, 'source': source}, alias=None, name=ast.Name( loc={'start': 22, 'end': 24, 'source': source}, value='id'), arguments=[], directives=[], selection_set=None), ast.Field( loc={'start': 30, 'end': 34, 'source': source}, alias=None, name=ast.Name( loc={'start': 30, 'end': 34, 'source': source}, value='name'), arguments=[], directives=[], selection_set=None)]))]))])
--- prev: 4_quick-start next: 6_retrieve-visits-and-stats --- # Increments and Decrements ## Increment ### One ```php visits($post)->increment(); ``` ### More than one ```php visits($post)->increment(10); ``` ## Decrement ### One ```php visits($post)->decrement(); ``` ### More than one ```php visits($post)->decrement(10); ``` ::: tip Note Using Increment/decrement method will only work once every 15 minutes (default setting). You can use force methods or modifiy the time from settings or using seconds method. ::: ## Increment/decrement once per x seconds based on visitor's IP ```php visits($post)->seconds(30)->increment() ``` > **Note:** this will override default config setting (once each 15 minutes per IP). ## Force increment/decrement ```php visits($post)->forceIncrement(); visits($post)->forceDecrement(); ``` - This will ignore IP limitation and increment/decrement every visit. ## Ignore recording extra information If you want to stop recoding some of the extra information that the package collected during incrementing the counter such as country and language of visior, then just pass it to the ignore parameter ```php //any of 'country', 'refer', 'periods', 'operatingSystem', 'language' visits('App\Post')->increment(1, false, ['country', 'language']); ``` or you can ignore it permanently from config/visits.php ::: warning If you choose to ignore `periods` then you won't be able to get the count of visits during specific period of time. :::
# frozen_string_literal: true class FakeHttpLibrary def get(_url, _params = nil); end end
package org.apache.lucene.store; /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 java.io.IOException; /** Abstract base class for output to a file in a Directory. A random-access * output stream. Used for all Lucene index output operations. * @see Directory * @see IndexInput */ public abstract class IndexOutput { /** Writes a single byte. * @see IndexInput#readByte() */ public abstract void writeByte(byte b) throws IOException; /** Writes an array of bytes. * @param b the bytes to write * @param length the number of bytes to write * @see IndexInput#readBytes(byte[],int,int) */ public void writeBytes(byte[] b, int length) throws IOException { writeBytes(b, 0, length); } /** Writes an array of bytes. * @param b the bytes to write * @param offset the offset in the byte array * @param length the number of bytes to write * @see IndexInput#readBytes(byte[],int,int) */ public abstract void writeBytes(byte[] b, int offset, int length) throws IOException; /** Writes an int as four bytes. * @see IndexInput#readInt() */ public void writeInt(int i) throws IOException { writeByte((byte)(i >> 24)); writeByte((byte)(i >> 16)); writeByte((byte)(i >> 8)); writeByte((byte) i); } /** Writes an int in a variable-length format. Writes between one and * five bytes. Smaller values take fewer bytes. Negative numbers are not * supported. * @see IndexInput#readVInt() */ public void writeVInt(int i) throws IOException { while ((i & ~0x7F) != 0) { writeByte((byte)((i & 0x7f) | 0x80)); i >>>= 7; } writeByte((byte)i); } /** Writes a long as eight bytes. * @see IndexInput#readLong() */ public void writeLong(long i) throws IOException { writeInt((int) (i >> 32)); writeInt((int) i); } /** Writes an long in a variable-length format. Writes between one and five * bytes. Smaller values take fewer bytes. Negative numbers are not * supported. * @see IndexInput#readVLong() */ public void writeVLong(long i) throws IOException { while ((i & ~0x7F) != 0) { writeByte((byte)((i & 0x7f) | 0x80)); i >>>= 7; } writeByte((byte)i); } /** Writes a string. * @see IndexInput#readString() */ public void writeString(String s) throws IOException { int length = s.length(); writeVInt(length); writeChars(s, 0, length); } /** Writes a sequence of UTF-8 encoded characters from a string. * @param s the source of the characters * @param start the first character in the sequence * @param length the number of characters in the sequence * @see IndexInput#readChars(char[],int,int) */ public void writeChars(String s, int start, int length) throws IOException { final int end = start + length; for (int i = start; i < end; i++) { final int code = (int)s.charAt(i); if (code >= 0x01 && code <= 0x7F) writeByte((byte)code); else if (((code >= 0x80) && (code <= 0x7FF)) || code == 0) { writeByte((byte)(0xC0 | (code >> 6))); writeByte((byte)(0x80 | (code & 0x3F))); } else { writeByte((byte)(0xE0 | (code >>> 12))); writeByte((byte)(0x80 | ((code >> 6) & 0x3F))); writeByte((byte)(0x80 | (code & 0x3F))); } } } /** Forces any buffered output to be written. */ public abstract void flush() throws IOException; /** Closes this stream to further operations. */ public abstract void close() throws IOException; /** Returns the current position in this file, where the next write will * occur. * @see #seek(long) */ public abstract long getFilePointer(); /** Sets current position in this file, where the next write will occur. * @see #getFilePointer() */ public abstract void seek(long pos) throws IOException; /** The number of bytes in the file. */ public abstract long length() throws IOException; }
import pickle import traceback from os.path import exists, join from utils import create_if_not_exists from settings import ClientSettings class Channel: def __init__(self, client, server, channel): self.name = channel.name self.id = channel.id self.channel_loc = '{}'.format(channel.id) self.type = channel.type self.discord_channel = channel channel_dir = join(join(join('servers', server.server_loc), 'channels'), self.channel_loc) create_if_not_exists(channel_dir) self.settings_pickle = join(channel_dir, 'settings.pickle') if exists(self.settings_pickle): # Load settings with open(self.settings_pickle, 'r+b') as f: self.settings = pickle.load(f) else: self.settings = ClientSettings() with open(self.settings_pickle, 'w+b') as f: pickle.dump(self.settings, f) def change_settings(self, in_settings): for setting, value in in_settings.items(): setattr(self.settings, setting, value) with open(self.settings_pickle, 'w+b') as f: pickle.dump(self.settings, f) def list_settings(self): return self.settings.__dict__
use crate::utils::{is_dir, libc_call, with_c_str}; use std::ffi::{CStr, CString}; use std::os::unix::ffi::OsStrExt; use std::path::Path; use std::{fs, io, ptr}; use anyhow::Result; use nix::fcntl::{self, OFlag}; use nix::sys::stat::Mode; use nix::unistd::{self, AccessFlags}; pub fn bind_mount(src_path: &Path, dst_path: &Path, recursive: bool, readonly: bool) -> Result<()> { let src: &CStr = &CString::new(src_path.as_os_str().as_bytes())?; let dst: &CStr = &CString::new(dst_path.as_os_str().as_bytes())?; let src_is_dir = is_dir(src)?; let dst_exists = unistd::access(dst, AccessFlags::F_OK).is_ok(); if !dst_exists { if src_is_dir { fs::create_dir_all(dst_path)?; } else { if let Some(parent_dir) = dst_path.parent() { fs::create_dir_all(parent_dir)?; } let fd = fcntl::open( dst, OFlag::O_CREAT | OFlag::O_RDONLY | OFlag::O_CLOEXEC, Mode::from_bits_truncate(0o644), )?; let _ = unistd::close(fd); } } let do_mount = |flags| unsafe { libc_call(|| libc::mount(src.as_ptr(), dst.as_ptr(), ptr::null(), flags, ptr::null())) }; do_mount(if recursive { libc::MS_BIND | libc::MS_REC } else { libc::MS_BIND })?; if readonly { do_mount(libc::MS_REMOUNT | libc::MS_BIND | libc::MS_RDONLY)?; } Ok(()) } unsafe fn special_mount(dst: &Path, fstype: &[u8]) -> io::Result<()> { if !dst.exists() { fs::create_dir_all(dst)?; } with_c_str(dst.as_os_str().as_bytes(), |dst| { let src = b"none\0".as_ptr().cast(); let fstype = fstype.as_ptr().cast(); libc_call(|| libc::mount(src, dst.as_ptr(), fstype, 0, ptr::null()))?; Ok(()) }) } pub fn mount_proc(dst: &Path) -> io::Result<()> { unsafe { special_mount(dst, b"proc\0".as_ref()) } } pub fn mount_tmpfs(dst: &Path) -> io::Result<()> { unsafe { special_mount(dst, b"tmpfs\0".as_ref()) } } /// prevent propagation of mount events to other mount namespaces /// https://man7.org/linux/man-pages/man7/mount_namespaces.7.html pub fn make_root_private() -> io::Result<()> { libc_call(|| unsafe { let flags = libc::MS_PRIVATE | libc::MS_REC; let dst = b"/\0".as_ptr().cast(); let null = ptr::null(); libc::mount(null, dst, null, flags, null.cast()) })?; Ok(()) }
# CCA matching personality test A more efficient way to choose your CCA by narrowing down your choices based on your skills, talents and interests. :D (my previous README.md is in the infocomm club file)
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.SocialElement = exports.Social = undefined; var _Social2 = require('./Social'); var _Social3 = _interopRequireDefault(_Social2); var _SocialElement2 = require('./SocialElement'); var _SocialElement3 = _interopRequireDefault(_SocialElement2); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.Social = _Social3.default; exports.SocialElement = _SocialElement3.default;
import React, { useState } from 'react'; import { Admin, ListGuesser, Resource, ShowGuesser, EditGuesser, Create, SimpleForm, TextInput, } from 'react-admin'; import { createTRPCDataProvider, Resources } from 'ra-trpc/client'; import superjson from 'superjson'; import { createTRPCClient } from '@trpc/client'; import { AppRouter } from '../server/routers/app'; import type { Post, User } from '.prisma/client'; const ReactAdmin = () => { const [trpcClient] = useState(() => createTRPCClient<AppRouter>({ url: `http://localhost:3000/api/trpc`, transformer: superjson, }), ); const resources: Resources<{ post: Post; user: User }> = { post: { fields: ['id', 'title', 'text'] }, user: { fields: ['id', 'name'], }, }; const trpcDataProvider = createTRPCDataProvider(trpcClient, resources); return ( <Admin dataProvider={trpcDataProvider}> <Resource name="post" list={ListGuesser} show={ShowGuesser} edit={EditGuesser} create={PostCreate} /> <Resource name="user" list={ListGuesser} show={ShowGuesser} edit={EditGuesser} /> </Admin> ); }; export default ReactAdmin; const PostCreate = (props: any) => { return ( <Create {...props}> <SimpleForm> <TextInput source="title" /> <TextInput source="text" /> </SimpleForm> </Create> ); };
import React from "react"; import { Avatar } from "@windmill/react-ui"; export const AvatarWithName: React.FC<{ name: string; subtitle?: string; ImageIcon: any; }> = ({ name, subtitle, ImageIcon }) => { return ( <div className="flex items-center text-sm"> <Avatar className="hidden mr-3 md:block" src={ImageIcon} alt="User image" /> <div> <p className="font-semibold">{name}</p> {subtitle && ( <p className="text-xs text-gray-600 dark:text-gray-400">{subtitle}</p> )} </div> </div> ); };
<?php namespace CleaniqueCoders\Profile\Traits\Morphs; /** * Emailable Trait. */ trait Emailable { /** * Get all emails. */ public function emails() { return $this->morphMany( config('profile.providers.email.model'), config('profile.providers.email.type') ); } }
import React from 'react' import { Link } from 'gatsby' import styles from './footer-handbook.module.css' export default () => ( <div className={styles.footer}> <div className={styles.column}> <div className={styles.header}>Get in touch</div> <div className={styles.contactEmail}> <a href="mailto:hey@ashlyn.app?subject=I'm contacting you from your website">hey@ashlyn.app</a> </div> </div> <div className={styles.column}> <div className={styles.header}>More</div> <ul className={styles.navigation}> <li className={styles.navigationItem}> <Link to="/">Handbooks</Link> </li> <li className={styles.navigationItem}> <Link to="/about/">About</Link> </li> <li className={styles.navigationItem}> <Link to="/">Articles</Link> </li> </ul> </div> </div> )
class CreateOpenidUrls < ActiveRecord::Migration[4.2] def change create_table :openid_urls do |t| t.string "str" t.integer "profile_id" t.datetime "created_at" t.datetime "updated_at" t.boolean "primary_openid" t.timestamps end create_table "open_id_associations", :force => true do |t| t.binary "server_url" t.string "handle" t.binary "secret" t.integer "issued" t.integer "lifetime" t.string "assoc_type" end create_table "open_id_nonces", :force => true do |t| t.string "server_url", :null => false t.integer "timestamp", :null => false t.string "salt", :null => false end end end
--- layout: post title: "xShell 介绍" subtitle: "xShell 是一个很好用的 ssh远程访问 linux 服务器的工具" date: 2018-01-01 author: Mcoder catalog: true --- # 介绍 xShell 是一个对个人和教育用户免费的远程终端软件,可以用来连接远程的 linux 服务器,反应很快,样式也不错。 ![](/imgs/xShell.png) # Reference - [xShell download](http://www.netsarang.com/download/down_form.html?code=522)
// fileDownload is a wrapper for the blodDownload function, but allows users to specify the data as string. export const fileDownload = (data: string, filename: string): void => { const blob = new Blob([data]); blobDownload(blob, filename); }; // blobDownload can be used to download the given data as file. // See: https://github.com/kennethjiang/js-file-download export const blobDownload = (blob: Blob, filename: string): void => { const blobURL = window.URL && window.URL.createObjectURL ? window.URL.createObjectURL(blob) : window.webkitURL.createObjectURL(blob); const tempLink = document.createElement('a'); tempLink.style.display = 'none'; tempLink.href = blobURL; tempLink.setAttribute('download', filename); if (typeof tempLink.download === 'undefined') { tempLink.setAttribute('target', '_blank'); } document.body.appendChild(tempLink); tempLink.click(); setTimeout(function () { document.body.removeChild(tempLink); window.URL.revokeObjectURL(blobURL); }, 200); };
cd $TRESTLE_BASEDIR/catalogs/mycatalog # Splits the properties listed in the -e option that must exist in the file specified in the -f option. trestle split -f ./catalog.json -e 'catalog.metadata,catalog.groups,catalog.back-matter' # In the near future, trestle split should be smart enough to figure out which json file contains the elemenets you want to split # In that case, the -f option would be deprecated and the commands would look like: trestle split -e 'catalog.metadata,catalog.groups,catalog.back-matter' REVERSE: trestle merge -e 'catalog.metadata,catalog.groups,catalog.back-matter' or trestle merge -e 'catalog.*'
#ifndef HR_EDL_STOPWATCH_H_ #define HR_EDL_STOPWATCH_H_ #include <atomic> #include <chrono> namespace hr_edl { // Thanks to Incomputable // https://codereview.stackexchange.com/questions/196245/extremely-simple-timer-class-in-c // for this. template <typename Clock = std::chrono::steady_clock> class Stopwatch { public: Stopwatch() : start_time_(Clock::now()) {} void reset() { start_time_ = Clock::now(); } template <typename Rep = typename Clock::duration::rep, typename Units = typename Clock::duration> Rep duration() const { std::atomic_thread_fence(std::memory_order_relaxed); const auto duration = std::chrono::duration_cast<Units>(Clock::now() - start_time_).count(); std::atomic_thread_fence(std::memory_order_relaxed); return static_cast<Rep>(duration); } double seconds() const { return duration<double, std::chrono::seconds>(); } double milliseconds() const { return duration<double, std::chrono::milliseconds>(); } private: typename Clock::time_point start_time_; }; } // namespace hr_edl #endif // HR_EDL_STOPWATCH_H_
/* * The contents of this file are subject to the terms of the Common Development * and Distribution License (the License). You may not use this file except in * compliance with the License. * * You can obtain a copy of the License at http://www.netbeans.org/cddl.html * or http://www.netbeans.org/cddl.txt. * * When distributing Covered Code, include this CDDL Header Notice in each file * and include the License file at http://www.netbeans.org/cddl.txt. * If applicable, add the following below the CDDL Header, with the fields * enclosed by brackets [] replaced by your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * The Original Software is NetBeans. The Initial Developer of the Original * Software is Sun Microsystems, Inc. Portions Copyright 1997-2007 Sun * Microsystems, Inc. All Rights Reserved. */ package org.netbeans.modules.gwt4nb.services.refactoring.ui; import java.util.Hashtable; import org.netbeans.api.project.FileOwnerQuery; import org.netbeans.api.project.Project; import org.openide.cookies.EditorCookie; import org.openide.loaders.DataObject; import org.openide.nodes.Node; import org.openide.text.CloneableEditorSupport.Pane; import org.openide.util.HelpCtx; import org.openide.util.Lookup; import org.openide.util.NbBundle; import org.openide.util.actions.CookieAction; import org.openide.util.lookup.AbstractLookup; import org.openide.util.lookup.InstanceContent; import org.openide.windows.TopComponent; public final class ServiceDeleteAction extends CookieAction { private static final long serialVersionUID = 1; protected void performAction(Node[] activatedNodes) { ServiceRefactoringActionsProvider.doDelete(getLookup(activatedNodes)); } protected boolean enable(Node[] node) { if (node==null || node.length<1){ return false; } DataObject dataObject = node[0].getCookie(DataObject.class); if (dataObject != null){ Project p = FileOwnerQuery.getOwner(dataObject.getPrimaryFile()); if (p != null && org.netbeans.modules.gwt4nb.GWTProjectInfo.isGWTProject(p)) { return ServiceRefactoringActionsProvider.canDelete(getLookup(node)); } } return false; } protected int mode() { return CookieAction.MODE_EXACTLY_ONE; } public String getName() { return NbBundle.getMessage(ServiceDeleteAction.class, "CTL_ServiceDeleteAction1"); // NOI18N } protected Class<?>[] cookieClasses() { return new Class<?>[] { Project.class }; } protected void initialize() { super.initialize(); // see org.openide.util.actions.SystemAction.iconResource() javadoc for more details putValue("noIconInMenu", Boolean.TRUE); // NOI18N } public HelpCtx getHelpCtx() { return HelpCtx.DEFAULT_HELP; } protected boolean asynchronous() { return false; } protected Lookup getLookup(Node[] n) { InstanceContent ic = new InstanceContent(); for (Node node:n) ic.add(node); if (n.length>0) { EditorCookie tc = getTextComponent(n[0]); if (tc != null) { ic.add(tc); } } ic.add(new Hashtable<Object, Object>(0)); return new AbstractLookup(ic); } protected static EditorCookie getTextComponent(Node n) { DataObject dobj = n.getCookie(DataObject.class); if (dobj != null) { EditorCookie ec = dobj.getCookie(EditorCookie.class); if (ec != null) { TopComponent activetc = TopComponent.getRegistry().getActivated(); if (activetc instanceof Pane) { return ec; } } } return null; } }
namespace BotFramework.Setup { /// <summary> /// Chat Type /// </summary> public enum InChat { /// <summary> /// Private chat aka peer-to-peer with bot /// </summary> Private, /// <summary> /// Public chats (in both privacy mode), not peer-to-peer with bot /// </summary> Public, Channel, All } }
--- layout: post title: " 2022 Flag " date: 2022-01-17 categories: 思考我自己 十年后的我 职业生涯规划 --- ### 2022 Flag Description: 思考我自己的 - Feature,本文主要围绕三大问题 : 当下的工作是我想要的的吗? 当下自己的状态是自己喜欢的吗? 10年后的我在干什么?现在的我对十年后的我帮助很大吗? --- <h3> 当下的工作是我想要的的吗? ```python class MyThink1(): pass ``` <h3> 当下自己的状态是自己喜欢的吗? ```python Click 【鼠标点击组件】 Type_info【文本输入组件】 ``` <h3> 10年后的我在干什么?现在的我对十年后的我帮助很大吗? ```python Click 【鼠标点击组件】 Type_info【文本输入组件】 ```
package info.unbelievable9.environment.db; import bitronix.tm.resource.jdbc.PoolingDataSource; import info.unbelievable9.shared.util.ImprovedH2Dialect; import org.hibernate.dialect.MySQL57Dialect; /** * Created on : 2018/8/8 * Author : Unbelievable9 **/ public enum DatabaseProduct { H2( (poolingDataSource, connectionURL) -> { poolingDataSource.setClassName("org.h2.jdbcx.JdbcDataSource"); poolingDataSource.getDriverProperties().put("user", "sa"); poolingDataSource.getDriverProperties().put( "URL", connectionURL != null ? connectionURL : "jdbc:h2:mem:test"); }, ImprovedH2Dialect.class.getName() ), MYSQL( (poolingDataSource, connectionURL) -> { // Use latest MySQL XA support, no need to set driver class name. poolingDataSource.setClassName("com.mysql.cj.jdbc.MysqlXADataSource"); poolingDataSource.getDriverProperties().put("user", "demo"); poolingDataSource.getDriverProperties().put("password", "demo"); poolingDataSource.getDriverProperties().put( "url", connectionURL != null ? connectionURL : "jdbc:mysql://localhost:3306/hibernate" ); }, MySQL57Dialect.class.getName() ); public DatasSourceConfiguration datasSourceConfiguration; public String hibernateDialect; DatabaseProduct(DatasSourceConfiguration datasSourceConfiguration, String hibernateDialect) { this.datasSourceConfiguration = datasSourceConfiguration; this.hibernateDialect = hibernateDialect; } public interface DatasSourceConfiguration { void configure(PoolingDataSource poolingDataSource, String connectionURL); } }
# Simulation Models of Power Systems ## SimPowerSystem Model of San Francisco Bay Area electric power system (PG & E) Requires SimPower libraries. Can be converted and used using real-time simulators, such as Opal-RT WARNING: The model is figuratative, composed of few substations, and not for research and representative purposes only.
'use strict'; /* eslint-env node */ const Funnel = require('broccoli-funnel'); module.exports = function(env) { let file; if (env === 'debug') { file = 'external-helpers-dev.js'; } else if (env === 'prod') { file = 'external-helpers-prod.js' } return new Funnel('packages/external-helpers/lib', { files: [file], getDestinationPath() { return 'ember-babel.js'; } }); }
# MATLAB MATLAB is a platform for solving engineering, mathematical, and graphical problems. To find out more, visit the MATLAB website at: http://se.mathworks.com/help/matlab ## License Information ### Academic users Academic users need a link to a MATLAB license server for their university (UiB, UiT, UiO or NTNU). Users from other universities can also use MATLAB on Fram. Send an email to support@metacenter.no and ask for the link for your university and the license name to use when submitting jobs. Add this link to the environment variable MLM_LICENSE_FILE: export MLM_LICENSE_FILE=<link-to-matlab-license-server> Add this environment variable setting into your `~/.bashrc`. When submitting a job with, e.g., sbatch, use `sbatch --licenses=<license-name>`. #### Third-Party Access for Collaborative Research in Academia See this link: https://se.mathworks.com/support/collaborative-research-academia.html #### Commercial users Commercial users need to sign a Hosting Provider agreement. Contact: sigma2@uninett.no ## Running MATLAB | Module | Version | | :------------- | :------------- | | MATLAB |2017a| | MATLAB |2018a| | MATLAB |2018b| | MATLAB |2019a| | MATLAB |2020b| To see available versions when logged into Fram issue command module spider matlab To use MATLAB type module load MATLAB/<version> (eg. module load MATLAB/2020b) specifying one of the available versions. ### Sample MATLAB Job Script ``` #!/bin/bash #SBATCH --account=nnNNNNk #SBATCH --job-name=jobname #SBATCH --time=1-0:0:0 #SBATCH --nodes=1 ## Recommended safety settings: set -o errexit # Make bash exit on any error set -o nounset # Treat unset variables as errors module restore system module load MATLAB/<version> matlab -nodisplay -nodesktop -nojvm -r "myprogram" ## Note: if you are using the Parallel Computing Toolbox, remove -nojvm ``` ## MPI for Matlab MPI for Matlab is installed on Fram (for parallelizing on many compute nodes) User guide: Distributed Matlab (for non MPI programmers): https://www.hpc.ntnu.no/pages/viewpage.action?pageId=15794234 Matlab MPI: https://www.hpc.ntnu.no/display/hpc/Matlab+MPI
package com.redberrystudios.whatsfordinner.security.authenticators; public interface ThirdPartyAuthentication { String getName(); String getEmail(); String getProfileImage(); }
namespace Joker.OData.Hosting { public class IISODataWebHostConfig : ODataWebHostConfig { } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: client_proto_id.proto package com.gc.patrol_robot.protobuf; public final class CliProtoId { private CliProtoId() {} public static void registerAllExtensions( com.google.protobuf.ExtensionRegistryLite registry) { } public static void registerAllExtensions( com.google.protobuf.ExtensionRegistry registry) { registerAllExtensions( (com.google.protobuf.ExtensionRegistryLite) registry); } /** * <pre> * MSG_CLI_REGISTER_REQ = 3000; //玩家注册 * MSG_CLI_REGISTER_RSP = 3001; * </pre> * * Protobuf enum {@code ClientProtocols.ClientProtoId} */ public enum ClientProtoId implements com.google.protobuf.ProtocolMessageEnum { /** * <pre> *用户相关协议 * </pre> * * <code>MSG_CLI_LOGIN_REQ = 3000;</code> */ MSG_CLI_LOGIN_REQ(3000), /** * <pre> * </pre> * * <code>MSG_CLI_LOGIN_RSP = 3001;</code> */ MSG_CLI_LOGIN_RSP(3001), /** * <pre> *修改用户信息,用户名,密码等 * </pre> * * <code>MSG_CLI_CHANGE_USER_INFO_REQ = 3002;</code> */ MSG_CLI_CHANGE_USER_INFO_REQ(3002), /** * <pre> * </pre> * * <code>MSG_CLI_CHANGE_USER_INFO_RSP = 3003;</code> */ MSG_CLI_CHANGE_USER_INFO_RSP(3003), /** * <pre> *添加其它账号 * </pre> * * <code>MSG_CLI_ADD_USER_REQ = 3004;</code> */ MSG_CLI_ADD_USER_REQ(3004), /** * <pre> * </pre> * * <code>MSG_CLI_ADD_USER_RSP = 3005;</code> */ MSG_CLI_ADD_USER_RSP(3005), /** * <pre> *删除其它账号 * </pre> * * <code>MSG_CLI_DEL_USER_REQ = 3006;</code> */ MSG_CLI_DEL_USER_REQ(3006), /** * <pre> * </pre> * * <code>MSG_CLI_DEL_USER_RSP = 3007;</code> */ MSG_CLI_DEL_USER_RSP(3007), /** * <pre> *进入服务器 * </pre> * * <code>MSG_CLI_ENTER_SERVER_REQ = 3008;</code> */ MSG_CLI_ENTER_SERVER_REQ(3008), /** * <pre> * </pre> * * <code>MSG_CLI_ENTER_SERVER_RSP = 3009;</code> */ MSG_CLI_ENTER_SERVER_RSP(3009), /** * <pre> *管理员给用户赋权限 * </pre> * * <code>MSG_CLI_ASSIGN_RIGHT_REQ = 3010;</code> */ MSG_CLI_ASSIGN_RIGHT_REQ(3010), /** * <pre> *管理员给用户赋权限 * </pre> * * <code>MSG_CLI_ASSIGN_RIGHT_RSP = 3011;</code> */ MSG_CLI_ASSIGN_RIGHT_RSP(3011), /** * <pre> * 获取当前用户拥有的设备列表 * </pre> * * <code>MSG_CLI_GET_DC_LIST_REQ = 3012;</code> */ MSG_CLI_GET_DC_LIST_REQ(3012), /** * <pre> * </pre> * * <code>MSG_CLI_GET_DC_LIST_RSP = 3013;</code> */ MSG_CLI_GET_DC_LIST_RSP(3013), /** * <pre> *心跳 * </pre> * * <code>MSG_CLI_HEART_BEAT_REQ = 3014;</code> */ MSG_CLI_HEART_BEAT_REQ(3014), /** * <pre> *获取设备所在多媒体server地址 * </pre> * * <code>MSG_GET_DC_MEDIA_SERVER_ADDR_REQ = 3015;</code> */ MSG_GET_DC_MEDIA_SERVER_ADDR_REQ(3015), /** * <pre> * </pre> * * <code>MSG_GET_DC_MEDIA_SERVER_ADDR_RSP = 3016;</code> */ MSG_GET_DC_MEDIA_SERVER_ADDR_RSP(3016), /** * <pre> *服务器主动下发的消息 * </pre> * * <code>MSG_CLI_INFO_NTF = 3017;</code> */ MSG_CLI_INFO_NTF(3017), /** * <pre> *获取当前用户可见的用户列表 * </pre> * * <code>MSG_CLI_GET_VISIBLE_USER_LIST_REQ = 3018;</code> */ MSG_CLI_GET_VISIBLE_USER_LIST_REQ(3018), /** * <pre> * </pre> * * <code>MSG_CLI_GET_VISIBLE_USER_LIST_RSP = 3019;</code> */ MSG_CLI_GET_VISIBLE_USER_LIST_RSP(3019), /** * <pre> *获取http地址 * </pre> * * <code>MSG_CLI_GET_HTTP_ADDR_REQ = 3020;</code> */ MSG_CLI_GET_HTTP_ADDR_REQ(3020), /** * <pre> * * </pre> * * <code>MSG_CLI_GET_HTTP_ADDR_RSP = 3021;</code> */ MSG_CLI_GET_HTTP_ADDR_RSP(3021), /** * <pre> *--------------------巡检点类型相关协议------------------------------------ *巡检点类型操作 * </pre> * * <code>MSG_CLI_PATROL_PT_TYPE_OP_REQ = 3022;</code> */ MSG_CLI_PATROL_PT_TYPE_OP_REQ(3022), /** * <pre> *消息体同 CommonProtocols.DT_PATROL_PT_TYPE_NTF * </pre> * * <code>MSG_CLI_PATROL_PT_TYPE_NTF = 3023;</code> */ MSG_CLI_PATROL_PT_TYPE_NTF(3023), /** * <pre> *获取巡检点类型列表 * </pre> * * <code>MSG_CLI_GET_PATROL_PT_TYPE_LIST_REQ = 3024;</code> */ MSG_CLI_GET_PATROL_PT_TYPE_LIST_REQ(3024), /** * <code>MSG_CLI_GET_PATROL_PT_TYPE_LIST_RSP = 3025;</code> */ MSG_CLI_GET_PATROL_PT_TYPE_LIST_RSP(3025), /** * <pre> *--------------------巡检点相关协议--------------------------------------- *巡检点增删改 * </pre> * * <code>MSG_CLI_PATROL_PT_OP_REQ = 3026;</code> */ MSG_CLI_PATROL_PT_OP_REQ(3026), /** * <pre> *消息体同 CommonProtocols.DT_PATROL_PT_NTF * </pre> * * <code>MSG_CLI_PATROL_PT_NTF = 3027;</code> */ MSG_CLI_PATROL_PT_NTF(3027), /** * <pre> *后去巡检点列表 * </pre> * * <code>MSG_CLI_GET_PATROL_PT_LIST_REQ = 3028;</code> */ MSG_CLI_GET_PATROL_PT_LIST_REQ(3028), /** * <code>MSG_CLI_GET_PATROL_PT_LIST_RSP = 3029;</code> */ MSG_CLI_GET_PATROL_PT_LIST_RSP(3029), /** * <pre> *-----------------------巡检任务相关协议--------------------- * </pre> * * <code>MSG_CLI_GET_TASK_LIST_REQ = 3030;</code> */ MSG_CLI_GET_TASK_LIST_REQ(3030), /** * <code>MSG_CLI_GET_TASK_LIST_RSP = 3031;</code> */ MSG_CLI_GET_TASK_LIST_RSP(3031), /** * <code>MSG_CLI_TASK_OP_REQ = 3032;</code> */ MSG_CLI_TASK_OP_REQ(3032), /** * <pre> *消息体同 CommonProtocols.DT_TASK_NTF * </pre> * * <code>MSG_CLI_TASK_NTF = 3033;</code> */ MSG_CLI_TASK_NTF(3033), /** * <pre> *------自动模式还是手动控制模式 * </pre> * * <code>MSG_CLI_DEVICE_CONTROL_MODE_REQ = 3034;</code> */ MSG_CLI_DEVICE_CONTROL_MODE_REQ(3034), /** * <pre> *不需要回复,只需要发控制指令即可 * </pre> * * <code>MSG_CLI_DC_CTL_OP_REQ = 3035;</code> */ MSG_CLI_DC_CTL_OP_REQ(3035), /** * <pre> *请求构建地图开始或者结束的请求, CommonProtocols.DT_MAP_CONSTRUCT_NTF * </pre> * * <code>MSG_CLI_CONSTRUCT_MAP_REQ = 3036;</code> */ MSG_CLI_CONSTRUCT_MAP_REQ(3036), /** * <pre> *设置设备当前的工作地图,消息同CommonProtocols.DT_DC_CURR_MAP * </pre> * * <code>MSG_CLI_SET_DC_CURR_MAP_REQ = 3037;</code> */ MSG_CLI_SET_DC_CURR_MAP_REQ(3037), /** * <pre> *--- 场景模式 * </pre> * * <code>MSG_CLI_SET_DC_SCENE_MODE_REQ = 3038;</code> */ MSG_CLI_SET_DC_SCENE_MODE_REQ(3038), /** * <pre> *检测点结果通知 * </pre> * * <code>MSG_CLI_PT_RESULT_NTF = 3039;</code> */ MSG_CLI_PT_RESULT_NTF(3039), /** * <pre> *处理巡检结果 * </pre> * * <code>MSG_CLI_PROCESS_PATROL_RESULT_REQ = 3040;</code> */ MSG_CLI_PROCESS_PATROL_RESULT_REQ(3040), ; /** * <pre> *用户相关协议 * </pre> * * <code>MSG_CLI_LOGIN_REQ = 3000;</code> */ public static final int MSG_CLI_LOGIN_REQ_VALUE = 3000; /** * <pre> * </pre> * * <code>MSG_CLI_LOGIN_RSP = 3001;</code> */ public static final int MSG_CLI_LOGIN_RSP_VALUE = 3001; /** * <pre> *修改用户信息,用户名,密码等 * </pre> * * <code>MSG_CLI_CHANGE_USER_INFO_REQ = 3002;</code> */ public static final int MSG_CLI_CHANGE_USER_INFO_REQ_VALUE = 3002; /** * <pre> * </pre> * * <code>MSG_CLI_CHANGE_USER_INFO_RSP = 3003;</code> */ public static final int MSG_CLI_CHANGE_USER_INFO_RSP_VALUE = 3003; /** * <pre> *添加其它账号 * </pre> * * <code>MSG_CLI_ADD_USER_REQ = 3004;</code> */ public static final int MSG_CLI_ADD_USER_REQ_VALUE = 3004; /** * <pre> * </pre> * * <code>MSG_CLI_ADD_USER_RSP = 3005;</code> */ public static final int MSG_CLI_ADD_USER_RSP_VALUE = 3005; /** * <pre> *删除其它账号 * </pre> * * <code>MSG_CLI_DEL_USER_REQ = 3006;</code> */ public static final int MSG_CLI_DEL_USER_REQ_VALUE = 3006; /** * <pre> * </pre> * * <code>MSG_CLI_DEL_USER_RSP = 3007;</code> */ public static final int MSG_CLI_DEL_USER_RSP_VALUE = 3007; /** * <pre> *进入服务器 * </pre> * * <code>MSG_CLI_ENTER_SERVER_REQ = 3008;</code> */ public static final int MSG_CLI_ENTER_SERVER_REQ_VALUE = 3008; /** * <pre> * </pre> * * <code>MSG_CLI_ENTER_SERVER_RSP = 3009;</code> */ public static final int MSG_CLI_ENTER_SERVER_RSP_VALUE = 3009; /** * <pre> *管理员给用户赋权限 * </pre> * * <code>MSG_CLI_ASSIGN_RIGHT_REQ = 3010;</code> */ public static final int MSG_CLI_ASSIGN_RIGHT_REQ_VALUE = 3010; /** * <pre> *管理员给用户赋权限 * </pre> * * <code>MSG_CLI_ASSIGN_RIGHT_RSP = 3011;</code> */ public static final int MSG_CLI_ASSIGN_RIGHT_RSP_VALUE = 3011; /** * <pre> * 获取当前用户拥有的设备列表 * </pre> * * <code>MSG_CLI_GET_DC_LIST_REQ = 3012;</code> */ public static final int MSG_CLI_GET_DC_LIST_REQ_VALUE = 3012; /** * <pre> * </pre> * * <code>MSG_CLI_GET_DC_LIST_RSP = 3013;</code> */ public static final int MSG_CLI_GET_DC_LIST_RSP_VALUE = 3013; /** * <pre> *心跳 * </pre> * * <code>MSG_CLI_HEART_BEAT_REQ = 3014;</code> */ public static final int MSG_CLI_HEART_BEAT_REQ_VALUE = 3014; /** * <pre> *获取设备所在多媒体server地址 * </pre> * * <code>MSG_GET_DC_MEDIA_SERVER_ADDR_REQ = 3015;</code> */ public static final int MSG_GET_DC_MEDIA_SERVER_ADDR_REQ_VALUE = 3015; /** * <pre> * </pre> * * <code>MSG_GET_DC_MEDIA_SERVER_ADDR_RSP = 3016;</code> */ public static final int MSG_GET_DC_MEDIA_SERVER_ADDR_RSP_VALUE = 3016; /** * <pre> *服务器主动下发的消息 * </pre> * * <code>MSG_CLI_INFO_NTF = 3017;</code> */ public static final int MSG_CLI_INFO_NTF_VALUE = 3017; /** * <pre> *获取当前用户可见的用户列表 * </pre> * * <code>MSG_CLI_GET_VISIBLE_USER_LIST_REQ = 3018;</code> */ public static final int MSG_CLI_GET_VISIBLE_USER_LIST_REQ_VALUE = 3018; /** * <pre> * </pre> * * <code>MSG_CLI_GET_VISIBLE_USER_LIST_RSP = 3019;</code> */ public static final int MSG_CLI_GET_VISIBLE_USER_LIST_RSP_VALUE = 3019; /** * <pre> *获取http地址 * </pre> * * <code>MSG_CLI_GET_HTTP_ADDR_REQ = 3020;</code> */ public static final int MSG_CLI_GET_HTTP_ADDR_REQ_VALUE = 3020; /** * <pre> * * </pre> * * <code>MSG_CLI_GET_HTTP_ADDR_RSP = 3021;</code> */ public static final int MSG_CLI_GET_HTTP_ADDR_RSP_VALUE = 3021; /** * <pre> *--------------------巡检点类型相关协议------------------------------------ *巡检点类型操作 * </pre> * * <code>MSG_CLI_PATROL_PT_TYPE_OP_REQ = 3022;</code> */ public static final int MSG_CLI_PATROL_PT_TYPE_OP_REQ_VALUE = 3022; /** * <pre> *消息体同 CommonProtocols.DT_PATROL_PT_TYPE_NTF * </pre> * * <code>MSG_CLI_PATROL_PT_TYPE_NTF = 3023;</code> */ public static final int MSG_CLI_PATROL_PT_TYPE_NTF_VALUE = 3023; /** * <pre> *获取巡检点类型列表 * </pre> * * <code>MSG_CLI_GET_PATROL_PT_TYPE_LIST_REQ = 3024;</code> */ public static final int MSG_CLI_GET_PATROL_PT_TYPE_LIST_REQ_VALUE = 3024; /** * <code>MSG_CLI_GET_PATROL_PT_TYPE_LIST_RSP = 3025;</code> */ public static final int MSG_CLI_GET_PATROL_PT_TYPE_LIST_RSP_VALUE = 3025; /** * <pre> *--------------------巡检点相关协议--------------------------------------- *巡检点增删改 * </pre> * * <code>MSG_CLI_PATROL_PT_OP_REQ = 3026;</code> */ public static final int MSG_CLI_PATROL_PT_OP_REQ_VALUE = 3026; /** * <pre> *消息体同 CommonProtocols.DT_PATROL_PT_NTF * </pre> * * <code>MSG_CLI_PATROL_PT_NTF = 3027;</code> */ public static final int MSG_CLI_PATROL_PT_NTF_VALUE = 3027; /** * <pre> *后去巡检点列表 * </pre> * * <code>MSG_CLI_GET_PATROL_PT_LIST_REQ = 3028;</code> */ public static final int MSG_CLI_GET_PATROL_PT_LIST_REQ_VALUE = 3028; /** * <code>MSG_CLI_GET_PATROL_PT_LIST_RSP = 3029;</code> */ public static final int MSG_CLI_GET_PATROL_PT_LIST_RSP_VALUE = 3029; /** * <pre> *-----------------------巡检任务相关协议--------------------- * </pre> * * <code>MSG_CLI_GET_TASK_LIST_REQ = 3030;</code> */ public static final int MSG_CLI_GET_TASK_LIST_REQ_VALUE = 3030; /** * <code>MSG_CLI_GET_TASK_LIST_RSP = 3031;</code> */ public static final int MSG_CLI_GET_TASK_LIST_RSP_VALUE = 3031; /** * <code>MSG_CLI_TASK_OP_REQ = 3032;</code> */ public static final int MSG_CLI_TASK_OP_REQ_VALUE = 3032; /** * <pre> *消息体同 CommonProtocols.DT_TASK_NTF * </pre> * * <code>MSG_CLI_TASK_NTF = 3033;</code> */ public static final int MSG_CLI_TASK_NTF_VALUE = 3033; /** * <pre> *------自动模式还是手动控制模式 * </pre> * * <code>MSG_CLI_DEVICE_CONTROL_MODE_REQ = 3034;</code> */ public static final int MSG_CLI_DEVICE_CONTROL_MODE_REQ_VALUE = 3034; /** * <pre> *不需要回复,只需要发控制指令即可 * </pre> * * <code>MSG_CLI_DC_CTL_OP_REQ = 3035;</code> */ public static final int MSG_CLI_DC_CTL_OP_REQ_VALUE = 3035; /** * <pre> *请求构建地图开始或者结束的请求, CommonProtocols.DT_MAP_CONSTRUCT_NTF * </pre> * * <code>MSG_CLI_CONSTRUCT_MAP_REQ = 3036;</code> */ public static final int MSG_CLI_CONSTRUCT_MAP_REQ_VALUE = 3036; /** * <pre> *设置设备当前的工作地图,消息同CommonProtocols.DT_DC_CURR_MAP * </pre> * * <code>MSG_CLI_SET_DC_CURR_MAP_REQ = 3037;</code> */ public static final int MSG_CLI_SET_DC_CURR_MAP_REQ_VALUE = 3037; /** * <pre> *--- 场景模式 * </pre> * * <code>MSG_CLI_SET_DC_SCENE_MODE_REQ = 3038;</code> */ public static final int MSG_CLI_SET_DC_SCENE_MODE_REQ_VALUE = 3038; /** * <pre> *检测点结果通知 * </pre> * * <code>MSG_CLI_PT_RESULT_NTF = 3039;</code> */ public static final int MSG_CLI_PT_RESULT_NTF_VALUE = 3039; /** * <pre> *处理巡检结果 * </pre> * * <code>MSG_CLI_PROCESS_PATROL_RESULT_REQ = 3040;</code> */ public static final int MSG_CLI_PROCESS_PATROL_RESULT_REQ_VALUE = 3040; public final int getNumber() { return value; } /** * @deprecated Use {@link #forNumber(int)} instead. */ @java.lang.Deprecated public static ClientProtoId valueOf(int value) { return forNumber(value); } public static ClientProtoId forNumber(int value) { switch (value) { case 3000: return MSG_CLI_LOGIN_REQ; case 3001: return MSG_CLI_LOGIN_RSP; case 3002: return MSG_CLI_CHANGE_USER_INFO_REQ; case 3003: return MSG_CLI_CHANGE_USER_INFO_RSP; case 3004: return MSG_CLI_ADD_USER_REQ; case 3005: return MSG_CLI_ADD_USER_RSP; case 3006: return MSG_CLI_DEL_USER_REQ; case 3007: return MSG_CLI_DEL_USER_RSP; case 3008: return MSG_CLI_ENTER_SERVER_REQ; case 3009: return MSG_CLI_ENTER_SERVER_RSP; case 3010: return MSG_CLI_ASSIGN_RIGHT_REQ; case 3011: return MSG_CLI_ASSIGN_RIGHT_RSP; case 3012: return MSG_CLI_GET_DC_LIST_REQ; case 3013: return MSG_CLI_GET_DC_LIST_RSP; case 3014: return MSG_CLI_HEART_BEAT_REQ; case 3015: return MSG_GET_DC_MEDIA_SERVER_ADDR_REQ; case 3016: return MSG_GET_DC_MEDIA_SERVER_ADDR_RSP; case 3017: return MSG_CLI_INFO_NTF; case 3018: return MSG_CLI_GET_VISIBLE_USER_LIST_REQ; case 3019: return MSG_CLI_GET_VISIBLE_USER_LIST_RSP; case 3020: return MSG_CLI_GET_HTTP_ADDR_REQ; case 3021: return MSG_CLI_GET_HTTP_ADDR_RSP; case 3022: return MSG_CLI_PATROL_PT_TYPE_OP_REQ; case 3023: return MSG_CLI_PATROL_PT_TYPE_NTF; case 3024: return MSG_CLI_GET_PATROL_PT_TYPE_LIST_REQ; case 3025: return MSG_CLI_GET_PATROL_PT_TYPE_LIST_RSP; case 3026: return MSG_CLI_PATROL_PT_OP_REQ; case 3027: return MSG_CLI_PATROL_PT_NTF; case 3028: return MSG_CLI_GET_PATROL_PT_LIST_REQ; case 3029: return MSG_CLI_GET_PATROL_PT_LIST_RSP; case 3030: return MSG_CLI_GET_TASK_LIST_REQ; case 3031: return MSG_CLI_GET_TASK_LIST_RSP; case 3032: return MSG_CLI_TASK_OP_REQ; case 3033: return MSG_CLI_TASK_NTF; case 3034: return MSG_CLI_DEVICE_CONTROL_MODE_REQ; case 3035: return MSG_CLI_DC_CTL_OP_REQ; case 3036: return MSG_CLI_CONSTRUCT_MAP_REQ; case 3037: return MSG_CLI_SET_DC_CURR_MAP_REQ; case 3038: return MSG_CLI_SET_DC_SCENE_MODE_REQ; case 3039: return MSG_CLI_PT_RESULT_NTF; case 3040: return MSG_CLI_PROCESS_PATROL_RESULT_REQ; default: return null; } } public static com.google.protobuf.Internal.EnumLiteMap<ClientProtoId> internalGetValueMap() { return internalValueMap; } private static final com.google.protobuf.Internal.EnumLiteMap< ClientProtoId> internalValueMap = new com.google.protobuf.Internal.EnumLiteMap<ClientProtoId>() { public ClientProtoId findValueByNumber(int number) { return ClientProtoId.forNumber(number); } }; public final com.google.protobuf.Descriptors.EnumValueDescriptor getValueDescriptor() { return getDescriptor().getValues().get(ordinal()); } public final com.google.protobuf.Descriptors.EnumDescriptor getDescriptorForType() { return getDescriptor(); } public static final com.google.protobuf.Descriptors.EnumDescriptor getDescriptor() { return com.gc.patrol_robot.protobuf.CliProtoId.getDescriptor().getEnumTypes().get(0); } private static final ClientProtoId[] VALUES = values(); public static ClientProtoId valueOf( com.google.protobuf.Descriptors.EnumValueDescriptor desc) { if (desc.getType() != getDescriptor()) { throw new java.lang.IllegalArgumentException( "EnumValueDescriptor is not for this type."); } return VALUES[desc.getIndex()]; } private final int value; private ClientProtoId(int value) { this.value = value; } // @@protoc_insertion_point(enum_scope:ClientProtocols.ClientProtoId) } public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() { return descriptor; } private static com.google.protobuf.Descriptors.FileDescriptor descriptor; static { java.lang.String[] descriptorData = { "\n\025client_proto_id.proto\022\017ClientProtocols" + "*\266\n\n\rClientProtoId\022\026\n\021MSG_CLI_LOGIN_REQ\020" + "\270\027\022\026\n\021MSG_CLI_LOGIN_RSP\020\271\027\022!\n\034MSG_CLI_CH" + "ANGE_USER_INFO_REQ\020\272\027\022!\n\034MSG_CLI_CHANGE_" + "USER_INFO_RSP\020\273\027\022\031\n\024MSG_CLI_ADD_USER_REQ" + "\020\274\027\022\031\n\024MSG_CLI_ADD_USER_RSP\020\275\027\022\031\n\024MSG_CL" + "I_DEL_USER_REQ\020\276\027\022\031\n\024MSG_CLI_DEL_USER_RS" + "P\020\277\027\022\035\n\030MSG_CLI_ENTER_SERVER_REQ\020\300\027\022\035\n\030M" + "SG_CLI_ENTER_SERVER_RSP\020\301\027\022\035\n\030MSG_CLI_AS" + "SIGN_RIGHT_REQ\020\302\027\022\035\n\030MSG_CLI_ASSIGN_RIGH" + "T_RSP\020\303\027\022\034\n\027MSG_CLI_GET_DC_LIST_REQ\020\304\027\022\034" + "\n\027MSG_CLI_GET_DC_LIST_RSP\020\305\027\022\033\n\026MSG_CLI_" + "HEART_BEAT_REQ\020\306\027\022%\n MSG_GET_DC_MEDIA_SE" + "RVER_ADDR_REQ\020\307\027\022%\n MSG_GET_DC_MEDIA_SER" + "VER_ADDR_RSP\020\310\027\022\025\n\020MSG_CLI_INFO_NTF\020\311\027\022&" + "\n!MSG_CLI_GET_VISIBLE_USER_LIST_REQ\020\312\027\022&" + "\n!MSG_CLI_GET_VISIBLE_USER_LIST_RSP\020\313\027\022\036" + "\n\031MSG_CLI_GET_HTTP_ADDR_REQ\020\314\027\022\036\n\031MSG_CL" + "I_GET_HTTP_ADDR_RSP\020\315\027\022\"\n\035MSG_CLI_PATROL" + "_PT_TYPE_OP_REQ\020\316\027\022\037\n\032MSG_CLI_PATROL_PT_" + "TYPE_NTF\020\317\027\022(\n#MSG_CLI_GET_PATROL_PT_TYP" + "E_LIST_REQ\020\320\027\022(\n#MSG_CLI_GET_PATROL_PT_T" + "YPE_LIST_RSP\020\321\027\022\035\n\030MSG_CLI_PATROL_PT_OP_" + "REQ\020\322\027\022\032\n\025MSG_CLI_PATROL_PT_NTF\020\323\027\022#\n\036MS" + "G_CLI_GET_PATROL_PT_LIST_REQ\020\324\027\022#\n\036MSG_C" + "LI_GET_PATROL_PT_LIST_RSP\020\325\027\022\036\n\031MSG_CLI_" + "GET_TASK_LIST_REQ\020\326\027\022\036\n\031MSG_CLI_GET_TASK" + "_LIST_RSP\020\327\027\022\030\n\023MSG_CLI_TASK_OP_REQ\020\330\027\022\025" + "\n\020MSG_CLI_TASK_NTF\020\331\027\022$\n\037MSG_CLI_DEVICE_" + "CONTROL_MODE_REQ\020\332\027\022\032\n\025MSG_CLI_DC_CTL_OP" + "_REQ\020\333\027\022\036\n\031MSG_CLI_CONSTRUCT_MAP_REQ\020\334\027\022" + " \n\033MSG_CLI_SET_DC_CURR_MAP_REQ\020\335\027\022\"\n\035MSG" + "_CLI_SET_DC_SCENE_MODE_REQ\020\336\027\022\032\n\025MSG_CLI" + "_PT_RESULT_NTF\020\337\027\022&\n!MSG_CLI_PROCESS_PAT" + "ROL_RESULT_REQ\020\340\027B*\n\034com.gc.patrol_robot" + ".protobufB\nCliProtoId" }; com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner = new com.google.protobuf.Descriptors.FileDescriptor. InternalDescriptorAssigner() { public com.google.protobuf.ExtensionRegistry assignDescriptors( com.google.protobuf.Descriptors.FileDescriptor root) { descriptor = root; return null; } }; com.google.protobuf.Descriptors.FileDescriptor .internalBuildGeneratedFileFrom(descriptorData, new com.google.protobuf.Descriptors.FileDescriptor[] { }, assigner); } // @@protoc_insertion_point(outer_class_scope) }
package com.evguard.tools; import android.content.Context; import android.util.DisplayMetrics; import android.util.SparseArray; import android.view.View; import android.view.WindowManager; public class DateUtils { /** * 获取屏幕的比例 * * @return */ public static float getScaledDensity(Context context) { DisplayMetrics dm = context.getResources().getDisplayMetrics(); float value = dm.scaledDensity; return value; } /** * 将dip转换为px * * @return */ public static int dip2Px(Context context, float dip) { return (int) (context.getResources().getDisplayMetrics().density * dip); } /** * 将px转换为dip * * @return */ public static int px2dip(Context context, float pxValue) { final float scale = context.getResources().getDisplayMetrics().density; return (int) (pxValue / scale + 0.5f); } /** * base64编码后调用 * * @param str * @return */ public static String encodeReplace(String str) { str = str.replace("+", "_").replace("=", "%").replace("/", "*"); return str; } /** * base64解码前调用 * * @param str * @return */ public static String decodeReplace(String str) { str = str.replace("_", "+").replace("%", "=").replace("*", "/"); return str; } /** * 适用于Adapter中简化ViewHolder相关代码 * * @param convertView * @param id * @param <T> * @return */ @SuppressWarnings("unchecked") public static <T extends View> T obtainView(View convertView, int id) { SparseArray<View> holder = (SparseArray<View>) convertView.getTag(); if (holder == null) { holder = new SparseArray<View>(); convertView.setTag(holder); } View childView = holder.get(id); if (childView == null) { childView = convertView.findViewById(id); holder.put(id, childView); } return (T) childView; } /** * 获取控件的高度,如果获取的高度为0,则重新计算尺寸后再返回高度 * * @param view * @return */ public static int getViewMeasuredHeight(View view) { calcViewMeasure(view); return view.getMeasuredHeight(); } /** * 获取控件的宽度,如果获取的宽度为0,则重新计算尺寸后再返回宽度 * * @param view * @return */ public static int getViewMeasuredWidth(View view) { calcViewMeasure(view); return view.getMeasuredWidth(); } /** * 测量控件的尺寸 * * @param view */ public static void calcViewMeasure(View view) { int width = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED); int expandSpec = View.MeasureSpec.makeMeasureSpec( Integer.MAX_VALUE >> 2, View.MeasureSpec.AT_MOST); view.measure(width, expandSpec); } public static String splitDateString(String date){ //1942年 return date.split(" ")[0]; } /** * 获取屏幕宽度(像素) * * @param context * @return */ public static int getScreenWidth(Context context) { WindowManager windowManager = (WindowManager) context .getSystemService(Context.WINDOW_SERVICE); return windowManager.getDefaultDisplay().getWidth(); } /** * 获取屏幕高度(像素) * * @param context * @return */ public static int getScreenHeight(Context context) { WindowManager windowManager = (WindowManager) context .getSystemService(Context.WINDOW_SERVICE); return windowManager.getDefaultDisplay().getHeight(); } }
## Spring Data JPA - Repositories ### Relevant Articles: - [Introduction to Spring Data JPA](https://www.baeldung.com/the-persistence-layer-with-spring-data-jpa) - More articles: [[<-- prev]](/spring-data-jpa-repo/)
package io.github.wulkanowy.data.repositories.appcreator import android.content.res.AssetManager import com.google.gson.Gson import io.github.wulkanowy.data.pojos.AppCreator import io.reactivex.Single import javax.inject.Inject import javax.inject.Singleton @Singleton class AppCreatorRepository @Inject constructor(private val assets: AssetManager) { fun getAppCreators(): Single<List<AppCreator>> { return Single.fromCallable<List<AppCreator>> { Gson().fromJson( assets.open("creators.json").bufferedReader().use { it.readText() }, Array<AppCreator>::class.java ).toList() } } }
import { model, Schema } from 'mongoose'; const Users = model('User', new Schema({ username: { type: String, required: true }, password: { type: String, required: true }, salt: String, firstName: String, lastName: String, email: String, role: { type: String, enum: ['user', 'developer'], default: 'user' }, apiToken: [{ type: String }], controllers: [{ type: Schema.Types.ObjectId, ref: 'Controller' }], })); export default Users;
package trace import ( "context" "math/rand" "sync" "time" ) var ( traceRand = rand.New(rand.NewSource(time.Now().UnixNano())) traceRandMutex = sync.Mutex{} ) // value 记录了 context 里面的 trace 信息。 // // 这里为了能够实现跨越 rpc 边界传递 trace 信息,特别是时间相关信息, // 专门设计了 Now、Timeout、ElapsedTime 这三个字段来持久化这些信息。 // 对于任何一个新创建的 trace context 来说: // // * Now 记录的是创建 context的时间。 // * Timeout 是最上游设定的超时时间,层层传递到最底层服务。 // * ElapsedTime 是上游已经消耗掉的时间,这样就可以实现跨越服务边界 // 的超时控制,下游服务的 deadline 始终是 now + timeout - elapsed。 type value struct { mu sync.Mutex Info infoString string // 缓存了 Info 的 String 结果。 Now time.Time Timeout time.Duration ElapsedTime time.Duration PrevCaller string PrevCallee string } func newValue(ctx context.Context, tr Trace) *value { v, ok := ctx.Value(keyForValueOfContext).(*value) if !ok || v == nil { v = &value{} } v.merge(tr) v.normalize() v.infoString = makeLogString(v.Traceid, v.Spanid, v.HintCode, v.Locale, v.Timezone) return v } func parseValue(ctx context.Context) *value { v, ok := ctx.Value(keyForValueOfContext).(*value) if !ok { return nil } v.AdjustTime() return v } // Merge 从 tr 里继承部分数据。 func (v *value) merge(tr Trace) { if tr == nil { return } if traceid := tr.Traceid(); traceid != "" { v.Traceid = traceid } if locale := tr.Locale(); locale != "" { v.Locale = locale } if timezone := tr.Timezone(); timezone != "" { v.Timezone = timezone } if hintCode := tr.HintCode(); !hintCode.IsEmpty() { v.HintCode = hintCode } if hintContent := tr.HintContent(); hintContent != "" { v.HintContent = hintContent } if timeout := tr.timeout(); timeout > 0 { v.Timeout = timeout } if elapsed := tr.ElapsedTime(); elapsed > 0 { v.ElapsedTime = elapsed } if cspanid := tr.CSpanid(); cspanid != "" { v.Spanid = Spanid(cspanid) } if callee := tr.Callee(); callee != "" { v.PrevCallee = callee } if caller := tr.Caller(); caller != "" { v.PrevCaller = caller } if now := tr.now(); !now.IsZero() { v.Now = now } if fakeNow := tr.fakeNow(); !fakeNow.IsZero() { v.FakeNow = fakeNow } } func (v *value) normalize() { now := time.Now() nowNano := now.UnixNano() if v.Traceid == "" { v.Traceid = MakeTraceid(nowNano) } if v.Logid == "" { v.Logid = MakeLogid(nowNano) } if v.Spanid == "" { v.Spanid = MakeSpanid(nowNano) } if v.Now.IsZero() { v.Now = now } } func (v *value) AdjustTime() { if v.Now.IsZero() { return } v.mu.Lock() defer v.mu.Unlock() now := time.Now() v.ElapsedTime += now.Sub(v.Now) v.Now = now } func (v *value) Deadline() (deadline time.Time, ok bool) { if v.Timeout <= 0 { return } deadline = v.Now.Add(v.Timeout - v.ElapsedTime) ok = true return } func (v *value) Trace(ctx context.Context) Trace { info := parseInfo(ctx) vInfo := v.Info vInfo.Merge(info) tr := vInfo.Trace() deadline, ok := ctx.Deadline() vDeadline, vOK := v.Deadline() vNow := v.Now timeout := v.Timeout elapsed := v.ElapsedTime // ctx 的超时时间比 v 还短,那么使用 ctx 的时间。 if ok && (!vOK || deadline.Before(vDeadline)) { if vNow.IsZero() { vNow = time.Now() } timeout = deadline.Sub(vNow) elapsed = 0 } if timeout > 0 { tr.setTimeout(timeout) if !vNow.IsZero() { tr.setNow(vNow) } } if elapsed > 0 { tr.setElapsedTime(elapsed) } return tr } func (v *value) LogString() string { return v.infoString }
import 'dart:convert'; import 'package:at_base2e15/at_base2e15.dart'; import 'package:at_commons/at_commons.dart'; import 'package:at_wavi_app/model/user.dart'; import 'package:at_wavi_app/services/at_key_set_service.dart'; import 'package:at_wavi_app/services/backend_service.dart'; import 'package:at_wavi_app/services/field_order_service.dart'; import 'package:at_wavi_app/services/nav_service.dart'; import 'package:at_wavi_app/utils/at_enum.dart'; import 'package:at_wavi_app/utils/at_key_constants.dart'; import 'package:at_wavi_app/utils/constants.dart'; import 'package:at_wavi_app/view_models/follow_service.dart'; import 'package:provider/provider.dart'; class AtKeyGetService { AtKeyGetService._(); static AtKeyGetService _instance = AtKeyGetService._(); factory AtKeyGetService() => _instance; Map<dynamic, dynamic> _tempObject = {}; User user = User(allPrivate: false, atsign: ''); init() { user = User(allPrivate: false, atsign: ''); user.atsign = BackendService().atClientInstance.getCurrentAtSign()!; } resetUser() { init(); user.customFields[AtCategory.DETAILS.name] = []; user.customFields[AtCategory.LOCATION.name] = []; user.customFields[AtCategory.SOCIAL.name] = []; user.customFields[AtCategory.GAMER.name] = []; user.customFields[AtCategory.ADDITIONAL_DETAILS.name] = []; user.customFields[AtCategory.FEATURED.name] = []; } // TODO: for testing only deleteKeys() async { var scanKeys = await BackendService().getAtKeys(); for (var key in scanKeys) { await BackendService().atClientInstance.delete(key); } } ///fetches [atsign] profile. Future<User?> getProfile({String? atsign}) async { bool _containsPrivateAccountKey = false; resetUser(); try { // _setUser(atsign: atsign); atsign = atsign ?? BackendService().atClientInstance.getCurrentAtSign(); var scanKeys = await BackendService().getAtKeys(); // user.allPrivate = true; for (var key in scanKeys) { await _performLookupAndSetUser(key); // if (!result) errorCallBack(false); if (key.key!.contains(FieldsEnum.PRIVATEACCOUNT.name)) { _containsPrivateAccountKey = true; } } await createPrivateAccountKey(atsign!, _containsPrivateAccountKey); return user; // _container.updateWidgets(); // successCallBack(true); // await _sdkService.sync(); } catch (err) { // _logger.severe('Fetching ${_sdkService.currentAtsign} throws $err'); // errorCallBack(err); print('Error in getProfile $err'); return User(atsign: atsign); } } /// check & create 'PRIVATEACCOUNT key createPrivateAccountKey( String atsign, bool _containsPrivateAccountKey) async { try { if (atsign == BackendService().atClientInstance.getCurrentAtSign()) { if (!_containsPrivateAccountKey) { await AtKeySetService().update( BasicData(value: user.allPrivate.toString()), FieldsEnum.PRIVATEACCOUNT.name); } } } catch (err) { print('Error in createPrivateAccountKey $err'); } } ///Returns `true` on fetching value for [atKey]. Future<bool> _performLookupAndSetUser(AtKey atKey) async { try { var isSetUserField = false; var isCustom; if (atKey.key == null) { return false; } isCustom = atKey.key!.contains(AtText.CUSTOM); if (atKey.key == FieldsEnum.IMAGE.name) { atKey.metadata!.isBinary = true; } var successValue = await BackendService().atClientInstance.get(atKey); if (atKey.key!.contains(MixedConstants.fieldOrderKey)) { FieldOrderService().addFieldOrder(successValue); } if (atKey.key!.contains(MixedConstants.FOLLOWERS_KEY)) { Provider.of<FollowService>(NavService.navKey.currentContext!, listen: false) .addFollowersData(successValue); } if (atKey.key!.contains(MixedConstants.FOLLOWING_KEY)) { Provider.of<FollowService>(NavService.navKey.currentContext!, listen: false) .addFollowingData(successValue); } if (successValue.value != null && successValue.value != '') { isSetUserField = _setUserField(atKey.key, successValue.value, isCustom, isPublic: successValue.metadata?.isPublic); } return isSetUserField; } catch (e) { return false; } } /// sets user field with [value]. bool _setUserField(var key, var value, bool isCustom, {bool? isPublic}) { try { bool isPrivate = true; if (isPublic != null && isPublic) { isPrivate = false; } _tempObject[key] = value; if (isCustom) { _setCustomField(value, isPrivate); return true; } set(key, value, isPrivate: isPrivate); } catch (ex) { // _logger.severe('setting the $key key for user throws ${ex.toString()}'); } return true; } ///sets user customFields. void _setCustomField(String response, isPrivate) { var json = jsonDecode(response); if (json != 'null' && json != null) { String category = json[CustomFieldConstants.category]; var type = getType(json[CustomFieldConstants.type]); var value = getCustomContentValue(type: type, json: json); String label = json[CustomFieldConstants.label]; String? valueDescription = json[CustomFieldConstants.valueDescription]; BasicData basicData = BasicData( accountName: label, value: value, isPrivate: isPrivate, type: type, valueDescription: valueDescription ?? ''); // _container.createCustomField(basicData, category.toUpperCase()); if (user.customFields[category.toUpperCase()] == null) { user.customFields[category.toUpperCase()] = []; } user.customFields[category.toUpperCase()]!.add(basicData); // if (!basicData.isPrivate) { // user.allPrivate = false; // } } } ///Feches type of customField. getType(type) { if (type is String) { return type; } if (type[CustomFieldConstants.name] == CustomFieldConstants.txtInNumber) return CustomContentType.Number.name; else if (type[CustomFieldConstants.name] == CustomFieldConstants.txtInText) return CustomContentType.Text.name; else if (type[CustomFieldConstants.name] == CustomFieldConstants.txtInUrl) return CustomContentType.Link.name; } ///parses customField value from [json] based on type. getCustomContentValue({required var type, required var json}) { if (type == CustomContentType.Image.name) { try { return base64Decode(json[CustomFieldConstants.value]); } catch (e) { return Base2e15.decode(json[CustomFieldConstants.value]); } } else if (type == CustomContentType.Youtube.name) { if (json[CustomFieldConstants.valueLabel] != null && json[CustomFieldConstants.valueLabel] != '') { return json[CustomFieldConstants.valueLabel]; } return json[CustomFieldConstants.value]; } else { return json[CustomFieldConstants.value]; } } Map<dynamic, dynamic> objectReference() { return _tempObject; } dynamic set(String property, value, {isPrivate, valueDescription}) { // if (user == null) user = User(); FieldsEnum field = valueOf(property); var data = formData(property, value, private: isPrivate ?? false, valueDescription: valueDescription); switch (field) { case FieldsEnum.PRIVATEACCOUNT: user.allPrivate = value == 'true' ? true : false; break; case FieldsEnum.ATSIGN: user.atsign = value; break; case FieldsEnum.IMAGE: user.image = data; break; case FieldsEnum.FIRSTNAME: user.firstname = data; break; case FieldsEnum.LASTNAME: user.lastname = data; break; case FieldsEnum.PHONE: user.phone = data; break; case FieldsEnum.EMAIL: user.email = data; break; case FieldsEnum.ABOUT: user.about = data; break; case FieldsEnum.PRONOUN: user.pronoun = data; break; case FieldsEnum.LOCATION: user.location = data; break; case FieldsEnum.LOCATIONNICKNAME: user.locationNickName = data; break; case FieldsEnum.TWITTER: user.twitter = data; break; case FieldsEnum.FACEBOOK: user.facebook = data; break; case FieldsEnum.LINKEDIN: user.linkedin = data; break; case FieldsEnum.INSTAGRAM: user.instagram = data; break; case FieldsEnum.YOUTUBE: user.youtube = data; break; case FieldsEnum.TUMBLR: user.tumbler = data; break; case FieldsEnum.MEDIUM: user.medium = data; break; case FieldsEnum.TIKTOK: user.tiktok = data; break; case FieldsEnum.SNAPCHAT: user.snapchat = data; break; case FieldsEnum.GITHUB: user.github = data; break; case FieldsEnum.PINTEREST: user.pinterest = data; break; case FieldsEnum.PS4: user.ps4 = data; break; case FieldsEnum.XBOX: user.xbox = data; break; case FieldsEnum.STEAM: user.steam = data; break; case FieldsEnum.DISCORD: user.discord = data; break; case FieldsEnum.TWITCH: user.twitch = data; break; case FieldsEnum.HTMLTOASTVIEW: user.htmlToastView = data; break; default: break; } } } class CustomFieldConstants { static const String label = 'label'; static const String value = 'value'; static const String valueLabel = 'valueLabel'; static const String category = 'category'; static const String type = 'type'; static const String name = 'name'; static const String valueDescription = 'valueDescription'; static const String txtInNumber = 'TextInputType.number'; static const String txtInText = 'TextInputType.text'; static const String txtInUrl = 'TextInputType.url'; }
<?php date_default_timezone_set('asia/jakarta'); function dateEng($date){ $dateConvert = str_replace('/', '-', $date); $newDate = date('Y-m-d', strtotime($dateConvert)); return $newDate; } function dateTime($date, $sts){ $dateConvert = str_replace('/', '-', $date); if($sts == true){ $newDate = date('d M Y, H:i', strtotime($dateConvert)); }else{ $newDate = date('d M Y', strtotime($dateConvert)); } return $newDate; } function dateIna($date){ $dateConvert = str_replace('-', '/', $date); $newDate = date('d/m/Y', strtotime($dateConvert)); return $newDate; } function getDay($date){ $dateConvert = str_replace('-', '/', $date); $newDate = date('D', strtotime($dateConvert)); return $newDate; } function getDayTime($date){ $dateConvert = str_replace('-', '/', $date); $newDate = date('D, H : i', strtotime($dateConvert)); return $newDate; } function getWeeks($date, $rollover) { $cut = substr($date, 0, 8); $daylen = 86400; $timestamp = strtotime($date); $first = strtotime($cut . "00"); $elapsed = ($timestamp - $first) / $daylen; $weeks = 1; for ($i = 1; $i <= $elapsed; $i++) { $dayfind = $cut . (strlen($i) < 2 ? '0' . $i : $i); $daytimestamp = strtotime($dayfind); $day = strtolower(date("l", $daytimestamp)); if($day == strtolower($rollover)) $weeks ++; } return $weeks; } function formatBytes($bytes, $precision = 2) { $units = array('B', 'KB', 'MB', 'GB', 'TB'); $bytes = max($bytes, 0); $pow = floor(($bytes ? log($bytes) : 0) / log(1024)); $pow = min($pow, count($units) - 1); $bytes /= pow(1024, $pow); return round($bytes, $precision) . ' ' . $units[$pow]; } function selisihHari($mulai, $selesai){ $selesai = strtotime($selesai); $mulai = strtotime($mulai); $waktu = ($selesai - $mulai); $hari = floor($waktu /(60*60*24)); return $hari; } function sisaHari($selesai){ $tgl = strtotime($selesai); $diff= $tgl-time(); $days = floor($diff/(60*60*24)); return $days; } function waktuIstirahat($istirahat){ $default = strtotime('00:00:00'); $waktu_istirahat = strtotime($istirahat); $istirahat = ($waktu_istirahat - $default); $jam_izin = floor($istirahat / (60 * 3600)); $menit_istirahat = $istirahat - $jam_izin * floor(60 * 60); $hasil_istrirahat = $menit_istirahat / 60; return $hasil_istrirahat; } function waktuKerja($mulai, $selesai){ $waktu_sampai = strtotime($selesai); $waktu_dari = strtotime($mulai); $waktu = ($waktu_sampai - $waktu_dari); $jam = floor($waktu / (60 * 3600)); $menit = $waktu - $jam * floor(60 * 60); $hasil_menit = $menit / 60 ; return $hasil_menit; } function angkaKeBulan($number){ $bulan = "Januari Februari Maret April Mei Juni Juli Agustus September Oktober November Desember"; $array = explode(" ", $bulan); return $array[$number - 1]; } function get_time_difference_php($created_time) { $str = strtotime($created_time); $today = strtotime(date('Y-m-d H:i:s')); // It returns the time difference in Seconds... $time_differnce = $today-$str; // To Calculate the time difference in Years... $years = 60*60*24*365; // To Calculate the time difference in Months... $months = 60*60*24*30; // To Calculate the time difference in Days... $days = 60*60*24; // To Calculate the time difference in Hours... $hours = 60*60; // To Calculate the time difference in Minutes... $minutes = 60; if(intval($time_differnce/$years) > 1) { return intval($time_differnce/$years)." tahun yang lalu"; } else if(intval($time_differnce/$years) > 0) { return intval($time_differnce/$years)." tahun yang lalu"; } else if(intval($time_differnce/$months) > 1) { return intval($time_differnce/$months)." bulan yang lalu"; } else if(intval(($time_differnce/$months)) > 0) { return intval(($time_differnce/$months))." bulan yang lalu"; } else if(intval(($time_differnce/$days)) > 1) { return intval(($time_differnce/$days))." hari yang lalu"; } else if (intval(($time_differnce/$days)) > 0) { return intval(($time_differnce/$days))." hari yang lalu"; } else if (intval(($time_differnce/$hours)) > 1) { return intval(($time_differnce/$hours))." jam yang lalu"; } else if (intval(($time_differnce/$hours)) > 0) { return intval(($time_differnce/$hours))." jam yang lalu"; } else if (intval(($time_differnce/$minutes)) > 1) { return intval(($time_differnce/$minutes))." menit yang lalu"; } else if (intval(($time_differnce/$minutes)) > 0) { return intval(($time_differnce/$minutes))." menit yang lalu"; } else if (intval(($time_differnce)) > 1) { return intval(($time_differnce))." detik yang lalu"; }else { return "beberapa detik yang lalu"; } } // Function to get the client IP address function get_client_ip() { $ipaddress = ''; if (getenv('HTTP_CLIENT_IP')) $ipaddress = getenv('HTTP_CLIENT_IP'); else if(getenv('HTTP_X_FORWARDED_FOR')) $ipaddress = getenv('HTTP_X_FORWARDED_FOR'); else if(getenv('HTTP_X_FORWARDED')) $ipaddress = getenv('HTTP_X_FORWARDED'); else if(getenv('HTTP_FORWARDED_FOR')) $ipaddress = getenv('HTTP_FORWARDED_FOR'); else if(getenv('HTTP_FORWARDED')) $ipaddress = getenv('HTTP_FORWARDED'); else if(getenv('REMOTE_ADDR')) $ipaddress = getenv('REMOTE_ADDR'); else $ipaddress = 'UNKNOWN'; return $ipaddress; } function myMonth($tanggal) { $bulan = array (1 => 'Januari', 'Februari', 'Maret', 'April', 'Mei', 'Juni', 'Juli', 'Agustus', 'September', 'Oktober', 'November', 'Desember' ); $split = explode('-', $tanggal); return $bulan[ (int)$split[1] ]; } function firstSentence($string) { $sentences = explode(" ", $string); return $sentences[0]; }
% 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. -module(ejson). -export([encode/1, decode/1]). -on_load(init/0). init() -> SoName = case code:priv_dir(ejson) of {error, bad_name} -> case filelib:is_dir(filename:join(["..", priv])) of true -> filename:join(["..", priv, ejson]); false -> filename:join([priv, ejson]) end; Dir -> filename:join(Dir, ejson) end, (catch erlang:load_nif(SoName, 0)), case erlang:system_info(otp_release) of "R13B03" -> true; _ -> ok end. decode(undefined) -> throw({invalid_json, undefined}); decode(IoList) -> try nif_decode(IoList) catch exit:ejson_nif_not_loaded -> erl_decode(IoList) end. encode(EJson) -> try nif_encode(EJson) catch exit:ejson_nif_not_loaded -> erl_encode(EJson) end. nif_decode(IoList) -> case reverse_tokens(IoList) of {ok, ReverseTokens} -> [[EJson]] = make_ejson(ReverseTokens, [[]]), EJson; Error -> throw({invalid_json, {Error, IoList}}) end. erl_decode(IoList) -> try (mochijson2:decoder([{object_hook, fun({struct, L}) -> {L} end}]))(IoList) catch _Type:Error -> throw({invalid_json, {Error, IoList}}) end. nif_encode(EJson) -> RevList = encode_rev(EJson), final_encode(lists:reverse(lists:flatten([RevList]))). erl_encode(EJson) -> Opts = [{handler, fun mochi_encode_handler/1}], iolist_to_binary((mochijson2:encoder(Opts))(EJson)). mochi_encode_handler({L}) when is_list(L) -> {struct, L}; mochi_encode_handler(Bad) -> exit({json_encode, {bad_term, Bad}}). % Encode the json into a reverse list that's almost an iolist % everything in the list is the final output except for tuples with % {0, Strings} and {1, Floats}, which are to be converted to strings % inside the NIF. encode_rev(true) -> <<"true">>; encode_rev(false) -> <<"false">>; encode_rev(null) -> <<"null">>; encode_rev(I) when is_integer(I) -> list_to_binary(integer_to_list(I)); encode_rev(S) when is_binary(S) -> {0, S}; encode_rev(S) when is_atom(S) -> {0, list_to_binary(atom_to_list(S))}; encode_rev(F) when is_float(F) -> {1, F}; encode_rev({Props}) when is_list(Props) -> encode_proplist_rev(Props, [<<"{">>]); encode_rev(Array) when is_list(Array) -> encode_array_rev(Array, [<<"[">>]); encode_rev(Bad) -> throw({json_encode, {bad_term, Bad}}). encode_array_rev([], Acc) -> [<<"]">> | Acc]; encode_array_rev([Val | Rest], [<<"[">>]) -> encode_array_rev(Rest, [encode_rev(Val), <<"[">>]); encode_array_rev([Val | Rest], Acc) -> encode_array_rev(Rest, [encode_rev(Val), <<",">> | Acc]). encode_proplist_rev([], Acc) -> [<<"}">> | Acc]; encode_proplist_rev([{Key,Val} | Rest], [<<"{">>]) -> encode_proplist_rev( Rest, [encode_rev(Val), <<":">>, {0, as_binary(Key)}, <<"{">>]); encode_proplist_rev([{Key,Val} | Rest], Acc) -> encode_proplist_rev( Rest, [encode_rev(Val), <<":">>, {0, as_binary(Key)}, <<",">> | Acc]). as_binary(B) when is_binary(B) -> B; as_binary(A) when is_atom(A) -> list_to_binary(atom_to_list(A)); as_binary(L) when is_list(L) -> list_to_binary(L). make_ejson([], Stack) -> Stack; make_ejson([0 | RevEvs], [ArrayValues, PrevValues | RestStack]) -> % 0 ArrayStart make_ejson(RevEvs, [[ArrayValues | PrevValues] | RestStack]); make_ejson([1 | RevEvs], Stack) -> % 1 ArrayEnd make_ejson(RevEvs, [[] | Stack]); make_ejson([2 | RevEvs], [ObjValues, PrevValues | RestStack]) -> % 2 ObjectStart make_ejson(RevEvs, [[{ObjValues} | PrevValues] | RestStack]); make_ejson([3 | RevEvs], Stack) -> % 3 ObjectEnd make_ejson(RevEvs, [[] | Stack]); make_ejson([{0, Value} | RevEvs], [Vals | RestStack] = _Stack) -> % {0, IntegerString} make_ejson(RevEvs, [[list_to_integer(binary_to_list(Value)) | Vals] | RestStack]); make_ejson([{1, Value} | RevEvs], [Vals | RestStack] = _Stack) -> % {1, FloatString} make_ejson(RevEvs, [[list_to_float(binary_to_list(Value)) | Vals] | RestStack]); make_ejson([{3, String} | RevEvs], [[PrevValue|RestObject] | RestStack] = _Stack) -> % {3 , ObjectKey} make_ejson(RevEvs, [[{String, PrevValue}|RestObject] | RestStack]); make_ejson([Value | RevEvs], [Vals | RestStack] = _Stack) -> make_ejson(RevEvs, [[Value | Vals] | RestStack]). reverse_tokens(_) -> exit(ejson_nif_not_loaded). final_encode(_) -> exit(ejson_nif_not_loaded).
<?php declare(strict_types=1); /** * This file is part of vfsStream. * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace bovigo\vfs\tests; use bovigo\vfs\vfsStream; use bovigo\vfs\vfsStreamDirectory; use PHPUnit\Framework\TestCase; use function bovigo\assert\assertFalse; use function bovigo\assert\assertThat; use function bovigo\assert\assertTrue; use function bovigo\assert\expect; use function bovigo\assert\predicate\equals; use function fclose; use function file_put_contents; use function fopen; use function ftruncate; /** * Test for quota related functionality of bovigo\vfs\vfsStreamWrapper. * * @group issue_35 */ class vfsStreamWrapperQuotaTestCase extends TestCase { /** * access to root * * @var vfsStreamDirectory */ private $root; /** * set up test environment */ protected function setUp(): void { $this->root = vfsStream::setup(); vfsStream::setQuota(10); } /** * @test */ public function writeLessThanQuotaWritesEverything(): void { assertThat(file_put_contents(vfsStream::url('root/file.txt'), '123456789'), equals(9)); assertThat($this->root->getChild('file.txt')->getContent(), equals('123456789')); } /** * @test */ public function writeUpToQotaWritesEverything(): void { assertThat(file_put_contents(vfsStream::url('root/file.txt'), '1234567890'), equals(10)); assertThat($this->root->getChild('file.txt')->getContent(), equals('1234567890')); } /** * @test */ public function writeMoreThanQotaWritesOnlyUpToQuota(): void { expect(static function (): void { file_put_contents(vfsStream::url('root/file.txt'), '12345678901'); })->triggers() ->withMessage('file_put_contents(): Only 10 of 11 bytes written, possibly out of free disk space'); assertThat($this->root->getChild('file.txt')->getContent(), equals('1234567890')); } /** * @test */ public function considersAllFilesForQuota(): void { vfsStream::newFile('foo.txt') ->withContent('foo') ->at(vfsStream::newDirectory('bar')->at($this->root)); expect(static function (): void { file_put_contents(vfsStream::url('root/file.txt'), '12345678901'); })->triggers() ->withMessage('file_put_contents(): Only 7 of 11 bytes written, possibly out of free disk space'); assertThat($this->root->getChild('file.txt')->getContent(), equals('1234567')); } /** * @test * @group issue_33 */ public function truncateToLessThanQuotaWritesEverything(): void { $fp = fopen(vfsStream::url('root/file.txt'), 'w+'); assertTrue(ftruncate($fp, 9)); fclose($fp); assertThat($this->root->getChild('file.txt')->size(), equals(9)); assertThat( $this->root->getChild('file.txt')->getContent(), equals("\0\0\0\0\0\0\0\0\0") ); } /** * @test * @group issue_33 */ public function truncateUpToQotaWritesEverything(): void { $fp = fopen(vfsStream::url('root/file.txt'), 'w+'); assertTrue(ftruncate($fp, 10)); fclose($fp); assertThat($this->root->getChild('file.txt')->size(), equals(10)); assertThat( $this->root->getChild('file.txt')->getContent(), equals("\0\0\0\0\0\0\0\0\0\0") ); } /** * @test * @group issue_33 */ public function truncateToMoreThanQotaWritesOnlyUpToQuota(): void { $fp = fopen(vfsStream::url('root/file.txt'), 'w+'); assertTrue(ftruncate($fp, 11)); fclose($fp); assertThat($this->root->getChild('file.txt')->size(), equals(10)); assertThat( $this->root->getChild('file.txt')->getContent(), equals("\0\0\0\0\0\0\0\0\0\0") ); } /** * @test * @group issue_33 */ public function truncateConsidersAllFilesForQuota(): void { vfsStream::newFile('bar.txt') ->withContent('bar') ->at(vfsStream::newDirectory('bar') ->at($this->root)); $fp = fopen(vfsStream::url('root/file.txt'), 'w+'); assertTrue(ftruncate($fp, 11)); fclose($fp); assertThat($this->root->getChild('file.txt')->size(), equals(7)); assertThat( $this->root->getChild('file.txt')->getContent(), equals("\0\0\0\0\0\0\0") ); } /** * @test * @group issue_33 */ public function canNotTruncateToGreaterLengthWhenDiscQuotaReached(): void { vfsStream::newFile('bar.txt') ->withContent('1234567890') ->at(vfsStream::newDirectory('bar') ->at($this->root)); $fp = fopen(vfsStream::url('root/file.txt'), 'w+'); assertFalse(ftruncate($fp, 11)); fclose($fp); assertThat($this->root->getChild('file.txt')->size(), equals(0)); assertThat( $this->root->getChild('file.txt')->getContent(), equals('') ); } }
#!/bin/bash set -e +x clean_project() { # Remove compiled files that might cause conflicts rm -rf /io/.cache /io/.eggs /io/build /io/*.egg-info find /io/ -name "__pycache__" -type d -print0 | xargs -0 rm -rf find /io/ -name "*.pyc" -type f -print0 | xargs -0 rm -rf find /io/ -name "*.so" -type f -print0 | xargs -0 rm -rf } # Add cargo to path export RUSTUP_HOME="/usr" export CARGO_HOME="/usr" export SCCACHE_DIR="/var/cache/sccache" export RUSTC_WRAPPER="sccache" # Install rustup curl -SsL https://sh.rustup.rs | sh -s -- -y --no-modify-path --default-toolchain nightly # Install sccache LATEST=$(cargo search -q sccache | grep sccache | cut -f2 -d"\"") URL="https://github.com/mozilla/sccache/releases/download/${LATEST}/sccache-${LATEST}-x86_64-unknown-linux-musl.tar.gz" echo -e "\e[32m\e[1m Downloading\e[0m sccache v$LATEST" curl -SsL $URL | tar xzvC /tmp mv "/tmp/sccache-${LATEST}-x86_64-unknown-linux-musl/sccache" "${CARGO_HOME}/bin/sccache" mkdir -p "$SCCACHE_DIR" # Compile wheels for PYBIN in /opt/python/cp{27,35,36}*/bin; do export PYTHON_SYS_EXECUTABLE="$PYBIN/python" export PYTHON_LIB=$(${PYBIN}/python -c "import sysconfig; print(sysconfig.get_config_var('LIBDIR'))") export LIBRARY_PATH="$LIBRARY_PATH:$PYTHON_LIB" export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:$PYTHON_LIB" echo -e "\e[32m\e[1m Building\e[0m wheel for $($PYBIN/python --version)" "${PYBIN}/pip" install -U setuptools setuptools-rust wheel "${PYBIN}/pip" wheel /io/ -w /io/dist/ done # Bundle external shared libraries into the wheels for whl in /io/dist/*linux*.whl; do echo -e "\e[32m\e[1m Auditing\e[0m wheel $(basename $whl)" auditwheel repair "$whl" -w /io/dist/ rm $whl done
/** * 模块作用:统计推荐算法 * 启动服务:mongodb */ /** * MongoDB: * RateMoreMovies * RateMoreRecentlyMovies * AverageMovies * GenresTopMovies */ package com.zyx.statistics import java.text.SimpleDateFormat import java.util.Date import org.apache.spark.SparkConf import org.apache.spark.sql.SparkSession /** * movies.csv * @param mid 电影ID * @param name 电影名称 * @param descri 电影详情描述 * @param timelong 电影时长 * @param issue 电影发行日期 * @param shoot 电影拍摄日期 * @param language 电影语言 * @param genres 电影类型 * @param actors 电影演员表 * @param directors 电影导演 */ case class Movie(mid: Int, name: String, descri: String, timelong: String, issue: String, shoot: String, language: String, genres: String, actors: String, directors: String) /** * MongoDB的连接配置 * @param uri MongoDB的连接 * @param db MongoDB操作的数据库 */ case class MongoConfig(uri:String, db:String) /** * rating.csv * @param uid 用户ID * @param mid 电影ID * @param score 用户对于电影的评分 * @param timestamp 用户对于电影的评分的时间 */ case class Rating(uid: Int, mid: Int, score: Double, timestamp: Int) /** * 推荐电影 * @param mid 电影推荐的id * @param score 电影推荐的评分 */ case class Recommendation(mid:Int, score:Double) /** * 电影类别推荐 * @param genres 电影类别 * @param recs top10的电影集合 */ case class GenresRecommendation(genres:String, recs:Seq[Recommendation]) object StatisticsRecommender { // 数据集的绝对路径 val MOVIE_DATA_PATH = "/Users/nanase/Documents/GitHub/skills/Spark/Project/Movie_Recommender_System/MovieRecommenderSystem/recommender/DataLoader/src/main/resources/movies.csv" val RATING_DATA_PATH = "/Users/nanase/Documents/GitHub/skills/Spark/Project/Movie_Recommender_System/MovieRecommenderSystem/recommender/DataLoader/src/main/resources/ratings.csv" // 设置topk中的k值 val MOST_SCORE_OF_NUMBER = 10 // MongoDB中的表名 val MONGODB_RATING_COLLECTION = "Rating" val MONGODB_MOVIE_COLLECTION = "Movie" // 统计表的名称 val RATE_MORE_MOVIES = "RateMoreMovies" val RATE_MORE_RECENTLY_MOVIES = "RateMoreRecentlyMovies" val AVERAGE_MOVIES = "AverageMovies" val GENRES_TOP_MOVIES = "GenresTopMovies" def main(args: Array[String]): Unit = { /** * 设置配置信息 */ val config = Map( "spark.cores" -> "local[*]", "mongo.uri" -> "mongodb://10.0.0.11:27017/recommender", "mongo.db" -> "recommender" ) /** * 创建spark配置 */ // 创建sparkConf配置 val sparkConf = new SparkConf().setMaster(config.get("spark.cores").get).setAppName("StatisticsRecommender") // 创建sparkSession val spark = SparkSession.builder().config(sparkConf).getOrCreate() /** * 加载数据 */ var mongoConfig = MongoConfig(config("mongo.uri"),config("mongo.db")) import spark.implicits._ val ratingDF = spark .read .option("uri", mongoConfig.uri) .option("collection", MONGODB_RATING_COLLECTION) .format("com.mongodb.spark.sql") .load() .as[Rating] .toDF() val movieDF = spark .read .option("uri", mongoConfig.uri) .option("collection", MONGODB_MOVIE_COLLECTION) .format("com.mongodb.spark.sql") .load() .as[Movie] .toDF() // 创建ratings表 ratingDF.createOrReplaceTempView("ratings") /** * 统计推荐算法 */ /** * 统计历史热门电影 */ val rateMoreMoviesDF = spark.sql("select mid,count(mid) as count from ratings group by mid") rateMoreMoviesDF .write .option("uri", mongoConfig.uri) .option("collection", RATE_MORE_MOVIES) .mode("overwrite") .format("com.mongodb.spark.sql") .save() /** * 统计最近热门电影 */ val simpleDateFormat = new SimpleDateFormat("yyyyMM") // 用于将rating数据中的timestamp转换成年月格式 spark.udf.register("changeDate", (x:Int) => simpleDateFormat.format(new Date(x * 1000L)).toInt) val ratingOfYearMonth = spark.sql("select mid, score, changeDate(timestamp) as yearmonth from ratings") // 创建ratingOfMonth表 ratingOfYearMonth.createOrReplaceTempView("ratingOfMonth") // 先以yearmonth分组再以mid分组 val rateMoreRecentlyMovies = spark.sql("select mid, count(mid) as count, yearmonth from ratingOfMonth group by yearmonth, mid") rateMoreRecentlyMovies .write .option("uri", mongoConfig.uri) .option("collection", RATE_MORE_RECENTLY_MOVIES) .mode("overwrite") .format("com.mongodb.spark.sql") .save() /** * 统计电影的平均评分 */ val averageMoviesDF = spark.sql("select mid, avg(score) as avg from ratings group by mid") averageMoviesDF .write .option("uri", mongoConfig.uri) .option("collection", AVERAGE_MOVIES) .mode("overwrite") .format("com.mongodb.spark.sql") .save() /** * 统计每种类别top10 */ // join数据集averageMoviesDF和movieWithScore val movieWithScore = movieDF.join(averageMoviesDF, Seq("mid")) // 电影种类 val genres = List("Action","Adventure","Animation","Comedy","Crime","Documentary","Drama","Family","Fantasy","Foreign", "History","Horror","Music","Mystery" ,"Romance","Science","Tv","Thriller","War","Western") // genres转换为RDD val genresRDD = spark.sparkContext.makeRDD(genres) // movieWithScore与genres进行笛卡尔积 val genresTopMovies = genresRDD.cartesian(movieWithScore.rdd) .filter{ // 过滤电影类别不匹配的电影 case(genres, row) => row.getAs[String]("genres").toLowerCase.contains(genres.toLowerCase) } .map{ // 减少数据集的数据量 case(genres, row) => (genres, ((row.getAs[Int]("mid")), row.getAs[Double]("avg"))) }.groupByKey() // 将数据集中的类别相同的电影进行聚合 .map{ // 通过评分大小进行降序排序 case (genres, items) => GenresRecommendation(genres, items.toList.sortWith(_._2 > _._2) .take(MOST_SCORE_OF_NUMBER).map(item => Recommendation(item._1, item._2))) }.toDF() genresTopMovies .write .option("uri", mongoConfig.uri) .option("collection", GENRES_TOP_MOVIES) .mode("overwrite") .format("com.mongodb.spark.sql") .save() spark.stop() } }
@extends('layout.v_template') @section('title','Home') @section('content') <!-- Begin Page Content --> <div class="container-fluid"> <br> <h2 class="text-center">Selamat Datang di Sistem Informasi GadgetShop</h2> </div> <!-- End of Main Content --> @endsection
package opengis.process /** * Created by Chris on 12/08/2017. */ class Projections { companion object { fun main( args: Array<String> ) { /* fun Usage(s = ""): print "Usage: globalmaptiles.py [-profile 'mercator'|'geodetic'] zoomlevel lat lon [latmax lonmax]" print if s: print s print print "This utility prints for given WGS84 lat/lon coordinates (or bounding box) the list of tiles" print "covering specified area. Tiles are in the given 'profile' (default is Google Maps 'mercator')" print "and in the given pyramid 'zoomlevel'." print "For each tile several information is printed including bonding box in EPSG:900913 and WGS84." sys.exit(1) profile = 'mercator' zoomlevel = None lat, lon, latmax, lonmax = None, None, None, None boundingbox = False argv = sys.argv i = 1 while i < len(argv): arg = argv[i] if arg == '-profile': i = i + 1 profile = argv[i] if zoomlevel is None: zoomlevel = int(argv[i]) elif lat is None: lat = float(argv[i]) elif lon is None: lon = float(argv[i]) elif latmax is None: latmax = float(argv[i]) elif lonmax is None: lonmax = float(argv[i]) else: Usage("ERROR: Too many parameters") i = i + 1 if profile != 'mercator': Usage("ERROR: Sorry, given profile is not implemented yet.") if zoomlevel == None or lat == None or lon == None: Usage("ERROR: Specify at least 'zoomlevel', 'lat' and 'lon'.") if latmax is not None and lonmax is None: Usage("ERROR: Both 'latmax' and 'lonmax' must be given.") if latmax != None and lonmax != None: if latmax < lat: Usage("ERROR: 'latmax' must be bigger then 'lat'") if lonmax < lon: Usage("ERROR: 'lonmax' must be bigger then 'lon'") boundingbox = (lon, lat, lonmax, latmax) tz = zoomlevel mercator = GlobalMercator() mx, my = mercator.LatLonToMeters( lat, lon ) print "Spherical Mercator (ESPG:900913) coordinates for lat/lon: " print (mx, my) tminx, tminy = mercator.MetersToTile( mx, my, tz ) if boundingbox: mx, my = mercator.LatLonToMeters( latmax, lonmax ) print "Spherical Mercator (ESPG:900913) cooridnate for maxlat/maxlon: " print (mx, my) tmaxx, tmaxy = mercator.MetersToTile( mx, my, tz ) else: tmaxx, tmaxy = tminx, tminy for ty in range(tminy, tmaxy+1): for tx in range(tminx, tmaxx+1): tilefilename = "%s/%s/%s" % (tz, tx, ty) print tilefilename, "( TileMapService: z / x / y )" gx, gy = mercator.GoogleTile(tx, ty, tz) print "\tGoogle:", gx, gy quadkey = mercator.QuadTree(tx, ty, tz) print "\tQuadkey:", quadkey, '(',int(quadkey, 4),')' bounds = mercator.TileBounds( tx, ty, tz) print print "\tEPSG:900913 Extent: ", bounds wgsbounds = mercator.TileLatLonBounds( tx, ty, tz) print "\tWGS84 Extent:", wgsbounds print "\tgdalwarp -ts 256 256 -te %s %s %s %s %s %s_%s_%s.tif" % ( bounds[0], bounds[1], bounds[2], bounds[3], "<your-raster-file-in-epsg900913.ext>", tz, tx, ty) print */ } } }
package ftl.reports.util import java.io.File import java.nio.file.Paths fun File.getMatrixPath(objectName: String) = getShardName(objectName)?.asObjectPath() private fun File.getShardName(objectName: String) = shardNameRegex(objectName) .find(toString()) ?.value ?.removePrefix("/")?.removeSuffix("/") private fun shardNameRegex(objectName: String) = "/($objectName)/(shard_|matrix_)\\d+(-rerun_\\d+)?/".toRegex() private fun String.asObjectPath() = Paths.get(this).toString()
package phonetics import ( "errors" "regexp" "strings" ) func EncodeMetaphone(word string, lang ...string) string { _lang := "en" if len(lang) > 0 { _lang = lang[0] } else { var re = regexp.MustCompile("^[A-Za-z0-1]+$") if re.MatchString(word) { _lang = "en" } else { var re = regexp.MustCompile("^[А-Яа-я0-1ЇІЄїіє]+$") if re.MatchString(word) { _lang = "ru" } } } switch _lang { case "ua", "ru": return encodeMetaphoneRu(word) case "en": return encodeMetaphoneEn(word) default: panic(errors.New("Lang (" + _lang + ") not support")) } } func EncodeMetaphoneWords(word string, lang ...string) []string { _lang := "en" if len(lang) > 0 { _lang = lang[0] } else { var re = regexp.MustCompile("^[A-Za-z0-1 ]+$") if re.MatchString(word) { _lang = "en" } else { var re = regexp.MustCompile("^[А-Яа-я0-1ЇІЄїіє ]+$") if re.MatchString(word) { _lang = "ru" } } } words := strings.Split(word, " ") var wordsReturn []string switch _lang { case "ua", "ru": for _, value := range words { wordsReturn = append(wordsReturn, encodeMetaphoneRu(value)) } case "en": for _, value := range words { wordsReturn = append(wordsReturn, encodeMetaphoneEn(value)) } default: panic(errors.New("Lang (" + _lang + ") not support")) } return wordsReturn }
# Copyright (C) 2013, 2014 by Dmitry Maksyoma <ledestin@gmail.com> module FrugalTimeout # Timeout request, holding expiry time, what exception to raise and in which # thread. It is active by default, but can be defused. If it's defused, then # timeout won't be enforced when #enforce is called. class Request #:nodoc: include Comparable @@mutex = Mutex.new attr_reader :at, :klass, :thread def initialize thread, at, klass @thread, @at, @klass = thread, at, klass @defused = false end def <=>(other) @at <=> other.at end # Timeout won't be enforced if you defuse the request. def defuse! @@mutex.synchronize { @defused = true } end def defused? @@mutex.synchronize { @defused } end # Enforce this timeout request, unless it's been defused. # Return true if was enforced, false otherwise. def enforce @@mutex.synchronize { return false if @defused @thread.raise @klass, 'execution expired' @defused = true true } end end end