file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
12.1k
suffix
large_stringlengths
0
12k
middle
large_stringlengths
0
7.51k
fim_type
large_stringclasses
4 values
rpc.rs
use crate::internal::common::WrappedRcRefCell; use crate::internal::messages::worker::{ FromWorkerMessage, StealResponseMsg, TaskResourceAllocation, TaskResourceAllocationValue, ToWorkerMessage, WorkerOverview, WorkerRegistrationResponse, WorkerStopReason, }; use crate::internal::server::rpc::ConnectionDescript...
use crate::internal::common::resources::map::ResourceMap; use crate::internal::common::resources::{Allocation, AllocationValue};
random_line_split
rpc.rs
_idle_timeout); let start_task_notify = Rc::new(Notify::new()); let comm = WorkerComm::new(queue_sender, start_task_notify.clone()); let state_ref = WorkerStateRef::new( comm, worker_id, configuration.clone(), ...
{ state.reset_idle_timer(); }
conditional_block
rpc.rs
ends. const MAX_WAIT_FOR_RUNNING_TASKS_SHUTDOWN: Duration = Duration::from_secs(5); /// Connects to the server and starts a message receiving loop. /// The worker will attempt to clean up after itself once it's stopped or once stop_flag is notified. pub async fn run_worker( scheduler_addresses: &[SocketAddr], ...
idle_timeout_process
identifier_name
mopac_qr.py
_keys: self.int_params[key] = None for key in bool_keys: self.bool_params[key] = None for key in float_keys: self.float_params[key] = None # set initial values functional = 'PM7' env = os.environ.get('MOPAC_FUNCTIONAL', None) if env: f...
(self,command): """ execute <command> in a subprocess and check error code """ from subprocess import Popen, PIPE, STDOUT if command == '': raise RuntimeError('no command for run_command :(') # print 'Running: ', command #debug proc = Popen([command], ...
run_command
identifier_name
mopac_qr.py
mopac_input += 'RELSCF=' + str(self.float_params['RELSCF']) + ' ' #write charge/ # charge = sum(atoms.get_initial_charges()) #if charge != 0: # mopac_input += 'CHARGE=%i ' % (charge) charge=self.int_params['charge'] mopac_input += 'CHARGE= ' + str(charge)+' ' ...
self.atoms = atoms_new.copy() self.run() def run_qr(self, atoms_new, **kwargs):
random_line_split
mopac_qr.py
_keys: self.int_params[key] = None for key in bool_keys: self.bool_params[key] = None for key in float_keys: self.float_params[key] = None # set initial values functional = 'PM7' env = os.environ.get('MOPAC_FUNCTIONAL', None) if env: f...
elif key in self.int_params: self.int_params[key] = kwargs[key] elif key in self.str_params: self.str_params[key] = kwargs[key] elif key in self.float_params: self.float_params[key] = kwargs[key] else: raise...
self.bool_params[key] = kwargs[key]
conditional_block
mopac_qr.py
spin spin = self.int_params['spin'] if spin == 1.: mopac_input += 'DOUBLET ' elif spin == 2.: mopac_input += 'TRIPLET ' #input down mopac_input += '\n' mopac_input += 'Title: ASE job\n\n' f = 1 # write coordinates for iat...
self.int_params['nproc'] = nproc
identifier_body
manager.go
Username, esCachePassword, authGrantType, authClientID, authClientSecret, authAudience, auth0URL, env, webHookURL string) (*Manager, error) { mng := &Manager{ Endpoint: endPoint, Slug: slug, SHConnString: shConnStr, FetcherBackendVersion: fetcherBackendVersion, Enri...
ESCacheURL: esCacheURL, ESCacheUsername: esCacheUsername, ESCachePassword: esCachePassword, AuthGrantType: authGrantType, AuthClientID: authClientID, AuthClientSecret: authClientSecret, AuthAudience: authAudience, Auth0URL: auth0...
AffBaseURL: affBaseURL,
random_line_split
manager.go
else { remainingItemsLength = len(data[lastIndex:]) } } else { // handle cases where remaining messages are less than the limit _, err = m.esClientProvider.BulkInsert(data[lastIndex:]) if err != nil { ch <- err return } // invalidate loop lastIndex = ...
{ u, err := url.Parse(targetURL) if err != nil { return "", err } path := u.Path if strings.HasPrefix(path, "/") { path = strings.TrimPrefix(path, "/") } if strings.HasSuffix(path, "/") { path = strings.TrimSuffix(path, "/") } path = strings.ReplaceAll(path, "/", "-") return path, nil }
identifier_body
manager.go
Username, esCachePassword, authGrantType, authClientID, authClientSecret, authAudience, auth0URL, env, webHookURL string) (*Manager, error) { mng := &Manager{ Endpoint: endPoint, Slug: slug, SHConnString: shConnStr, FetcherBackendVersion: fetcherBackendVersion, Enri...
() error { lastActionCachePostfix := "-last-action-date-cache" status := make(map[string]bool) status["doneFetch"] = !m.Fetch status["doneEnrich"] = !m.Enrich fetchCh := m.fetch(m.fetcher, lastActionCachePostfix) var err error if status["doneFetch"] == false { err = <-fetchCh if err == nil { status["do...
Sync
identifier_name
manager.go
Username, esCachePassword, authGrantType, authClientID, authClientSecret, authAudience, auth0URL, env, webHookURL string) (*Manager, error) { mng := &Manager{ Endpoint: endPoint, Slug: slug, SHConnString: shConnStr, FetcherBackendVersion: fetcherBackendVersion, Enri...
for _, message := range raw { data = append(data, elastic.BulkData{IndexName: fmt.Sprintf("%s-raw", m.ESIndex), ID: message.UUID, Data: message}) } // set mapping and create index if not exists _, err = m.esClientProvider.CreateIndex(fmt.Sprintf("%s-raw", m.ESIndex), PipermailRawMapping) if err != nil {...
{ from = &raw[len(raw)-1].ChangedAt }
conditional_block
main.py
device = 'cuda:0' if torch.cuda.is_available() else 'cpu' # initialize policy learning if args.learn_policy: policy = MLP(args.num_variables, [512, 256, 128]).float() policy = policy.to(device) policy_optimizer = torch.optim.Adam(policy.parameters(), lr=1e-4) rewards...
"""Executes a causal discovery algorithm on synthetic data from a sampled DAG, using a specified heuristic for choosing intervention variables. Args: args: Object from the argument parser that defines various settings of the causal structure and discovery process. """ # ini...
identifier_body
main.py
env = CausalEnv(num_vars=args.num_variables, min_categs=args.min_categories, max_categs=args.max_categories, graph_structure=args.graph_structure, edge_prob=args.edge_prob, dag=dag) obs_data = env.reset(n_samp...
def init_model(args: argparse.Namespace, device) -> Tuple[MultivarMLP, AdjacencyMatrix]: """Initializes a complete model of the causal structure, consisting of a multivariable MLP which models the conditional distributions of the causal variables, and gamma and theta values which define the adjacency ...
return log_probs_lst, reward_lst
random_line_split
main.py
env = CausalEnv(num_vars=args.num_variables, min_categs=args.min_categories, max_categs=args.max_categories, graph_structure=args.graph_structure, edge_prob=args.edge_prob, dag=dag) obs_data = env.reset(n_samp...
def train(args, env, obs_dataloader, device, policy=None): # initialize model of the causal structure model, adj_matrix = init_model(args, device) # initialize optimizers model_optimizer = torch.optim.Adam(model.parameters(), lr=args.lr_model, betas=args.betas_model) ...
train(args, env, obs_dataloader, device, policy)
conditional_block
main.py
(args: argparse.Namespace, dag: CausalDAG=None, policy=None): """Executes a causal discovery algorithm on synthetic data from a sampled DAG, using a specified heuristic for choosing intervention variables. Args: args: Object from the argument parser that defines various settings of ...
main
identifier_name
srt.rs
(&self, f: &mut Formatter<'_>) -> fmt::Result { f.debug_struct("KeyingMaterialMessage") .field("pt", &self.pt) .field("key_flags", &self.key_flags) .field("keki", &self.keki) .field("cipher", &self.cipher) .field("auth", &self.auth) .finish...
fmt
identifier_name
srt.rs
is enough space // salt + keys (there's a 1 for each in key flags, it's already been anded with 0b11 so max is 2), wrap data is 8 long if buf.remaining() < salt_len + key_len * (key_flags.bits().count_ones() as usize) + 8 { return Err(PacketParseError::NotEnoughData); } //...
{ let salt = b"\x00\x00\x00\x00\x00\x00\x00\x00\x85\x2c\x3c\xcd\x02\x65\x1a\x22"; let wrapped = b"U\x06\xe9\xfd\xdfd\xf1'nr\xf4\xe9f\x81#(\xb7\xb5D\x19{\x9b\xcdx"; let km = KeyingMaterialMessage { pt: PacketType::KeyingMaterial, key_flags: KeyFlags::EVEN, kek...
identifier_body
srt.rs
01; const ODD = 0b10; } } impl TryFrom<u8> for PacketType { type Error = PacketParseError; fn try_from(value: u8) -> Result<Self, Self::Error> { match value { 1 => Ok(PacketType::MediaStream), 2 => Ok(PacketType::KeyingMaterial), err => Err(PacketParseErr...
/// from https://github.com/Haivision/srt/blob/2ef4ef003c2006df1458de6d47fbe3d2338edf69/haicrypt/hcrypt_msg.h#L121-L124 #[derive(Debug, Clone, Copy, Eq, PartialEq)] pub enum CipherType { None = 0, Ecb = 1, Ctr = 2, Cbc = 3, } /// The SRT handshake object #[derive(Debug, Clone, Copy, Eq, PartialEq)] pu...
} }
random_line_split
play_blackjack.py
'└───────┘' def show_card(self): print(self.card_line1) print(self.card_line2) print(self.card_line3) print(self.card_line4) print(self.card_line5) print(self.card_line6) print(self.card_line7) class Deck(): # Create ...
if this Hand is in BUST state or not. ''' if self.hand_total() > 21: self.busted = True return True else: self.busted = False return False def show_hand(self): for card in self.cards: print(card.card_line1...
# sum the hand again to see if it is 21 or less. This will be repeated # if there are more Aces in the hand and the sum total remains over 21. aces -= 1 hand_value -= 10 if hand_value <= 21: # print(f"NOT BUST: Hand value i...
conditional_block
play_blackjack.py
'└───────┘' def show_card(self): print(self.card_line1) print(self.card_line2) print(self.card_line3) print(self.card_line4) print(self.card_line5) print(self.card_line6) print(self.card_line7) class Deck(): # Create ...
# These lists will be used to populate the Deck suits = [("Hearts","Red",0),("Diamonds","Red",1),("Clubs","Black",2),("Spades","Black",3)] names = [("Two",2,"2"),("Three",3,"3"),("Four",4,"4"),("Five",5,"5"),("Six",6,"6"),("Seven",7,"7"),("Eight",8,"8"),("Nine",9,"9"),("Ten",10,"10"),("Jack",10,"J"),("Quee...
identifier_name
play_blackjack.py
players. Let's # make it visible. card.set_hidden() player.add_card(card) # Once the card has been given out, we need to make sure to # remove it from the Deck, so that no one else gets...
y: bet = int(input(f"{player_hand.player}, how much would you like to bet? ($20 to $100)?")) except: print("You must enter a numeric value between 20 and 100.") bet = 0 player_hand.amount_bet = bet def play(): # Get the Deck ...
identifier_body
play_blackjack.py
'└───────┘'
print(self.card_line3) print(self.card_line4) print(self.card_line5) print(self.card_line6) print(self.card_line7) class Deck(): # Create a blank list to hold the cards that are # added to this Deck # cards = [] # These lists will be used to...
def show_card(self): print(self.card_line1) print(self.card_line2)
random_line_split
mod.rs
} } impl From<[Data; 6]> for Register { fn from(value: [Data; 6]) -> Self { Register(value) } } impl Index<Data> for Register { type Output = Data; fn index(&self, index: Data) -> &Self::Output { &self.0[index as usize] } } impl IndexMut<Data> for Register { fn index_mut(...
optimized
identifier_name
mod.rs
2 //! addi 0 1 0 //! addr 1 2 3 //! setr 1 0 0 //! seti 8 0 4 //! seti 9 0 5 //! ``` //! //! When executed, the following instructions are executed. Each line contains //! the value of the instruction pointer at the time the instruction started, //! the values of the six registers before executing the instructions (in...
//! bound to register 0 in this program. This is not an instruction, and so //! the value of the instruction pointer does not change during the processing //! of this line. //! * The instruction pointer contains 0, and so the first instruction is //! executed (seti 5 0 1). It updates register 0 to the current i...
//! In detail, when running this program, the following events occur: //! //! * The first line (#ip 0) indicates that the instruction pointer should be
random_line_split
mod.rs
2 //! addi 0 1 0 //! addr 1 2 3 //! setr 1 0 0 //! seti 8 0 4 //! seti 9 0 5 //! ``` //! //! When executed, the following instructions are executed. Each line contains //! the value of the instruction pointer at the time the instruction started, //! the values of the six registers before executing the instructions (in ...
, } } #[inline] fn _trace(ip: Addr, Instruction { opcode, a, b, c }: Instruction, reg: &Register) { match opcode { AddR => println
{ 0 }
conditional_block
outputschedule.py
0.7, ## 1.5, etc. If the end time is 1, the output times will be ## 0.1, 0.3, 0.7, and 1.0. If the solution is continued, the ## next time will be 3.1, although it probably should be 1.5. if self.lasttime is None: self.lasttime = self.time0 self.lasttime += self.nex...
for output in self.outputs: output.save(datafile, meshctxt)
identifier_body
outputschedule.py
to distinguish between static and # quasistatic evolutions. return None def setOffset(self, time0): # adjust for relative vs absolute scheduletypes self.time0 = time0 class UnconditionalSchedule(Schedule): conditional = False def __iter__(self): return self class Condition...
names
identifier_name
outputschedule.py
def __init__(self): self.time0 = 0.0 def reset(self, continuing): pass def singleTime(self): # In subclasses this should return the time if the Schedule # contains only a single time, or None if the Schedule # contains multiple times. If it contains a single unknown ...
random_line_split
outputschedule.py
def __init__(self): self.time0 = 0.0 def reset(self, continuing): pass def singleTime(self): # In subclasses this should return the time if the Schedule # contains only a single time, or None if the Schedule # contains multiple times. If it contains a single unknown ...
return False
conditional_block
dynamic_model_python_basic.py
0., 0.])) return f_engines_body def get_f_aero_body(X, Usfc, P, Pdyn): """ return aerodynamic forces expressed in body frame """ d_alpha = X[sv_alpha] - P.alpha0 rvel = X[sv_p:sv_r+1]*np.array([P.Bref, P.Cref, P.Bref])/2/P.Vref CL = P.CL0 + P.CL_alpha*d_alpha + P.CL_beta*X[sv_beta] +\ ...
print "Info: Dynamic fixed wing basic" dm.DynamicModel.__init__(self) if params == None: params="../config/Rcam_single_engine.xml" self.X = np.zeros(DynamicModel.sv_size) self.P = Param(params) self.reset()
identifier_body
dynamic_model_python_basic.py
)/X[sv_v] u, v, w = vel_body ud, vd, wd = accel_body Xdot[sv_alpha] = (u*wd - w*ud)/(u**2+w**2) Xdot[sv_beta] = (X[sv_v]*vd - v*Xdot[sv_v]) / X[sv_v] / math.sqrt(u**2+w**2) Xdot[sv_phi:sv_psi+1] = pal.euler_derivatives(X_euler, X_rvel_body) Xdot[sv_p:sv_r+1] = raccel_body return Xdot ...
ax = plt.subplot(nrow, 3, i+1) plt.plot(time, data) pu.decorate(ax, title=title, ylab=ylab)
conditional_block
dynamic_model_python_basic.py
.Bref])/2/P.Vref Cl = P.Cl_alpha*d_alpha + P.Cl_beta*X[sv_beta] +\ np.dot(P.Cl_omega,rvel) + np.dot(P.Cl_sfc,Usfc) Cm = P.Cm0 + P.Cm_alpha*d_alpha + P.Cm_beta*X[sv_beta] +\ np.dot(P.Cm_omega,rvel) + np.dot(P.Cm_sfc,Usfc) Cn = P.Cn_alpha*d_alpha + P.Cn_beta*X[sv_beta] +\ ...
get_jacobian
identifier_name
dynamic_model_python_basic.py
cb , 0.], [sa*cb, -sa*sb, ca]]) def get_f_eng_body(X, U, P): """ return propulsion forces expressed in body frame """ rho = patm.get_rho(-X[sv_z]) f_engines_body = np.zeros((P.eng_nb, 3)) for i in range(0, P.eng_nb): thrust = U[i]*P.fmaxs[i]*math.pow((rho/P.rh...
Xdot = dyn(X, 0., U, P) Xdot_ref = [va*math.cos(gamma), 0., -va*math.sin(gamma), 0., 0., 0., 0., 0., 0., 0., 0., 0.] return np.linalg.norm(Xdot - Xdot_ref) p0 = [0.2, pu.rad_of_deg(2.), pu.rad_of_deg(0.)] thr_e, ele_e, alpha_e = scipy.optimize.fmin_powell(err_func, p0, disp=debug, ftol=...
def err_func((throttle, elevator, alpha)): X=[0., 0., -h, va, alpha, 0., 0., gamma+alpha, 0., 0., 0., 0.] U = np.zeros(P.input_nb) U[0:P.eng_nb] = throttle; U[P.eng_nb+iv_de] = elevator
random_line_split
ibazel_test.go
'd") debug.PrintStack() case <-time.After(time.Second): // works as expected } } type mockCommand struct { startupArgs []string bazelArgs []string target string args []string notifiedOfChanges bool started bool terminated bool signalChan chan syscall.Signal doTermChan ...
m.signalChan <- syscall.SIGTERM <-m.doTermChan m.terminated = true m.didTermChan <- struct{}{} } func (m *mockCommand) Kill() { if !m.started { panic("Sending kill signal before terminating") } m.signalChan <- syscall.SIGKILL } func (m *mockCommand) assertTerminated(t *testing.T) { select { case <-m.didTerm...
{ panic("Terminated before starting") }
conditional_block
ibazel_test.go
m.terminated = true m.didTermChan <- struct{}{} } func (m *mockCommand) Kill() { if !m.started { panic("Sending kill signal before terminating") } m.signalChan <- syscall.SIGKILL } func (m *mockCommand) assertTerminated(t *testing.T) { select { case <-m.didTermChan: // works as expected case <-time.After(t...
TestHandleSignals_SIGINTNormalTermination
identifier_name
ibazel_test.go
func assertOsExited(t *testing.T, osExitChan chan int) { select { case exitCode := <-osExitChan: assertEqual(t, 3, exitCode, "Should have exited ibazel") case <-time.After(time.Second): t.Errorf("It should have os.Exit'd") debug.PrintStack() } } func assertNotOsExited(t *testing.T, osExitChan chan int) { se...
{ if !reflect.DeepEqual(want, got) { t.Errorf("Wanted %s, got %s. %s", want, got, msg) debug.PrintStack() } }
identifier_body
ibazel_test.go
.Events() <-i.buildFileWatcher.Events() } func TestIBazelLoop(t *testing.T) { log.SetTesting(t) i, mockBazel := newIBazel(t) mockBazel.AddQueryResponse("buildfiles(deps(set(//my:target)))", &blaze_query.QueryResult{}) mockBazel.AddQueryResponse("kind('source file', deps(set(//my:target)))", &blaze_query.QueryRes...
cmd.assertSignal(t, syscall.SIGKILL) cmd.doTermChan <- struct{}{} cmd.assertTerminated(t) assertNotOsExited(t, osExitChan)
random_line_split
ym.rs
X X X X Fine period voice A /// 1: S S S S X X X X Coarse period voice A /// 2: X X X X X X X X Fine period voice B /// 3: S S S S X X X X Coarse period voice B /// 4: X X X X X X X X Fine period voice C /// 5: - - - - X X X X Coarse period voice C /// 6: P...
{ self.chipset_frequency = chipset_frequency; self.frame_frequency = frame_frequency; self }
identifier_body
ym.rs
/// 1: S S S S X X X X Coarse period voice A /// 2: X X X X X X X X Fine period voice B /// 3: S S S S X X X X Coarse period voice B /// 4: X X X X X X X X Fine period voice C /// 5: - - - - X X X X Coarse period voice C /// 6: P P P X X X X X Noise per...
song_duration
identifier_name
ym.rs
. pub chipset_frequency: u32, /// The number of frames played each second. pub frame_frequency: u16, /// The loop frame index. pub loop_frame: u32, /// The AY/YM state frames. pub frames: Box<[YmFrame]>, /// `DIGI-DRUM` samples. pub dd_samples: Box<[u8]>, /// `DIGI-DRUM` sample e...
/// uses one of the 40 predefined samples. /// /// * The effect starts when the highest bit (7) of the `Volume voice C` register (10) is 1. /// * The sample number is taken from the lowest 7 bits of the `Volume voice C` register (10). /// * The effect frequency is calculated by `(2457600 / 4) / X`, where `X` is the uns...
random_line_split
coprocessor.rs
self.tx.send(EndPointMessage::Close) { error!("failed to ask the coprocessor to stop: {:?}", e); } if let Err(e) = self.handle.take().unwrap().join() { error!("failed to stop the coprocessor: {:?}", e); } } } fn handle_request(req: Request, ch: Sen...
{ let mut rows = vec![]; let mut seek_key = r.take_start(); loop { trace!("seek {:?}", seek_key); let mut nk = try!(snap.scan(Key::from_raw(seek_key.clone()), 1)); if nk.is_empty() { debug!("no more data to scan"); return Ok(rows); } let (key, ...
identifier_body
coprocessor.rs
(&mut self) { if self.handle.is_none() { return; } if let Err(e) = self.tx.send(EndPointMessage::Close) { error!("failed to ask the coprocessor to stop: {:?}", e); } if let Err(e) = self.handle.take().unwrap().join() { error!("failed to stop th...
return Ok(rows); } let mut datums = box_try!(table::decode_index_key(&key)); let handle = if datums.len() > info.get_columns().len() { datums.pop().unwrap()
random_line_split
coprocessor.rs
_TYPE_INDEX: i64 = 102; const DEFAULT_ERROR_CODE: i32 = 1; quick_error! { #[derive(Debug)] pub enum Error { Region(err: errorpb::Error) { description("region related failure") display("region {:?}", err) } Locked(l: LockInfo) { description("key is lo...
(req: Request, ch: SendCh, token: Token, msg_id: u64, end_point: &SnapshotEndPoint) { let cb = box move |r| { let mut resp_msg = Message::new(); resp_msg.set_msg_type(MessageType::CopResp); resp_msg.set_cop_resp(r); ...
handle_request
identifier_name
ReviewIntangibleAssets.js
.setMonth(d.getMonth() + 1); for (var i = 0; i < 3; i++) { debugger;
ength == 0) { arr.push("Default"); } var dataAdapter = new $.jqx.dataAdapter(arr); $("#SubmitYearMonth").jqxComboBox({ selectedIndex: 0, source: dataAdapter, width: 198, height: 33 }); $("#SubmitYearMonth").jqxComboBox({ itemHeight: 33 }); $("#SubmitYearMonth input")....
var m = d.getMonth() - i; var y = d.getFullYear(); if (m <= 0) { m = m + 12; y = y - 1; } m = (m < 10 ? "0" + m : m); arr.push(y.toString() + "-" + m.toString()); } debugger; if (arr.l
conditional_block
ReviewIntangibleAssets.js
arr.push(y.toString() + "-" + m.toString()); } debugger; if (arr.length == 0) { arr.push("Default"); } var dataAdapter = new $.jqx.dataAdapter(arr); $("#SubmitYearMonth").jqxComboBox({ selectedIndex: 0, source: dataAdapter, width: 198, height: 33 }...
e='z-index: 999;
identifier_name
ReviewIntangibleAssets.js
= new $.jqx.dataAdapter(arr); $("#SubmitYearMonth").jqxComboBox({ selectedIndex: 0, source: dataAdapter, width: 198, height: 33 }); $("#SubmitYearMonth").jqxComboBox({ itemHeight: 33 }); $("#SubmitYearMonth input").click(function () { $("#SubmitYearMonth").jqxComboBox('clearSelectio...
var grid = selector.$grid();
random_line_split
ReviewIntangibleAssets.js
.setMonth(d.getMonth() + 1); for (var i = 0; i < 3; i++) { debugger; var m = d.getMonth() - i; var y = d.getFullYear(); if (m <= 0) { m = m + 12; y = y - 1; } m = (m < 10 ? "0" + m : m); arr.push(...
var source = { dataf ields: [ { name: "checkbox", type: null }, { name: 'VGUID', type: 'string' }, { name: 'OrderNumber', type: 'string' }, { name: 'PayItem', type: 'string' }, ...
success: function (msg) { switch (msg.Status) { case "0": jqxNotification("提交失败!", null, "error"); break; case "1": jqxNotification("提交成功!", null, "success"); ...
identifier_body
__main__.py
License for the specific language governing permissions and # limitations under the License. import sys import pkg_resources import subprocess import os import os.path from docopt import docopt import re __version__ = pkg_resources.get_distribution("git_devbliss").version github_devbliss = pkg_resources.load_entry_...
(): # check if pwd is repository root in order to run makefile hooks properly rev_parse = git('rev-parse --show-toplevel', pipe=True).strip() if os.path.abspath(rev_parse) != os.path.abspath(os.getcwd()): print('You need to run this command from the toplevel' ' of the working tree.', f...
check_repo_toplevel
identifier_name
__main__.py
License for the specific language governing permissions and # limitations under the License. import sys import pkg_resources import subprocess import os import os.path from docopt import docopt import re __version__ = pkg_resources.get_distribution("git_devbliss").version github_devbliss = pkg_resources.load_entry_...
def release(version): if not re.match(r'^\d+\.\d+\.\d+$', version): print('Invalid version number', file=sys.stderr) sys.exit(2) git('fetch --quiet origin') branch = git('rev-parse --abbrev-ref HEAD', pipe=True) if not is_repository_clean(): print('Error: Repository is not c...
if branch_name == 'finish': print('You are creating a branch "{branch_type}/{branch_name}". ' 'Did you mean to type "git devbliss finish"?'.format(**locals())) print('You can delete this branch with "git devbliss delete' ' {branch_type}/{branch_name}"'.format(**locals())) ...
identifier_body
__main__.py
License for the specific language governing permissions and # limitations under the License. import sys import pkg_resources import subprocess import os import os.path from docopt import docopt import re __version__ = pkg_resources.get_distribution("git_devbliss").version github_devbliss = pkg_resources.load_entry_...
try: git('checkout --quiet -b {branch_type}/{branch_name}'.format( **locals())) except subprocess.CalledProcessError: git('checkout --quiet {branch_type}/{branch_name}'.format( **locals())) git('push --set-upstream origin {branch_type}/{branch_name}'.format( *...
print('You can delete this branch with "git devbliss delete' ' {branch_type}/{branch_name}"'.format(**locals())) git('checkout --quiet master') git('pull --quiet origin master')
random_line_split
__main__.py
License for the specific language governing permissions and # limitations under the License. import sys import pkg_resources import subprocess import os import os.path from docopt import docopt import re __version__ = pkg_resources.get_distribution("git_devbliss").version github_devbliss = pkg_resources.load_entry_...
else: print('Warning: No Makefile found. All make hooks have been skipped.', file=sys.stderr) def branch(branch_type, branch_name): if branch_name == 'finish': print('You are creating a branch "{branch_type}/{branch_name}". ' 'Did you mean to type "git devbliss fin...
os.system( '{env_vars} make {hook} || echo "Warning: Makefile has no target' ' named {hook}"'.format(**locals())) if not is_repository_clean(): git('commit --quiet -am "Ran git devbliss {hook} hook"'.format( **locals()))
conditional_block
server.rs
<()>), ) -> Result<(), Error> where F: FnMut(Server, Option<mpsc::Receiver<LogEntry>>), { let mining_config = config.stratum_mining_config.clone(); let enable_test_miner = config.run_test_miner; let test_miner_wallet_url = config.test_miner_wallet_url.clone(); let serv = Server::new(config, stop_state, api...
(&self) -> Result<(), Error> { let head = self.chain.head()?; self.p2p.peers.check_all(head.total_difficulty, head.height); Ok(()) } /// Number of peers pub fn peer_count(&self) -> u32 { self.p2
ping_peers
identifier_name
server.rs
-> Result<Server, Error> { // Obtain our lock_file or fail immediately with an error. let lock_file = Server::one_grin_at_a_time(&config)?; // Defaults to None (optional) in config file. // This translates to false here. let archive_mode = match config.archive_mode { None => false, Some(b) => b, }; ...
{ self.chain.head().map_err(|e| e.into()) }
identifier_body
server.rs
seed_list, config.p2p_config.clone(), stop_state.clone(), )?); } // Defaults to None (optional) in config file. // This translates to false here so we do not skip by default. let skip_sync_wait = config.skip_sync_wait.unwrap_or(false); sync_state.update(SyncStatus::AwaitingPeers(!skip_sync_wait))...
let header_stats = ChainStats { latest_timestamp: header.timestamp, height: header.height, last_block_h: header.hash(), total_difficulty: header.total_difficulty(),
random_line_split
server.rs
<()>), ) -> Result<(), Error> where F: FnMut(Server, Option<mpsc::Receiver<LogEntry>>), { let mining_config = config.stratum_mining_config.clone(); let enable_test_miner = config.run_test_miner; let test_miner_wallet_url = config.test_miner_wallet_url.clone(); let serv = Server::new(config, stop_state, api...
}, p2p::Seeding::DNSSeed => seed::default_dns_seeds(), _ => unreachable!(), }; connect_thread = Some(seed::connect_and_monitor( p2p_server.clone(), seed_list, config.p2p_config.clone(), stop_state.clone(), )?); } // Defaults to None (optional) in config file. // This transl...
{ return Err(Error::Configuration( "Seeds must be configured for seeding type List".to_owned(), )); }
conditional_block
genesis.pb.go
0x34, 0xd2, 0x33, 0x4b, 0x32, 0x4a, 0x93, 0xf4, 0x92, 0xf3, 0x73, 0xf5, 0xbd, 0x33, 0x8b, 0x12, 0x9d, 0xf3, 0x8b, 0x52, 0xf5, 0x8b, 0x53, 0xb3, 0x13, 0x33, 0xf5, 0x2b, 0x60, 0xe1, 0x50, 0x52, 0x59, 0x90, 0x5a, 0x9c, 0xc4, 0x06, 0x0e, 0x07, 0x63, 0x40, 0x00, 0x00, 0x00, 0xff, 0xff, 0xad, 0xea, 0x38, 0x58, 0x7c, 0x01,...
{ return io.ErrUnexpectedEOF }
conditional_block
genesis.pb.go
Rates []*TokenRate `protobuf:"bytes,2,rep,name=rates,proto3" json:"rates,omitempty"` TokenBlackWhites *TokensWhiteBlack `protobuf:"bytes,3,opt,name=tokenBlackWhites,proto3" json:"tokenBlackWhites,omitempty"` } func (m *GenesisState) Reset() { *m = GenesisState{} } func (m *GenesisState) Strin...
type GenesisState struct { Aliases []*TokenAlias `protobuf:"bytes,1,rep,name=aliases,proto3" json:"aliases,omitempty"`
random_line_split
genesis.pb.go
() {} func (*GenesisState) Descriptor() ([]byte, []int) { return fileDescriptor_d3cbd9121e22d5d1, []int{0} } func (m *GenesisState) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } func (m *GenesisState) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { return xxx_messageInfo...
ProtoMessage
identifier_name
genesis.pb.go
var xxx_messageInfo_GenesisState proto.InternalMessageInfo func (m *GenesisState) GetAliases() []*TokenAlias { if m != nil { return m.Aliases } return nil } func (m *GenesisState) GetRates() []*TokenRate { if m != nil { return m.Rates } return nil } func (m *GenesisState) GetTokenBlackWhites() *TokensWhi...
{ xxx_messageInfo_GenesisState.DiscardUnknown(m) }
identifier_body
util.js
time: 'HH:MM:ss', datetime: 'yyyy-mm-dd HH:MM:ss', now: function () { return Date() }, format: function (date, format) { return dateFormat(date, format) } } export const HtmlUtil = { specialchars: function (str) { var s = []; if (!str) { return ''; ...
} else { ret += chr; } } return ret; }, getQueries(query = undefined) { return UrlUtil.parseQuery(query) }, getQuery(key, defaultValue = null, query = undefined) { const param = UrlUtil.parseQuery(query) if (key in param) { ...
ret += asc2str(parseInt("0x" + asc)); i += 2; }
conditional_block
util.js
time: 'HH:MM:ss', datetime: 'yyyy-mm-dd HH:MM:ss', now: function () { return Date() }, format: function (date, format) { return dateFormat(date, format) } } export const HtmlUtil = { specialchars: function (str) { var s = []; if (!str) { return ''; ...
export const FormatUtil = { telephone(number) { if (!number) { return null } // console.log('before',number); [/\+86/g, /\+/g, / /g, /\(/g, /\)/g, /-/g, /(/g, /)/g, / /g, /"/g, /;/g, /\t/g].forEach(o => { number = number.replace(o, '') }) // co...
random_line_split
util.js
time: 'HH:MM:ss', datetime: 'yyyy-mm-dd HH:MM:ss', now: function () { return Date() }, format: function (date, format) { return dateFormat(date, format) } } export const HtmlUtil = { specialchars: function (str) { var s = []; if (!str) { return ''; ...
bean,beanNewValue可以是部分字段 * @param bean * @param beanNewValue */ update(bean, beanNewValue) { if (!bean || !beanNewValue) { return } Object.keys(beanNewValue).map(o => { bean[o] = beanNewValue[o] }) }, /** * 判断两个Bean是否相等,注意键值的顺序也要一样 ...
return } Object.keys(bean).map(o => { bean[o] = valuePool[o] }) }, /** * 使用 beanNewValue 更新
identifier_body
util.js
: 'HH:MM:ss', datetime: 'yyyy-mm-dd HH:MM:ss', now: function () { return Date() }, format: function (date, format) { return dateFormat(date, format) } } export const HtmlUtil = { specialchars: function (str) { var s = []; if (!str) { return ''; ...
{ let ret = ""; const strSpecial = "!\"#$%&'()*+,/:;<=>?[]^`{|}~%"; let tt = ""; for (let i = 0; i < str.length; i++) { let chr = str.charAt(i); let c = str2asc(chr); tt += chr + ":" + c + "n"; if (parseInt("0x" + c) > 0x7f) { ...
ode(str)
identifier_name
fileopentypeenum.go
ups. var mFileOpenTypeLwrCaseStringToInt = map[string]int{} // FileOpenType - In order to open a file, exactly one of the // following File Open Codes MUST be specified: // // FileOpenType(0).TypeReadOnly() // FileOpenType(0).TypeWriteOnly() // FileOpenType(0).TypeReadWrite() // // In addition, one of the three pr...
// for this type. // func (fOpenType FileOpenType) IsValid() error { fOpenType.checkInitializeMaps(false) _, ok := mFileOpenTypeIntToString[int(fOpenType)] if !ok { ePrefix := "FileOpenType.IsValid() " return fmt.Errorf(ePrefix+ "Error: Invalid FileOpenType! Current FileOpenType='%v'", fOpe...
// this method will return an error. If the FileOpenType is 'valid', // this method will return a value of 'nil'. // // This is a standard utility method and is not part of the valid enumerations
random_line_split
fileopentypeenum.go
. var mFileOpenTypeLwrCaseStringToInt = map[string]int{} // FileOpenType - In order to open a file, exactly one of the // following File Open Codes MUST be specified: // // FileOpenType(0).TypeReadOnly() // FileOpenType(0).TypeWriteOnly() // FileOpenType(0).TypeReadWrite() // // In addition, one of the three previo...
var ok bool var idx int if caseSensitive { if !strings.HasPrefix(valueString, "Type") { valueString = "Type" + valueString } idx, ok = mFileOpenTypeStringToInt[valueString] if !ok { return FileOpenType(0), fmt.Errorf(ePrefix+ "'valueString' did NOT MATCH a FileO...
{ return result, fmt.Errorf(ePrefix+ "Input parameter 'valueString' is INVALID! valueString='%v' ", valueString) }
conditional_block
fileopentypeenum.go
. var mFileOpenTypeLwrCaseStringToInt = map[string]int{} // FileOpenType - In order to open a file, exactly one of the // following File Open Codes MUST be specified: // // FileOpenType(0).TypeReadOnly() // FileOpenType(0).TypeWriteOnly() // FileOpenType(0).TypeReadWrite() // // In addition, one of the three previo...
// ReadOnly - File opened for 'Read Only' access func (fOpenType FileOpenType) TypeReadOnly() FileOpenType { return FileOpenType(os.O_RDONLY) } // WriteOnly - File opened for 'Write Only' access func (fOpenType FileOpenType) TypeWriteOnly() FileOpenType { return FileOpenType(os.O_WRONLY) } // ReadWrite - File opene...
{ return -1 }
identifier_body
fileopentypeenum.go
ups. var mFileOpenTypeLwrCaseStringToInt = map[string]int{} // FileOpenType - In order to open a file, exactly one of the // following File Open Codes MUST be specified: // // FileOpenType(0).TypeReadOnly() // FileOpenType(0).TypeWriteOnly() // FileOpenType(0).TypeReadWrite() // // In addition, one of the three pr...
() FileOpenType { return FileOpenType(os.O_RDONLY) } // WriteOnly - File opened for 'Write Only' access func (fOpenType FileOpenType) TypeWriteOnly() FileOpenType { return FileOpenType(os.O_WRONLY) } // ReadWrite - File opened for 'Read and Write' access func (fOpenType FileOpenType) TypeReadWrite() FileOpenType { re...
TypeReadOnly
identifier_name
activeTopicPage.js
Page(); }).on('tap', '.add-cart', function (event) { event.preventDefault(); var id=$(this).parents('.goods').data('id'), price = parseFloat($(this).parents('.goods-info').find('.price').text()); if(!isApp){ URL.assign(decodeURI('http://test.un...
identifier_body
activeTopicPage.js
/js/common/transDialog' ], function ($, Data, Common,LoadImage, Nexter, Goods, Cart, WeiXin, URL,Banner,Dialog) { var Page, CateTabs, dialog, Cates = Storage.Cates.get(), isApp = URL.param.isApp, topicId = URL.param.topicId, parameter = '', firstLoad = true...
gid = view.data('id'), item = Cart.query(gid) || Cart.create(Goods.query(gid)); if (item) { item.add({ btn: btn, start: function(newCount) { btn.addClass('adding'); view.find('.count').text(newCount); ...
ds'),
identifier_name
activeTopicPage.js
firstLoad = true; function init() { render(); //Common.to_Top('#listPage');//返回顶部 } function render() { Page = $('<div id="listPage"> <section id="_listPage"><div class="scroll-content"><div class="banner pic-carousel" id="banner" data-banner="418"><img src=""/> </div><div class=...
} }); }, count: 1,
random_line_split
activeTopicPage.js
.returnPrePage(); }).on('tap', '.add-cart', function (event) { event.preventDefault(); var id=$(this).parents('.goods').data('id'), price = parseFloat($(this).parents('.goods-info').find('.price').text()); if(!isApp){ URL.assign(decodeURI('http...
}); } } function refreshCart() { Common.getCartCount(); Common.isLogin && Cart.ready(function() { // renderSmallCart(); // refreshListCount(); }); }
conditional_block
main.go
8.10.135", Port: 80, Channel: "730836803556343808", // laser } DeviceMap["laser2"] = deviceStruct{ Name: "laser", Hostname: "192.168.10.136", Port: 80, Channel: "730836803556343808", // laser } ActionMap["maintenance"] = actionStruct{ Name: "maintenance", States: []string{"on", "of...
if err != nil { log.Fatal(err) } var mystatus shortStatusResult err = json.Unmarshal([]byte(bodyBytes), &mystatus) if err != nil { fmt.Println("unmarshal error: ") fmt.Println(err) } var returnText = "" if mystatus.State == "on" { returnText = Emojis["laseron"] + " **" + strings.ToUpper(myst...
resp, err := client.Do(req) if resp.StatusCode == http.StatusOK { bodyBytes, err := ioutil.ReadAll(resp.Body)
random_line_split
main.go
NewRequest: ", err) return "" } client := &http.Client{} client.Timeout = time.Second * 15 resp, err := client.Do(req) if resp.StatusCode == http.StatusOK { bodyBytes, err := ioutil.ReadAll(resp.Body) if err != nil { log.Fatal(err) } var mystatus shortStatusResult err = json.Unmarshal([]byte(bodyByt...
{ fmt.Println("starting handlerLaser2") queries := r.URL.Query() fmt.Printf("queries = %q\n", queries) if APITOKEN != queries.Get("api") { fmt.Fprintf(webprint, "%s", "ERROR: Invalid API") return } var returnText = "" switch strings.ToLower(queries.Get("action")) { case "off": returnText = Emojis["eeht...
identifier_body
main.go
.10.135", Port: 80, Channel: "730836803556343808", // laser } DeviceMap["laser2"] = deviceStruct{ Name: "laser", Hostname: "192.168.10.136", Port: 80, Channel: "730836803556343808", // laser } ActionMap["maintenance"] = actionStruct{ Name: "maintenance", States: []string{"on", "off...
if m.Content == "!laser backlight on" { s.ChannelMessageSend(m.ChannelID, backlight("on")) } if m.Content == "!laser backlight off" { s.ChannelMessageSend(m.ChannelID, backlight("off")) } if m.Content == "!laser fullstatus" { s.ChannelMessageSend(m.ChannelID, fullStatus()) } if m.Content == "!laser he...
{ return }
conditional_block
main.go
Map[steve].Name, " Host:", DeviceMap[steve].Hostname, ":", DeviceMap[steve].Port, " Channel:", DeviceMap[steve].Channel) steve = "laser2" fmt.Println("Name:", DeviceMap[steve].Name, " Host:", DeviceMap[steve].Hostname, ":", DeviceMap[steve].Port, " Channel:", DeviceMap[steve].Channel) */ for k, v := range Device...
backlightold
identifier_name
hkdf_test.rs
1e55298da9d0506b9ae52057220a306e07b6b87e8df21d0ea00033de03984d34918", }, Rfc5869Test{ hash: HashType::Sha1, key: "0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c", salt: "", info: "", output_length: 42, okm...
{ assert!( HkdfPrf::new( HashType::Sha256, &[ 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10 ], &[] ) .is_ok(), "Expected HkdfPrf::new to work empty salt" ...
identifier_body
hkdf_test.rs
132333435363738393a3b3c3d3e3f404142434445464748494a4b4c4d4e4f", salt: "606162636465666768696a6b6c6d6e6f707172737475767778797a7b7c7d7e7f808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9fa0a1a2a3a4a5a6a7a8a9aaabacadaeaf", info: "b0b1b2b3b4b5b6b7b8b9babbbcbdbebfc0c1c2c3c...
0x0f, 0x10 ],
random_line_split
hkdf_test.rs
2d9d201395faa4b61a96c8", }, Rfc5869Test{ hash: HashType::Sha1, key: "0b0b0b0b0b0b0b0b0b0b0b", salt: "000102030405060708090a0b0c", info: "f0f1f2f3f4f5f6f7f8f9", output_length: 42, okm: "085a01ea1b...
{ assert_eq!( res, tc.okm, "Computed HKDF {:?} PRF and expected for test case {} ({}) do not match", hash, tc.case.case_id, tc.case.comment ); }
conditional_block
hkdf_test.rs
5f6f7f8f9fafbfcfdfeff", output_length: 82, okm: "b11e398dc80327a1c8e7f78c596a49344f012eda2d4efad8a050cc4c19afa97c59045a99cac7827271cb41c65e590e09da3275600c2f09b8367793a9aca3db71cc30c58179ec3e87c14c01d5c1f3434f1d87", }, Rfc5869Test{ hash: HashType::Sha25...
() { for hash in &[HashType::Sha1, HashType::Sha256, HashType::Sha512] { let hash_name = format!("{:?}", hash); let filename = format!("testvectors/hkdf_{}_test.json", hash_name.to_lowercase()); println!("wycheproof file '{}' hash {}", filename, hash_name); let bytes = tink_tests::wy...
test_hkdf_prf_wycheproof_cases
identifier_name
config.rs
impl TendermintConfig { /// Parse Tendermint `config.toml` pub fn parse_toml<T: AsRef<str>>(toml_string: T) -> Result<Self, Error> { Ok(toml::from_str(toml_string.as_ref())?) } /// Load `config.toml` from a file pub fn load_toml_file<P>(path: &P) -> Result<Self, Error> where P: ...
(String); impl AsRef<str> for CorsMethod { fn as_ref(&self) -> &str { self.0.as_ref() } } impl fmt::Display for CorsMethod { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", &self.0) } } /// HTTP headers allowed to be sent via CORS to the RPC API // TODO(tarc...
CorsMethod
identifier_name
config.rs
impl TendermintConfig { /// Parse Tendermint `config.toml` pub fn parse_toml<T: AsRef<str>>(toml_string: T) -> Result<Self, Error> { Ok(toml::from_str(toml_string.as_ref())?) } /// Load `config.toml` from a file pub fn load_toml_file<P>(path: &P) -> Result<Self, Error> where P: ...
let key = parts[0].to_owned(); let value = parts[1].to_owned(); if levels.insert(key, value).is_some() { return Err(err!( ErrorKind::Parse, "duplicate log level setting for: {}", level )); ...
{ return Err(err!(ErrorKind::Parse, "error parsing log level: {}", level)); }
conditional_block
config.rs
impl TendermintConfig { /// Parse Tendermint `config.toml` pub fn parse_toml<T: AsRef<str>>(toml_string: T) -> Result<Self, Error> { Ok(toml::from_str(toml_string.as_ref())?) } /// Load `config.toml` from a file pub fn load_toml_file<P>(path: &P) -> Result<Self, Error> where P: ...
} /// Mechanism to connect to the ABCI application: socket | grpc #[derive(Copy, Clone, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)] pub enum AbciMode { /// Socket #[serde(rename = "socket")] Socket, /// GRPC #[serde(rename = "grpc")] Grpc, } /// Tendermint `config.toml` file's `[rpc]...
Plain, /// JSON #[serde(rename = "json")] Json,
random_line_split
wvc_data.py
[], 0.01 for k in np.unique(self.img_labels): idxs = np.where(self.img_labels == k)[0] idxs = np.random.choice(idxs, int(np.ceil(len(idxs)*frac)), replace=False) sampled_idxs.extend(idxs.tolist()) self.img_ids, self.img_files, self.img_labels = se...
class JigsawTransform: def __init__(self, grid_size=3, patch_size=64): self.grid_size = grid_size self.patch_size = patch_size def __call__(self, img): w, h = img.size crops = [] for c_i, c_j in itertools.product(range(self.grid_size), range(self.grid_size)): ...
return self.num_samples
identifier_body
wvc_data.py
[], 0.01 for k in np.unique(self.img_labels): idxs = np.where(self.img_labels == k)[0] idxs = np.random.choice(idxs, int(np.ceil(len(idxs)*frac)), replace=False) sampled_idxs.extend(idxs.tolist()) self.img_ids, self.img_files, self.img_labels = se...
self.class_freq = -1*np.ones(5000) self.sample_weight = np.ones(self.img_labels.size, np.float) _logger.info("Webvision {} dataset read with {} images".format(split, len(self.img_ids))) def __getitem__(self, index): img_id = self.img_ids[index] label = self.img_labe...
# assert self.class_freq.size == 5000 self.sample_weight = self.img_labels.size / (self.class_freq[self.img_labels] + 1e-6) else:
random_line_split
wvc_data.py
[], 0.01 for k in np.unique(self.img_labels): idxs = np.where(self.img_labels == k)[0] idxs = np.random.choice(idxs, int(np.ceil(len(idxs)*frac)), replace=False) sampled_idxs.extend(idxs.tolist()) self.img_ids, self.img_files, self.img_labels = se...
(self, grid_size=3, patch_size=64): self.grid_size = grid_size self.patch_size = patch_size def __call__(self, img): w, h = img.size crops = [] for c_i, c_j in itertools.product(range(self.grid_size), range(self.grid_size)): # find patch coordinates t...
__init__
identifier_name
wvc_data.py
[], 0.01 for k in np.unique(self.img_labels): idxs = np.where(self.img_labels == k)[0] idxs = np.random.choice(idxs, int(np.ceil(len(idxs)*frac)), replace=False) sampled_idxs.extend(idxs.tolist()) self.img_ids, self.img_files, self.img_labels = se...
else: self.class_freq = -1*np.ones(5000) self.sample_weight = np.ones(self.img_labels.size, np.float) _logger.info("Webvision {} dataset read with {} images".format(split, len(self.img_ids))) def __getitem__(self, index): img_id = self.img_ids[index] label ...
self.class_freq = np.bincount(self.img_labels) # assert self.class_freq.size == 5000 self.sample_weight = self.img_labels.size / (self.class_freq[self.img_labels] + 1e-6)
conditional_block
eeglab2hadoop.py
0][0]) latencyInFrame.append(this_latency) label.append(this_label) if this_label not in uniqueLabel: uniqueLabel.append(this_label) gc.enable() uniqueLabel=[int(x) for x in uniqueLabel] events['uniqueLabel'] = [str(x) for x in sorted(uniqueLabel)] #-1 for Matlab i...
if raw_data is None: continue print(filename + ': identifying outliers') artifact_indexes = find_artifact_indexes(eeg, ica_act) eeg['artifact_indexes'] = artifact_indexes; f=open('..\\artifact_indexes', 'w') pickle.dump(artifact_indexes,f) f.close()...
continue
conditional_block
eeglab2hadoop.py
0][0]) latencyInFrame.append(this_latency) label.append(this_label) if this_label not in uniqueLabel: uniqueLabel.append(this_label) gc.enable() uniqueLabel=[int(x) for x in uniqueLabel] events['uniqueLabel'] = [str(x) for x in sorted(uniqueLabel)] #-1 for Matlab i...
cur_val = sorted_x[0][0] last_rank = 0 for i in range(len(sorted_x)): if cur_val != sorted_x[i][0]: cur_val = sorted_x[i][0] for j in range(last_rank, i): r[sorted_x[j][1]] = float(last_rank+1+i)/2.0 last_rank = i if i==len(sorted_x)-1: ...
""" from: https://github.com/benhamner/Metrics/blob/master/Python/ml_metrics/auc.py Computes the tied rank of elements in x. This function computes the tied rank of elements in x. Parameters ---------- x : list of numbers, numpy array Returns ------- score : list of numbers ...
identifier_body
eeglab2hadoop.py
import numpy as np from numpy import array import os import sys import pickle import argparse import base64 import gc import multiprocessing as mp from hadoop.io import SequenceFile, Text NUMFOLDS = 5 NUM_SAMPLES = 0 SAMPLE_RATE = 0 NUM_EVENTS = 0 NUM_POINTS = 0 pool=None def get_eeg(path, file_name): print 'get...
from scipy.io import loadmat, savemat
random_line_split
eeglab2hadoop.py
0][0]) latencyInFrame.append(this_latency) label.append(this_label) if this_label not in uniqueLabel: uniqueLabel.append(this_label) gc.enable() uniqueLabel=[int(x) for x in uniqueLabel] events['uniqueLabel'] = [str(x) for x in sorted(uniqueLabel)] #-1 for Matlab i...
(input_str, substitute, outputpath=''): temp = input_str.rpartition(os.sep) path_temp = temp[0] file_temp = temp[2] f=open(outputpath+os.sep+'manifest.txt','w') if outputpath is not '': try: os.mkdir(outputpath) except: pass ica_key, ica_val, raw_key, raw_val = Tex...
create_file_manifest
identifier_name
instream.rs
required for an instream are stored in this object. We also store a pointer /// to the raw instream so that it can be passed to `InStreamReader` in the write callback. pub struct InStreamUserData<'a> { pub instream: *mut raw::SoundIoInStream, pub read_callback: Box<dyn FnMut(&mut InStreamReader) + 'a>, pu...
} // TODO: Can pause() be called from the read callback? /// If the underlying backend and device support pausing, this pauses the /// stream. The `write_callback()` may be called a few more times if /// the buffer is not full. /// /// Pausing might put the hardware into a low power state ...
}
random_line_split
instream.rs
a>>, } impl<'a> Drop for InStreamUserData<'a> { fn drop(&mut self) { unsafe { raw::soundio_instream_destroy(self.instream); } } } impl<'a> InStream<'a> { /// Starts the stream, returning `Ok(())` if it started successfully. Once /// started the read callback will be periodi...
{ assert!(self.read_started); self.frame_count }
identifier_body
instream.rs
for an instream are stored in this object. We also store a pointer /// to the raw instream so that it can be passed to `InStreamReader` in the write callback. pub struct InStreamUserData<'a> { pub instream: *mut raw::SoundIoInStream, pub read_callback: Box<dyn FnMut(&mut InStreamReader) + 'a>, pub overflo...
(&mut self) -> Result<()> { match unsafe { raw::soundio_instream_start(self.userdata.instream) } { 0 => Ok(()), x => Err(x.into()), } } // TODO: Can pause() be called from the read callback? /// If the underlying backend and device support pausing, this pauses the ...
start
identifier_name
__init__.py
, errors) if isinstance(v, bytes): v = quote_via(v, safe) else: v = quote_via(str(v), safe, encoding, errors) l.append(k + "=" + v) else: for k, v in query: if isi...
>>> sanitize('name with multiple spaces') 'name_with_multiple_spaces' >>> sanitize('âtre fête île alcôve bûche çà génèse où Noël ovoïde capharnaüm') 'atre_fete_ile_alcove_buche_ca_genese_ou_Noel_ovoide_capharnaum' >>> sanitize('replace,ponctuation:;signs!?byunderscorekeeping-hyphen.dot_and_undersco...
'productName'
random_line_split
__init__.py
valid value " "%s." % (rv, self.max), param, ctx, ) elif self.max is None: self.fail( "%s is smaller than the minimum valid value " "%s." % (rv, self.min), param, ...
` `n` times with `args`""" return starmap(func, repeat(args, n)) def makedi
identifier_body
__init__.py
, errors) if isinstance(v, bytes): v = quote_via(v, safe) else: v = quote_via(str(v), safe, encoding, errors) l.append(k + "=" + v) else: for k, v in query: if isi...
(self): return "FloatRange(%r, %r)" % (self.min, self.max) def slugify(value, allow_unicode=False): """Copied from Django Source code, only modifying last line (no need for safe strings). source: https://github.com/django/django/blob/master/django/utils/text.py Convert to ASCII if 'allow_unic...
__repr__
identifier_name
__init__.py
""" try: # PY2 value = unicode(value) except NameError: # PY3 value = str(value) if allow_unicode: value = unicodedata.normalize("NFKC", value) else: value = ( unicodedata.normalize("NFKD", value) .encode("ascii", "ignore") .decode("...
update_nested_dict( old_dict[k], v, extend_list_values=extend_list_values )
conditional_block
02.代码实现-06Tensorflow-01Cifar10-01基本网络.py
.0) conv1_out = Conv2d(images_holder, weights, biases, stride=1, padding='SAME') with tf.name_scope('Pool2d_1'): #池化层1 pool1_out = Pool2d(conv1_out, pool=tf.nn.max_pool, k=3, stride=2, padding='SAME') with tf.name_scope('Conv2d_2'): # 卷积层2 weights = WeightsVariable(shape=[5, 5, conv1_k...
correct_predicted += np.sum(predictions)
random_line_split
02.代码实现-06Tensorflow-01Cifar10-01基本网络.py
为100 线性全连接层:神经元个数10 softmax层 ''' import tensorflow as tf import os import cifar_input,cifar_toTFRecords import numpy as np import csv os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' learning_rate_init = 0.001 training_epochs = 1 batch_size = 100 display_step = 10 dataset_dir = '../Total_Data/TempData/' num_examples_per_epo...
with tf.name_scope('FC2_nonlinear'): #非线性全连接层2 weights = WeightsVariable(shape=[fc1_units_num, fc2_units_num], name_str='weights', stddev=4e-2) biases = BiasesVariable(shape=[fc2_units_num], name_str='biases', init_value=0.1) fc2_out = FullyConnected(fc1_out, weights, biases, ...
_out, pool=tf.nn.max_pool, k=3, stride=2, padding='SAME') with tf.name_scope('Conv2d_2'): # 卷积层2 weights = WeightsVariable(shape=[5, 5, conv1_kernel_num, conv2_kernel_num], name_str='weights', stddev=5e-2) biases = BiasesVariable(shape=[conv2_kernel_num], name_str='biases', init_value=0.0) ...
identifier_body
02.代码实现-06Tensorflow-01Cifar10-01基本网络.py
_kernel_num], name_str='biases', init_value=0.0) conv1_out = Conv2d(images_holder, weights, biases, stride=1, padding='SAME') with tf.name_scope('Pool2d_1'): #池化层1 pool1_out = Pool2d(conv1_out, pool=tf.nn.max_pool, k=3, stride=2, padding='SAME') with tf.name_scope('Conv2d_2'): # 卷积层2 w...
labels_holder : label_batch}) batch_accuracy = np.sum(predictions) / batch_size results_list.append([training_step, loss_value, training_step, batch_accuracy]) print("Training Step:...
conditional_block