file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
39k
suffix
large_stringlengths
0
36.1k
middle
large_stringlengths
0
29.4k
fim_type
large_stringclasses
4 values
attr.rs
//! Parameters for modifying the appearance or behavior of [`ContentItem`]s. use { std::{ convert::{ TryFrom, TryInto, }, fmt, str::FromStr, }, css_color_parser::ColorParseError, url::Url, crate::{ ContentItem, Menu, }, }; ...
s: P) -> Command { Command { params: args.into(), terminal: false, } } } /// Used by `ContentItem::image` and `ContentItem::template_image`. #[derive(Debug, Clone)] pub struct Image { /// The base64-encoded image data. pub base64_data: String, /// If this is `tru...
(arg
identifier_name
attr.rs
//! Parameters for modifying the appearance or behavior of [`ContentItem`]s. use { std::{ convert::{ TryFrom, TryInto, }, fmt, str::FromStr, }, css_color_parser::ColorParseError, url::Url, crate::{ ContentItem, Menu, }, }; ...
type Error = Vec<T>; fn try_from(mut v: Vec<T>) -> Result<Params, Vec<T>> { match v.len() { 1..=6 => Ok(Params { cmd: v.remove(0).to_string(), params: v.into_iter().map(|x| x.to_string()).collect(), }), _ => Err(v), } } } ...
} } impl<T: ToString> TryFrom<Vec<T>> for Params {
random_line_split
smc_samplers.py
# -*- coding: utf-8 -*- """ SMC samplers. Overview ======== This module implements: * `StaticModel`: a base class for defining static models (and the corresponding target distributions). * `FeynmanKac` sub-classes that correspond to the following SMC samplers: + `IBIS` + `AdaptiveTempe...
class RandomWalkProposal(object): def __init__(self, x, scale=None, adaptive=True): if adaptive: if scale is None: scale = 2.38 / np.sqrt(x.shape[1]) cov = np.cov(x.T) try: self.L = scale * cholesky(cov, lo...
ield
conditional_block
smc_samplers.py
# -*- coding: utf-8 -*- """ SMC samplers. Overview ======== This module implements: * `StaticModel`: a base class for defining static models (and the corresponding target distributions). * `FeynmanKac` sub-classes that correspond to the following SMC samplers: + `IBIS` + `AdaptiveTempe...
self.proposal = model.prior if proposal is None else proposal self.model = model def run(self, N=100): """ Parameter --------- N: int number of particles Returns ------- wgts: Weights object The importance weights (wi...
""" def __init__(self, model=None, proposal=None):
random_line_split
smc_samplers.py
# -*- coding: utf-8 -*- """ SMC samplers. Overview ======== This module implements: * `StaticModel`: a base class for defining static models (and the corresponding target distributions). * `FeynmanKac` sub-classes that correspond to the following SMC samplers: + `IBIS` + `AdaptiveTempe...
self, key, value): self.l[key] = value def copy(self): return cp.deepcopy(self) def copyto(self, src, where=None): """ Same syntax and functionality as numpy.copyto """ for n, _ in enumerate(self.l): if where[n]: self.l[n] = src.l[n]...
_setitem__(
identifier_name
smc_samplers.py
# -*- coding: utf-8 -*- """ SMC samplers. Overview ======== This module implements: * `StaticModel`: a base class for defining static models (and the corresponding target distributions). * `FeynmanKac` sub-classes that correspond to the following SMC samplers: + `IBIS` + `AdaptiveTempe...
def default_moments(self, W, x): return rs.wmean_and_var_str_array(W, x.theta) def summary_format(self, smc): if smc.rs_flag: ars = np.array(smc.X.acc_rates[-1]) to_add = ', Metropolis acc. rate (over %i steps): %.3f' % ( ars.size, ars.mean()) el...
eturn self.model.T
identifier_body
main.go
package main import ( "bufio" "flag" "fmt" "io" "math" "os" "strings" "sync" "time" "github.com/dghubble/go-twitter/twitter" "github.com/dghubble/oauth1" "github.com/fatih/color" "github.com/joho/godotenv" "github.com/vysiondev/thighs/utils" ) const ( OAuthConsumerKey = "OAUTH_CONSUMER_KEY" OA...
() { err := godotenv.Load() if err != nil { color.HiRed("[!] Could not load .env file; it might be missing. Add it to your project root.") return } for _, v := range [4]string{ OAuthConsumerKey, OAuthConsumerSecret, OAuthToken, OAuthTokenSecret, } { if os.Getenv(v) == "" { color.HiRed("[!] %s is m...
main
identifier_name
main.go
package main import ( "bufio" "flag" "fmt" "io" "math" "os" "strings" "sync" "time" "github.com/dghubble/go-twitter/twitter" "github.com/dghubble/oauth1" "github.com/fatih/color" "github.com/joho/godotenv" "github.com/vysiondev/thighs/utils" ) const ( OAuthConsumerKey = "OAUTH_CONSUMER_KEY" OA...
{ err := godotenv.Load() if err != nil { color.HiRed("[!] Could not load .env file; it might be missing. Add it to your project root.") return } for _, v := range [4]string{ OAuthConsumerKey, OAuthConsumerSecret, OAuthToken, OAuthTokenSecret, } { if os.Getenv(v) == "" { color.HiRed("[!] %s is miss...
identifier_body
main.go
package main import ( "bufio" "flag" "fmt" "io" "math" "os" "strings" "sync" "time" "github.com/dghubble/go-twitter/twitter" "github.com/dghubble/oauth1" "github.com/fatih/color" "github.com/joho/godotenv" "github.com/vysiondev/thighs/utils" ) const ( OAuthConsumerKey = "OAUTH_CONSUMER_KEY" OA...
needToWaitSecs = wait if *debug { color.HiBlack("[debug] FINALIZE call successful") if needToWaitSecs > 0 { color.HiBlack("[debug] FINALIZE says upload is not done processing; we need to wait") } } if needToWaitSecs > 0 { statusChecks := 0 var status *MediaStatusResponse color....
random_line_split
main.go
package main import ( "bufio" "flag" "fmt" "io" "math" "os" "strings" "sync" "time" "github.com/dghubble/go-twitter/twitter" "github.com/dghubble/oauth1" "github.com/fatih/color" "github.com/joho/godotenv" "github.com/vysiondev/thighs/utils" ) const ( OAuthConsumerKey = "OAUTH_CONSUMER_KEY" OA...
color.White("Sending tweet...") tweet, res, err := client.Statuses.Update(tweetTextJoined, &twitter.StatusUpdateParams{ Status: "", InReplyToStatusID: *replyToPtr, PossiblySensitive: nil, Lat: latPtr, Long: longPtr, PlaceID: "", TrimUser: nil, ...
{ color.HiBlack("[debug] completed upload of all files") }
conditional_block
train.py
import warnings warnings.filterwarnings(action='ignore') import os import sys import keras from utils import rle2mask, img_preprocess from model import * from generator import * from metric import bce_dice_loss,bce_logdice_loss,dice_coef,dice_loss import numpy as np import tensorflow as tf import sys import argparse i...
print(model_path) print(graph_path) print(log_path) print(pred_path) print(valid_path) # sys.exit() history = compile_and_train(seg_model, train_batches, valid_batches, int(FLAGS.epoch), model_path = model_path, graph_path = graph_path, log_path...
os.makedirs(path)
conditional_block
train.py
import warnings warnings.filterwarnings(action='ignore') import os import sys import keras from utils import rle2mask, img_preprocess from model import * from generator import * from metric import bce_dice_loss,bce_logdice_loss,dice_coef,dice_loss import numpy as np import tensorflow as tf import sys import argparse i...
(df): df_copy = df.copy() df_copy['Class'] = df_copy.apply(lambda x : label_concat(x, df.columns[3:].tolist() ), axis=1) train_idx, valid_idx = train_test_split(df_copy.index.values, test_size =0.2, stratify = df_copy['C...
train_split
identifier_name
train.py
import warnings warnings.filterwarnings(action='ignore') import os import sys import keras from utils import rle2mask, img_preprocess from model import * from generator import * from metric import bce_dice_loss,bce_logdice_loss,dice_coef,dice_loss import numpy as np import tensorflow as tf import sys import argparse i...
def train_split(df): df_copy = df.copy() df_copy['Class'] = df_copy.apply(lambda x : label_concat(x, df.columns[3:].tolist() ), axis=1) train_idx, valid_idx = train_test_split(df_copy.index.values, test_size =0.2, stra...
df = df[labels] label_list = df[df!=''].keys().values.tolist() return label_list
identifier_body
train.py
import warnings warnings.filterwarnings(action='ignore') import os import sys import keras from utils import rle2mask, img_preprocess from model import * from generator import * from metric import bce_dice_loss,bce_logdice_loss,dice_coef,dice_loss import numpy as np import tensorflow as tf import sys import argparse i...
# # self.data_path = path +'train_images/' # self.data_path = train_path + '/' # elif self.subset =='test': # # self.data_path = path + 'test_images/' # self.data_path = test_path + '/' # self.on_epoch_end() # def __len__(self): # ...
# if self.subset =='train':
random_line_split
lmerge_ins.py
import sys import numpy as np import argparse import heapq import re import os ar=os.path.dirname(os.path.realpath(__file__)).split('/') svtpath='/'.join(ar[0:(len(ar)-1)]) sys.path.insert(1, svtpath) import svtools.l_bp as l_bp from svtools.breakpoint import Breakpoint import svtools.logspace as ls from svtools.vcf....
sum_L = sum(p_L) sum_R = sum(p_R) p_L = [x/sum_L for x in p_L] p_R = [x/sum_L for x in p_R] [clip_start_L, clip_end_L] = l_bp.trim(p_L) [clip_start_R, clip_end_R] = l_bp.trim(p_R) [ new_start_L, new_end_L ] = [ start_L + clip_start_L, end_L - clip_end_L ] [ new_start_R, new_end_R ] ...
p_R.append(ls.get_p(ls.ls_divide(ls_p, ls_sum_R)))
conditional_block
lmerge_ins.py
import sys import numpy as np import argparse import heapq import re import os ar=os.path.dirname(os.path.realpath(__file__)).split('/') svtpath='/'.join(ar[0:(len(ar)-1)]) sys.path.insert(1, svtpath) import svtools.l_bp as l_bp from svtools.breakpoint import Breakpoint import svtools.logspace as ls from svtools.vcf....
(BP, sample_order, v_id, use_product, vcf, vcf_out, include_genotypes): A = BP[0].l.rstrip().split('\t') var = Variant(A,vcf) try: sname = var.get_info('SNAME') var.set_info('SNAME', sname + ':' + var.var_id) except KeyError: pass var.var_id=str(v_id) if use_product: ...
merge_single_bp
identifier_name
lmerge_ins.py
import sys import numpy as np import argparse import heapq import re import os ar=os.path.dirname(os.path.realpath(__file__)).split('/') svtpath='/'.join(ar[0:(len(ar)-1)]) sys.path.insert(1, svtpath) import svtools.l_bp as l_bp from svtools.breakpoint import Breakpoint import svtools.logspace as ls from svtools.vcf....
else: BP.sort(key=lambda x: x.left.start) ordered_cliques = [] order_cliques(BP, ordered_cliques) #merge cliques for cliq in ordered_cliques: v_id+=1 var=create_merged_variant(BP, cliq, v_id, vcf, use_product, weighting_scheme) combine_va...
v_id+=1 var=merge_single_bp(BP, sample_order, v_id, use_product, vcf, vcf_out, include_genotypes) write_var(var, vcf_out, include_genotypes)
random_line_split
lmerge_ins.py
import sys import numpy as np import argparse import heapq import re import os ar=os.path.dirname(os.path.realpath(__file__)).split('/') svtpath='/'.join(ar[0:(len(ar)-1)]) sys.path.insert(1, svtpath) import svtools.l_bp as l_bp from svtools.breakpoint import Breakpoint import svtools.logspace as ls from svtools.vcf....
def l_cluster_by_line(file_name, tempdir, percent_slop=0, fixed_slop=0, use_product=False, include_genotypes=False, weighting_scheme='unweighted'): v_id = 0 in_header = True header = [] vcf = Vcf() vcf_out=sys.stdout with InputStream(file_name, tempdir) as vcf_stream: BP_l = [] ...
BP_l.sort(key=lambda x: x.right.start) BP_l.sort(key=lambda x: x.right.chrom) BP_r = [] BP_max_end_r = -1 BP_chr_r = '' for b in BP_l: if (len(BP_r) == 0) or \ ((b.right.start <= BP_max_end_r) and \ (b.right.chrom == BP_chr_r)): BP_r.append(b) ...
identifier_body
Popup.ts
import {DisplayObject} from './DisplayOject'; import {is} from '../util/utils' const DEFAULTS = { callback: null, title: null, // titlebar text. titlebar will not be visible if not set. btnClose: true, // display close link in titlebar? btnMax: false, // display max link in titlebar? ...
$('<div class="row tb-row" />').prependTo(this.boxy).append(tb); } function setDraggable(self) { let tb = self.titleBar; tb.on('mousedown', function (evt) { self.toTop(); if (evt.target.tagName === 'B') return; if (evt.button < 2 && self.state !== "max") { tb.on('mousemove.boxy', function (e) { ...
if (cfg.drag) { setDraggable.call(this, this, cfg); }
random_line_split
Popup.ts
import {DisplayObject} from './DisplayOject'; import {is} from '../util/utils' const DEFAULTS = { callback: null, title: null, // titlebar text. titlebar will not be visible if not set. btnClose: true, // display close link in titlebar? btnMax: false, // display max link in titlebar? ...
() { this.boxy.stop(true, true).css(this.restoreSize); if (this.btnMax) this.btnMax.toggleClass('dg-btn-max dg-btn-restore'); //$(document.body).removeClass('no-scroll'); this.state = 'normal'; return this; } destroy() { if (this.titleBar) { this.titleBar.off('mousedown'); if (this.btnMa...
restore
identifier_name
Popup.ts
import {DisplayObject} from './DisplayOject'; import {is} from '../util/utils' const DEFAULTS = { callback: null, title: null, // titlebar text. titlebar will not be visible if not set. btnClose: true, // display close link in titlebar? btnMax: false, // display max link in titlebar? ...
max() { //resize window entity this.boxy.stop(true, true).css({ left: 0, top: 0, width: '100%', height: '100%' }); if (this.btnMax) this.btnMax.toggleClass('dg-btn-max dg-btn-restore'); //$(document.body).addClass('no-scroll'); this.state = 'max'; return this; } restore() { th...
{ let that = this; let css = this.getPosition(); css.opacity = 0; css.top = Math.max(css.top - 40, 0); this.mask.animate({opacity: 0}, 200); this.boxy.stop(true, true).animate(css, 300, function () { if (typeof that.cfg.onClose === 'function') that.cfg.onClose.call(that); if (typeof fn === '...
identifier_body
Popup.ts
import {DisplayObject} from './DisplayOject'; import {is} from '../util/utils' const DEFAULTS = { callback: null, title: null, // titlebar text. titlebar will not be visible if not set. btnClose: true, // display close link in titlebar? btnMax: false, // display max link in titlebar? ...
this.mask.css({display: "block", opacity: 1}); let topPx = this.boxy.position().top; //console.warn(this.boxy[0], topPx); this.boxy.css({top: topPx - 20, opacity: 0}).animate({opacity: 1, top: topPx}, 200); this.visible = true; return this; } close(fn?: Function) { let that = this; let css = t...
{ return this.toTop(); }
conditional_block
quasar.ts
import { BloomFilter } from './bloomfilter'; import { knuthShuffle as shuffle } from './shuffle'; import * as uuid from 'uuid'; const LRUCache = require('lru-cache'); const kad = require('kad'); export interface QuasarOptions { maxRelayHops?:number, randomRelay?:boolean, lruCacheSize?:number, logger?:any } /*...
else { try { resolve(BloomFilter.deserialize(message.result.filters)); } catch (err) { reject(new Error('Failed to deserialize bloom filter')); } } }); }); } /** * Send the contact our updated attenuated bloom filter * @private */ ...
{ reject(new Error('Invalid response received')); }
conditional_block
quasar.ts
import { BloomFilter } from './bloomfilter'; import { knuthShuffle as shuffle } from './shuffle'; import * as uuid from 'uuid'; const LRUCache = require('lru-cache'); const kad = require('kad'); export interface QuasarOptions { maxRelayHops?:number, randomRelay?:boolean, lruCacheSize?:number, logger?:any } /*...
(neighbors, params):Promise<any> { var nodeID = this._router._self.nodeID; let _relayToRandomNeighbor = () => { var randNeighbor = this._getRandomOverlayNeighbor(nodeID, params.topic); this._sendPublish(randNeighbor, params); } if (this._options.randomRelay) { _relayToRandomNeighbor(...
_relayPublication
identifier_name
quasar.ts
import { BloomFilter } from './bloomfilter'; import { knuthShuffle as shuffle } from './shuffle'; import * as uuid from 'uuid'; const LRUCache = require('lru-cache'); const kad = require('kad'); export interface QuasarOptions { maxRelayHops?:number, randomRelay?:boolean, lruCacheSize?:number, logger?:any } /*...
* @param {Object} options * @param {String} options.key - Use neighbors close to this key (optional) */ publish(topic:string, data:any, options?:{ key?:string }):Promise<any> { let nodeID = this._router._self.nodeID; let limit = kad.constants.ALPHA; let key = options ? (options.key || nodeID) : n...
/** * Publish some data for the given topic * @param {String} topic - The publication identifier * @param {Object} data - Arbitrary publication contents
random_line_split
quasar.ts
import { BloomFilter } from './bloomfilter'; import { knuthShuffle as shuffle } from './shuffle'; import * as uuid from 'uuid'; const LRUCache = require('lru-cache'); const kad = require('kad'); export interface QuasarOptions { maxRelayHops?:number, randomRelay?:boolean, lruCacheSize?:number, logger?:any } /*...
/** * Publish some data for the given topic * @param {String} topic - The publication identifier * @param {Object} data - Arbitrary publication contents * @param {Object} options * @param {String} options.key - Use neighbors close to this key (optional) */ publish(topic:string, data:any, options...
{ if (!(router instanceof kad.Router)) throw new Error('Invalid router supplied'); this._router = router; this._options = Object.create(Quasar.DEFAULTS); Object.assign(this._options, options); this._protocol = {}; this._seen = new LRUCache(this._options.lruCacheSize); this._log = this._opti...
identifier_body
state.rs
use std::sync::Mutex; use wasm_bindgen::prelude::*; use web_sys::CanvasRenderingContext2d; #[wasm_bindgen] extern "C" { pub type TimeoutId; #[wasm_bindgen(js_name = "setTimeout")] pub fn set_timeout_inner(cb: &JsValue, timeout: f64) -> TimeoutId; #[wasm_bindgen(js_name = "clearTimeout")] pub fn c...
if id > self.last_rendered { self.reset_buffer(); self.last_rendered = id; } let mut bright = vec![0_u32; self.config.rendering.width * self.config.rendering.height]; array.copy_to(&mut bright); for i in 0..bright.len() { self.buffer[i] += br...
{ let (worker, busy, queued) = &mut self.workers[worker]; match queued { None => { // log!("Finished a thread"); *busy = false } Some(message) => { // log!("Sending a new config to render"...
conditional_block
state.rs
use std::sync::Mutex; use wasm_bindgen::prelude::*; use web_sys::CanvasRenderingContext2d; #[wasm_bindgen] extern "C" { pub type TimeoutId; #[wasm_bindgen(js_name = "setTimeout")] pub fn set_timeout_inner(cb: &JsValue, timeout: f64) -> TimeoutId; #[wasm_bindgen(js_name = "clearTimeout")] pub fn c...
() -> bool { match STATE.lock().unwrap().as_mut() { Some(_) => true, None => false, } } pub fn with<R, F: FnOnce(&mut State) -> R>(f: F) -> R { match STATE.lock().unwrap().as_mut() { Some(mut state) => f(&mut state), None => { log!("!!! Error: tried to handle sta...
has_state
identifier_name
state.rs
use std::sync::Mutex; use wasm_bindgen::prelude::*; use web_sys::CanvasRenderingContext2d; #[wasm_bindgen] extern "C" { pub type TimeoutId; #[wasm_bindgen(js_name = "setTimeout")] pub fn set_timeout_inner(cb: &JsValue, timeout: f64) -> TimeoutId; #[wasm_bindgen(js_name = "clearTimeout")] pub fn c...
pub fn add_worker(&mut self, worker: web_sys::Worker) { self.workers.push((worker, false, None)) } pub fn invalidate_past_renders(&mut self) { self.render_id += 1; self.last_rendered = self.render_id; } pub fn undo(&mut self) -> Result<(), JsValue> { log!("Undo {}...
{ self.buffer = vec![0_u32; self.config.rendering.width * self.config.rendering.height]; self.invalidate_past_renders(); }
identifier_body
state.rs
use std::sync::Mutex; use wasm_bindgen::prelude::*; use web_sys::CanvasRenderingContext2d; #[wasm_bindgen] extern "C" { pub type TimeoutId; #[wasm_bindgen(js_name = "setTimeout")] pub fn set_timeout_inner(cb: &JsValue, timeout: f64) -> TimeoutId; #[wasm_bindgen(js_name = "clearTimeout")] pub fn c...
pub fn handle_render( &mut self, worker: usize, id: usize, array: js_sys::Uint32Array, ) -> Result<(), JsValue> { if id < self.last_rendered { let (worker, busy, queued) = &mut self.workers[worker]; match queued { None => { ...
// } }
random_line_split
health.pb.go
// Code generated by protoc-gen-go. DO NOT EDIT. // source: proto/health.proto package healthpb import ( context "context" fmt "fmt" proto "github.com/golang/protobuf/proto" _ "google.golang.org/genproto/googleapis/api/annotations" grpc "google.golang.org/grpc" codes "google.golang.org/grpc/codes" status "goog...
func (m *HealthCheckRequest) XXX_DiscardUnknown() { xxx_messageInfo_HealthCheckRequest.DiscardUnknown(m) } var xxx_messageInfo_HealthCheckRequest proto.InternalMessageInfo func (m *HealthCheckRequest) GetService() string { if m != nil { return m.Service } return "" } type HealthCheckResponse struct { Status ...
{ return xxx_messageInfo_HealthCheckRequest.Size(m) }
identifier_body
health.pb.go
// Code generated by protoc-gen-go. DO NOT EDIT. // source: proto/health.proto package healthpb import ( context "context" fmt "fmt" proto "github.com/golang/protobuf/proto" _ "google.golang.org/genproto/googleapis/api/annotations" grpc "google.golang.org/grpc" codes "google.golang.org/grpc/codes" status "goog...
() string { if m != nil { return m.Service } return "" } type HealthCheckResponse struct { Status HealthCheckResponse_ServingStatus `protobuf:"varint,1,opt,name=status,proto3,enum=health.HealthCheckResponse_ServingStatus" json:"status,omitempty"` XXX_NoUnkeyedLiteral struct{} ...
GetService
identifier_name
health.pb.go
// Code generated by protoc-gen-go. DO NOT EDIT. // source: proto/health.proto package healthpb import ( context "context" fmt "fmt" proto "github.com/golang/protobuf/proto" _ "google.golang.org/genproto/googleapis/api/annotations" grpc "google.golang.org/grpc" codes "google.golang.org/grpc/codes" status "goog...
func (m *HealthCheckRequest) GetService() string { if m != nil { return m.Service } return "" } type HealthCheckResponse struct { Status HealthCheckResponse_ServingStatus `protobuf:"varint,1,opt,name=status,proto3,enum=health.HealthCheckResponse_ServingStatus" json:"status,omitempty"` XXX_NoUnkey...
func (m *HealthCheckRequest) XXX_DiscardUnknown() { xxx_messageInfo_HealthCheckRequest.DiscardUnknown(m) } var xxx_messageInfo_HealthCheckRequest proto.InternalMessageInfo
random_line_split
health.pb.go
// Code generated by protoc-gen-go. DO NOT EDIT. // source: proto/health.proto package healthpb import ( context "context" fmt "fmt" proto "github.com/golang/protobuf/proto" _ "google.golang.org/genproto/googleapis/api/annotations" grpc "google.golang.org/grpc" codes "google.golang.org/grpc/codes" status "goog...
info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/health.Health/Ready", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(HealthServer).Ready(ctx, req.(*HealthCheckRequest)) } return interceptor(ctx, in, info, handler) } var _Health_serviceDesc = grpc.Se...
{ return srv.(HealthServer).Ready(ctx, in) }
conditional_block
lib.rs
#![cfg_attr(not(feature = "std"), no_std)] //! Kalman filter and Rauch-Tung-Striebel smoothing implementation //! //! Characteristics: //! - Uses the [nalgebra](https://nalgebra.org) crate for math. //! - Supports `no_std` to facilitate running on embedded microcontrollers. //! - Includes [various methods of computing ...
( &self, prior: &StateAndCovariance<R, SS>, observation: &OVector<R, OS>, covariance_method: CoverianceUpdateMethod, ) -> Result<StateAndCovariance<R, SS>, Error> { // Use conventional (e.g. wikipedia) names for these variables let h = self.observation_matrix(); ...
update
identifier_name
lib.rs
#![cfg_attr(not(feature = "std"), no_std)] //! Kalman filter and Rauch-Tung-Striebel smoothing implementation //! //! Characteristics: //! - Uses the [nalgebra](https://nalgebra.org) crate for math. //! - Supports `no_std` to facilitate running on embedded microcontrollers. //! - Includes [various methods of computing ...
#[inline] fn is_nan<R: RealField>(x: R) -> bool { x.partial_cmp(&R::zero()).is_none() } #[test] fn test_is_nan() { assert_eq!(is_nan::<f64>(-1.0), false); assert_eq!(is_nan::<f64>(0.0), false); assert_eq!(is_nan::<f64>(1.0), false); assert_eq!(is_nan::<f64>(1.0 / 0.0), false); assert_eq!(is_na...
Ok(StateAndCovariance::new(state, covariance)) } }
random_line_split
10162017.js
//Create jQuery Alias to aviod conflict with preloaded libraries var jq = jQuery.noConflict(); window.onload = setUp; setUp(); function setUp() { var spymode = "single" //var spymode="multiple" var spyModeOptn = "show" //Main call switch (spymode) { case "single": var style = d...
else { var element_sibling = element; var sibling_cnt = 1; while (element_sibling = element_sibling.previousElementSibling) { if (element_sibling.nodeName.toLowerCase() == selector) sibling_cnt++; } if (sibling_cnt != 1) ...
{ if (element.id.indexOf('-') > -1) { selector += '[id = "' + element.id + '"]'; } else { selector += '#' + element.id; } path.unshift(selector); break; }
conditional_block
10162017.js
//Create jQuery Alias to aviod conflict with preloaded libraries var jq = jQuery.noConflict(); window.onload = setUp; setUp(); function setUp() { var spymode = "single" //var spymode="multiple" var spyModeOptn = "show" //Main call switch (spymode) { case "single": var style = d...
() { //jq(".ignrPopUp").detach(); jq("#ATOMspyPopUpDiv").hide(); } function spyMouseOut(e) { var element = e.target; e.stopPropagation(); //jq("#ATOMspyPopUpDiv").hide(); element.style.outline = '' } function getObjectType(object) { var title = jq(object).get(0).tagName.toLowerCase()...
removeSpyPanel
identifier_name
10162017.js
//Create jQuery Alias to aviod conflict with preloaded libraries var jq = jQuery.noConflict(); window.onload = setUp; setUp(); function setUp() { var spymode = "single" //var spymode="multiple" var spyModeOptn = "show" //Main call switch (spymode) { case "single": var style = d...
function spyMouseOut(e) { var element = e.target; e.stopPropagation(); //jq("#ATOMspyPopUpDiv").hide(); element.style.outline = '' } function getObjectType(object) { var title = jq(object).get(0).tagName.toLowerCase(); switch (title) { case "a": return ('Link'); ...
{ //jq(".ignrPopUp").detach(); jq("#ATOMspyPopUpDiv").hide(); }
identifier_body
10162017.js
//Create jQuery Alias to aviod conflict with preloaded libraries var jq = jQuery.noConflict(); window.onload = setUp; setUp(); function setUp() { var spymode = "single" //var spymode="multiple" var spyModeOptn = "show" //Main call switch (spymode) { case "single": var style = d...
function getObjectType(object) { var title = jq(object).get(0).tagName.toLowerCase(); switch (title) { case "a": return ('Link'); break; case "button": return ('Button'); break; case "caption": case "table": case "caption...
}
random_line_split
utils.ts
import { myer } from './myer-array-diff'; /** * Merge object by another one. Use default value if new value is undefined or null * @param obj * @param newObj * @param defaults * @returns {any} */ export function mergeWithDefaults(obj, newObj = {}, defaults = {}) { for (let k in newObj) { const newVal...
docElem = doc.documentElement; win = getWindow(doc); return { top: box.top + win.pageYOffset - docElem.clientTop, left: box.left + win.pageXOffset - docElem.clientLeft }; } function getWindow(elem) { return elem != null && elem === elem.window ? elem : elem.nodeType === 9 && elem...
{ return; }
conditional_block
utils.ts
import { myer } from './myer-array-diff'; /** * Merge object by another one. Use default value if new value is undefined or null * @param obj * @param newObj * @param defaults * @returns {any} */ export function mergeWithDefaults(obj, newObj = {}, defaults = {}) { for (let k in newObj) { const newVal...
clear() { this.cache = []; } private getValue(cacheItem) { if (cacheItem) { return cacheItem.v; } } }
{ // Remove duplicates, remove all except '' this.cache = this.cache.filter(cacheItem => cacheItem.q !== query && cacheItem.q === ''); this.cache.unshift({q: query, v: value, t: (new Date().getTime())}) }
identifier_body
utils.ts
import { myer } from './myer-array-diff'; /** * Merge object by another one. Use default value if new value is undefined or null * @param obj * @param newObj * @param defaults * @returns {any} */ export function mergeWithDefaults(obj, newObj = {}, defaults = {}) { for (let k in newObj) { const newVal...
} else { current = current[paths[i]]; } } return current; } /** * Highlight `substr` in `str` by `<mark>` or custom tag * * @param {string} str * @param {string} substr * @param {string} tagName. `mark` by default * @returns {string} highlighted string */ export function high...
for (i = 0; i < paths.length; ++i) { if (current[paths[i]] == undefined) { return undefined;
random_line_split
utils.ts
import { myer } from './myer-array-diff'; /** * Merge object by another one. Use default value if new value is undefined or null * @param obj * @param newObj * @param defaults * @returns {any} */ export function mergeWithDefaults(obj, newObj = {}, defaults = {}) { for (let k in newObj) { const newVal...
(groups) { for (let k in groups) { if (groups.hasOwnProperty(k) && groups[k].length) { return false; } } return true; } /** * Find array intersections * Equal of lodash _.intersection + getter + invert * * @param {any[]} xArr * @param {any[]} yArr * @param {Function} gette...
groupsIsEmpty
identifier_name
tarea8.py
# -*- coding: utf-8 -*- """ Created on Thu Oct 26 17:55:59 2017 @author: Ricardo Chávez Cáliz """ import numpy as np from numpy import zeros from numpy import log from numpy import exp from numpy.random import rand from numpy.random import normal from numpy.random import gamma from numpy.random impo...
""" Grafica una muestra normal bivriada de tamaño n con parámetros m y sigma usando el metodo de MH con kerneles híbridos de parametro w1, junto con los contornos de nivel de la densidad correspondiente. Input: array, array, float, int (media, matriz de covarianza, probabiidad de to...
m,sigma,w1,n):
identifier_name
tarea8.py
# -*- coding: utf-8 -*- """ Created on Thu Oct 26 17:55:59 2017 @author: Ricardo Chávez Cáliz """ import numpy as np from numpy import zeros from numpy import log from numpy import exp from numpy.random import rand from numpy.random import normal from numpy.random import gamma from numpy.random impo...
lp)/(a*l)) + (ap-a)*log(r1)- lp*sap + l*sa c=min(0,aux) return ap,lp,exp(c) else: ap=a + normal(0,sigma) lp= l suma=0 for t in T: suma = suma + log(t) sap=0 for t in T: sap = sap + t**ap sa=0 ...
log((ap*
conditional_block
tarea8.py
# -*- coding: utf-8 -*- """ Created on Thu Oct 26 17:55:59 2017 @author: Ricardo Chávez Cáliz """ import numpy as np from numpy import zeros from numpy import log from numpy import exp from numpy.random import rand from numpy.random import normal from numpy.random import gamma from numpy.random impo...
omo funcion objetivo la distribución normal bivariada: Considere las siguientes propuestas: q1 ((x01, x02)|(x1, x2)) = f_X1|X2(x01|x2)1(x02 = x2) q2 ((x01, x02)|(x1, x2)) = fX2|X1(x02|x1)1(x01 = x1) A partir del algoritmo MH usando Kerneles híbridos simule valores de la dist...
s(n) plt.scatter(x, y, s=area, c=colors, alpha=0.8) plt.show() if __name__ == "__main__": """ 1. Aplique el algoritmo de Metropolis-Hastings considerando c
identifier_body
tarea8.py
# -*- coding: utf-8 -*- """ Created on Thu Oct 26 17:55:59 2017 @author: Ricardo Chávez Cáliz """ import numpy as np from numpy import zeros from numpy import log from numpy import exp from numpy.random import rand from numpy.random import normal from numpy.random import gamma from numpy.random impo...
Propuesta 1: λp|α,t ̄∼ Gamaα + n , b +Xni=1tαi! Propuesta 2: αp|λ,t ̄ ∼ Gama (n + 1 , −log(b) − log(r1) + c) Propuesta 3: αp ∼ exp(c) y λp|αp ∼ Gama(αp, b) Propuesta 4 (RWMH): αp = α + , con ∼ N(0, σ) y dejando λ fijo. con distribuciones a priori datos ...
la distribución posterior f(α, λ|t ̄) ∝ f(t ̄|α, λ)f(α, λ), considerando las siguientes propuestas:
random_line_split
GraphAlgo.py
import json import random import matplotlib.pyplot as plt from typing import List from GraphAlgoInterface import GraphAlgoInterface from DiGraph import DiGraph, GeoLocation from GraphInterface import GraphInterface from queue import Queue class GraphAlgo(GraphAlgoInterface): """ * This class represents a se...
def save_to_json(self, file_name: str) -> bool: """ Saves the graph in JSON format to a file @param file_name: The path to the out file @return: True if the save was successful, False o.w. """ flag = True with open(file_name, "w") as jsonFile: tr...
""" Loads a graph from a json file. @param file_name: The path to the json file @returns: True if the loading was successful, False o.w. """ flag = True try: with open(file_name, 'r') as jsonFile: load = json.load(jsonFile) grap...
identifier_body
GraphAlgo.py
import json import random import matplotlib.pyplot as plt from typing import List from GraphAlgoInterface import GraphAlgoInterface from DiGraph import DiGraph, GeoLocation from GraphInterface import GraphInterface from queue import Queue class GraphAlgo(GraphAlgoInterface): """ * This class represents a se...
(self): return self._graph.__repr__() def __str__(self): return self._graph.__str__()
__repr__
identifier_name
GraphAlgo.py
import json import random import matplotlib.pyplot as plt from typing import List from GraphAlgoInterface import GraphAlgoInterface from DiGraph import DiGraph, GeoLocation from GraphInterface import GraphInterface from queue import Queue class GraphAlgo(GraphAlgoInterface): """ * This class represents a se...
ans.reverse() # Inserted from return ans def reset_tags(self): for key in self._graph.get_all_v().keys(): node = self.get_graph().get_node(key) node.tag = 0 def set_weights_infinity(self): for key in self._graph.get_all_v().keys(): node = ...
ans.append(self._graph.get_node(src))
conditional_block
GraphAlgo.py
import json import random import matplotlib.pyplot as plt from typing import List from GraphAlgoInterface import GraphAlgoInterface from DiGraph import DiGraph, GeoLocation from GraphInterface import GraphInterface from queue import Queue class GraphAlgo(GraphAlgoInterface): """ * This class represents a se...
if self._graph is None or self._graph.get_node(id1) is None: return [] self.reset_tags() # This method executes a BFS and tag nodes so reset_tags() must be called. # Traverse the original graph, from node id1, and tag all reachable nodes ans = [] src = id1 # alias...
* Notes: If the graph is None or id1 is not in the graph, the function should return an empty list [] @param id1: The node id @return: The list of nodes in the SCC """
random_line_split
cvssV3.controller.js
(function () { 'use strict'; /** * Controller for the CVSS page, this is the only controller. * Dependencies: * - PlotService, used to invoke legacy js code used to display jqplot bar charts * - BaseDataFactory/BaseCalcService, used to handle Base selections and calculations * - T...
/** * Only used during Testing to test the calculations. This function can be activated via * some button click on a page using ng-click */ vm.testScores = function() { vm.testData = BaseCalcService.testCombs(); }; /** * Utilizes a filte...
{ vm.impactScore = 'NA'; vm.exploitScore = 'NA'; vm.baseScore = 'NA'; vm.temporalScore = 'NA'; vm.environScore = 'NA'; vm.modImpactScore = 'NA'; vm.overallScore = 'NA'; vm.cvssString = $sce.trustAsHtml('NA'); }
identifier_body
cvssV3.controller.js
(function () { 'use strict'; /** * Controller for the CVSS page, this is the only controller. * Dependencies: * - PlotService, used to invoke legacy js code used to display jqplot bar charts * - BaseDataFactory/BaseCalcService, used to handle Base selections and calculations * - T...
() { console.log('setScore()'); // do we have all the Base selections? if (!(vm.baseSelect.isReady())) { vm.showAlert = true; // show alert message stating Base selections must be made return; } // We are ready to com...
setScore
identifier_name
cvssV3.controller.js
(function () { 'use strict'; /** * Controller for the CVSS page, this is the only controller. * Dependencies: * - PlotService, used to invoke legacy js code used to display jqplot bar charts * - BaseDataFactory/BaseCalcService, used to handle Base selections and calculations * - T...
console.log('temporalSelect', vm.temportalSelect); console.log('environSelect', vm.environSelect); // check for Cve (Vuln) Id and set text/link in model for display vm.cveId = $sce.trustAsHtml(''); // default to nothing if (PlotService....
TemporalDataFactory.setValues(vectorStr); EnvironDataFactory.setValues(vectorStr); vm.setScore(); // call 'main' function to compute scores and display console.log('baseSelect', vm.baseSelect);
random_line_split
svg.go
package svgg import ( "fmt" "image/color" "math" "github.com/ajstarks/svgo" "github.com/vdobler/chart" ) // SvgGraphics implements BasicGraphics and uses the generic implementations type SvgGraphics struct { svg *svg.SVG w, h int font string fs int bg color.RGBA tx, ty int } // New creates...
func New(sp *svg.SVG, width, height int, font string, fontsize int, background color.RGBA) *SvgGraphics { if font == "" { font = "Helvetica" } if fontsize == 0 { fontsize = 12 } s := SvgGraphics{svg: sp, w: width, h: height, font: font, fs: fontsize, bg: background} return &s } // AddTo returns a new ImageGr...
random_line_split
svg.go
package svgg import ( "fmt" "image/color" "math" "github.com/ajstarks/svgo" "github.com/vdobler/chart" ) // SvgGraphics implements BasicGraphics and uses the generic implementations type SvgGraphics struct { svg *svg.SVG w, h int font string fs int bg color.RGBA tx, ty int } // New creates...
const n = 5 // default size a := int(n*f + 0.5) // standard b := int(n/2*f + 0.5) // smaller c := int(1.155*n*f + 0.5) // triangel long sist d := int(0.577*n*f + 0.5) // triangle short dist e := int(0.866*n*f + 0.5) // diagonal sg.svg.Gstyle(fmt.Sprintf("%s; stroke-width: %d", st, lw))...
{ lw = style.LineWidth }
conditional_block
svg.go
package svgg import ( "fmt" "image/color" "math" "github.com/ajstarks/svgo" "github.com/vdobler/chart" ) // SvgGraphics implements BasicGraphics and uses the generic implementations type SvgGraphics struct { svg *svg.SVG w, h int font string fs int bg color.RGBA tx, ty int } // New creates...
(x, y int, t string, align string, rot int, f chart.Font) { if len(align) == 1 { align = "c" + align } _, fh, _ := sg.FontMetrics(f) trans := "" if rot != 0 { trans = fmt.Sprintf("transform=\"rotate(%d %d %d)\"", -rot, x, y) } // Hack because baseline alignments in svg often broken switch align[0] { case...
Text
identifier_name
svg.go
package svgg import ( "fmt" "image/color" "math" "github.com/ajstarks/svgo" "github.com/vdobler/chart" ) // SvgGraphics implements BasicGraphics and uses the generic implementations type SvgGraphics struct { svg *svg.SVG w, h int font string fs int bg color.RGBA tx, ty int } // New creates...
func (sg *SvgGraphics) Scatter(points []chart.EPoint, plotstyle chart.PlotStyle, style chart.Style) { chart.GenericScatter(sg, points, plotstyle, style) /*********************************************** // First pass: Error bars ebs := style ebs.LineColor, ebs.LineWidth, ebs.LineStyle = ebs.FillColor, 1, chart.S...
{ lw := style.LineWidth if style.LineColor != nil { s = fmt.Sprintf("stroke:%s; ", hexcol(style.LineColor)) } s += fmt.Sprintf("stroke-width: %d; fill:none; ", lw) s += fmt.Sprintf("opacity: %s; ", alpha(style.LineColor)) if style.LineStyle != chart.SolidLine { s += fmt.Sprintf("stroke-dasharray:") for _, d...
identifier_body
transport_test.go
// Copyright (c) 2022 Uber Technologies, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge...
(t *testing.T) { type testStruct struct { msg string // identifiers defines all the Identifiers that will be used in // the actions up from so they can be generated and passed as deps identifiers []string // subscriberDefs defines all the Subscribers that will be used in // the actions up from so they ca...
TestTransport
identifier_name
transport_test.go
// Copyright (c) 2022 Uber Technologies, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge...
} func TestTransportClient(t *testing.T) { transport := NewTransport() assert.NotNil(t, transport.client) } func TestTransportClientOpaqueOptions(t *testing.T) { // Unfortunately the KeepAlive is obfuscated in the client, so we can't really // assert this worked. transport := NewTransport( KeepAlive(testtime...
{ t.Run(tt.msg, func(t *testing.T) { mockCtrl := gomock.NewController(t) defer mockCtrl.Finish() transport := NewTransport() defer transport.Stop() deps := TransportDeps{ PeerIdentifiers: createPeerIdentifierMap(tt.identifiers), Subscribers: CreateSubscriberMap(mockCtrl, tt.subscriberDefs...
conditional_block
transport_test.go
// Copyright (c) 2022 Uber Technologies, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge...
func TestTransport(t *testing.T) { type testStruct struct { msg string // identifiers defines all the Identifiers that will be used in // the actions up from so they can be generated and passed as deps identifiers []string // subscriberDefs defines all the Subscribers that will be used in // the action...
{ pids := make(map[string]peer.Identifier, len(ids)) for _, id := range ids { pids[id] = &testIdentifier{id} } return pids }
identifier_body
transport_test.go
// Copyright (c) 2022 Uber Technologies, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge...
InputSubscriberID: "s1", ExpectedErrType: peer.ErrTransportHasNoReferenceToPeer{}, }, }, }, { msg: "one retains, one release (from different subscriber)", identifiers: []string{"i1"}, subscriberDefs: []SubscriberDefinition{ {ID: "s1"}, {ID: "s2"}, }, actions: []Tran...
ReleaseAction{ InputIdentifierID: "i1",
random_line_split
data_feature_engineering.py
# *- coding: utf-8 -*- # ================================= # time: 2020.7.28 # author: @tangzhilin(Resigned) # function: 数据特征工程 # update: 8.18日 更改了数据的连接方式 # update: 9.08日 依照新的标签数据标准更改了代码 # ================================= import pandas as pd import numpy as np import re import jieba import jieba.analyse import warni...
identifier_name
data_feature_engineering.py
# *- coding: utf-8 -*- # ================================= # time: 2020.7.28 # author: @tangzhilin(Resigned) # function: 数据特征工程 # update: 8.18日 更改了数据的连接方式 # update: 9.08日 依照新的标签数据标准更改了代码 # ================================= import pandas as pd import numpy as np import re import jieba import jieba.analyse import warni...
more_labels_df = datas_labels.loc[datas_labels['labels'].str.contains(','), :] # 剔除多标签文本保留单标签文本 datas_labels.loc[datas_labels['labels'].str.contains(','), 'text'] = np.nan datas_labels.dropna(subset=['text'], inplace=True) more_labels_df['labels'] = more_labels_df['labels'].apply( lambda x...
# 找到并将多标签文本单独拎出来
conditional_block
data_feature_engineering.py
# *- coding: utf-8 -*- # ================================= # time: 2020.7.28 # author: @tangzhilin(Resigned) # function: 数据特征工程 # update: 8.18日 更改了数据的连接方式 # update: 9.08日 依照新的标签数据标准更改了代码 # ================================= import pandas as pd import numpy as np import re import jieba import jieba.analyse import warni...
mark_words = ['没问题', '不客气', '仅限', '有的', '是的', '好的', '可以', '不了', '不到', '谢谢', '对的', '没空', '不错', '没车', '到店', '没呢', '清楚', '明白', '确认', '没法', '不到', '了解', '都是', '还没', '比较', '地址', '不多', '没有', '放心', '嗯', '恩', '行', '没', '有'] # 针对标签...
dex index = index - 1 index = indexs + 1 while end_index == -1.0: if datas.iloc[index].solve != -1.0: end_index = index index = index + 1 text = '' for i in range(start_index, end_index + 1): ...
identifier_body
data_feature_engineering.py
# *- coding: utf-8 -*- # ================================= # time: 2020.7.28 # author: @tangzhilin(Resigned) # function: 数据特征工程 # update: 8.18日 更改了数据的连接方式 # update: 9.08日 依照新的标签数据标准更改了代码 # ================================= import pandas as pd import numpy as np import re import jieba import jieba.analyse import warni...
}) id_count_words.columns = ['count_pos_word'] id_count_words.reset_index(inplace=True) id_count_words = pd.DataFrame(id_count_words) datas = pd.merge(datas, id_count_words[['id', 'count_pos_word']], on=['id'], how='left') # 连接 针对原始训练文本处理 # datas['labels'].fillna("remo...
# 以文本id为维度, 获取文本中出了几次 正向词
random_line_split
Menu.ts
import * as Async from "@typescene/core/Async"; import { Page, Screen, Component, PointerEvent, Menu, Style } from "@typescene/core/UI"; import * as DOM from "./DOM"; import { DOMBlock } from "./DOM/DOMBlock"; import { Renderer as LabelRenderer } from "./Renderers/Controls/Label"; /** Mouse hover timeout after which t...
}); // update element height estimate after display this.Rendered.connectOnce(out => { Async.sleep(30).then(() => { var elt: HTMLElement = out.element; if (elt) { var max = 0; for (var li of <any>elt.querySelec...
{ // create a text option, add click handler var a = document.createElement("a"); a.className = "dropdown-item"; a.href = "#"; if (option.disabled) { a.className += " disabled"; a.style.cursor = "defa...
conditional_block
Menu.ts
import * as Async from "@typescene/core/Async"; import { Page, Screen, Component, PointerEvent, Menu, Style } from "@typescene/core/UI"; import * as DOM from "./DOM"; import { DOMBlock } from "./DOM/DOMBlock"; import { Renderer as LabelRenderer } from "./Renderers/Controls/Label"; /** Mouse hover timeout after which t...
(options: Menu.Option[] = []) { super(); this.options = options; // create UL node var menu = document.createElement("ul"); menu.style.cssFloat = "none"; menu.style.position = "static"; menu.style.boxShadow = "none"; menu.style.margin = "0"; menu....
constructor
identifier_name
Menu.ts
import * as Async from "@typescene/core/Async"; import { Page, Screen, Component, PointerEvent, Menu, Style } from "@typescene/core/UI"; import * as DOM from "./DOM"; import { DOMBlock } from "./DOM/DOMBlock"; import { Renderer as LabelRenderer } from "./Renderers/Controls/Label"; /** Mouse hover timeout after which t...
super(); this.options = options; // create UL node var menu = document.createElement("ul"); menu.style.cssFloat = "none"; menu.style.position = "static"; menu.style.boxShadow = "none"; menu.style.margin = "0"; menu.className = "dropdown-menu show"...
constructor(options: Menu.Option[] = []) {
random_line_split
Menu.ts
import * as Async from "@typescene/core/Async"; import { Page, Screen, Component, PointerEvent, Menu, Style } from "@typescene/core/UI"; import * as DOM from "./DOM"; import { DOMBlock } from "./DOM/DOMBlock"; import { Renderer as LabelRenderer } from "./Renderers/Controls/Label"; /** Mouse hover timeout after which t...
private _addLinkHoverHandler(elt: HTMLAnchorElement, i: number) { var option = this.options[i]; elt.onmouseover = () => { // clear timer to show/hide (other) sub menu if (_hoverTimer) { window.clearTimeout(_hoverTimer); _hoverTimer = undefine...
{ var option = this.options[i]; elt.onclick = event => { event.preventDefault(); if (this._isBase) Screen.remove(this); this._resolver(option.key || (i + 1)); } }
identifier_body
wallpaper.rs
use std::ffi::{OsStr, OsString}; use std::iter::once; use std::os::windows::ffi::{OsStrExt, OsStringExt}; use std::ptr::null_mut; use std::process::Command; use serde::{Serialize, Deserialize}; use winapi::shared::windef::{HWND, RECT, PPOINT, POINT}; use winapi::shared::minwindef::LPARAM; use winapi::um::errhandlinga...
} if handle.is_null() { eprintln!("Cannot find handle using selector: {:?}", selector); return false; } self.add_window_by_handle(handle, properties) } pub fn remove_wallpaper(&self, hwnd: HWND) { // TODO ensure that provided handle is ...
{ break; }
conditional_block
wallpaper.rs
use std::ffi::{OsStr, OsString}; use std::iter::once; use std::os::windows::ffi::{OsStrExt, OsStringExt}; use std::ptr::null_mut; use std::process::Command; use serde::{Serialize, Deserialize}; use winapi::shared::windef::{HWND, RECT, PPOINT, POINT}; use winapi::shared::minwindef::LPARAM; use winapi::um::errhandlinga...
fn to_wide(s: &str) -> Vec<u16> { OsStr::new(s).encode_wide().chain(once(0)).collect() } pub fn get_window_name(hwnd: HWND) -> String { use winapi::um::winuser::{GetWindowTextLengthW, GetWindowTextW}; if hwnd.is_null() { panic!("Invalid HWND"); } let text = unsafe { let text_len...
{ use winapi::um::winuser::FindWindowW; unsafe { FindWindowW(to_wide(class).as_ptr(), null_mut()) } }
identifier_body
wallpaper.rs
use std::ffi::{OsStr, OsString}; use std::iter::once; use std::os::windows::ffi::{OsStrExt, OsStringExt}; use std::ptr::null_mut; use std::process::Command; use serde::{Serialize, Deserialize}; use winapi::shared::windef::{HWND, RECT, PPOINT, POINT}; use winapi::shared::minwindef::LPARAM; use winapi::um::errhandlinga...
let wnd_class = { let wnd_class: &mut [u16] = &mut [0; 512]; GetClassNameW(wnd, wnd_class.as_mut_ptr(), wnd_class.len() as i32 - 1); OsString::from_wide(&wnd_class[..wnd_class.iter().position(|&c| c == 0).unwrap()]) }; if wallpaper == wnd || wnd_class == "Shell_TrayWnd" { ep...
WS_EX_DLGMODALFRAME, WS_EX_COMPOSITED, WS_EX_WINDOWEDGE, WS_EX_CLIENTEDGE, WS_EX_LAYERED, WS_EX_STATICEDGE, WS_EX_TOOLWINDOW, WS_EX_APPWINDOW, };
random_line_split
wallpaper.rs
use std::ffi::{OsStr, OsString}; use std::iter::once; use std::os::windows::ffi::{OsStrExt, OsStringExt}; use std::ptr::null_mut; use std::process::Command; use serde::{Serialize, Deserialize}; use winapi::shared::windef::{HWND, RECT, PPOINT, POINT}; use winapi::shared::minwindef::LPARAM; use winapi::um::errhandlinga...
(wnd: HWND, data: LPARAM) -> i32 { let mut data = data as *mut Data; unsafe { let mut this_pid: DWORD = 0; GetWindowThreadProcessId(wnd, &mut this_pid as LPDWORD); if this_pid == (*data).pid { (*data).handle = wnd; return 0; ...
enum_windows
identifier_name
tile.rs
//! Representation of tiles //! //! Items within a hex are usually given in hexagon-space. This is a 3D space //! where the axis are at 60° to each other. An example of the axis is given //! below. Note that the orientation of the axis when the hexagons are oriented //! with horizontal edges differs from when the hexag...
} impl TileSpec for TileDefinition { fn paths(&self) -> Vec<Path> { self.paths.clone() } fn cities(&self) -> Vec<City> { self.cities.clone() } fn stops(&self) -> Vec<Stop> { self.stops.clone() } fn is_lawson(&self) -> bool { self.is_lawson } fn color(&self) -> colors::Color { colors::GROUND } f...
TileDefinition { name: "NoName".to_string(), paths: vec![], cities: vec![], stops: vec![], is_lawson: false, text: vec![], } }
identifier_body
tile.rs
//! Representation of tiles //! //! Items within a hex are usually given in hexagon-space. This is a 3D space //! where the axis are at 60° to each other. An example of the axis is given //! below. Note that the orientation of the axis when the hexagons are oriented //! with horizontal edges differs from when the hexag...
{ Rough, Hill, Mountain, River, Marsh, } /// Reads and parses all tile definitions in ./tiledefs/ pub fn definitions(options: &super::Options) -> HashMap<String, TileDefinition> { println!("Reading tile definitions from file..."); let def_files: Vec<PathBuf> = match fs::read_dir("ti...
errainType
identifier_name
tile.rs
//! Representation of tiles //! //! Items within a hex are usually given in hexagon-space. This is a 3D space //! where the axis are at 60° to each other. An example of the axis is given //! below. Note that the orientation of the axis when the hexagons are oriented //! with horizontal edges differs from when the hexag...
//! * `C`: center of hexagon //! //! ![Coordinate system](../../../../axes.svg) extern crate nalgebra as na; extern crate serde_yaml; use std::collections::HashMap; use std::f64::consts::PI; use std::fs; use std::path::PathBuf; use std::fs::File; use std::process; /// Standard colors that can be used pub mod colors...
random_line_split
noxAlarmProcess.py
# coding: utf-8 from gevent import monkey monkey.patch_all() from os.path import abspath as abspath # Convert relative to absolute path from os.path import dirname as dirname # Name of the last directory of a path from os.path import basename as basename from os.path import join as join # Detect ENV type from...
nt = 'stop' logger.info('state is %s' % (event)) self.push_socket_event(event) color = NoxAlarm.colors[NoxAlarm.events.index(event)] self.make_DBLog("event", event, color) def detection(self): event = 'detection' logger.info('state is %s' % (event)) self.push...
eve
identifier_name
noxAlarmProcess.py
# coding: utf-8 from gevent import monkey monkey.patch_all() from os.path import abspath as abspath # Convert relative to absolute path from os.path import dirname as dirname # Name of the last directory of a path from os.path import basename as basename from os.path import join as join # Detect ENV type from...
signal.signal(signal.SIGTERM, self.exit_from_signals) # Supervisor Exit code (15) self.init_socket() self.init_config() self.init_statemachine() self.init_state() # Read inputs and Set state after init def __str__(self): out = '' out ...
# KeyboardInterrupt (SIGINT) managed directly in main loop
random_line_split
noxAlarmProcess.py
# coding: utf-8 from gevent import monkey monkey.patch_all() from os.path import abspath as abspath # Convert relative to absolute path from os.path import dirname as dirname # Name of the last directory of a path from os.path import basename as basename from os.path import join as join # Detect ENV type from...
equest(self): """ Check if a request is received and process it Request can be Command (start, stop) Request can be "Status update" requested by web app """ try: payload = self.SUB_COMMAND.recv_string(flags=zmq.NOBLOCK) topic, command = payload.split() ...
alue == 0): self.any_to_off() def receive_r
conditional_block
noxAlarmProcess.py
# coding: utf-8 from gevent import monkey monkey.patch_all() from os.path import abspath as abspath # Convert relative to absolute path from os.path import dirname as dirname # Name of the last directory of a path from os.path import basename as basename from os.path import join as join # Detect ENV type from...
__name__ == '__main__': """ Init nox Alarm Statemachine and run infinite loop Called from console for debug Called and managed by supervisor for production """ if DEBUG: logger.warning("DEBUG mode ON") else: logger.debug("DEBUG mode OFF") nox = NoxAlarm() logger.info("Pro...
est is received and process it Request can be Command (start, stop) Request can be "Status update" requested by web app """ try: payload = self.SUB_COMMAND.recv_string(flags=zmq.NOBLOCK) topic, command = payload.split() if (topic == zmq_socket_config...
identifier_body
account_transform.rs
//! Functionality for modifying accounts according to actions. use std::{collections::BTreeMap, marker::PhantomData}; use anyhow::bail; use async_trait::*; use ed25519_dalek::Signer; use serde::{de::DeserializeOwned, Deserialize, Serialize}; use crate::blockdata::{Action, MainBlock, SendInfo}; use crate::crypto::{has...
let recipient: HashCode = get_arg(&action.args, 0)?; let send_amount: u128 = get_arg(&action.args, 1)?; let initialize_spec: Option<Hash<Vec<u8>>> = get_arg(&action.args, 2)?; let message: Vec<u8> = get_arg(&action.args, 3)?; verify_signature_argument(at.this_account, action, 4)...
{ bail!("send can't initialize an account"); }
conditional_block
account_transform.rs
//! Functionality for modifying accounts according to actions. use std::{collections::BTreeMap, marker::PhantomData}; use anyhow::bail; use async_trait::*; use ed25519_dalek::Signer; use serde::{de::DeserializeOwned, Deserialize, Serialize}; use crate::blockdata::{Action, MainBlock, SendInfo}; use crate::crypto::{has...
pub fn from_path(path: HexPath) -> TypedDataField<T> { TypedDataField { path, phantom: PhantomData, } } } /// Account balance field. pub fn field_balance() -> TypedDataField<u128> { TypedDataField::from_path(bytes_to_path(b"balance")) } /// Account stake field. pub ...
impl<T> TypedDataField<T> { /// Creates a `TypedDataField` given a path.
random_line_split
account_transform.rs
//! Functionality for modifying accounts according to actions. use std::{collections::BTreeMap, marker::PhantomData}; use anyhow::bail; use async_trait::*; use ed25519_dalek::Signer; use serde::{de::DeserializeOwned, Deserialize, Serialize}; use crate::blockdata::{Action, MainBlock, SendInfo}; use crate::crypto::{has...
/// A context providing operations related to transforming an account (e.g. /// running actions). pub struct AccountTransform<'a, HL: HashLookup> { /// The `HashLookup` used to look up previous account data. pub hl: &'a HL, /// Whether this account is initializing. pub is_initializing: bool, /// T...
{ let mut path = bytes_to_path(b"received"); path.0.extend(&bytes_to_path(&send.code).0); TypedDataField::from_path(path) }
identifier_body
account_transform.rs
//! Functionality for modifying accounts according to actions. use std::{collections::BTreeMap, marker::PhantomData}; use anyhow::bail; use async_trait::*; use ed25519_dalek::Signer; use serde::{de::DeserializeOwned, Deserialize, Serialize}; use crate::blockdata::{Action, MainBlock, SendInfo}; use crate::crypto::{has...
<'a, HL: HashLookup> { /// The `HashLookup` used to look up previous account data. pub hl: &'a HL, /// Whether this account is initializing. pub is_initializing: bool, /// The account being transformed. pub this_account: HashCode, /// The hash code of the last main block. pub last_main: ...
AccountTransform
identifier_name
runsex_final_VIDEO_Aug2018.py
#codigo que corre sextractor para una lista de imagenes filtrandolas import glob import numpy as np #import pyfits as pf import math import os #import time import matplotlib.pyplot as plt from scipy import misc from scipy import ndimage from astropy.io import fits #start = time.clock() filt = 'Ks'#filter band field ...
(pos_ver, pos_hor, img, lado): #if verbose: print 'Radius %i' % radius counts=np.sum(img[pos_ver : pos_ver + lado, pos_hor : pos_hor + lado]) numpix=lado**2 return counts,numpix def get_error_model(img,seg,apmin,apmax,numap): hdufits_ima = fits.open(img) imag_data = hdufits_ima[0].data ...
get_flux
identifier_name
runsex_final_VIDEO_Aug2018.py
#codigo que corre sextractor para una lista de imagenes filtrandolas import glob import numpy as np #import pyfits as pf import math import os #import time import matplotlib.pyplot as plt from scipy import misc from scipy import ndimage from astropy.io import fits #start = time.clock() filt = 'Ks'#filter band field ...
empty_ap=np.array(empty_ap) #plt.hist(empty_ap,50) #plt.savefig(image+'_hist_'+str(lado)+'.png') #plt.close('all') empty_ap2=empty_ap[np.where((empty_ap<(np.mean(empty_ap)+3*np.std(empty_ap))) & (empty_ap>(np.mean(empty_ap)-3*np.std(empty_ap))))] return (np.median(empty_ap2),np.mean(empty_...
counts,npix=get_flux(random_center[0], random_center[1], imag_data, int(lado)) empty_ap.append(counts) n += 1 matrix_used[random_center[0]:random_center[0]+lado, random_center[1]:random_center[1] + lado ]=22
conditional_block
runsex_final_VIDEO_Aug2018.py
#codigo que corre sextractor para una lista de imagenes filtrandolas import glob import numpy as np #import pyfits as pf import math import os #import time import matplotlib.pyplot as plt from scipy import misc from scipy import ndimage from astropy.io import fits #start = time.clock() filt = 'Ks'#filter band field ...
new_cols=fits.ColDefs([c1,c2,c3,c4,c5]) #thdu=fits.new_table(orig_cols+new_cols) thdu = fits.BinTableHDU.from_columns(orig_cols + new_cols) thdu.writeto("temp/"+list_img_name[i]+"_"+str(j)+"_"+filt+".cat2.fits") #print...
random_line_split
runsex_final_VIDEO_Aug2018.py
#codigo que corre sextractor para una lista de imagenes filtrandolas import glob import numpy as np #import pyfits as pf import math import os #import time import matplotlib.pyplot as plt from scipy import misc from scipy import ndimage from astropy.io import fits #start = time.clock() filt = 'Ks'#filter band field ...
def get_flux(pos_ver, pos_hor, img, lado): #if verbose: print 'Radius %i' % radius counts=np.sum(img[pos_ver : pos_ver + lado, pos_hor : pos_hor + lado]) numpix=lado**2 return counts,numpix def get_error_model(img,seg,apmin,apmax,numap): hdufits_ima = fits.open(img) imag_data = hdufits_...
hdufits_ima = fits.open(image) imag_data = hdufits_ima[0].data ver_max,hor_max = imag_data.shape hdufits_seg = fits.open(seg) segm_data = hdufits_seg[0].data filtered_segm_data=ndimage.gaussian_filter(segm_data, 2) segm_mask = (filtered_segm_data > 0) #segm_mask = (segm_data > 0) n...
identifier_body
github.go
package github import ( "context" "fmt" "net/http" "sort" "strings" "sync" "time" "github.com/google/go-github/v53/github" "github.com/lindell/multi-gitter/internal/scm" "github.com/pkg/errors" log "github.com/sirupsen/logrus" "golang.org/x/oauth2" ) type Config struct { Token string Base...
_, err = retryWithoutReturn(ctx, func() (*github.Response, error) { return g.ghClient.Git.DeleteRef(ctx, pr.prOwnerName, pr.prRepoName, fmt.Sprintf("heads/%s", pr.branchName)) }) return err } // ForkRepository forks a repository. If newOwner is empty, fork on the logged in user func (g *Github) ForkRepository(c...
{ return err }
conditional_block
github.go
package github import ( "context" "fmt" "net/http" "sort" "strings" "sync" "time" "github.com/google/go-github/v53/github" "github.com/lindell/multi-gitter/internal/scm" "github.com/pkg/errors" log "github.com/sirupsen/logrus" "golang.org/x/oauth2" ) type Config struct { Token string Base...
(ctx context.Context, repo scm.Repository, branchName string) (scm.PullRequest, error) { r := repo.(repository) headOwner, err := g.headOwner(ctx, r.ownerName) if err != nil { return nil, err } prs, _, err := retry(ctx, func() ([]*github.PullRequest, *github.Response, error) { return g.ghClient.PullRequests....
GetOpenPullRequest
identifier_name
github.go
package github import ( "context" "fmt" "net/http" "sort" "strings" "sync" "time" "github.com/google/go-github/v53/github" "github.com/lindell/multi-gitter/internal/scm" "github.com/pkg/errors" log "github.com/sirupsen/logrus" "golang.org/x/oauth2" ) type Config struct { Token string Base...
repos = append(repos, newRepo) } return repos, nil } func (g *Github) getRepositories(ctx context.Context) ([]*github.Repository, error) { allRepos := []*github.Repository{} for _, org := range g.Organizations { repos, err := g.getOrganizationRepositories(ctx, org) if err != nil { return nil, errors.Wra...
if err != nil { return nil, err }
random_line_split
github.go
package github import ( "context" "fmt" "net/http" "sort" "strings" "sync" "time" "github.com/google/go-github/v53/github" "github.com/lindell/multi-gitter/internal/scm" "github.com/pkg/errors" log "github.com/sirupsen/logrus" "golang.org/x/oauth2" ) type Config struct { Token string Base...
// ForkRepository forks a repository. If newOwner is empty, fork on the logged in user func (g *Github) ForkRepository(ctx context.Context, repo scm.Repository, newOwner string) (scm.Repository, error) { r := repo.(repository) g.modLock() defer g.modUnlock() createdRepo, _, err := retry(ctx, func() (*github.Rep...
{ pr := pullReq.(pullRequest) g.modLock() defer g.modUnlock() _, _, err := retry(ctx, func() (*github.PullRequest, *github.Response, error) { return g.ghClient.PullRequests.Edit(ctx, pr.ownerName, pr.repoName, pr.number, &github.PullRequest{ State: &[]string{"closed"}[0], }) }) if err != nil { return e...
identifier_body
server.rs
// Copyright Materialize, Inc. and contributors. All rights reserved. // // Use of this software is governed by the Business Source License // included in the LICENSE file. // // As of the Change Date specified in that file, in accordance with // the Business Source License, use of this software will be governed // by ...
async fn build_timely( user_worker_config: Worker, config: TimelyConfig, epoch: ClusterStartupEpoch, persist_clients: Arc<PersistClientCache>, tracing_handle: Arc<TracingHandle>, tokio_executor: Handle, ) -> Result<TimelyContainer<C, R, Worker::Activatable>, Error...
worker: worker_config, } }
random_line_split
server.rs
// Copyright Materialize, Inc. and contributors. All rights reserved. // // Use of this software is governed by the Business Source License // included in the LICENSE file. // // As of the Change Date specified in that file, in accordance with // the Business Source License, use of this software will be governed // by ...
<Worker, C, R>( config: ClusterConfig, worker_config: Worker, ) -> Result< ( TimelyContainerRef<C, R, Worker::Activatable>, impl Fn() -> Box<ClusterClient<PartitionedClient<C, R, Worker::Activatable>, Worker, C, R>>, ), Error, > where C: Send + 'static, R: Send + 'static, ...
serve
identifier_name
model.ts
import * as _ from 'underscore'; import {EventEmitter} from '@angular/core'; import * as mixin from './mixin'; import {IAttributes, IEvent} from './interface'; import {Synchronizable} from './synchronizable'; import {Observable} from 'rxjs/Rx'; export class Model<A extends IAttributes> extends Synchronizable { publi...
this.cid = _.uniqueId(this.cidPrefix); if (options.parse) attrs = this.parse(attrs, options) || <A> {}; let defaults = _.result(this, 'defaults'); attrs = _.defaults(_.extend({}, defaults, attrs), defaults); this.set(attrs, options); } // Attributes protected attributes: A = <A> {}; protect...
super(options); // For clearing status when destroy model on collection this.event$.filter(e => e.topic == 'destroy') .subscribe(e => this._resetStatus());
random_line_split
model.ts
import * as _ from 'underscore'; import {EventEmitter} from '@angular/core'; import * as mixin from './mixin'; import {IAttributes, IEvent} from './interface'; import {Synchronizable} from './synchronizable'; import {Observable} from 'rxjs/Rx'; export class Model<A extends IAttributes> extends Synchronizable { publi...
validate(attrs, options) { } // Create a new model with identical attributes to this one. clone() : Model<A> { return this.service.createModel(this.attributes); } // A model is new if it has never been saved to the server, and lacks an id. isNew() : boolean { return !this.has(this.idAttribute)...
{ return resp; }
identifier_body
model.ts
import * as _ from 'underscore'; import {EventEmitter} from '@angular/core'; import * as mixin from './mixin'; import {IAttributes, IEvent} from './interface'; import {Synchronizable} from './synchronizable'; import {Observable} from 'rxjs/Rx'; export class Model<A extends IAttributes> extends Synchronizable { publi...
else { (attrs = {})[key] = val; } // Run validation. if (!this._validate(attrs, options)) return this; // Extract attributes and options. var unset = options.unset; var silent = options.silent; var changes = []; var changing = this._changing; this._changing = t...
{ attrs = key; options = val; }
conditional_block
model.ts
import * as _ from 'underscore'; import {EventEmitter} from '@angular/core'; import * as mixin from './mixin'; import {IAttributes, IEvent} from './interface'; import {Synchronizable} from './synchronizable'; import {Observable} from 'rxjs/Rx'; export class Model<A extends IAttributes> extends Synchronizable { publi...
(options) { return this._validate({}, _.extend({}, options, {validate: true})); } // Run validation against the next complete set of model attributes, // returning `true` if all is well. Otherwise, fire an `"invalid"` event. _validate(attrs, options) { if (!options.validate || !this.validate) return tr...
isValid
identifier_name