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
utpgo.go
// Copyright (c) 2021 Storj Labs, Inc. // Copyright (c) 2010 BitTorrent, Inc. // See LICENSE for copying information. package utp import ( "context" "crypto/tls" "errors" "fmt" "io" "net" "os" "runtime/pprof" "sync" "syscall" "time" "github.com/go-logr/logr" "storj.io/utp-go/buffers" "storj.io/utp-go/...
a []byte, destAddr *net.UDPAddr) { sm.baseConnLock.Lock() defer sm.baseConnLock.Unlock() sm.mx.IsIncomingUTP(gotIncomingConnectionCallback, packetSendCallback, sm, data, destAddr) } func (sm *socketManager) checkTimeouts() { sm.baseConnLock.Lock() defer sm.baseConnLock.Unlock() sm.mx.CheckTimeouts() } func (sm ...
essIncomingPacket(dat
identifier_name
utpgo.go
// Copyright (c) 2021 Storj Labs, Inc. // Copyright (c) 2010 BitTorrent, Inc. // See LICENSE for copying information. package utp import ( "context" "crypto/tls" "errors" "fmt" "io" "net" "os" "runtime/pprof" "sync" "syscall" "time" "github.com/go-logr/logr" "storj.io/utp-go/buffers" "storj.io/utp-go/...
func (u *utpSocket) LocalAddr() net.Addr { return (*Addr)(u.localAddr) } type socketManager struct { mx *libutp.SocketMultiplexer logger logr.Logger udpSocket *net.UDPConn // this lock should be held when invoking any libutp functions or methods // that are not thread-safe or which themselves might in...
close(c.connectChan) } }
random_line_split
utpgo.go
// Copyright (c) 2021 Storj Labs, Inc. // Copyright (c) 2010 BitTorrent, Inc. // See LICENSE for copying information. package utp import ( "context" "crypto/tls" "errors" "fmt" "io" "net" "os" "runtime/pprof" "sync" "syscall" "time" "github.com/go-logr/logr" "storj.io/utp-go/buffers" "storj.io/utp-go/...
func (c *Conn) WriteContext(ctx context.Context, buf []byte) (n int, err error) { c.stateLock.Lock() if c.writePending { c.stateLock.Unlock() return 0, buffers.WriterAlreadyWaitingErr } c.writePending = true deadline := c.writeDeadline c.stateLock.Unlock() if err != nil { if err == io.EOF { // remote s...
return c.WriteContext(context.Background(), buf) }
identifier_body
chain_spec.rs
// Copyright 2018-2019 Parity Technologies (UK) Ltd. // This file is part of Substrate. // Substrate is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) a...
/// IceFrog testnet config generator pub fn gen_icefrog_testnet_config() -> ChainSpec { fn icefrog_config_genesis() -> GenesisConfig { darwinia_genesis( vec![ ( hex!["be3fd892bf0e2b33dbfcf298c99a9f71e631a57af6c017dc5ac078c5d5b3494b"].into(), //stash hex!["70bf51d123581d6e51af70b342cac75ae0a0fc71d1...
{ fn icefrog_config_genesis() -> GenesisConfig { darwinia_genesis( vec![ get_authority_keys_from_seed("Alice"), get_authority_keys_from_seed("Bob"), ], hex!["a60837b2782f7ffd23e95cd26d1aa8d493b8badc6636234ccd44db03c41fcc6c"].into(), // 5FpQFHfKd1xQ9HLZLQoG1JAQSCJoUEVBELnKsKNcuRLZejJR vec![ he...
identifier_body
chain_spec.rs
// Copyright 2018-2019 Parity Technologies (UK) Ltd. // This file is part of Substrate. // Substrate is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) a...
; const RING_ENDOWMENT: Balance = 20_000_000 * COIN; const KTON_ENDOWMENT: Balance = 10 * COIN; const STASH: Balance = 1000 * COIN; GenesisConfig { frame_system: Some(SystemConfig { code: WASM_BINARY.to_vec(), changes_trie_config: Default::default(), }), pallet_indices: Some(IndicesConfig { ids: en...
{ vec![initial_authorities[0].clone().1, initial_authorities[1].clone().1] }
conditional_block
chain_spec.rs
// Copyright 2018-2019 Parity Technologies (UK) Ltd. // This file is part of Substrate. // Substrate is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) a...
stakers: initial_authorities .iter() .map(|x| (x.0.clone(), x.1.clone(), STASH, StakerStatus::Validator)) .collect(), invulnerables: initial_authorities.iter().map(|x| x.0.clone()).collect(), slash_reward_fraction: Perbill::from_percent(10), ..Default::default() }), } } /// Staging testnet c...
pallet_staking: Some(StakingConfig { current_era: 0, validator_count: initial_authorities.len() as u32 * 2, minimum_validator_count: initial_authorities.len() as u32,
random_line_split
chain_spec.rs
// Copyright 2018-2019 Parity Technologies (UK) Ltd. // This file is part of Substrate. // Substrate is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) a...
() -> GenesisConfig { darwinia_genesis( vec![ get_authority_keys_from_seed("Alice"), get_authority_keys_from_seed("Bob"), ], hex!["a60837b2782f7ffd23e95cd26d1aa8d493b8badc6636234ccd44db03c41fcc6c"].into(), // 5FpQFHfKd1xQ9HLZLQoG1JAQSCJoUEVBELnKsKNcuRLZejJR vec![ hex!["a60837b2782f7ffd23e95cd2...
icefrog_config_genesis
identifier_name
mnist_benchmark.py
# Copyright 2017 PerfKitBenchmarker Authors. All rights reserved. # # 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 appli...
return samples def MakeSamplesFromEvalOutput(metadata, output, elapsed_seconds): """Create a sample containing evaluation metrics. Args: metadata: dict contains all the metadata that reports. output: string, command output elapsed_seconds: float, elapsed seconds from saved checkpoint. Example o...
global_step_sec = get_mean(regex_util.ExtractAllMatches( r'global_step/sec: (\S+)', output)) samples.append(sample.Sample( 'Global Steps Per Second', global_step_sec, 'global_steps/sec', metadata_copy)) examples_sec = global_step_sec * metadata['train_batch_size'] if 'examples/sec: '...
conditional_block
mnist_benchmark.py
# Copyright 2017 PerfKitBenchmarker Authors. All rights reserved. # # 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 appli...
metadata_with_index = copy.deepcopy(metadata) metadata_with_index['index'] = index samples.append(sample.Sample(metric, float(value), unit, metadata_with_index)) return samples def MakeSamplesFromTrainOutput(metadata, output, elapsed_seconds, step): """Create a sample ...
""" matches = regex_util.ExtractAllMatches(regex, output) samples = [] for index, value in enumerate(matches):
random_line_split
mnist_benchmark.py
# Copyright 2017 PerfKitBenchmarker Authors. All rights reserved. # # 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 appli...
(benchmark_spec): """Update the benchmark_spec with supplied command line flags. Args: benchmark_spec: benchmark specification to update """ benchmark_spec.data_dir = FLAGS.mnist_data_dir benchmark_spec.iterations = FLAGS.tpu_iterations benchmark_spec.gcp_service_account = FLAGS.gcp_service_account b...
_UpdateBenchmarkSpecWithFlags
identifier_name
mnist_benchmark.py
# Copyright 2017 PerfKitBenchmarker Authors. All rights reserved. # # 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 appli...
def Run(benchmark_spec): """Run MNIST on the cluster. Args: benchmark_spec: The benchmark specification. Contains all data that is required to run the benchmark. Returns: A list of sample.Sample objects. """ _UpdateBenchmarkSpecWithFlags(benchmark_spec) vm = benchmark_spec.vms[0] if ...
"""Create a sample containing evaluation metrics. Args: metadata: dict contains all the metadata that reports. output: string, command output elapsed_seconds: float, elapsed seconds from saved checkpoint. Example output: perfkitbenchmarker/tests/linux_benchmarks/mnist_benchmark_test.py Returns:...
identifier_body
ext.rs
//! Safe wrapper around externalities invokes. use wasm_std::{ self, types::{H256, U256, Address} }; /// Generic wasm error #[derive(Debug)] pub struct Error; mod external { extern "C" { // Various call variants /// Direct/classic call. /// Corresponds to "CALL" opcode in EVM ...
/// Get the block's timestamp /// /// It can be viewed as an output of Unix's `time()` function at /// current block's inception. pub fn timestamp() -> u64 { unsafe { external::timestamp() as u64 } } /// Get the block's number /// /// This value represents number of ancestor blocks. /// The genesis block has a num...
unsafe { fetch_address(|x| external::coinbase(x) ) } }
identifier_body
ext.rs
//! Safe wrapper around externalities invokes. use wasm_std::{ self, types::{H256, U256, Address} }; /// Generic wasm error #[derive(Debug)] pub struct Error; mod external { extern "C" { // Various call variants /// Direct/classic call. /// Corresponds to "CALL" opcode in EVM ...
else { Err(Error) } } } /// Returns hash of the given block or H256::zero() /// /// Only works for 256 most recent blocks excluding current /// Returns H256::zero() in case of failure pub fn block_hash(block_number: u64) -> H256 { let mut res = H256::zero(); unsafe { external::...
{ Ok(()) }
conditional_block
ext.rs
//! Safe wrapper around externalities invokes. use wasm_std::{ self, types::{H256, U256, Address} }; /// Generic wasm error #[derive(Debug)] pub struct Error; mod external { extern "C" { // Various call variants /// Direct/classic call. /// Corresponds to "CALL" opcode in EVM ...
if external::create( endowment_arr.as_ptr(), code.as_ptr(), code.len() as u32, (&mut result).as_mut_ptr() ) == 0 { Ok(result) } else { Err(Error) } } } #[cfg(feature = "kip4")] /// Create a new account with the ...
random_line_split
ext.rs
//! Safe wrapper around externalities invokes. use wasm_std::{ self, types::{H256, U256, Address} }; /// Generic wasm error #[derive(Debug)] pub struct Error; mod external { extern "C" { // Various call variants /// Direct/classic call. /// Corresponds to "CALL" opcode in EVM ...
-> u64 { unsafe { external::blocknumber() as u64 } } /// Get the block's difficulty. pub fn difficulty() -> U256 { unsafe { fetch_u256(|x| external::difficulty(x) ) } } /// Get the block's gas limit. pub fn gas_limit() -> U256 { unsafe { fetch_u256(|x| external::gaslimit(x) ) } } #[cfg(feature = "kip6")...
ock_number()
identifier_name
networking.py
from __future__ import division import struct from cStringIO import StringIO #import pyraknet #from pyraknet import PacketTypes, PacketReliability, PacketPriority import socket, traceback, os, sys, threading from Queue import Queue from unit import Unit from buildings.igloo import Igloo from player import Player im...
(self): w = Writer() w.single("H", self.dmo_id) w.string(self.image_name) w.single("HH", *self.position) w.single("B", (self.hidden << 0) + (self.obstruction << 1)) w.string(self.minimapimage) return w.data.getvalue() @classmethod def from_stream(cls, stre...
pack
identifier_name
networking.py
from __future__ import division import struct from cStringIO import StringIO #import pyraknet #from pyraknet import PacketTypes, PacketReliability, PacketPriority import socket, traceback, os, sys, threading from Queue import Queue from unit import Unit from buildings.igloo import Igloo from player import Player im...
type_id = 116 # TODO class MResourceQuantity(Message): type_id = 117 struct_format = "!hhh" attrs = ("tx", "ty", "q") # Player/connection stuff class MNewPlayer(Message): type_id = 120 attrs = ("player_id", "name", "color", "loading") def pack(self): w = Writer() w.s...
type_id = 115 struct_format = "!HB" attrs = ("dmo_id", "hidden") class MDMOPosition(Message):
random_line_split
networking.py
from __future__ import division import struct from cStringIO import StringIO #import pyraknet #from pyraknet import PacketTypes, PacketReliability, PacketPriority import socket, traceback, os, sys, threading from Queue import Queue from unit import Unit from buildings.igloo import Igloo from player import Player im...
self.data.write(struct.pack(format, *values)) def multi(self, format, values): self.single("!H", len(values)) if len(format.strip("@=<>!")) > 1: for v in values: self.single(format, *v) else: for v in values: self.single(forma...
format = "!"+format
conditional_block
networking.py
from __future__ import division import struct from cStringIO import StringIO #import pyraknet #from pyraknet import PacketTypes, PacketReliability, PacketPriority import socket, traceback, os, sys, threading from Queue import Queue from unit import Unit from buildings.igloo import Igloo from player import Player im...
def values(self): l = [] for a in self.attrs: l.append(getattr(self, a)) return l @classmethod def from_stream(cls, stream): res = struct.unpack(cls.struct_format, stream.read(struct.calcsize(cls.struct_format))) return cls(*res) de...
attrs = list(self.attrs) for arg in pargs: n = attrs.pop(0) setattr(self, n, arg) for n in attrs: setattr(self, n, kwargs.pop(n)) if kwargs: raise TypeError("unexpected keyword argument '%s'" % kwargs.keys()[0])
identifier_body
async_await_basics.rs
use futures::executor::block_on; use std::thread::Thread; use std::sync::mpsc; use futures::join; use { std::{ pin::Pin, task::Waker, thread, }, }; use { futures::{ future::{FutureExt, BoxFuture}, task::{ArcWake, waker_ref}, }, std::{ future::Future, ...
{ shared_state: Arc<Mutex<SharedState>>, } /// Shared state between the future and the waiting thread struct SharedState { /// Whether or not the sleep time has elapsed completed: bool, /// The waker for the task that `TimerFuture` is running on. /// The thread can use this after setting `complet...
TimerFuture
identifier_name
async_await_basics.rs
use futures::executor::block_on; use std::thread::Thread; use std::sync::mpsc; use futures::join; use { std::{ pin::Pin, task::Waker, thread, }, }; use { futures::{ future::{FutureExt, BoxFuture}, task::{ArcWake, waker_ref}, }, std::{ future::Future, ...
// function, but we omit that here to keep things simple. shared_state.waker = Some(cx.waker().clone()); Poll::Pending } } } impl TimerFuture { /// Create a new `TimerFuture` which will complete after the provided /// timeout. pub fn new(duration: Duration) -...
// // N.B. it's possible to check for this using the `Waker::will_wake`
random_line_split
async_await_basics.rs
use futures::executor::block_on; use std::thread::Thread; use std::sync::mpsc; use futures::join; use { std::{ pin::Pin, task::Waker, thread, }, }; use { futures::{ future::{FutureExt, BoxFuture}, task::{ArcWake, waker_ref}, }, std::{ future::Future, ...
async fn learn_and_sing() { let song = learn_song().await; sing_song(song).await; } async fn async_main() { let f2 = dance(); let f1 = learn_and_sing(); futures::join!(f2, f1); } // Each time a future is polled, it is polled as part of a "task". Tasks are the top-level futures // that have been...
{ println!("Dance!!") }
identifier_body
async_await_basics.rs
use futures::executor::block_on; use std::thread::Thread; use std::sync::mpsc; use futures::join; use { std::{ pin::Pin, task::Waker, thread, }, }; use { futures::{ future::{FutureExt, BoxFuture}, task::{ArcWake, waker_ref}, }, std::{ future::Future, ...
} } } } // In practice, this problem is solved through integration with an IO-aware system blocking primitive, // such as epoll on Linux, kqueue on FreeBSD and Mac OS, IOCP on Windows, and ports on Fuchsia (all // of which are exposed through the cross-platform Rust crate mio). These primitive...
{ // We're not done processing the future, so put it // back in its task to be run again in the future. *future_slot = Some(future); }
conditional_block
controller.py
""" Venter på innkommende meldinger som enten gir oppgaver å jobbe med, eller etterspør et rom å søke gjennom Tar inn "Kode" som skal knekkes, samt rom det skal søkes i, (muligens størrelse på hver enkelt arbeidoppgave?) og eventuell hashing-algoritme. Fordeler arbeidoppgaver ved å motta en forespørsel, og sende...
int, end_point, keyword, chars, searchwidth, algorithm, id): self.start_point = start_point # Where to start searching self.end_point = end_point # Where to end the search self.keyword = keyword # What you're searching for self.chars = chars # Characters t...
start_po
identifier_name
controller.py
""" Venter på innkommende meldinger som enten gir oppgaver å jobbe med, eller etterspør et rom å søke gjennom Tar inn "Kode" som skal knekkes, samt rom det skal søkes i, (muligens størrelse på hver enkelt arbeidoppgave?) og eventuell hashing-algoritme. Fordeler arbeidoppgaver ved å motta en forespørsel, og sende...
conditional_block
controller.py
""" Venter på innkommende meldinger som enten gir oppgaver å jobbe med, eller etterspør et rom å søke gjennom Tar inn "Kode" som skal knekkes, samt rom det skal søkes i, (muligens størrelse på hver enkelt arbeidoppgave?) og eventuell hashing-algoritme. Fordeler arbeidoppgaver ved å motta en forespørsel, og sende...
k_id(tasks): task_id_unique = False temp_id = floor(random()*10000) while not task_id_unique: task_id_unique = True temp_id = floor(random()*10000) for task in tasks: if task.id == temp_id: task_id_unique = False return temp_id class Task: ...
ps(get_next_job()) def gen_tas
identifier_body
controller.py
""" Venter på innkommende meldinger som enten gir oppgaver å jobbe med, eller etterspør et rom å søke gjennom Tar inn "Kode" som skal knekkes, samt rom det skal søkes i, (muligens størrelse på hver enkelt arbeidoppgave?) og eventuell hashing-algoritme. Fordeler arbeidoppgaver ved å motta en forespørsel, og sende...
self.current_point = self.start_point # Will be increased as workers are given blocks to search through self.finished = False self.keyword_found = "" def get_task(self): return { 'id':self.id, 'finished':self.finished, 'algorithm':self.a...
random_line_split
main.rs
//! # Basic Subclass example //! //! This file creates a `GtkApplication` and a `GtkApplicationWindow` subclass //! and showcases how you can override virtual funcitons such as `startup` //! and `activate` and how to interact with the GObjects and their private //! structs. extern crate gstreamer as gst; extern crate ...
} use std::time::Duration; use std::io::Seek; use std::io::SeekFrom; fn main() { gtk::init().expect("Failed to initialize gtk"); let app = SimpleApplication::new(); let args: Vec<String> = std::env::args().collect(); app.run(&args); }
{ glib::Object::new( Self::static_type(), &[ ("application-id", &"org.gtk-rs.SimpleApplication"), ("flags", &ApplicationFlags::empty()), ], ) .expect("Failed to create SimpleApp") .downcast() .expect("Created sim...
identifier_body
main.rs
//! # Basic Subclass example //! //! This file creates a `GtkApplication` and a `GtkApplicationWindow` subclass //! and showcases how you can override virtual funcitons such as `startup` //! and `activate` and how to interact with the GObjects and their private //! structs. extern crate gstreamer as gst; extern crate ...
audio_player_clone.pause_music(); }); // Connect our method `on_increment_clicked` to be called // when the increment button is clicked. increment.connect_clicked(clone!(@weak self_ => move |_| { let priv_ = SimpleWindowPrivate::from_instance(&self_); ...
pause_button.connect_clicked(move |_| {
random_line_split
main.rs
//! # Basic Subclass example //! //! This file creates a `GtkApplication` and a `GtkApplicationWindow` subclass //! and showcases how you can override virtual funcitons such as `startup` //! and `activate` and how to interact with the GObjects and their private //! structs. extern crate gstreamer as gst; extern crate ...
(&self) { self.counter.set(self.counter.get() + 1); let w = self.widgets.get().unwrap(); w.label .set_text(&format!("Your life has {} meaning", self.counter.get())); } fn on_decrement_clicked(&self) { self.counter.set(self.counter.get().wrapping_sub(1)); let w...
on_increment_clicked
identifier_name
configfunction.js
//验证数据有效性 function validationData(types,data){ //if(types=="1"||types=="整型"){ if(types=="1"||types=="\u6574\u578B"){ var re=/^-?[0-9]\d*$/; if(!data.match(re)){ //return "类型为整型的数据值必须是整数。<br>"; return "\u7C7B\u578B\u4E3A\u6574\u578B\u7684\u6570\u636E\u503C\u5FC5\u987B\u662F\u6574\u6570\u3002<br>"; } //}el...
obj.className = "input_mouseout"; }
eBorder(obj){
identifier_name
configfunction.js
//验证数据有效性 function validationData(types,data){ //if(types=="1"||types=="整型"){ if(types=="1"||types=="\u6574\u578B"){ var re=/^-?[0-9]\d*$/; if(!data.match(re)){ //return "类型为整型的数据值必须是整数。<br>"; return "\u7C7B\u578B\u4E3A\u6574\u578B\u7684\u6570\u636E\u503C\u5FC5\u987B\u662F\u6574\u6570\u3002<br>"; } //}el...
var tempValues = td.getElementsByTagName("INPUT")[0].value; if(trimSpace(tempValues)!=""){ //校验数据值是否含有不允许的特殊字符 var validateDataRegexInfo = validateDataRegex(trimSpace(tempValues)); if(validateDataRegexInfo){ msg += "\u6570\u636E\u503C\u533A\u57DF\u7B2C"+i+"\u884C\u002C\u7B2C"+(j+1)+"\u5217"...
if(td){
random_line_split
configfunction.js
//验证数据有效性 function validationData(types,data){ //if(types=="1"||types=="整型"){ if(types=="1"||types=="\u6574\u578B"){ var re=/^-?[0-9]\d*$/; if(!data.match(re)){ //return "类型为整型的数据值必须是整数。<br>"; return "\u7C7B\u578B\u4E3A\u6574\u578B\u7684\u6570\u636E\u503C\u5FC5\u987B\u662F\u6574\u6570\u3002<br>"; } //}el...
40D\u79F0\u4E0D\u80FD\u4E3A\u7A7A<br>"; } if(trimSpace(attrCode).length==0){ //msg+="属性编码不能为空<br>"; msg+="\u5C5E\u6027\u7F16\u7801\u4E0D\u80FD\u4E3A\u7A7A<br>"; }else{ msg += isRepeat(attrCode,temp); } if(msg.length>0){ cui.alert(msg); return; } //var info = "名称:"+trimSpace(attrName)+",编码:"+trimSpace(a...
eDataRegexInfo; } flag = false; //只有值不为空时才进行验证 //验证输入的值是否合法 var attributeType = trimSpace(jsonHead[j-1].attributeType); var vInfo = validationData(attributeType,trimSpace(tempValues)); if(vInfo!=""){ //msg += "数据值区域第"+i+"行,第"+(j+1)+"列"+vInfo; msg += "\u6570\u636E\u503C\u53...
conditional_block
configfunction.js
//验证数据有效性 function validationData(types,data){ //if(types=="1"||types=="整型"){ if(types=="1"||types=="\u6574\u578B"){ var re=/^-?[0-9]\d*$/; if(!data.match(re)){ //return "类型为整型的数据值必须是整数。<br>"; return "\u7C7B\u578B\u4E3A\u6574\u578B\u7684\u6570\u636E\u503C\u5FC5\u987B\u662F\u6574\u6570\u3002<br>"; } //}el...
identifier_body
lstm.py
import pandas as pd from sklearn import model_selection, preprocessing, linear_model, metrics from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.feature_extraction.text import TfidfTransformer from sklearn.metrics import classification_report, confusion_matrix, accuracy_score import seaborn as sn...
(self, x, hidden): """ Perform a forward pass of our model on some input and hidden state. """ batch_size = x.size(0) # embeddings and lstm_out embeds = self.embedding(x) lstm_out, hidden = self.lstm(embeds, hidden) # stack up lstm outputs ...
forward
identifier_name
lstm.py
import pandas as pd from sklearn import model_selection, preprocessing, linear_model, metrics from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.feature_extraction.text import TfidfTransformer from sklearn.metrics import classification_report, confusion_matrix, accuracy_score import seaborn as sn...
# Get test data loss and accuracy # = [] # track loss num_correct = 0 # init hidden state h = net.init_hidden(batch_size, train_on_gpu) counter=0 net.eval() all_prediction = [] # iterate over test data for inputs, labels in test_loader: counter += 1 print('epoce: {e}, batch: {b}'.format(e=e, b=counter)...
h = net.init_hidden(batch_size, train_on_gpu) counter = 0 # batch loop for inputs, labels in train_loader: counter += 1 #print('epoce: {e}, batch: {b}'.format(e=e, b=counter)) if (labels.shape[0] != batch_size): continue inputs = inputs.type(torch.LongTensor) ...
conditional_block
lstm.py
import pandas as pd from sklearn import model_selection, preprocessing, linear_model, metrics from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.feature_extraction.text import TfidfTransformer from sklearn.metrics import classification_report, confusion_matrix, accuracy_score import seaborn as sn...
def forward(self, x, hidden): """ Perform a forward pass of our model on some input and hidden state. """ batch_size = x.size(0) # embeddings and lstm_out embeds = self.embedding(x) lstm_out, hidden = self.lstm(embeds, hidden) # stack up lst...
""" Initialize the model by setting up the layers. """ super(SentimentRNN, self).__init__() self.output_size = output_size self.n_layers = n_layers self.hidden_dim = hidden_dim # embedding and LSTM layers self.embedding = nn.Embedding(vocab_size,...
identifier_body
lstm.py
import pandas as pd from sklearn import model_selection, preprocessing, linear_model, metrics from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.feature_extraction.text import TfidfTransformer from sklearn.metrics import classification_report, confusion_matrix, accuracy_score import seaborn as sns...
print(type(text)) label=[] for item in stars: if item>= 4: y=1 else: y=0 label.append(y) label=np.array(label) #we can get punctuation from string library from string import punctuation print(punctuation) all_reviews=[] for item in text: item = item.lower() item = "".join([ch for ch in...
text=list(df_filtered['text']) stars=list(df_filtered['stars'])
random_line_split
Master Solution.py
#!/usr/bin/env python # coding: utf-8 # # Background # # - 1 The adjacent 3 tabs contain a data dump of search strings used by EXP clients to access relevant content available on Gartner.com for the months of August, September and October in the year 2018. Every row mentions if the EXP client is "P...
(data): #convert text to lower-case data['processed_text'] = data['Query Text'].apply(lambda x:' '.join(x.lower() for x in x.split())) #remove punctuations, unwanted characters data['processed_text_1']= data['processed_text'].apply(lambda x: "".join([char for char in x if char not in string.punctu...
text_preprocessing
identifier_name
Master Solution.py
#!/usr/bin/env python # coding: utf-8 # # Background # # - 1 The adjacent 3 tabs contain a data dump of search strings used by EXP clients to access relevant content available on Gartner.com for the months of August, September and October in the year 2018. Every row mentions if the EXP client is "P...
# In[9]: df.isnull().sum() # In[10]: df.drop_duplicates(subset ="Query Text", keep = 'last', inplace = True) # In[11]: df.info() # In[12]: # check the length of documents document_lengths = np.array(list(map(len, df['Query Text'].str.split(' ')))) print("The average number of wor...
random_line_split
Master Solution.py
#!/usr/bin/env python # coding: utf-8 # # Background # # - 1 The adjacent 3 tabs contain a data dump of search strings used by EXP clients to access relevant content available on Gartner.com for the months of August, September and October in the year 2018. Every row mentions if the EXP client is "P...
# In[15]: #pre-processing or cleaning data text_preprocessing(df) df.head() # In[16]: #create tokenized data for LDA df['final_tokenized'] = list(map(nltk.word_tokenize, df.final_text)) df.head() # ## LDA training # In[17]: # Create Dictionary id2word = corpora.Dictionary(df['final_tokenized']) tex...
data['processed_text'] = data['Query Text'].apply(lambda x:' '.join(x.lower() for x in x.split())) #remove punctuations, unwanted characters data['processed_text_1']= data['processed_text'].apply(lambda x: "".join([char for char in x if char not in string.punctuation])) #remove numbers data['processed...
identifier_body
Master Solution.py
#!/usr/bin/env python # coding: utf-8 # # Background # # - 1 The adjacent 3 tabs contain a data dump of search strings used by EXP clients to access relevant content available on Gartner.com for the months of August, September and October in the year 2018. Every row mentions if the EXP client is "P...
nique labels for entities : ", Counter(ent_label)) print("Top 3 frequent tokens : ", Counter(ent_common).most_common(3)) # In[40]: sentences = [] for i, doc in enumerate(corpus): for ent in doc.sents: sentences.append(ent) print(sentences[0]) # In[41]: # Most popular ents import operator sor...
nt.label_) ent_common.append(ent.text) print("U
conditional_block
helpers.go
package en import ( "bytes" "fmt" "log" "regexp" "strconv" "strings" "time" "github.com/golang-collections/collections/stack" "golang.org/x/net/html" ) // Tag string type that corresponds to the html tags type Tag struct { Tag string Attrs map[string]string } const ( iTag string = "i" bTag ...
if mrHr := reHr.FindAllStringSubmatch(res, -1); len(mrHr) > 0 { for _, item := range mrHr { res = regexp.MustCompile(item[0]).ReplaceAllLiteralString(res, "\n") } } if mrP := reP.FindAllStringSubmatch(res, -1); len(mrP) > 0 { for _, item := range mrP { res = regexp.MustCompile(regexp.QuoteMeta(item[0])). ...
for _, item := range mrBr { res = regexp.MustCompile(item[0]).ReplaceAllLiteralString(res, "\n") } }
conditional_block
helpers.go
package en import ( "bytes" "fmt" "log" "regexp" "strconv" "strings" "time" "github.com/golang-collections/collections/stack" "golang.org/x/net/html" ) // Tag string type that corresponds to the html tags type Tag struct { Tag string Attrs map[string]string } const ( iTag string = "i" bTag ...
// ReplaceCommonTags deprecated - should be removed!!! func ReplaceCommonTags(text string) string { log.Print("Replace html tags") var ( reBr = regexp.MustCompile("<br\\s*/?>") reHr = regexp.MustCompile("<hr.*?/?>") reP = regexp.MustCompile("<p>([^ ]+?)</p>") reBold = regexp.MustCompile("<b.*...
{ var ( parser = html.NewTokenizer(strings.NewReader(text)) tagStack = stack.New() textToTag = map[int]string{} ) for { node := parser.Next() switch node { case html.ErrorToken: result := strings.Replace(textToTag[0], "&nbsp;", " ", -1) return result case html.TextToken: t := string(parse...
identifier_body
helpers.go
package en import ( "bytes" "fmt" "log" "regexp" "strconv" "strings" "time" "github.com/golang-collections/collections/stack" "golang.org/x/net/html" ) // Tag string type that corresponds to the html tags type Tag struct { Tag string Attrs map[string]string } const ( iTag string = "i" bTag ...
reCenter = regexp.MustCompile("<center>((?s:.*?))</center>") reFont = regexp.MustCompile("<font.+?color\\s*=\\\\?[\"«]?#?(\\w+)\\\\?[\"»]?.*?>((?s:.*?))</font>") reA = regexp.MustCompile("<a.+?href=\\\\?\"(.+?)\\\\?\".*?>(.+?)</a>") res = text ) res = strings.Replace(text, "_", "\\_", -1) if mrB...
reStrong = regexp.MustCompile("<strong.*?>(.*?)</strong>") reItalic = regexp.MustCompile("<i>((?s:.+?))</i>") reSpan = regexp.MustCompile("<span.*?>(.*?)</span>")
random_line_split
helpers.go
package en import ( "bytes" "fmt" "log" "regexp" "strconv" "strings" "time" "github.com/golang-collections/collections/stack" "golang.org/x/net/html" ) // Tag string type that corresponds to the html tags type Tag struct { Tag string Attrs map[string]string } const ( iTag string = "i" bTag ...
(text string, re *regexp.Regexp) (string, Coordinates) { var ( result = text mr = re.FindAllStringSubmatch(text, -1) coords = Coordinates{} ) if len(mr) > 0 { for _, item := range mr { lon, _ := strconv.ParseFloat(item[1], 64) lat, _ := strconv.ParseFloat(item[2], 64) if len(item) > 3 { coor...
extractCoordinates
identifier_name
trainPredictor.py
#!/usr/bin/env python3 from builtins import zip from builtins import str from builtins import range import sys import os import json import pickle import traceback import numpy as np import time import datetime as dtime from progressbar import ProgressBar, ETA, Bar, Percentage from sklearn.base import clone from skle...
pathjoin = os.path.join pathexists = os.path.exists mdy = dtime.datetime.now().strftime('%m%d%y') product_type = 'interferogram' cache_dir = 'cached' train_folds = np.inf # inf = leave-one-out, otherwise k-fold cross validation train_state = 42 # random seed train_verbose = 0 train_jobs = -1 cv_type...
print(process,exitv,message)
identifier_body
trainPredictor.py
#!/usr/bin/env python3 from builtins import zip from builtins import str from builtins import range import sys import os import json import pickle import traceback import numpy as np import time import datetime as dtime from progressbar import ProgressBar, ETA, Bar, Percentage from sklearn.base import clone from skle...
(usertags,classmap): ''' return dictionary of matched (tag,label) pairs in classmap for all tags returns {} if none of the tags are present in classmap ''' labelmap = {} for tag in usertags: tag = tag.strip() for k,v in list(classmap.items()): if tag.count(k): ...
usertags2label
identifier_name
trainPredictor.py
#!/usr/bin/env python3 from builtins import zip from builtins import str from builtins import range import sys import os import json import pickle import traceback import numpy as np import time import datetime as dtime from progressbar import ProgressBar, ETA, Bar, Percentage from sklearn.base import clone from skle...
else: print("invalid clf_type") return {} clf = clone(model_clf) if model_tuned is not None and len(model_tuned) != 0 and \ len(model_tuned[0]) != 0: cv = GridSearchCV(clf,model_tuned,cv=gridcv_folds,scoring=gridcv_score, n_jobs=gridcv_jobs,ver...
model_clf = RandomForestClassifier(**rf_defaults) model_tuned = [rf_tuned]
conditional_block
trainPredictor.py
#!/usr/bin/env python3 from builtins import zip from builtins import str from builtins import range import sys import os import json import pickle import traceback import numpy as np import time import datetime as dtime from progressbar import ProgressBar, ETA, Bar, Percentage from sklearn.base import clone from skle...
return url.replace(product_type,'features').replace('features__','features_'+product_type+'__') def fdict2vec(featdict,clfinputs): ''' extract feature vector from dict given classifier parameters specifying which features to use ''' fvec = [] try: featspec = clfinputs['feature...
- feature id for url """
random_line_split
photcalibration.py
#from __future__ import absolute_import, division, print_function, unicode_literals import matplotlib from longtermphotzp import photdbinterface matplotlib.use('Agg') import matplotlib.pyplot as plt plt.style.use('ggplot') import numpy as np import argparse import re import glob import os import math import sys impo...
def crawlSiteCameraArchive(site, camera, args, date=None): ''' Process in the archive :param site: :param camera: :param args: :param date: :return: ''' if date is None: date = '*' if site is None: _logger.error ("Must define a site !") exit (1) ...
search = "%s/*-[es][19]1.fits.fz" % (directory) inputlist = glob.glob(search) initialsize = len (inputlist) rejects = [] if not args.redo: for image in inputlist: if db.exists(image): rejects.append (image) for r in rejects: inputlist.remove (r)...
identifier_body
photcalibration.py
#from __future__ import absolute_import, division, print_function, unicode_literals import matplotlib from longtermphotzp import photdbinterface matplotlib.use('Agg') import matplotlib.pyplot as plt plt.style.use('ggplot') import numpy as np import argparse import re import glob import os import math import sys impo...
select_from_cat = (cat_ra_shifted > min_ra) & (cat_ra_shifted < max_ra) & (cat_dec > min_dec) & ( cat_dec < max_dec) array_to_add = cat_full[select_from_cat] _logger.debug("Read %d sources from %s" % (array_to_add.shape[0], catalogname)) if (full_catal...
cat_ra_shifted[cat_ra > 180] -= 360
conditional_block
photcalibration.py
#from __future__ import absolute_import, division, print_function, unicode_literals import matplotlib from longtermphotzp import photdbinterface matplotlib.use('Agg') import matplotlib.pyplot as plt plt.style.use('ggplot') import numpy as np import argparse import re import glob import os import math import sys impo...
:param args: :param date: :return: ''' if date is None: date = '*' if site is None: _logger.error ("Must define a site !") exit (1) imagedb = photdbinterface(args.imagedbPrefix) searchdir = "%s/%s/%s/%s/%s" % (args.rootdir, site, camera, date, args.processstat...
:param site: :param camera:
random_line_split
photcalibration.py
#from __future__ import absolute_import, division, print_function, unicode_literals import matplotlib from longtermphotzp import photdbinterface matplotlib.use('Agg') import matplotlib.pyplot as plt plt.style.use('ggplot') import numpy as np import argparse import re import glob import os import math import sys impo...
(directory, db, args): search = "%s/*-[es][19]1.fits.fz" % (directory) inputlist = glob.glob(search) initialsize = len (inputlist) rejects = [] if not args.redo: for image in inputlist: if db.exists(image): rejects.append (image) for r in rejects: ...
crawlDirectory
identifier_name
genetic.py
import copy import random import time import sys # TODO: accept user args for states, give up, etc # TODO: set up signal handler for Ctrl-C DEBUG = True history = [] # a record of states GIVE_UP = 1000 # give up after x iterations POOL_SIZE = 10 NUM_VARS = 0 NUM_CLAUSES = 0 CNF = [] #TODO: fix evaluate function ...
flips = 0 while counter < GIVE_UP: if rand_restarts and counter>0 and not (counter % restart): # random restarts if not tb: print("restarting: (" + str(new_vals[0]) + "/" + str(NUM_CLAUSES) + ")") initialize_states(gene_pool, gene_pool[0]) if not tb: print("iteration", ...
restart = int(tries/5)
random_line_split
genetic.py
import copy import random import time import sys # TODO: accept user args for states, give up, etc # TODO: set up signal handler for Ctrl-C DEBUG = True history = [] # a record of states GIVE_UP = 1000 # give up after x iterations POOL_SIZE = 10 NUM_VARS = 0 NUM_CLAUSES = 0 CNF = [] #TODO: fix evaluate function ...
# not currently using def flip_heuristic(safe, new_pool, evaluations): for i in range(safe, POOL_SIZE): flipped = flip_bits(new_pool[i]) value = evaluate(flipped) if value >= evaluations[i]: evaluations[i] = value new_pool[i] = flipped def flip_bits(string): n...
new_str = string[:index] + ("1" if string[index]=="0" else "0") + string[(index+1):] new_eval = evaluate(new_str) if new_eval > evaluation: return (new_str, new_eval) return (None, None)
identifier_body
genetic.py
import copy import random import time import sys # TODO: accept user args for states, give up, etc # TODO: set up signal handler for Ctrl-C DEBUG = True history = [] # a record of states GIVE_UP = 1000 # give up after x iterations POOL_SIZE = 10 NUM_VARS = 0 NUM_CLAUSES = 0 CNF = [] #TODO: fix evaluate function ...
for i in range(num): res[i][i] = inf return res def calc_dist(a, b): return ((a[0]-b[0])**2 + (a[1]-b[1])**2)**.5 def closest(a, adj): return min(adj[a][:]) def find_closest(a, others, adj): min_dist = 1000 closest = -1 for i in others: if adj[a][i] < min_dist: ...
for j in range(num): res[i][j] = calc_dist(cities[i][1], cities[j][1]) res[j][i] = res[i][j]
conditional_block
genetic.py
import copy import random import time import sys # TODO: accept user args for states, give up, etc # TODO: set up signal handler for Ctrl-C DEBUG = True history = [] # a record of states GIVE_UP = 1000 # give up after x iterations POOL_SIZE = 10 NUM_VARS = 0 NUM_CLAUSES = 0 CNF = [] #TODO: fix evaluate function ...
(safe, new_pool): for i in range(safe, POOL_SIZE): if flip_coin(.9): mutant = "" for j in range(len(new_pool[i])): if flip_coin(): mutant += str(1 - int(new_pool[i][j])) else: mutant += new_pool[i][j] ...
mutate
identifier_name
Data_Exploration.py
from __future__ import print_function, division, unicode_literals from datetime import date, datetime import simplejson from flask import Flask, request, jsonify from www.archive.datasources import AsterixDataSource from www.archive.datasources import SolrDataSource from www.archive.datasources import convertToIn fr...
l.append(d) # theresult_json = json.dumps(l, default=json_serial) conn.close() return theresult_json @app.route("/api/correlation/<col1>/<col2>") def Correlation(col1, col2): engine = create_engine('postgresql+psycopg2://student:123456@132.249.238.27:5432/bookstore_dp') conn = engi...
c = request.args[item] print (c) d[c] = result[c]
conditional_block
Data_Exploration.py
from __future__ import print_function, division, unicode_literals from datetime import date, datetime import simplejson from flask import Flask, request, jsonify from www.archive.datasources import AsterixDataSource from www.archive.datasources import SolrDataSource from www.archive.datasources import convertToIn fr...
@app.route("/api/web_method/<format>") def api_web_method(format): engine = create_engine('postgresql+psycopg2://student:123456@132.249.238.27:5432/bookstore_dp') conn = engine.connect() sql = """ select * from orderlines o, products p where o.productid = p.productid LIMIT 10 """ ...
"""JSON serializer for objects not serializable by default json code""" if isinstance(obj, (datetime, date)): return obj.isoformat() raise TypeError ("Type %s not serializable" % type(obj))
identifier_body
Data_Exploration.py
from __future__ import print_function, division, unicode_literals from datetime import date, datetime import simplejson from flask import Flask, request, jsonify from www.archive.datasources import AsterixDataSource from www.archive.datasources import SolrDataSource from www.archive.datasources import convertToIn fr...
(obj): """JSON serializer for objects not serializable by default json code""" if isinstance(obj, (datetime, date)): return obj.isoformat() raise TypeError ("Type %s not serializable" % type(obj)) @app.route("/api/web_method/<format>") def api_web_method(format): engine = create_engine('postg...
json_serial
identifier_name
Data_Exploration.py
from __future__ import print_function, division, unicode_literals from datetime import date, datetime import simplejson from flask import Flask, request, jsonify from www.archive.datasources import AsterixDataSource from www.archive.datasources import SolrDataSource from www.archive.datasources import convertToIn fr...
app = Flask(__name__) @app.route("/") def Hello(): return "Hello World!" @app.route('/api/service', methods=['POST']) def api_service(): query = request.get_json(silent=True) # needs to change to reading from xml file xml = VirtualIntegrationSchema() web_session = WebSession(xml) return j...
from json import loads import psycopg2 from sqlalchemy import create_engine, text import pysolr from textblob import TextBlob as tb
random_line_split
ConfiguredResourceUploader.js
/* * web: ConfiguredResourceUploader.js * XNAT http://www.xnat.org * Copyright (c) 2005-2017, Washington University School of Medicine and Howard Hughes Medical Institute * All Rights Reserved * * Released under the Simplified BSD. */ /* * resource dialog is used to upload resources at any level *...
if(tempConfigs.length>0){ if(value.dontHide){ $(value).color(value.defaultColor); $(value).css('cursor:pointer'); } $(this).click(function(){ XNAT.app.crUploader.show(this); return false; }); $(this).show(); }else{ if(!value.dontHide){ $(this).hid...
var tempConfigs=XNAT.app.crConfigs.getAllConfigsByType(type,props)
random_line_split
ConfiguredResourceUploader.js
/* * web: ConfiguredResourceUploader.js * XNAT http://www.xnat.org * Copyright (c) 2005-2017, Washington University School of Medicine and Howard Hughes Medical Institute * All Rights Reserved * * Released under the Simplified BSD. */ /* * resource dialog is used to upload resources at any level *...
this.dialog.hide(); }, confirm : function (header, msg, handleYes, handleNo) { var dialog = new YAHOO.widget.SimpleDialog('widget_confirm', { visible:false, width: '20em', zIndex: 9998, close: false, fixedcenter: true, modal: true, draggable: true, constraintoviewport: tru...
{ showMessage("page_body","Failed upload.",response.responseText); }
conditional_block
extractdicom.go
package bulkprocess import ( "archive/zip" "fmt" "image" "image/color" "io" "log" "math" "strconv" "cloud.google.com/go/storage" "github.com/suyashkumar/dicom" "github.com/suyashkumar/dicom/dicomtag" "github.com/suyashkumar/dicom/element" ) // ExtractDicomFromGoogleStorage fetches a dicom from within a z...
} // Draw the overlay if opts.IncludeOverlay && img != nil && overlayPixels != nil { // Iterate over the bytes. There will be 1 value for each cell. // So in a 1024x1024 overlay, you will expect 1,048,576 cells. for i, overlayValue := range overlayPixels { row := i / nOverlayCols col := i % nOverlayCols...
random_line_split
extractdicom.go
package bulkprocess import ( "archive/zip" "fmt" "image" "image/color" "io" "log" "math" "strconv" "cloud.google.com/go/storage" "github.com/suyashkumar/dicom" "github.com/suyashkumar/dicom/dicomtag" "github.com/suyashkumar/dicom/element" ) // ExtractDicomFromGoogleStorage fetches a dicom from within a z...
func ApplyPythonicWindowScaling(intensity, maxIntensity int) uint16 { if intensity < 0 { intensity = 0 } return uint16(float64(math.MaxUint16) * float64(intensity) / float64(maxIntensity)) } func ApplyNoWindowScaling(intensity int) uint16 { return uint16(intensity) }
{ // 1: StoredValue to ModalityValue var modalityValue float64 if rescaleSlope == 0 { // Via https://dgobbi.github.io/vtk-dicom/doc/api/image_display.html : // For modalities such as ultrasound and MRI that do not have any units, // the RescaleSlope and RescaleIntercept are absent and the Modality // Values ...
identifier_body
extractdicom.go
package bulkprocess import ( "archive/zip" "fmt" "image" "image/color" "io" "log" "math" "strconv" "cloud.google.com/go/storage" "github.com/suyashkumar/dicom" "github.com/suyashkumar/dicom/dicomtag" "github.com/suyashkumar/dicom/element" ) // ExtractDicomFromGoogleStorage fetches a dicom from within a z...
(zipPath, dicomName string, includeOverlay bool) (image.Image, error) { return ExtractDicomFromGoogleStorage(zipPath, dicomName, includeOverlay, nil) } // ExtractDicomFromZipReader consumes a zip reader of the UK Biobank format, // finds the dicom of the desired name, and returns that image, with or without // the ov...
ExtractDicomFromLocalFile
identifier_name
extractdicom.go
package bulkprocess import ( "archive/zip" "fmt" "image" "image/color" "io" "log" "math" "strconv" "cloud.google.com/go/storage" "github.com/suyashkumar/dicom" "github.com/suyashkumar/dicom/dicomtag" "github.com/suyashkumar/dicom/element" ) // ExtractDicomFromGoogleStorage fetches a dicom from within a z...
} return img, err } // See 'Grayscale Image Display' under // https://dgobbi.github.io/vtk-dicom/doc/api/image_display.html . In addition, // we also scale the output so that it is appropriate for producing a 16-bit // grayscale image. E.g., if the native dicom is 8-bit, we still rescale the // output here for a 1...
{ row := i / nOverlayCols col := i % nOverlayCols if overlayValue != 0 { img.SetGray16(col, row, color.White) } }
conditional_block
lib.rs
//! A thread-safe object pool with automatic return and attach/detach semantics //! //! The goal of an object pool is to reuse expensive to allocate objects or frequently allocated objects //! //! # Examples //! //! ## Creating a Pool //! //! The general pool creation looks like this //! ``` //! let pool: MemPool<T> =...
elf.run_block.lock(); log::trace!("attach started<<<<<<<<<<<<<<<<"); log::trace!("recyled an item "); let mut wait_list = { self.waiting.lock() }; log::trace!("check waiting list ok :{}", wait_list.len()); if wait_list.len() > 0 && self.len() >= wait_list[0].min_request { ...
_x = s
identifier_name
lib.rs
//! A thread-safe object pool with automatic return and attach/detach semantics //! //! The goal of an object pool is to reuse expensive to allocate objects or frequently allocated objects //! //! # Examples //! //! ## Creating a Pool //! //! The general pool creation looks like this //! ``` //! let pool: MemPool<T> =...
waiting.lock().len() * 60 + 2 }; log::trace!("try again :{} with retries backoff:{}", str, to_retry); for i in 0..to_retry { sleep(std::time::Duration::from_secs(1)); if let Ok(item) = self.objects.1.try_recv() { log::trace!("get ok:{}", str); ...
); (Some(Reusable::new(&self, item)), false) /* } else if (self.pending.lock().len() == 0) { log::trace!("get should pend:{}", str); self.pending.lock().push(PendingInfo { id: String::from(str), notif...
conditional_block
lib.rs
//! A thread-safe object pool with automatic return and attach/detach semantics //! //! The goal of an object pool is to reuse expensive to allocate objects or frequently allocated objects //! //! # Examples //! //! ## Creating a Pool //! //! The general pool creation looks like this //! ``` //! let pool: MemPool<T> =...
usize { self.objects.1.len() } #[inline] pub fn is_empty(&self) -> bool { self.objects.1.is_empty() } #[inline] pub fn pending(&'static self, str: &str, sender: channel::Sender<Reusable<T>>, releasable: usize) -> (Option<Reusable<T>>, bool) { log::trace!("pending item:{...
{}", cap); log::trace!("mempool remains:{}", cap); let mut objects = channel::unbounded(); for _ in 0..cap { &objects.0.send(init()); } MemoryPool { objects, pending: Arc::new(Mutex::new(Vec::new())), waiting: Arc::new(Mutex::new(Ve...
identifier_body
lib.rs
//! A thread-safe object pool with automatic return and attach/detach semantics //! //! The goal of an object pool is to reuse expensive to allocate objects or frequently allocated objects //! //! # Examples //! //! ## Creating a Pool //! //! The general pool creation looks like this //! ``` //! let pool: MemPool<T> =...
//! some_file.read_to_end(reusable_buff); //! // reusable_buff is automatically returned to the pool when it goes out of scope //! ``` //! Pull from pool and `detach()` //! ``` //! let pool: MemoryPool<Vec<u8>> = MemoryPool::new(32, || Vec::with_capacity(4096)); //! let mut reusable_buff = pool.pull().unwrap(); // retu...
//! let pool: MemoryPool<Vec<u8>> = MemoryPool::new(32, || Vec::with_capacity(4096)); //! let mut reusable_buff = pool.pull().unwrap(); // returns None when the pool is saturated //! reusable_buff.clear(); // clear the buff before using
random_line_split
counter.rs
use std::ffi::CString; use std::io; use std::sync::{Mutex, Once}; #[cfg(target_os = "freebsd")] use libc::EDOOFUS; #[cfg(target_os = "freebsd")] use pmc_sys::{ pmc_allocate, pmc_attach, pmc_detach, pmc_id_t, pmc_init, pmc_mode_PMC_MODE_SC, pmc_mode_PMC_MODE_TC, pmc_read, pmc_release, pmc_rw, pmc_start, pmc_sto...
(&mut self) { unsafe { pmc_stop(self.counter.id) }; } } /// An allocated PMC counter. /// /// Counters are initialised using the [`CounterBuilder`] type. /// /// ```no_run /// use std::{thread, time::Duration}; /// /// let instr = CounterConfig::default() /// .attach_to(vec![0]) /// .allocate("inst...
drop
identifier_name
counter.rs
use std::ffi::CString; use std::io; use std::sync::{Mutex, Once}; #[cfg(target_os = "freebsd")] use libc::EDOOFUS; #[cfg(target_os = "freebsd")] use pmc_sys::{ pmc_allocate, pmc_attach, pmc_detach, pmc_id_t, pmc_init, pmc_mode_PMC_MODE_SC, pmc_mode_PMC_MODE_TC, pmc_read, pmc_release, pmc_rw, pmc_start, pmc_sto...
handles.push(AttachHandle { id, pid }) } c.attached = Some(handles) } Ok(c) } /// Start this counter. /// /// The counter stops when the returned [`Running`] handle is dropped. #[must_use = "counter only runs until handle is dropped"] ...
{ return match io::Error::raw_os_error(&io::Error::last_os_error()) { Some(libc::EBUSY) => unreachable!(), Some(libc::EEXIST) => Err(new_os_error(ErrorKind::AlreadyAttached)), Some(libc::EPERM) => Err(new_os_error(ErrorKind::For...
conditional_block
counter.rs
use std::ffi::CString; use std::io; use std::sync::{Mutex, Once}; #[cfg(target_os = "freebsd")] use libc::EDOOFUS; #[cfg(target_os = "freebsd")] use pmc_sys::{ pmc_allocate, pmc_attach, pmc_detach, pmc_id_t, pmc_init, pmc_mode_PMC_MODE_SC, pmc_mode_PMC_MODE_TC, pmc_read, pmc_release, pmc_rw, pmc_start, pmc_sto...
// Allocate the PMC let mut id = 0; if unsafe { pmc_allocate( c_spec.as_ptr(), pmc_mode, 0, cpu.unwrap_or(CPU_ANY), &mut id, 0, ) } != 0 { return ma...
let c_spec = CString::new(event_spec.into()).map_err(|_| new_error(ErrorKind::InvalidEventSpec))?;
random_line_split
sync.js
/* * image sync plugin (September 2, 2018) * whenever an operation is performed on this image, sync the target images */ /*global JS9, $ */ "use strict"; JS9.Sync = {}; JS9.Sync.CLASS = "JS9"; // class of plugins (1st part of div class) JS9.Sync.NAME = "Sync"; // name of this plugin (2nd part of div class...
// for each op (colormap, pan, etc.) for(i=0; i<xops.length; i++){ // current op xop = xops[i]; this.syncs[xop] = this.syncs[xop] || []; ims = this.syncs[xop]; // add images not already in the list for(j=0; j<xlen; j++){ xim = xims[j]; if( $.inArray(xim, ims) < 0 ){ // add to list ims.push(...
{ delete opts.reverse; for(i=0; i<xlen; i++){ JS9.Sync.sync.call(xims[i], xops, [this]); } return; }
conditional_block
sync.js
/* * image sync plugin (September 2, 2018) * whenever an operation is performed on this image, sync the target images */ /*global JS9, $ */ "use strict"; JS9.Sync = {}; JS9.Sync.CLASS = "JS9"; // class of plugins (1st part of div class) JS9.Sync.NAME = "Sync"; // name of this plugin (2nd part of div class...
if( xim && (xim.id !== this.id || (xim.display.id !== this.display.id)) ){ xims[j++] = xim; } } return xims; }; // sync image(s) when operations are performed on an originating image // called in the image context JS9.Sync.sync = function(...args){ let i, j, xop, xim, xops, xims, xlen; let ...
} else { xim = ims[i]; } // exclude the originating image
random_line_split
model_sql.go
package mc import ( "fmt" "github.com/spf13/cast" "gorm.io/gorm" "reflect" "strings" ) //kvs查询选项 type KvsQueryOption struct { DB *gorm.DB //当此项为空的,使用model.db KvName string //kv配置项名 ExtraWhere []interface{} //额外附加的查询条件 ReturnPath bool //当模型为树型结构时,返回的key是否使用path代替 ExtraFi...
treePathField := m.FieldAddAlias(m.attr.Tree.PathField) fields = append(append(fields, treePathField), m.ParseTreeExtraField()...) } // 附加字段 if extraFields != nil { fields = append(fields, m.FieldsAddAlias(extraFields)...) } return } // 给字段加表别名 func (m *Model) FieldAddAlias(field string) string { if field ...
fields = append(fields, keyField, valueField) // 树型必备字段 if m.attr.IsTree {
random_line_split
model_sql.go
package mc import ( "fmt" "github.com/spf13/cast" "gorm.io/gorm" "reflect" "strings" ) //kvs查询选项 type KvsQueryOption struct { DB *gorm.DB //当此项为空的,使用model.db KvName string //kv配置项名 ExtraWhere []interface{} //额外附加的查询条件 ReturnPath bool //当模型为树型结构时,返回的key是否使用path代替 ExtraFi...
填字段 func (m *Model) CheckRequiredValues(data map[string]interface{}) (err error) { fieldTitles := make([]string, 0) //非自增PK表,检查PK字段 if !m.attr.AutoInc { if cast.ToString(data[m.attr.Pk]) == "" { fieldTitles = append(fieldTitles, m.attr.Fields[m.attr.fieldIndexMap[m.attr.Pk]].Title) } } //检查配置中的必填字段 for _, ...
r } else if total > 0 { return &Result{Message:fmt.Sprintf("记录已存在:【%s】存在重复", strings.Join(fileTitles, "、"))} } return nil } // 检查必
conditional_block
model_sql.go
package mc import ( "fmt" "github.com/spf13/cast" "gorm.io/gorm" "reflect" "strings" ) //kvs查询选项 type KvsQueryOption struct { DB *gorm.DB //当此项为空的,使用model.db KvName string //kv配置项名 ExtraWhere []interface{} //额外附加的查询条件 ReturnPath bool //当模型为树型结构时,返回的key是否使用path代替 ExtraFi...
", m.attr.Table, m.attr.Pk) field = make([]string, 3) //层级字段 field[0] = fmt.Sprintf("CEILING(LENGTH(%s)/%d) AS `__mc_level`", pathField, m.attr.Tree.PathBit) //父节点字段 field[1] = fmt.Sprintf("(SELECT %s FROM `%s` AS `__mc_%s` WHERE %s=LEFT(%s, LENGTH(%s)-%d) LIMIT 1) AS `__mc_parent`", __mc_pkField, m.attr.Table,...
t.ToString(data[i][m.attr.Tree.NameField]) } } return } // 分析树形结构查询必须的扩展字段 func (m *Model) ParseTreeExtraField() (field []string) { pathField := m.FieldAddAlias(m.attr.Tree.PathField) __mc_pathField := fmt.Sprintf("`__mc_%s`.`%s`", m.attr.Table, m.attr.Tree.PathField) __mc_pkField := fmt.Sprintf("`__mc_%s`.`%s...
identifier_body
model_sql.go
package mc import ( "fmt" "github.com/spf13/cast" "gorm.io/gorm" "reflect" "strings" ) //kvs查询选项 type KvsQueryOption struct { DB *gorm.DB //当此项为空的,使用model.db KvName string //kv配置项名 ExtraWhere []interface{} //额外附加的查询条件 ReturnPath bool //当模型为树型结构时,返回的key是否使用path代替 ExtraFi...
lue"]) } } } } } //树形 indent := "" if qo.TreeIndent == nil { indent = m.attr.Tree.Indent } else { indent = *qo.TreeIndent } if m.attr.IsTree && indent != "" { //树形名称字段加前缀 for i, _ := range data { data[i][m.attr.Tree.NameField] = nString(indent, cast.ToInt(data[i]["__mc_level"])-1) + cast.T...
ing]["__mc_va
identifier_name
script.padrao.js
/** * Esse script tem dependencia das seguintes bibliotecas: * * class.padrao.js * style.padrao.js * * Terceiros: * * Bootstrap 5.1 ou superior. * ChartJS;. * * */ const url = new URL(document.URL); const urlHost = `${url.protocol}//${url.host}`; const urlAPI = `${urlHost}/api/`; //const urlAPI = `ht...
alert(error); } } const API = { /** *Requisições do tipo GET * @param {Opções para a definição da requisição} options */ GET: (options) => { try { if (options == undefined || options == null) { return false; } Ajax(options); ...
} } catch (error) {
conditional_block
script.padrao.js
/** * Esse script tem dependencia das seguintes bibliotecas: * * class.padrao.js * style.padrao.js * * Terceiros: * * Bootstrap 5.1 ou superior. * ChartJS;. * * */ const url = new URL(document.URL); const urlHost = `${url.protocol}//${url.host}`; const urlAPI = `${urlHost}/api/`; //const urlAPI = `ht...
var divSpinner = Elements.Create('div', 'divGrowing', null, null, `z-index: 150 !important; color: ${spinnerColor} !important;`, ["spinner-grow", "text-primary"]); span = Elements.Create('span', 'loadGrowing', "visually-hidden", null); divSpinner....
div = Elements.Create('div', 'loadMestre', null, null, style);
random_line_split
mod.rs
use rstd::prelude::*; use codec::{Encode, Decode}; use support::{ StorageValue, StorageMap, decl_event, decl_storage, decl_module, ensure, traits::{ Currency, ReservableCurrency, OnFreeBalanceZero, OnUnbalanced, WithdrawReason, ExistenceRequirement, Imbalance, Get, }, dispatch::Result, }; use sr_primitives...
//! # Activity Module //! #![cfg_attr(not(feature = "std"), no_std)]
random_line_split
mod.rs
//! # Activity Module //! #![cfg_attr(not(feature = "std"), no_std)] use rstd::prelude::*; use codec::{Encode, Decode}; use support::{ StorageValue, StorageMap, decl_event, decl_storage, decl_module, ensure, traits::{ Currency, ReservableCurrency, OnFreeBalanceZero, OnUnbalanced, WithdrawReason, ExistenceReq...
<T: Trait>(#[codec(compact)] BalanceOf<T>); impl<T: Trait> TakeFees<T> { /// utility constructor. Used only in client/factory code. pub fn from(fee: BalanceOf<T>) -> Self { Self(fee) } /// Compute the final fee value for a particular transaction. /// /// The final fee is composed of: /// - _length-fee_: Th...
TakeFees
identifier_name
mod.rs
//! # Activity Module //! #![cfg_attr(not(feature = "std"), no_std)] use rstd::prelude::*; use codec::{Encode, Decode}; use support::{ StorageValue, StorageMap, decl_event, decl_storage, decl_module, ensure, traits::{ Currency, ReservableCurrency, OnFreeBalanceZero, OnUnbalanced, WithdrawReason, ExistenceReq...
// PRIVATE MUTABLES fn charge_for_energy(who: &T::AccountId, value: BalanceOf<T>) -> Result { // ensure reserve if !T::Currency::can_reserve(who, value) { return Err("not enough free funds"); } // check current_charged let current_charged = <Charged<T>>::get(who); let new_charged = current_charged.ch...
{ T::EnergyCurrency::available_free_balance(who) }
identifier_body
compile.ts
import fs from "fs"; import { SandboxStatus } from "simple-sandbox"; import objectHash from "object-hash"; import LruCache from "lru-cache"; import winston from "winston"; import { v4 as uuid } from "uuid"; import getLanguage, { LanguageConfig } from "./languages"; import { MappedPath, safelyJoinPath, ensureDirectory...
public async dereference() { if (--this.referenceCount === 0) { await fsNative.remove(this.binaryDirectory); } } async copyTo(newBinaryDirectory: string) { this.reference(); await fsNative.copy(this.binaryDirectory, newBinaryDirectory); await this.dereference(); return new Compile...
{ this.referenceCount++; return this; }
identifier_body
compile.ts
import fs from "fs"; import { SandboxStatus } from "simple-sandbox"; import objectHash from "object-hash"; import LruCache from "lru-cache"; import winston from "winston"; import { v4 as uuid } from "uuid"; import getLanguage, { LanguageConfig } from "./languages"; import { MappedPath, safelyJoinPath, ensureDirectory...
() { if (--this.referenceCount === 0) { await fsNative.remove(this.binaryDirectory); } } async copyTo(newBinaryDirectory: string) { this.reference(); await fsNative.copy(this.binaryDirectory, newBinaryDirectory); await this.dereference(); return new CompileResultSuccess( this.co...
dereference
identifier_name
compile.ts
import fs from "fs"; import { SandboxStatus } from "simple-sandbox"; import objectHash from "object-hash"; import LruCache from "lru-cache"; import winston from "winston"; import { v4 as uuid } from "uuid"; import getLanguage, { LanguageConfig } from "./languages"; import { MappedPath, safelyJoinPath, ensureDirectory...
await fsNative.copy(this.binaryDirectory, newBinaryDirectory); await this.dereference(); return new CompileResultSuccess( this.compileTaskHash, this.message, newBinaryDirectory, this.binaryDirectorySize, this.extraInfo ); } } // Why NOT using the task hash as the directo...
async copyTo(newBinaryDirectory: string) { this.reference();
random_line_split
supervised_ml_(classification)_assignment_(final).py
# -*- coding: utf-8 -*- """Supervised_ML_(Classification)_assignment_(final) Automatically generated by Colaboratory. Original file is located at https://colab.research.google.com/drive/1dt_czoLEqYxIoCA-v7Ynu0XHCWHnFWsB """ #import of libraries import pandas as pd import glob import numpy as np import seaborn as...
f = pd.concat(oob_list, axis=1).T.set_index('n_trees') ax = rf_oob_df.plot(legend=False, marker='x', figsize=(14, 7), linewidth=5) ax.set(ylabel='out-of-bag error'); """The key is to reduce our out-of-bag (OOB) error. We do this by increasing the number of possibilities and finding the possibility which produced the ...
ams(n_estimators=n_trees) # Fit the model RF.fit(x_train, y_train) # Get the oob error oob_error = 1 - RF.oob_score_ # Store it oob_list.append(pd.Series({'n_trees': n_trees, 'oob': oob_error})) rf_oob_d
conditional_block
supervised_ml_(classification)_assignment_(final).py
# -*- coding: utf-8 -*- """Supervised_ML_(Classification)_assignment_(final) Automatically generated by Colaboratory. Original file is located at https://colab.research.google.com/drive/1dt_czoLEqYxIoCA-v7Ynu0XHCWHnFWsB """ #import of libraries import pandas as pd import glob import numpy as np import seaborn as...
plt.show() """--- # Data Engineering/Modelling Because the data is already in a numerical form (int-type), it will not be required to engineer the data or reencode values. Though, given the tasks ahead, we may require data scaling for input into specific classifier models. We shall address this problem as we arr...
random_line_split
supervised_ml_(classification)_assignment_(final).py
# -*- coding: utf-8 -*- """Supervised_ML_(Classification)_assignment_(final) Automatically generated by Colaboratory. Original file is located at https://colab.research.google.com/drive/1dt_czoLEqYxIoCA-v7Ynu0XHCWHnFWsB """ #import of libraries import pandas as pd import glob import numpy as np import seaborn as...
e, y_pred, label): return pd.Series({'accuracy':accuracy_score(y_true, y_pred), 'precision': precision_score(y_true, y_pred), 'recall': recall_score(y_true, y_pred), 'f1': f1_score(y_true, y_pred)}, name=label) train_test_full_...
e_error(y_tru
identifier_name
supervised_ml_(classification)_assignment_(final).py
# -*- coding: utf-8 -*- """Supervised_ML_(Classification)_assignment_(final) Automatically generated by Colaboratory. Original file is located at https://colab.research.google.com/drive/1dt_czoLEqYxIoCA-v7Ynu0XHCWHnFWsB """ #import of libraries import pandas as pd import glob import numpy as np import seaborn as...
n_test_full_error = pd.concat([measure_error(y_train, y_train_pred, 'train'), measure_error(y_test, y_test_pred, 'test')], axis=1) train_test_full_error """The above output shows out accuracy prediction. This is quite low, could it be improved with Grid Sear...
pd.Series({'accuracy':accuracy_score(y_true, y_pred), 'precision': precision_score(y_true, y_pred), 'recall': recall_score(y_true, y_pred), 'f1': f1_score(y_true, y_pred)}, name=label) trai
identifier_body
tls.go
package main import ( "bytes" "context" "crypto/md5" "crypto/rand" "crypto/tls" "crypto/x509" "crypto/x509/pkix" "encoding/pem" "errors" "fmt" "io" "io/ioutil" "log" "math/big" "net" "net/http" "net/url" "runtime" "strings" "sync" "time" "github.com/open-ch/ja3" "go.starlark.net/starlark" "gol...
callStarlarkFunctions("ssl_bump", session) dialer := &net.Dialer{ Timeout: 30 * time.Second, KeepAlive: 30 * time.Second, DualStack: true, } if session.SourceIP != nil { dialer.LocalAddr = &net.TCPAddr{ IP: session.SourceIP, } } session.chooseAction() logAccess(cr, nil, 0, false, user, tally,...
{ session.PossibleActions = append(session.PossibleActions, "ssl-bump") }
conditional_block
tls.go
package main import ( "bytes" "context" "crypto/md5" "crypto/rand" "crypto/tls" "crypto/x509" "crypto/x509/pkix" "encoding/pem" "errors" "fmt" "io" "io/ioutil" "log" "math/big" "net" "net/http" "net/url" "runtime" "strings" "sync" "time" "github.com/open-ch/ja3" "go.starlark.net/starlark" "gol...
(certPath string) error { if c.ExtraRootCerts == nil { c.ExtraRootCerts = x509.NewCertPool() } pem, err := ioutil.ReadFile(certPath) if err != nil { return err } if !c.ExtraRootCerts.AppendCertsFromPEM(pem) { return fmt.Errorf("no certificates found in %s", certPath) } return nil }
addTrustedRoots
identifier_name
tls.go
package main import ( "bytes" "context" "crypto/md5" "crypto/rand" "crypto/tls" "crypto/x509" "crypto/x509/pkix" "encoding/pem" "errors" "fmt" "io" "io/ioutil" "log" "math/big" "net" "net/http" "net/url" "runtime" "strings" "sync" "time" "github.com/open-ch/ja3" "go.starlark.net/starlark" "gol...
session.ClientIP = client } obsoleteVersion := false invalidSSL := false // Read the client hello so that we can find out the name of the server (not // just the address). clientHello, err := readClientHello(conn) if err != nil { logTLS(user, serverAddr, "", fmt.Errorf("error reading client hello: %v", err)...
client := conn.RemoteAddr().String() if host, _, err := net.SplitHostPort(client); err == nil { session.ClientIP = host } else {
random_line_split
tls.go
package main import ( "bytes" "context" "crypto/md5" "crypto/rand" "crypto/tls" "crypto/x509" "crypto/x509/pkix" "encoding/pem" "errors" "fmt" "io" "io/ioutil" "log" "math/big" "net" "net/http" "net/url" "runtime" "strings" "sync" "time" "github.com/open-ch/ja3" "go.starlark.net/starlark" "gol...
var tlsSessionAttrNames = []string{"sni", "server_addr", "user", "client_ip", "acls", "scores", "source_ip", "action", "possible_actions", "header", "misc"} func (s *TLSSession) AttrNames() []string { return tlsSessionAttrNames } func (s *TLSSession) Attr(name string) (starlark.Value, error) { switch name { case...
{ return 0, errors.New("unhashable type: TLSSession") }
identifier_body
kek.py
#Импортирование библиотек import PySimpleGUI as sg from nltk.tokenize import word_tokenize from nltk.corpus import stopwords from nltk.stem import PorterStemmer import matplotlib.pyplot as plt from wordcloud import WordCloud from math import log import numpy as np import pandas as pd import nltk from sklearn.model_sele...
ие словрей спам и не спам слов spam_words = ' '.join(list(mails[mails['label'] == 1]['message'])) ham_words = ' '.join(list(mails[mails['label'] == 0]['message'])) trainData.head() trainData['label'].value_counts() testData.head() testData['label'].value_counts() #Обработка текста сообщений def process_message(mes...
ts() #Формирован
conditional_block
kek.py
#Импортирование библиотек import PySimpleGUI as sg from nltk.tokenize import word_tokenize from nltk.corpus import stopwords from nltk.stem import PorterStemmer import matplotlib.pyplot as plt from wordcloud import WordCloud from math import log import numpy as np import pandas as pd import nltk from sklearn.model_sele...
ate(spam_words) plt.figure(figsize = (10, 8), facecolor = 'k') plt.imshow(spam_wc) plt.axis('off') plt.tight_layout(pad = 0) plt.show() #Функция визуализации словаря легетимных слов def show_ham(ham_words): ham_wc = WordCloud(width = 512,height = 512).generate(ham_words) plt.figure(figsize =...
слов def show_spam(spam_words): spam_wc = WordCloud(width = 512,height = 512).gener
identifier_body
kek.py
#Импортирование библиотек import PySimpleGUI as sg from nltk.tokenize import word_tokenize from nltk.corpus import stopwords from nltk.stem import PorterStemmer import matplotlib.pyplot as plt from wordcloud import WordCloud from math import log import numpy as np import pandas as pd import nltk from sklearn.model_sele...
= self.spam_mails / self.total_mails, self.ham_mails / self.total_mails #Вычисление вероятностей def calc_TF_and_IDF(self): noOfMessages = self.mails.shape[0] self.spam_mails, self.ham_mails = self.labels.value_counts()[1], self.labels.value_counts()[0] self.total_mails = self.spam_mail...
_mail
identifier_name