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
mod.rs
pub mod data_cache; use std::collections::HashMap; use std::option::Option; use self::data_cache::base_data::City; struct DfaState { name:String, path:HashMap<char, DfaState>, } impl DfaState { fn new(n:String) -> DfaState { DfaState{name:n, path:HashMap::default()} } fn add_path(&mut self, ...
if (current_accepted as *const DfaState) != (&self.start_state as * const DfaState) { if !res.contains(&current_accepted.name) { res.push(current_accepted.name.to_string()); } self.scan_recur(chars, currect_accepted_idx + 1, currect_accepted_idx+1, 0, &self.start_state, &self.start_state, ...
{ if !res.contains(&cs.name) { res.push(cs.name.to_string()); } self.scan_recur(chars, from_idx, current_idx+1, currect_accepted_idx, &self.start_state, current_accepted, res); }
conditional_block
mod.rs
pub mod data_cache; use std::collections::HashMap; use std::option::Option; use self::data_cache::base_data::City; struct DfaState { name:String, path:HashMap<char, DfaState>, } impl DfaState { fn new(n:String) -> DfaState { DfaState{name:n, path:HashMap::default()} } fn add_path(&mut self, ...
() -> DFA { let (citys, name_map) = data_cache::assemble_data(); let mut dfa = DFA{start_state:DfaState::new("".to_string()), citys:citys, name_map: name_map}; for name in dfa.name_map.keys() { dfa.start_state.add_path_by_name(name); } dfa } pub fn print_states(&self) { println!("+++++++++++++...
new
identifier_name
mod.rs
pub mod data_cache; use std::collections::HashMap; use std::option::Option; use self::data_cache::base_data::City; struct DfaState { name:String, path:HashMap<char, DfaState>, } impl DfaState { fn new(n:String) -> DfaState
fn add_path(&mut self, c:char, name:&str) -> &mut DfaState { let mut res = self.path.entry(c).or_insert(DfaState::new(name.to_string())); if res.name == "" && name != "" { res.name = name.to_string(); } res } fn add_path_by_name(&mut self, name:&str) { let chars:Vec<char> = name.chars().colle...
{ DfaState{name:n, path:HashMap::default()} }
identifier_body
concat_roles.py
#!/usr/bin/python import glob import os import shutil import subprocess import sys import yaml def create_role(role): ret = subprocess.check_output( 'ansible-galaxy init {}'.format(role).split()) if not ret.strip().endswith('created successfully'): raise Exception('could not create role "{}"...
def fix_dependency(role, for_destination): """Fix the sub-role dependency. Dependency on a sub-role has to be changed once we move the base role. """ metadata = get_metadata(role) deps = metadata.setdefault('dependencies', []) def f(dep): if dep.startswith(role): ret...
try: return glob.glob(os.path.join(role, 'roles/*')) except OSError: return []
identifier_body
concat_roles.py
#!/usr/bin/python import glob import os
import subprocess import sys import yaml def create_role(role): ret = subprocess.check_output( 'ansible-galaxy init {}'.format(role).split()) if not ret.strip().endswith('created successfully'): raise Exception('could not create role "{}"'.format(role)) def get_metadata(role): try: ...
import shutil
random_line_split
concat_roles.py
#!/usr/bin/python import glob import os import shutil import subprocess import sys import yaml def create_role(role): ret = subprocess.check_output( 'ansible-galaxy init {}'.format(role).split()) if not ret.strip().endswith('created successfully'): raise Exception('could not create role "{}"...
(role, metadata): ensure_meta(role) new_main = os.path.join(role, 'meta/main.yml.new') orig_main = os.path.join(role, 'meta/main.yml') with open(new_main, 'w') as out: yaml.dump(metadata, out, default_flow_style=False, explicit_start=True) os.rename(new_main, orig_main) def add_dependency(...
set_metadata
identifier_name
concat_roles.py
#!/usr/bin/python import glob import os import shutil import subprocess import sys import yaml def create_role(role): ret = subprocess.check_output( 'ansible-galaxy init {}'.format(role).split()) if not ret.strip().endswith('created successfully'): raise Exception('could not create role "{}"...
fix_dependency(src_role, for_destination) def move(src_role, target_role, copy=False): op = shutil.copytree if copy else shutil.move try: os.makedirs(os.path.join(target_role, 'roles')) except OSError: pass fix_dependencies(src_role, for_destination=target_role) op(src_role, o...
fix_dependencies(role, for_destination)
conditional_block
loader.js
/** * TimedText loader. */ // Scope everything in "mw" ( keeps the global namespace clean ) ( function( mw ) { mw.addResourcePaths( { "mw.TimedText" : "mw.TimedText.js", "mw.style.TimedText" : "css/mw.style.TimedText.css", "mw.TimedTextEdit" : "mw.TimedTextEdit.js", "mw.style.TimedTextEdit" : "css/mw.style.T...
else { return false; } }; // TimedText editor: mw.addModuleLoader( 'TimedText.Edit', [ [ '$j.ui', '$j.widget', '$j.ui.mouse', '$j.ui.position', '$j.fn.menu', "mw.style.jquerymenu", 'mw.TimedText', 'mw.style.TimedText', 'mw.TimedTextEdit', 'mw.style.TimedTextEdit' ], [ ...
{ return true; }
conditional_block
loader.js
/** * TimedText loader. */ // Scope everything in "mw" ( keeps the global namespace clean )
mw.addResourcePaths( { "mw.TimedText" : "mw.TimedText.js", "mw.style.TimedText" : "css/mw.style.TimedText.css", "mw.TimedTextEdit" : "mw.TimedTextEdit.js", "mw.style.TimedTextEdit" : "css/mw.style.TimedTextEdit.css", "RemoteMwTimedText" : "remotes/RemoteMwTimedText.js" } ); // Merge in timed text rela...
( function( mw ) {
random_line_split
integration.rs
#![feature(duration)] #![deny(unused_mut)] extern crate zookeeper; extern crate env_logger; use zookeeper::{Acl, CreateMode, Watcher, WatchedEvent, ZooKeeper}; use zookeeper::perms; use std::io::{BufRead, BufReader, Write}; use std::process::{Child, Command, Stdio}; use std::time::Duration; struct LoggingWatcher; im...
let exists = client.exists("/test", true); assert!(exists.is_ok()); let children = client.get_children("/", true); assert!(children.is_ok()); let mut sorted_children = children.unwrap(); sorted_children.sort(); assert_eq!(sorted_children, vec!["test".to_string(), "zookeeper".to_string...
random_line_split
integration.rs
#![feature(duration)] #![deny(unused_mut)] extern crate zookeeper; extern crate env_logger; use zookeeper::{Acl, CreateMode, Watcher, WatchedEvent, ZooKeeper}; use zookeeper::perms; use std::io::{BufRead, BufReader, Write}; use std::process::{Child, Command, Stdio}; use std::time::Duration; struct LoggingWatcher; im...
(server: &mut Child) -> String { let mut reader = BufReader::new(server.stdout.as_mut().unwrap()); let mut connect_string = String::new(); if reader.read_line(&mut connect_string).is_err() { panic!("Couldn't read ZK connect_string") } connect_string.pop(); // remove '\n' connect_string ...
get_connect_string
identifier_name
integration.rs
#![feature(duration)] #![deny(unused_mut)] extern crate zookeeper; extern crate env_logger; use zookeeper::{Acl, CreateMode, Watcher, WatchedEvent, ZooKeeper}; use zookeeper::perms; use std::io::{BufRead, BufReader, Write}; use std::process::{Child, Command, Stdio}; use std::time::Duration; struct LoggingWatcher; im...
} fn start_zk() -> Child { match Command::new("java") .arg("-jar") .arg("zk-test-cluster/target/main.jar") .stdin(Stdio::piped()) .stdout(Stdio::piped()) .spawn() { Ok(p) => p, Err(e) => panic!("failed to execute process: {}", e), } }...
{ println!("{:?}", e) }
identifier_body
html2json.py
# coding: utf-8 import json import sys import codecs python3 = False if sys.version_info[0] == 3: #Python 3 python3 = True if not python3: reload(sys) sys.setdefaultencoding("utf-8") input = raw_input def parseHTML(file_path): fo = codecs.open(file_path, encoding='utf-8', mode='r+') origina...
else: args = [] args.append(input("Path to Exported Bookmark: ")) args.append(input("Export JSON to: ")) try: result = parseHTML(args[0]) writeJSON(result, args[1]) except: sys.stderr.write(sys.exc_info()) finally: input("Press [Enter] to continue...
args = [sys.argv[1],sys.argv[2]]
conditional_block
html2json.py
# coding: utf-8 import json import sys import codecs python3 = False if sys.version_info[0] == 3: #Python 3 python3 = True if not python3: reload(sys) sys.setdefaultencoding("utf-8") input = raw_input
fo.close() parsed = {} current_location = [] current_location_name = [] current_index = 0 header = original.find("<H1>") if header > -1: ender = original.find("</H1>") parsed[original[header+4:ender]] = {"link":[]} folder_begin = original.find("<DL><p>") if fo...
def parseHTML(file_path): fo = codecs.open(file_path, encoding='utf-8', mode='r+') original = fo.read()
random_line_split
html2json.py
# coding: utf-8 import json import sys import codecs python3 = False if sys.version_info[0] == 3: #Python 3 python3 = True if not python3: reload(sys) sys.setdefaultencoding("utf-8") input = raw_input def parseHTML(file_path):
while current_index+1<original_length: folder_title_header = original.find("<DT><H3", current_index) folder_title_ender = original.find("</H3>", current_index) folder_header = original.find("<DL><p>", current_index) folder_ender = original.find("</DL><p>", current_index) book...
fo = codecs.open(file_path, encoding='utf-8', mode='r+') original = fo.read() fo.close() parsed = {} current_location = [] current_location_name = [] current_index = 0 header = original.find("<H1>") if header > -1: ender = original.find("</H1>") parsed[original[header+4:e...
identifier_body
html2json.py
# coding: utf-8 import json import sys import codecs python3 = False if sys.version_info[0] == 3: #Python 3 python3 = True if not python3: reload(sys) sys.setdefaultencoding("utf-8") input = raw_input def
(file_path): fo = codecs.open(file_path, encoding='utf-8', mode='r+') original = fo.read() fo.close() parsed = {} current_location = [] current_location_name = [] current_index = 0 header = original.find("<H1>") if header > -1: ender = original.find("</H1>") parsed[or...
parseHTML
identifier_name
conf.py
# Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys, os # If extensions (or modules to document with autodoc) are in another directory, # add these directories to ...
# If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = ['sphinx.ext.autodoc', 'sphinx.ext.doctest', 'sphinx.ext.intersphin...
random_line_split
pool.rs
// Copyright 2017 The Gfx-rs Developers. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or ag...
use ash::vk; use ash::version::DeviceV1_0; use core::{self, pool}; use core::command::{Encoder}; use core::{CommandPool, GeneralQueue, GraphicsQueue, ComputeQueue, TransferQueue}; use command::CommandBuffer; use native::{self, GeneralCommandBuffer, GraphicsCommandBuffer, ComputeCommandBuffer, TransferCommandBuffer, Su...
use std::ops::DerefMut; use std::ptr; use std::sync::Arc;
random_line_split
mod.rs
//! Contains the types and functions to communicate with the MusicBrainz API. use crate::error::{Error, ErrorKind}; use crate::entities::{Mbid, ResourceOld, Resource}; use reqwest_mock::Client as MockClient; use reqwest_mock::GenericClient as HttpClient; use reqwest_mock::{StatusCode, Url}; use reqwest_mock::header::...
self.last_request = now; } pub fn get_by_mbid<Res, Resp, Opt>(&mut self, mbid: &Mbid, options: Opt) -> Result<Res, Error> where Res: Resource<Options = Opt, Response = Resp>, Resp: FromXml, { let request = Res::request(&options); let url = request.get_by_mbid_ur...
{ sleep(Duration::from_millis(self.config.waits.requests) - elapsed); }
conditional_block
mod.rs
//! Contains the types and functions to communicate with the MusicBrainz API. use crate::error::{Error, ErrorKind}; use crate::entities::{Mbid, ResourceOld, Resource}; use reqwest_mock::Client as MockClient; use reqwest_mock::GenericClient as HttpClient; use reqwest_mock::{StatusCode, Url}; use reqwest_mock::header::...
{ /// The user-agent to be sent with every request to the API. /// /// Provide a meaningful one as it will be used by MusicBrainz to identify /// your application and without a user agent sever throttling will be /// undertaken. The official suggestion is to use either one of the /// following ...
ClientConfig
identifier_name
mod.rs
//! Contains the types and functions to communicate with the MusicBrainz API. use crate::error::{Error, ErrorKind}; use crate::entities::{Mbid, ResourceOld, Resource}; use reqwest_mock::Client as MockClient; use reqwest_mock::GenericClient as HttpClient; use reqwest_mock::{StatusCode, Url}; use reqwest_mock::header::...
((duration.as_secs() as f64) + (duration.subsec_nanos() as f64) * 1e6) as u64 } /// Returns an `Instant` at least 1000 seconds ago. fn past_instant() -> Instant { Instant::now() - Duration::new(1000, 0) } /// Configuration for the client. #[derive(Clone, Debug)] pub struct ClientConfig { /// The user-agen...
mod error; pub(crate) use self::error::check_response_error; /// Helper extracting the number of milliseconds from a `Duration`. fn as_millis(duration: &Duration) -> u64 {
random_line_split
02.rs
use std::fs::File; use std::io::prelude::*; fn get_input() -> std::io::Result<String> { let mut file = File::open("02.txt")?; let mut contents = String::new(); file.read_to_string(&mut contents)?; Ok(contents) } fn run_program(program: &mut Vec<usize>) { let mut pointer = 0; loop { let target_value ...
println!("Part 1: {}", calculate_output(program.clone(), (12, 2))); for i in 0..=99 { for j in 0..=99 { let output = calculate_output(program.clone(), (i, j)); if output == 19690720 { println!("Part 2: {}", i * 100 + j); return; } } } }
.filter_map(|x| x.trim().parse::<usize>().ok()) .collect::<Vec<_>>();
random_line_split
02.rs
use std::fs::File; use std::io::prelude::*; fn get_input() -> std::io::Result<String> { let mut file = File::open("02.txt")?; let mut contents = String::new(); file.read_to_string(&mut contents)?; Ok(contents) } fn run_program(program: &mut Vec<usize>) { let mut pointer = 0; loop { let target_value ...
fn main() { let input = get_input().unwrap(); let program = input.split(',') .filter_map(|x| x.trim().parse::<usize>().ok()) .collect::<Vec<_>>(); println!("Part 1: {}", calculate_output(program.clone(), (12, 2))); for i in 0..=99 { for j in 0..=99 { let output = calculate_output(program.c...
{ program[1] = input.0; program[2] = input.1; run_program(&mut program); program[0] }
identifier_body
02.rs
use std::fs::File; use std::io::prelude::*; fn get_input() -> std::io::Result<String> { let mut file = File::open("02.txt")?; let mut contents = String::new(); file.read_to_string(&mut contents)?; Ok(contents) } fn
(program: &mut Vec<usize>) { let mut pointer = 0; loop { let target_value = { let get = |p| program[program[p]]; match program[pointer] { 1 => get(pointer + 1) + get(pointer + 2), 2 => get(pointer + 1) * get(pointer + 2), 99 => break, _ => panic!() } }; ...
run_program
identifier_name
testAndOutputGrids.py
random import sample from time import time import heapq import matplotlib matplotlib.use('Agg') from matplotlib import pyplot as plt import sys, os from eft_calculator import EFT_calculator, Water import tools def load_coordinates(name): lines = open('test.dat/random/'+name).readlines()[-7:-1] coors = [[floa...
def atomicEF(self, x0, e0, s0, q0, x1, e1, s1, q1): k = 138.935456 e = np.sqrt(e0 * e1) s = s0 + s1 r = np.linalg.norm(x0 - x1) if r <0.1 : return 100.0, np.array([100., 100.,100.,]) sor6 = (s/r) ** 6 evdw = e * (sor6**2 - 2 * sor6) fvdw = e / r**2 ...
mol = Water() coor0 = coors[:3] coor1 = coors[3:] e = 0. f = np.zeros(3) t = np.zeros(3) com1 = mol.getCOM(coor1) eps, sigma, charge = self.eps, self.sigma, self.charge for i in range(3): for j in range(3): ener, force = self.at...
identifier_body
testAndOutputGrids.py
random import sample from time import time import heapq import matplotlib matplotlib.use('Agg') from matplotlib import pyplot as plt import sys, os from eft_calculator import EFT_calculator, Water import tools def load_coordinates(name): lines = open('test.dat/random/'+name).readlines()[-7:-1] coors = [[floa...
all.append((-np.linalg.norm(np.array(fce0) - np.array(fce1)), name)) t2 = time() print('took %.1f s to evaluate the random set' % (t2 - t1)) heapq.heapify(all) #for i in range(3): # de, name = heapq.heappop(all) # print -de, name """ for i in range(len(e0)): if e1[...
name = 'test.dat/random/test%04d.inp.log' % i #if i == 1693: pdb.set_trace() eft, coors = calculator._parseQMlog(name) # evaluate with analytical function eft = cc.eval(coors) e0.append(eft[0]) fce0 += list(eft[1:4]) trq0 += list(eft[4:7]) # convert atomic...
conditional_block
testAndOutputGrids.py
random import sample from time import time import heapq import matplotlib matplotlib.use('Agg') from matplotlib import pyplot as plt import sys, os from eft_calculator import EFT_calculator, Water import tools def load_coordinates(name): lines = open('test.dat/random/'+name).readlines()[-7:-1] coors = [[floa...
(self, x0, e0, s0, q0, x1, e1, s1, q1): k = 138.935456 e = np.sqrt(e0 * e1) s = s0 + s1 r = np.linalg.norm(x0 - x1) if r <0.1 : return 100.0, np.array([100., 100.,100.,]) sor6 = (s/r) ** 6 evdw = e * (sor6**2 - 2 * sor6) fvdw = e / r**2 * sor6 * (sor6 - 1...
atomicEF
identifier_name
testAndOutputGrids.py
random import sample from time import time import heapq import matplotlib matplotlib.use('Agg') from matplotlib import pyplot as plt import sys, os from eft_calculator import EFT_calculator, Water import tools def load_coordinates(name): lines = open('test.dat/random/'+name).readlines()[-7:-1] coors = [[floa...
t0 = time() cc = Classical_calculator() if os.path.exists(databaseName): print("loaded a old database") calculator = EFT_calculator(databaseName) else: print("created a new mesh") calculator = EFT_calculator() if len(sys.argv) == 4: error_cutoff = float(sys.ar...
random_line_split
Position.js
define(function(require) { var Class = require('class/Class'); //Abstraction of relative positioning information, modeled after jQuery UI //(more predictable) and jquery.qTip (more precise) var Position = Class.extend(/** @lends Position.prototype */ { __defaults: { x: null, y: null, precedence: null...
var pos = new Position(); pos.precedence = axes[0]; axes.forEach(function(axis, i) { switch(axis) { case 'x': pos.x = parts[i]; break; case 'y': pos.y = parts[i]; break; } }); return pos; }; return Position; });
//each axis, if null ("center" was given), is the opposite of the other axis axes[0] = axes[0] || ((axes[1] === 'x') ? 'y' : 'x'); axes[1] = axes[1] || ((axes[0] === 'x') ? 'y' : 'x');
random_line_split
Position.js
define(function(require) { var Class = require('class/Class'); //Abstraction of relative positioning information, modeled after jQuery UI //(more predictable) and jquery.qTip (more precise) var Position = Class.extend(/** @lends Position.prototype */ { __defaults: { x: null, y: null, precedence: null...
else if (pos.x === 'right') { pos.x = 'left'; } else { pos.x = 'center'; } if (pos.y === 'top') { pos.y = 'bottom'; } else if (pos.y === 'bottom') { pos.y = 'top'; } else { pos.y = 'center'; } return pos; }, /** * @return {String} */ toString: functi...
{ pos.x = 'right'; }
conditional_block
mutable_counters.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use crate::error::SubcommandError; use anyhow::{format_err, Context, Error}; use clap_old::{App, Arg, ArgMatches, SubCommand}; use cmdlib:...
async fn mutable_counters_get( ctx: CoreContext, repo_id: RepositoryId, name: &str, mutable_counters: SqlMutableCounters, ) -> Result<(), Error> { let maybe_value = mutable_counters .get_counter(ctx.clone(), repo_id, name) .compat() .await?; println!("{:?}", maybe_valu...
{ let counters = mutable_counters .get_all_counters(ctx.clone(), repo_id) .compat() .await?; for (name, value) in counters { println!("{:<30}={}", name, value); } Ok(()) }
identifier_body
mutable_counters.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use crate::error::SubcommandError; use anyhow::{format_err, Context, Error}; use clap_old::{App, Arg, ArgMatches, SubCommand}; use cmdlib:...
info!( ctx.logger(), "Value of {} in {} set to {}", name, repo_id, value ); Ok(()) }
) -> Result<(), Error> { mutable_counters .set_counter(ctx.clone(), repo_id, name, value, None) .compat() .await?;
random_line_split
mutable_counters.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use crate::error::SubcommandError; use anyhow::{format_err, Context, Error}; use clap_old::{App, Arg, ArgMatches, SubCommand}; use cmdlib:...
(_, _) => Err(format_err!("unknown mutable_counters subcommand")), } .map_err(SubcommandError::from) } async fn mutable_counters_list( ctx: CoreContext, repo_id: RepositoryId, mutable_counters: SqlMutableCounters, ) -> Result<(), Error> { let counters = mutable_counters .get_al...
{ let name = sub_m .value_of(MUTABLE_COUNTERS_NAME) .ok_or_else(|| format_err!("{} is required", MUTABLE_COUNTERS_NAME))?; let value = args::get_i64_opt(sub_m, MUTABLE_COUNTERS_VALUE) .ok_or_else(|| format_err!("{} is required", MUTABLE_COUNTERS_V...
conditional_block
mutable_counters.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use crate::error::SubcommandError; use anyhow::{format_err, Context, Error}; use clap_old::{App, Arg, ArgMatches, SubCommand}; use cmdlib:...
( ctx: CoreContext, repo_id: RepositoryId, mutable_counters: SqlMutableCounters, ) -> Result<(), Error> { let counters = mutable_counters .get_all_counters(ctx.clone(), repo_id) .compat() .await?; for (name, value) in counters { println!("{:<30}={}", name, value); ...
mutable_counters_list
identifier_name
diapers1.py
from __future__ import print_function,division # duner. using numbers and sample. """ q +-----+ r +-----+ ---->| C |---->| D |--> s ^ +-----+ +-+---+ | | +-----------------+ C = stock of clean diapers D = stock of dirty diapers q = inflow of clean diapers r = flow of clean diapers...
def diapers(): def saturday(x): return int(x) % 7 == 6 world = o(C=20, D=0,q=0, r=8, s=0) for dt,t,u,v in sim(world,life=60,spy=True,dt=0.5): v.C += dt*(u.q - u.r) v.D += dt*(u.r - u.s) v.q = 70 if saturday(t) else 0 v.s = u.D if saturday(t) else 0 if t == 27: # special case (the da...
t += dt state1 = state0.copy() yield dt, t,state0,state1 state0 = state1 for key in state1.has().keys(): if state1[key] < 0: state1[key] = 0 if spy: print(t,state1)
conditional_block
diapers1.py
from __future__ import print_function,division # duner. using numbers and sample. """ q +-----+ r +-----+ ---->| C |---->| D |--> s ^ +-----+ +-+---+ | | +-----------------+ C = stock of clean diapers D = stock of dirty diapers q = inflow of clean diapers r = flow of clean diapers...
(i) : return 'o'+str(i.has()) def sim(state0,life=100,spy=False,dt=1): t= 0 while t < life: t += dt state1 = state0.copy() yield dt, t,state0,state1 state0 = state1 for key in state1.has().keys(): if state1[key] < 0: state1[key] = 0 if spy: print(t,state1) def ...
__repr__
identifier_name
diapers1.py
from __future__ import print_function,division # duner. using numbers and sample.
""" q +-----+ r +-----+ ---->| C |---->| D |--> s ^ +-----+ +-+---+ | | +-----------------+ C = stock of clean diapers D = stock of dirty diapers q = inflow of clean diapers r = flow of clean diapers to dirty diapers s = out-flow of dirty diapers """ class o: def has(i) ...
random_line_split
diapers1.py
from __future__ import print_function,division # duner. using numbers and sample. """ q +-----+ r +-----+ ---->| C |---->| D |--> s ^ +-----+ +-+---+ | | +-----------------+ C = stock of clean diapers D = stock of dirty diapers q = inflow of clean diapers r = flow of clean diapers...
def __getitem__(i,k): return i.has()[k] def __setitem__(i,k,v): i.has()[k] = v def __repr__(i) : return 'o'+str(i.has()) def sim(state0,life=100,spy=False,dt=1): t= 0 while t < life: t += dt state1 = state0.copy() yield dt, t,state0,state1 state0 = state1 for key in state1.has...
return o(**i.has().copy())
identifier_body
bench_engine_main.rs
#[macro_use] extern crate criterion; extern crate pleco; extern crate pleco_engine; mod eval_benches; mod multimove_benches; mod startpos_benches; trait DepthLimit { fn depth() -> u16; } struct Depth5 {} struct Depth6 {} struct Depth7 {} struct Depth8 {} struct Depth9 {} impl DepthLimit for Depth5 { fn dep...
startpos_benches::search_singular }
random_line_split
bench_engine_main.rs
#[macro_use] extern crate criterion; extern crate pleco; extern crate pleco_engine; mod eval_benches; mod multimove_benches; mod startpos_benches; trait DepthLimit { fn depth() -> u16; } struct Depth5 {} struct
{} struct Depth7 {} struct Depth8 {} struct Depth9 {} impl DepthLimit for Depth5 { fn depth() -> u16 {5} } impl DepthLimit for Depth6 { fn depth() -> u16 {6} } impl DepthLimit for Depth7 { fn depth() -> u16 {7} } impl DepthLimit for Depth8 { fn depth() -> u16 {8} } impl DepthLimit for Depth9 { fn depth() -> u16 {9}...
Depth6
identifier_name
test.py
# Python3 from solution1 import multiplicationTable as f qa = [ (5, [[1, 2, 3, 4, 5], [2, 4, 6, 8, 10], [3, 6, 9, 12, 15], [4, 8, 12, 16, 20], [5, 10, 15, 20, 25]]), (2, [[1, 2], [2, 4]]), (4, [[1, 2, 3, 4], [2, 4, 6, 8], [3, 6, 9, 12...
for i, e in enumerate(q): print('input{0}: {1}'.format(i + 1, e)) ans = f(*q) if ans != a: print(' [failed]') print(' output:', ans) print(' expected:', a) else: print(' [ok]') print(' output:', ans) print()
conditional_block
test.py
from solution1 import multiplicationTable as f qa = [ (5, [[1, 2, 3, 4, 5], [2, 4, 6, 8, 10], [3, 6, 9, 12, 15], [4, 8, 12, 16, 20], [5, 10, 15, 20, 25]]), (2, [[1, 2], [2, 4]]), (4, [[1, 2, 3, 4], [2, 4, 6, 8], [3, 6, 9, 12], [4...
# Python3
random_line_split
dense_v1.py
""" locally connected implimentation on the lip movement data. Akm Ashiquzzaman 13101002@uap-bd.edu Fall 2016 after 1 epoch , val_acc: 0.0926 """ from __future__ import print_function, division #random seed fixing for reproducibility import numpy as np np.random.seed(1337) import time #Data loading X_train = np....
#weight-checkmark checkpoint = ModelCheckpoint(weight_file, monitor='acc', verbose=1, save_best_only=True, mode='min') callbacks_list = [checkpoint] print('total time: ',time.time()-tt) seq.fit(X_train,Y_train,batch_size=batchSize, nb_epoch=tt_epoch ,validation_split=0.2,callbacks=callbacks_list) #generating pre...
seq.load_weights(weight_file)
conditional_block
dense_v1.py
""" locally connected implimentation on the lip movement data. Akm Ashiquzzaman 13101002@uap-bd.edu Fall 2016 after 1 epoch , val_acc: 0.0926 """ from __future__ import print_function, division #random seed fixing for reproducibility import numpy as np np.random.seed(1337) import time #Data loading X_train = np....
seq.add(Dense(4096)) seq.add(Activation('relu')) seq.add(Dropout(0.5)) #3rd lc layers seq.add(Dense(1024)) seq.add(Activation('relu')) seq.add(Dropout(0.5)) seq.add(Dense(1024)) seq.add(Activation('relu')) seq.add(Dropout(0.5)) seq.add(Dense(4702)) seq.add(Activation('softmax')) seq.compile(loss='binary_crossen...
seq.add(Dropout(0.25)) #second lc layer
random_line_split
mod.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except accordin...
// file at the top-level directory of this distribution and at
random_line_split
print.py
# Various functions for printing various specific values # in human-readable format import sys import time import pprint # pretty print object pp = pprint.PrettyPrinter(indent=4) def pretty_print(value): pp.pprint(value) # print timedelta, provided in seconds, # in human-readable format def print_elapsed_tim...
def print_progress(cur_value, max_value, width=72): """Print progress bar in form: [###-------].""" progress = int((cur_value * 100) / max_value) # effective width -- width of bar without brackets e_width = width - 2 # number of "#" in bar num_hashes = int((cur_value * e_width) / max_value) ...
gm_timedelta = time.gmtime(timedelta) hours = int(time.strftime('%H', gm_timedelta)) minutes = int(time.strftime('%M', gm_timedelta)) seconds = int(time.strftime('%S', gm_timedelta)) print('Total time elapsed: ', end='') if hours > 0: print('{0} hours, '.format(hours), end='') if minute...
identifier_body
print.py
# Various functions for printing various specific values # in human-readable format import sys import time import pprint # pretty print object pp = pprint.PrettyPrinter(indent=4) def pretty_print(value): pp.pprint(value) # print timedelta, provided in seconds, # in human-readable format def print_elapsed_tim...
if minutes > 0: print('{0} minutes, '.format(minutes), end='') print('{0} seconds.'.format(seconds), end='') print() def print_progress(cur_value, max_value, width=72): """Print progress bar in form: [###-------].""" progress = int((cur_value * 100) / max_value) # effective width -- ...
print('{0} hours, '.format(hours), end='')
conditional_block
print.py
# Various functions for printing various specific values # in human-readable format import sys import time import pprint # pretty print object pp = pprint.PrettyPrinter(indent=4) def
(value): pp.pprint(value) # print timedelta, provided in seconds, # in human-readable format def print_elapsed_time(timedelta): gm_timedelta = time.gmtime(timedelta) hours = int(time.strftime('%H', gm_timedelta)) minutes = int(time.strftime('%M', gm_timedelta)) seconds = int(time.strftime('%S', g...
pretty_print
identifier_name
print.py
# Various functions for printing various specific values # in human-readable format import sys import time import pprint # pretty print object pp = pprint.PrettyPrinter(indent=4) def pretty_print(value): pp.pprint(value)
def print_elapsed_time(timedelta): gm_timedelta = time.gmtime(timedelta) hours = int(time.strftime('%H', gm_timedelta)) minutes = int(time.strftime('%M', gm_timedelta)) seconds = int(time.strftime('%S', gm_timedelta)) print('Total time elapsed: ', end='') if hours > 0: print('{0} hours...
# print timedelta, provided in seconds, # in human-readable format
random_line_split
boilerplate.rs
#![allow(clippy::single_match)] use vangers::{ config::{settings::Terrain, Settings}, render::{ScreenTargets, DEPTH_FORMAT}, }; use futures::executor::{LocalPool, LocalSpawner}; use log::info; use winit::{ event, event_loop::{ControlFlow, EventLoop}, window::{Window, WindowBuilder}, }; pub trait A...
{ task_pool: LocalPool, event_loop: EventLoop<()>, window: Window, pub device: wgpu::Device, pub queue: wgpu::Queue, pub downlevel_caps: wgpu::DownlevelCapabilities, surface: wgpu::Surface, pub color_format: wgpu::TextureFormat, pub extent: wgpu::Extent3d, reload_on_focus: bool,...
Harness
identifier_name
boilerplate.rs
#![allow(clippy::single_match)] use vangers::{ config::{settings::Terrain, Settings}, render::{ScreenTargets, DEPTH_FORMAT}, }; use futures::executor::{LocalPool, LocalSpawner}; use log::info; use winit::{ event, event_loop::{ControlFlow, EventLoop}, window::{Window, WindowBuilder}, }; pub trait A...
depth_or_array_layers: 1, }; let config = wgpu::SurfaceConfiguration { usage: wgpu::TextureUsages::RENDER_ATTACHMENT, format: color_format, width: size.width, h...
random_line_split
boilerplate.rs
#![allow(clippy::single_match)] use vangers::{ config::{settings::Terrain, Settings}, render::{ScreenTargets, DEPTH_FORMAT}, }; use futures::executor::{LocalPool, LocalSpawner}; use log::info; use winit::{ event, event_loop::{ControlFlow, EventLoop}, window::{Window, WindowBuilder}, }; pub trait A...
let _ = window; *control_flow = ControlFlow::Poll; task_pool.run_until_stalled(); match event { event::Event::WindowEvent { event: event::WindowEvent::Resized(size), .. } => { inf...
{ use std::time; let mut last_time = time::Instant::now(); let mut needs_reload = false; let Harness { mut task_pool, event_loop, window, device, queue, downlevel_caps: _, surface, color_form...
identifier_body
boilerplate.rs
#![allow(clippy::single_match)] use vangers::{ config::{settings::Terrain, Settings}, render::{ScreenTargets, DEPTH_FORMAT}, }; use futures::executor::{LocalPool, LocalSpawner}; use log::info; use winit::{ event, event_loop::{ControlFlow, EventLoop}, window::{Window, WindowBuilder}, }; pub trait A...
else { Some(std::path::Path::new(&settings.render.wgpu_trace_path)) }, )) .unwrap(); let config = wgpu::SurfaceConfiguration { usage: wgpu::TextureUsages::RENDER_ATTACHMENT, format: surface .get_preferred_forma...
{ None }
conditional_block
Office365_Adal.js
// A '.tsx' file enables JSX support in the TypeScript compiler, // for more information see the following page on the TypeScript wiki: // https://github.com/Microsoft/TypeScript/wiki/JSX /// ../typings/es6-promise/es6-promise.d.ts var Adal = require('./adal.js'); // very important!!! if you put these locally then mul...
}); }); }; Office365_Adal.getUser = function (authContext) { var dummyAuthPage = 'default.html'; return new Promise(function (resolve, reject) { // If the user is cached, resolve the promise immediately. //var user = authContext.getCachedUser(); ...
{ console.log(error); return; }
conditional_block
Office365_Adal.js
// A '.tsx' file enables JSX support in the TypeScript compiler, // for more information see the following page on the TypeScript wiki: // https://github.com/Microsoft/TypeScript/wiki/JSX /// ../typings/es6-promise/es6-promise.d.ts var Adal = require('./adal.js'); // very important!!! if you put these locally then mul...
resource: 'https://outlook.office365.com', endpoints: { 'https://outlook.office.com/api/v1.0/me/folders/inbox/messages': 'https://outlook.office.com' } }; var authContext = new Adal.inject(config); // always logout for now authContext.l...
cacheLocation: 'localStorage', instance: 'https://login.windows.net/',
random_line_split
Office365_Adal.js
// A '.tsx' file enables JSX support in the TypeScript compiler, // for more information see the following page on the TypeScript wiki: // https://github.com/Microsoft/TypeScript/wiki/JSX /// ../typings/es6-promise/es6-promise.d.ts var Adal = require('./adal.js'); // very important!!! if you put these locally then mul...
() { } Office365_Adal.launchWebAuth = function () { // redirectUri: 'ms-app://S-1-15-2-362237037-3722746685-439561638-2597901564-3613092599-1873846187-518014421' /* GET https://login.microsoftonline.com/common/oauth2/v2.0/authorize? response_type=code& client_id=32613fc5-e7ac-48...
Office365_Adal
identifier_name
Office365_Adal.js
// A '.tsx' file enables JSX support in the TypeScript compiler, // for more information see the following page on the TypeScript wiki: // https://github.com/Microsoft/TypeScript/wiki/JSX /// ../typings/es6-promise/es6-promise.d.ts var Adal = require('./adal.js'); // very important!!! if you put these locally then mul...
Office365_Adal.launchWebAuth = function () { // redirectUri: 'ms-app://S-1-15-2-362237037-3722746685-439561638-2597901564-3613092599-1873846187-518014421' /* GET https://login.microsoftonline.com/common/oauth2/v2.0/authorize? response_type=code& client_id=32613fc5-e7ac-4894-ac94-fb...
{ }
identifier_body
main.rs
extern crate ndarray; #[macro_use] extern crate tvm; use ndarray::Array; use tvm::{ ffi::runtime::DLTensor, runtime::{Module, SystemLibModule}, }; fn
() { let syslib = SystemLibModule::default(); let add = syslib .get_function("default_function") .expect("main function not found"); let mut a = Array::from_vec(vec![1f32, 2., 3., 4.]); let mut b = Array::from_vec(vec![1f32, 0., 1., 0.]); let mut c = Array::from_vec(vec![0f32; 4]); let e = Array::fr...
main
identifier_name
main.rs
extern crate ndarray; #[macro_use] extern crate tvm; use ndarray::Array; use tvm::{ ffi::runtime::DLTensor, runtime::{Module, SystemLibModule}, }; fn main()
{ let syslib = SystemLibModule::default(); let add = syslib .get_function("default_function") .expect("main function not found"); let mut a = Array::from_vec(vec![1f32, 2., 3., 4.]); let mut b = Array::from_vec(vec![1f32, 0., 1., 0.]); let mut c = Array::from_vec(vec![0f32; 4]); let e = Array::from_...
identifier_body
main.rs
extern crate ndarray; #[macro_use] extern crate tvm; use ndarray::Array; use tvm::{ ffi::runtime::DLTensor, runtime::{Module, SystemLibModule}, }; fn main() { let syslib = SystemLibModule::default(); let add = syslib .get_function("default_function") .expect("main function not found");
let mut b = Array::from_vec(vec![1f32, 0., 1., 0.]); let mut c = Array::from_vec(vec![0f32; 4]); let e = Array::from_vec(vec![2f32, 2., 4., 4.]); let mut a_dl: DLTensor = (&mut a).into(); let mut b_dl: DLTensor = (&mut b).into(); let mut c_dl: DLTensor = (&mut c).into(); call_packed!(add, &mut a_dl, &mut ...
let mut a = Array::from_vec(vec![1f32, 2., 3., 4.]);
random_line_split
window_platform_event.py
#!/usr/bin/env python # ---------------------------------------------------------------------------- # pyglet # Copyright (c) 2006-2008 Alex Holkner # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are ...
if _have_win32: @Win32EventHandler(WM_DISPLAYCHANGE) def _on_window_display_change(self, msg, lParam, wParam): print 'Display resolution changed.' return 0 if _have_xlib: @XlibEventHandler(xlib.PropertyNotify) def _on_window_property_notify(self, event)...
print 'Clicked drag rgn.' carbon.CallNextEventHandler(next_handler, event) return noErr
identifier_body
window_platform_event.py
#!/usr/bin/env python # ---------------------------------------------------------------------------- # pyglet # Copyright (c) 2006-2008 Alex Holkner # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are ...
except ImportError: _have_win32 = False # Check for Xlib (Linux) try: from pyglet.window.xlib import * _have_xlib = True except ImportError: _have_xlib = False # Subclass Window class MyWindow(pyglet.window.Window): if _have_carbon: @CarbonEventHandler(kEventClassWindow, kEventWindowClickD...
_have_win32 = True
random_line_split
window_platform_event.py
#!/usr/bin/env python # ---------------------------------------------------------------------------- # pyglet # Copyright (c) 2006-2008 Alex Holkner # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are ...
(self, msg, lParam, wParam): print 'Display resolution changed.' return 0 if _have_xlib: @XlibEventHandler(xlib.PropertyNotify) def _on_window_property_notify(self, event): print 'Property notify.' if __name__ == '__main__': window = MyWindow() pyglet.ap...
_on_window_display_change
identifier_name
window_platform_event.py
#!/usr/bin/env python # ---------------------------------------------------------------------------- # pyglet # Copyright (c) 2006-2008 Alex Holkner # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are ...
if _have_xlib: @XlibEventHandler(xlib.PropertyNotify) def _on_window_property_notify(self, event): print 'Property notify.' if __name__ == '__main__': window = MyWindow() pyglet.app.run()
@Win32EventHandler(WM_DISPLAYCHANGE) def _on_window_display_change(self, msg, lParam, wParam): print 'Display resolution changed.' return 0
conditional_block
Variable.js
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Variable = void 0; const VariableBase_1 = require("./VariableBase"); /** * A Variable represents a locally scoped identifier. These include arguments to functions. */ class Variable extends VariableBase_1.VariableBase { /** ...
return this.defs.some(def => def.isVariableDefinition); } } exports.Variable = Variable; //# sourceMappingURL=Variable.js.map
{ // we don't statically know whether this is a type or a value return true; }
conditional_block
Variable.js
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Variable = void 0; const VariableBase_1 = require("./VariableBase"); /** * A Variable represents a locally scoped identifier. These include arguments to functions. */ class
extends VariableBase_1.VariableBase { /** * `true` if the variable is valid in a type context, false otherwise * @public */ get isTypeVariable() { if (this.defs.length === 0) { // we don't statically know whether this is a type or a value return true; } ...
Variable
identifier_name
Variable.js
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Variable = void 0; const VariableBase_1 = require("./VariableBase"); /** * A Variable represents a locally scoped identifier. These include arguments to functions. */ class Variable extends VariableBase_1.VariableBase { /** ...
/** * `true` if the variable is valid in a value context, false otherwise * @public */ get isValueVariable() { if (this.defs.length === 0) { // we don't statically know whether this is a type or a value return true; } return this.defs.some(def => d...
{ if (this.defs.length === 0) { // we don't statically know whether this is a type or a value return true; } return this.defs.some(def => def.isTypeDefinition); }
identifier_body
Variable.js
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Variable = void 0; const VariableBase_1 = require("./VariableBase"); /** * A Variable represents a locally scoped identifier. These include arguments to functions. */ class Variable extends VariableBase_1.VariableBase { /** ...
if (this.defs.length === 0) { // we don't statically know whether this is a type or a value return true; } return this.defs.some(def => def.isTypeDefinition); } /** * `true` if the variable is valid in a value context, false otherwise * @public */ ...
* @public */ get isTypeVariable() {
random_line_split
login.controller.js
'use strict'; angular.module('wordclashApp').controller('LoginCtrl', ['$scope', '$location', 'authService', 'ngAuthSettings', function ($scope, $location, authService, ngAuthSettings) { $scope.loginData = { userName: "", password: "", useRefreshTokens: false }; $scope.message = "";...
} }); } }]);
$scope.message = err.error_description; });
random_line_split
login.controller.js
'use strict'; angular.module('wordclashApp').controller('LoginCtrl', ['$scope', '$location', 'authService', 'ngAuthSettings', function ($scope, $location, authService, ngAuthSettings) { $scope.loginData = { userName: "", password: "", useRefreshTokens: false }; $scope.message = "";...
}); } }]);
//Obtain access token and redirect to orders var externalData = { provider: fragment.provider, externalAccessToken: fragment.external_access_token }; authService.obtainAccessToken(externalData).then(function (response) { $location.path('/arena'); ...
conditional_block
app-load.service.ts
import { Injectable, Injector } from '@angular/core'; import { AgendaAppConfig } from '../../site/agenda/agenda.config'; import { AppConfig, ModelEntry, SearchableModelEntry } from '../definitions/app-config'; import { BaseRepository } from 'app/core/repositories/base-repository'; import { ChatAppConfig } from 'app/si...
this.mainMenuService.registerEntries(config.mainMenuEntries); this.fallbackRoutesService.registerFallbackEntries(config.mainMenuEntries); } }); // Collect all services to notify for the OnAfterAppsLoadedHook const onAfterAppsLoadedItems = ServicesToLo...
{ const repositories: OnAfterAppsLoaded[] = []; appConfigs.forEach((config: AppConfig) => { if (config.models) { config.models.forEach(entry => { let repository: BaseRepository<any, any, any> = null; repository = this.injector.get(entry...
identifier_body
app-load.service.ts
import { Injectable, Injector } from '@angular/core'; import { AgendaAppConfig } from '../../site/agenda/agenda.config'; import { AppConfig, ModelEntry, SearchableModelEntry } from '../definitions/app-config'; import { BaseRepository } from 'app/core/repositories/base-repository'; import { ChatAppConfig } from 'app/si...
( private modelMapper: CollectionStringMapperService, private mainMenuService: MainMenuService, private searchService: SearchService, private injector: Injector, private fallbackRoutesService: FallbackRoutesService ) {} public async loadApps(): Promise<void> { co...
constructor
identifier_name
app-load.service.ts
import { Injectable, Injector } from '@angular/core'; import { AgendaAppConfig } from '../../site/agenda/agenda.config'; import { AppConfig, ModelEntry, SearchableModelEntry } from '../definitions/app-config'; import { BaseRepository } from 'app/core/repositories/base-repository'; import { ChatAppConfig } from 'app/si...
return false; } }
{ // We need to double check, because Typescipt cannot check contructors. If typescript could differentiate // between (ModelConstructor<BaseModel>) and (new (...args: any[]) => (BaseModel & Searchable)), // we would not have to check if the result of the contructor (the model insta...
conditional_block
app-load.service.ts
import { Injectable, Injector } from '@angular/core'; import { AgendaAppConfig } from '../../site/agenda/agenda.config'; import { AppConfig, ModelEntry, SearchableModelEntry } from '../definitions/app-config'; import { BaseRepository } from 'app/core/repositories/base-repository'; import { ChatAppConfig } from 'app/si...
* * @param modelMapper * @param mainMenuService * @param searchService */ public constructor( private modelMapper: CollectionStringMapperService, private mainMenuService: MainMenuService, private searchService: SearchService, private injector: Injector, ...
providedIn: 'root' }) export class AppLoadService { /** * Constructor.
random_line_split
cron-send-cpu-mem-stats.py
#!/usr/bin/env python2 ''' Simple monitoring script to collect per process cpu percentage and mem usage in bytes (vms or virt and rss) usage: cron-send-cpu-mem-stats process_name openshift.whatever.zabbix.key or cron-send-cpu-mem-stats 'something parameter more params' openshift.something.parameter.mo...
(): """ parse the args from the cli """ parser = argparse.ArgumentParser(description='CPU and Memory per process stats collector') parser.add_argument('--debug', action='store_true', default=None, help='Debug?') parser.add_argument('process_str', help='The process command line string to match') par...
parse_args
identifier_name
cron-send-cpu-mem-stats.py
#!/usr/bin/env python2 ''' Simple monitoring script to collect per process cpu percentage and mem usage in bytes (vms or virt and rss) usage: cron-send-cpu-mem-stats process_name openshift.whatever.zabbix.key or cron-send-cpu-mem-stats 'something parameter more params' openshift.something.parameter.mo...
def main(): """ Main function to run the check """ argz = parse_args() proc_parts = argz.process_str.split() zagg_data = {} for proc in psutil.process_iter(): try: if proc_parts[0] == proc.name(): proc.dict = proc.as_dict(['cmdline', 'memory_info']) ...
""" parse the args from the cli """ parser = argparse.ArgumentParser(description='CPU and Memory per process stats collector') parser.add_argument('--debug', action='store_true', default=None, help='Debug?') parser.add_argument('process_str', help='The process command line string to match') parser.add_...
identifier_body
cron-send-cpu-mem-stats.py
#!/usr/bin/env python2 ''' Simple monitoring script to collect per process cpu percentage and mem usage in bytes (vms or virt and rss) usage: cron-send-cpu-mem-stats process_name openshift.whatever.zabbix.key or cron-send-cpu-mem-stats 'something parameter more params' openshift.something.parameter.mo...
if __name__ == '__main__': main()
ms = MetricSender(debug=argz.debug) ms.add_metric(zagg_data) ms.send_metrics()
conditional_block
cron-send-cpu-mem-stats.py
#!/usr/bin/env python2 ''' Simple monitoring script to collect per process cpu percentage and mem usage in bytes (vms or virt and rss) usage: cron-send-cpu-mem-stats process_name openshift.whatever.zabbix.key or cron-send-cpu-mem-stats 'something parameter more params' openshift.something.parameter.mo...
except psutil.NoSuchProcess: pass if argz.debug: try: print 'Process ({0}) is using {1} CPU and {2} {3} memory'.format(argz.process_str, cpu_percent, ...
mem_rss = '{0}'.format(getattr(proc.dict['memory_info'], 'rss')) zagg_data = {'{0}.cpu'.format(argz.zabbix_key_prefix) : cpu_percent, '{0}.mem.vms'.format(argz.zabbix_key_prefix) : mem_vms, '{0}.mem.rss'.format(argz.zabbix_key_pre...
random_line_split
mCustomScrollbar.d.ts
// Type definitions for mCustomScrollbar 2.8.2 // Project: https://github.com/malihu/malihu-custom-scrollbar-plugin // Definitions by: Sarah Williams <https://github.com/flurg> // Definitions: https://github.com/borisyankov/DefinitelyTyped /// <reference path="../jquery/jquery.d.ts" /> declare module MCustomScrollbar...
*/ updateOnBrowserResize?: boolean; /** * Auto-update scrollbars on content resize (useful when adding/changing content progrmatically), value: true, false. Setting this to true makes the script check for content * length changes (every few milliseconds) and ...
} advanced?: { /** * Update scrollbars on browser resize (for fluid content blocks and layouts based on percentages), values: true, false. Set to false only when you content has fixed dimensions
random_line_split
Variable.js
import React from 'react'; import { Box, InfiniteScroll, Text } from 'grommet'; const allItems = Array(240) .fill() .map((_, i) => i + 1); export const Height = () => ( // Uncomment <Grommet> lines when using outside of storybook // <Grommet theme={...}> <Box> <InfiniteScroll items={allItems}> {(...
title: 'Utilities/InfiniteScroll/Variable item height', };
Height.parameters = { chromatic: { disable: true }, }; export default {
random_line_split
tag.py
from functools import partial def build_tag_filter(args): """
Returns a filter which selects entries with all of the given tags only. @param list(str) args, e.g. ["+tag1", "unrelated"] @return (callable filter, list remaining_args) """ remaining_args = [] tags = set() for arg in args: if arg.startswith('+'): tags.add(arg[1:]) ...
random_line_split
tag.py
from functools import partial def
(args): """ Returns a filter which selects entries with all of the given tags only. @param list(str) args, e.g. ["+tag1", "unrelated"] @return (callable filter, list remaining_args) """ remaining_args = [] tags = set() for arg in args: if arg.startswith('+'): tag...
build_tag_filter
identifier_name
tag.py
from functools import partial def build_tag_filter(args): """ Returns a filter which selects entries with all of the given tags only. @param list(str) args, e.g. ["+tag1", "unrelated"] @return (callable filter, list remaining_args) """ remaining_args = [] tags = set() for arg in ar...
filter = partial(get_entries_with_tags, tags) return filter, remaining_args def get_entries_with_tags(tags, entries): """ Returns all entries which match all of the given tags. @param set tags @return generator[Entry] """ for entry in entries: skip = False for wanted_...
if arg.startswith('+'): tags.add(arg[1:]) else: remaining_args.append(arg)
conditional_block
tag.py
from functools import partial def build_tag_filter(args): """ Returns a filter which selects entries with all of the given tags only. @param list(str) args, e.g. ["+tag1", "unrelated"] @return (callable filter, list remaining_args) """ remaining_args = [] tags = set() for arg in ar...
""" Returns all entries which match all of the given tags. @param set tags @return generator[Entry] """ for entry in entries: skip = False for wanted_tag in tags: if wanted_tag.lower() not in entry.get_tags(): skip = True break if ...
identifier_body
sabmark.py
import csv import os import os.path import sys import pybcb.flags as flags __TWILIGHT = 'twi_fp' __SUPERFAMILY = 'sup_fp' def join(*args): flags.assert_flag('sabmark-dir') flags.assert_flag('sabmark-set') if flags.config.sabmark_set == 'twilight': return os.path.join(flags.config.sabmark_dir, _...
return tps, fps
fps.append(row['Name'].strip())
random_line_split
sabmark.py
import csv import os import os.path import sys import pybcb.flags as flags __TWILIGHT = 'twi_fp' __SUPERFAMILY = 'sup_fp' def join(*args): flags.assert_flag('sabmark-dir') flags.assert_flag('sabmark-set') if flags.config.sabmark_set == 'twilight': return os.path.join(flags.config.sabmark_dir, _...
return tps, fps
if row['True pos'].strip() == '1': tps.append(row['Name'].strip()) else: fps.append(row['Name'].strip())
conditional_block
sabmark.py
import csv import os import os.path import sys import pybcb.flags as flags __TWILIGHT = 'twi_fp' __SUPERFAMILY = 'sup_fp' def join(*args): flags.assert_flag('sabmark-dir') flags.assert_flag('sabmark-set') if flags.config.sabmark_set == 'twilight': return os.path.join(flags.config.sabmark_dir, _...
def group_exists(group_num): return os.access(join('group%d' % group_num), os.R_OK) def sabid_pdb_path(group, sabid): return gjoin(group, 'pdb', sabid + '.ent') def group(group_num): ''' `group_num` is the group number in the alignment set of the context. (The alignment set is discovered throu...
return join('group%d' % group_num, *args)
identifier_body
sabmark.py
import csv import os import os.path import sys import pybcb.flags as flags __TWILIGHT = 'twi_fp' __SUPERFAMILY = 'sup_fp' def
(*args): flags.assert_flag('sabmark-dir') flags.assert_flag('sabmark-set') if flags.config.sabmark_set == 'twilight': return os.path.join(flags.config.sabmark_dir, __TWILIGHT, *args) else: return os.path.join(flags.config.sabmark_dir, __SUPERFAMILY, *args) def gjoin(group_num, *args): ...
join
identifier_name
default.js
import path from 'path';
* path objects from path.parse * * @param {string} innerPath * Path (relative to options.svgDir) to svg file * e.g. if svgFile was /home/user/icons/path/to/svg/file.svg * options.svgDir is /home/user/icons/ * innerPath is path/to/svg * * @param {object} options * @return {string} output file dest relati...
/* * Return path to write file to inside outputDir. * * @param {object} svgPathObj
random_line_split
default.js
import path from 'path'; /* * Return path to write file to inside outputDir. * * @param {object} svgPathObj * path objects from path.parse * * @param {string} innerPath * Path (relative to options.svgDir) to svg file * e.g. if svgFile was /home/user/icons/path/to/svg/file.svg * options.svgDir is /home/use...
fileName = fileName.replace(/(^.)|(_)(.)/g, (match, p1, p2, p3) => (p1 || p3).toUpperCase()); return path.join(innerPath, fileName); } export default defaultDestRewriter;
{ fileName = fileName.replace('.svg', '.js'); }
conditional_block
default.js
import path from 'path'; /* * Return path to write file to inside outputDir. * * @param {object} svgPathObj * path objects from path.parse * * @param {string} innerPath * Path (relative to options.svgDir) to svg file * e.g. if svgFile was /home/user/icons/path/to/svg/file.svg * options.svgDir is /home/use...
(svgPathObj, innerPath, options) { let fileName = svgPathObj.base; if (options.fileSuffix) { fileName.replace(options.fileSuffix, '.svg'); } else { fileName = fileName.replace('.svg', '.js'); } fileName = fileName.replace(/(^.)|(_)(.)/g, (match, p1, p2, p3) => (p1 || p3).toUpperCase()); return path....
defaultDestRewriter
identifier_name
default.js
import path from 'path'; /* * Return path to write file to inside outputDir. * * @param {object} svgPathObj * path objects from path.parse * * @param {string} innerPath * Path (relative to options.svgDir) to svg file * e.g. if svgFile was /home/user/icons/path/to/svg/file.svg * options.svgDir is /home/use...
export default defaultDestRewriter;
{ let fileName = svgPathObj.base; if (options.fileSuffix) { fileName.replace(options.fileSuffix, '.svg'); } else { fileName = fileName.replace('.svg', '.js'); } fileName = fileName.replace(/(^.)|(_)(.)/g, (match, p1, p2, p3) => (p1 || p3).toUpperCase()); return path.join(innerPath, fileName); }
identifier_body
pyunit_PUBDEV_8346_modelselection_result_frame.py
from __future__ import print_function from __future__ import division import sys sys.path.insert(1, "../../../") import h2o from tests import pyunit_utils from h2o.estimators.model_selection import H2OModelSelectionEstimator as modelSelection # test modelselection algorithm for regression only. Make sure the result f...
"".format(best_r2_value_maxr, model_r2_allsubsets) if __name__ == "__main__": pyunit_utils.standalone_test(test_gaussian_result_frame_model_id) else: test_gaussian_result_frame_model_id()
best_r2_value_allsubsets = best_r2_allsubsets[ind] one_model_allsubsets = h2o.get_model(result_frame_allsubsets["model_id"][ind, 0]) pred_allsubsets = one_model_allsubsets.predict(d) print("last element of predictor frame: {0}".format(pred_allsubsets[pred_allsubsets.nrows-1,pred_allsubsets.ncols...
conditional_block
pyunit_PUBDEV_8346_modelselection_result_frame.py
from __future__ import print_function from __future__ import division import sys sys.path.insert(1, "../../../") import h2o from tests import pyunit_utils from h2o.estimators.model_selection import H2OModelSelectionEstimator as modelSelection # test modelselection algorithm for regression only. Make sure the result f...
allsubsets_model = modelSelection(seed=12345, max_predictor_number=7, mode="allsubsets") allsubsets_model.train(training_frame=d, x=my_x, y=my_y) result_frame_allsubsets = allsubsets_model.result() numRows = result_frame_allsubsets.nrows best_r2_allsubsets = allsubsets_model.get_best_R2_values() ...
random_line_split
pyunit_PUBDEV_8346_modelselection_result_frame.py
from __future__ import print_function from __future__ import division import sys sys.path.insert(1, "../../../") import h2o from tests import pyunit_utils from h2o.estimators.model_selection import H2OModelSelectionEstimator as modelSelection # test modelselection algorithm for regression only. Make sure the result f...
(): d = h2o.import_file(path=pyunit_utils.locate("smalldata/logreg/prostate.csv")) my_y = "GLEASON" my_x = ["AGE","RACE","CAPSULE","DCAPS","PSA","VOL","DPROS"] maxr_model = modelSelection(seed=12345, max_predictor_number=7, mode="maxr") maxr_model.train(training_frame=d, x=my_x, y=my_y) all...
test_gaussian_result_frame_model_id
identifier_name
pyunit_PUBDEV_8346_modelselection_result_frame.py
from __future__ import print_function from __future__ import division import sys sys.path.insert(1, "../../../") import h2o from tests import pyunit_utils from h2o.estimators.model_selection import H2OModelSelectionEstimator as modelSelection # test modelselection algorithm for regression only. Make sure the result f...
"{1}".format(pred_allsubsets.nrows, d.nrows) best_r2_value_maxr = best_r2_maxr[ind] one_model_maxr = h2o.get_model(result_frame_maxr["model_id"][ind, 0]) pred_maxr = one_model_maxr.predict(d) pyunit_utils.compare_frames_local(pred_maxr, pr...
d = h2o.import_file(path=pyunit_utils.locate("smalldata/logreg/prostate.csv")) my_y = "GLEASON" my_x = ["AGE","RACE","CAPSULE","DCAPS","PSA","VOL","DPROS"] maxr_model = modelSelection(seed=12345, max_predictor_number=7, mode="maxr") maxr_model.train(training_frame=d, x=my_x, y=my_y) allsubsets_...
identifier_body
infect.py
from mininet.net import Mininet from ..util import findPyroObjectOrNone def monkeypatch(cls): def decorator(func): setattr(cls, func.__name__, func) return func return decorator def getOneNodeByName(net, name): if name in net.nameToNode: return net.nameToNode[name] else: return findPyroObjectO...
print "-- Executing: %s" % code exec(code, {'net': self})
identifier_body
infect.py
from mininet.net import Mininet from ..util import findPyroObjectOrNone def monkeypatch(cls): def decorator(func): setattr(cls, func.__name__, func) return func return decorator def getOneNodeByName(net, name): if name in net.nameToNode: return net.nameToNode[name] else: return findPyroObjectO...
def remoteExecute(self, code): print "-- Executing: %s" % code exec(code, {'net': self})
self.hosts.append(s) @monkeypatch(Mininet)
random_line_split
infect.py
from mininet.net import Mininet from ..util import findPyroObjectOrNone def monkeypatch(cls): def
(func): setattr(cls, func.__name__, func) return func return decorator def getOneNodeByName(net, name): if name in net.nameToNode: return net.nameToNode[name] else: return findPyroObjectOrNone(name) @monkeypatch(Mininet) def intakeNodes(self, networks): for netName in networks: net = findP...
decorator
identifier_name
infect.py
from mininet.net import Mininet from ..util import findPyroObjectOrNone def monkeypatch(cls): def decorator(func): setattr(cls, func.__name__, func) return func return decorator def getOneNodeByName(net, name): if name in net.nameToNode: return net.nameToNode[name] else:
@monkeypatch(Mininet) def intakeNodes(self, networks): for netName in networks: net = findPyroObjectOrNone(netName) if self.name == net.getName(): continue print "-- Intake nodes from %s" % net.getName() for h in net.getHosts(): self.nameToNode[h.getName()] = h self.hosts.append(h)...
return findPyroObjectOrNone(name)
conditional_block