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
lambda.rs
_COMMUNITY_KEYGEN_POLICY_ID").unwrap(); static ref SMTP_SERVER: String = env::var("SMTP_SERVER").unwrap(); static ref SMTP_USERNAME: String = env::var("SMTP_USERNAME").unwrap(); static ref SMTP_PASSWORD: String = env::var("SMTP_PASSWORD").unwrap(); } fn router(req: Request, c: Context) -> Result<Response<B...
let events_json = util::body_to_json(req.body())?; let events_json = events_json["events"].as_array().ok_or("invalid format")?; // TODO do not reply OK every time: check each event for e in events_json { let ty = e["type"].as_str().ok_or("invalid format")?; let data = &e["data"]; ...
{ return Ok(Response::builder() .status(http::StatusCode::UNAUTHORIZED) .body(Body::default()) .unwrap()); }
conditional_block
state.rs
: <JobId as ItemId>::IdType, task_id_counter: <TaskId as ItemId>::IdType, pub(crate) autoalloc_service: Option<AutoAllocService>, event_storage: EventStorage, server_info: ServerInfo, } define_wrapped_type!(StateRef, State, pub); fn cancel_tasks_from_callback( state_ref: &StateRef, tako_ref:...
pub fn new_job_id(&mut self) -> JobId { let id = self.job_id_counter; self.job_id_counter += 1; id.into() } pub fn revert_to_job_id(&mut self, id: JobId) { self.job_id_counter = id.as_num(); } pub fn last_n_ids(&self, n: u32) -> impl Iterator<Item = JobId> { ...
{ let job_id: JobId = *self.base_task_id_to_job_id.range(..=task_id).next_back()?.1; let job = self.jobs.get_mut(&job_id)?; if task_id < TakoTaskId::new( job.base_task_id.as_num() + job.n_tasks() as <TaskId as ItemId>::IdType, ) { Some(...
identifier_body
state.rs
: <JobId as ItemId>::IdType, task_id_counter: <TaskId as ItemId>::IdType, pub(crate) autoalloc_service: Option<AutoAllocService>, event_storage: EventStorage, server_info: ServerInfo, } define_wrapped_type!(StateRef, State, pub); fn cancel_tasks_from_callback( state_ref: &StateRef, tako_ref:...
(&mut self, msg: TaskUpdate, backend: &Backend) { log::debug!("Task id={} updated {:?}", msg.id, msg.state); let (mut job_id, mut is_job_terminated): (Option<JobId>, bool) = (None, false); match msg.state { TaskState::Running { worker_ids, context, ...
process_task_update
identifier_name
state.rs
: <JobId as ItemId>::IdType, task_id_counter: <TaskId as ItemId>::IdType, pub(crate) autoalloc_service: Option<AutoAllocService>, event_storage: EventStorage, server_info: ServerInfo, } define_wrapped_type!(StateRef, State, pub); fn cancel_tasks_from_callback( state_ref: &StateRef, tako_ref:...
self.event_storage .on_worker_added(msg.worker_id, msg.configuration); } pub fn process_worker_lost( &mut self, _state_ref: &StateRef, _tako_ref: &Backend, msg: LostWorkerMessage, ) { log::debug!("Worker lost id={}", msg.worker_id); let ...
{ autoalloc.on_worker_connected(msg.worker_id, &msg.configuration); }
conditional_block
state.rs
base_task_id_to_job_id .insert(job.base_task_id, job_id) .is_none()); self.event_storage.on_job_submitted( job_id, JobInfo { name: job.name.clone(), job_desc: job.job_desc.clone(), base_task_id: job.base_task_id, ...
random_line_split
parse.rs
{ for (idx, sub) in subs.into_iter().enumerate() { let substitution = Substitution::new(&args, sub.into_iter()); if let Ok(substitution) = substitution { reorder[idx].add_substitution( Ident::new(&ident.clone(), Span::call_site()), substitution, )?; } else { retu...
( tree: TokenTree, existing: &Option<HashSet<String>>, ) -> Result<SubstitutionGroup, (Span, String)> { // Must get span now, before it's corrupted. let tree_span = tree.span(); let group = check_group( tree, "Hint: When using verbose syntax, a substitutions must be enclosed in a \ group.\nExample:\n..\n[\n...
extract_verbose_substitutions
identifier_name
parse.rs
{ for (idx, sub) in subs.into_iter().enumerate() { let substitution = Substitution::new(&args, sub.into_iter()); if let Ok(substitution) = substitution { reorder[idx].add_substitution( Ident::new(&ident.clone(), Span::call_site()), substitution, )?; } else { ret...
if let Some(ident) = next_token(&mut stream, "Epected substitution identifier.")? { if let TokenTree::Ident(ident) = ident { let sub = parse_group( &mut stream, ident.span(), "Hint: A substitution identifier should be followed by a group containing the \ code to be inserted instead of...
{ // Must get span now, before it's corrupted. let tree_span = tree.span(); let group = check_group( tree, "Hint: When using verbose syntax, a substitutions must be enclosed in a \ group.\nExample:\n..\n[\n\tidentifier1 [ substitution1 ]\n\tidentifier2 [ substitution2 \ ]\n]", )?; if group.stream().into...
identifier_body
parse.rs
{ for (idx, sub) in subs.into_iter().enumerate() { let substitution = Substitution::new(&args, sub.into_iter()); if let Ok(substitution) = substitution { reorder[idx].add_substitution( Ident::new(&ident.clone(), Span::call_site()), substitution, )?; } else { ret...
let group = check_group( tree, "Hint: When using verbose syntax, a substitutions must be enclosed in a \ group.\nExample:\n..\n[\n\tidentifier1 [ substitution1 ]\n\tidentifier2 [ substitution2 \ ]\n]", )?; if group.stream().into_iter().count() == 0 { return Err((group.span(), "No substitution groups fo...
) -> Result<SubstitutionGroup, (Span, String)> { // Must get span now, before it's corrupted. let tree_span = tree.span();
random_line_split
font.go
StartIndex. func (f *Font) OffsetForIndexAdv(msg string, charStartIndex int, stopIndex int) float32 { var w float32 // sanity test the input if len(msg) < 1 { return 0.0 } if charStartIndex > stopIndex { return 0.0 } // see how much to scale the size based on current resolution vs desgin resolution fontSc...
{ return f.loadRGBAToTextureExt(rgba, imageSize, graphics.LINEAR, graphics.LINEAR, graphics.CLAMP_TO_EDGE, graphics.CLAMP_TO_EDGE) }
identifier_body
font.go
, but get the bounds for the font glyphBounds := ttfData.Bounds(scale) // width and height are getting +2 here since the glyph will be buffered by a // pixel in the texture glyphDimensions := glyphBounds.Max.Sub(glyphBounds.Min) glyphWidth := fixedInt26ToFloat(glyphDimensions.X) glyphHeight := fixedInt26ToFloat(...
(fixedInt fixed.Int26_6) float32 { var result float32 i := int32(fixedInt) result += float32(i >> 6) result += float32(i&0x003F) / float32(64.0) return result } // TextRenderData is a structure containing the raw OpenGL VBO data needed // to render a text string for a given texture. type TextRenderData struct { ...
fixedInt26ToFloat
identifier_name
font.go
but get the bounds for the font glyphBounds := ttfData.Bounds(scale) // width and height are getting +2 here since the glyph will be buffered by a // pixel in the texture glyphDimensions := glyphBounds.Max.Sub(glyphBounds.Min) glyphWidth := fixedInt26ToFloat(glyphDimensions.X) glyphHeight := fixedInt26ToFloat(g...
return w * fontScale } // fixedInt26ToFloat converts a fixed int 26:6 precision to a float32. func fixedInt26ToFloat(fixedInt fixed.Int26_6) float32 { var result float32 i := int32(fixedInt) result += float32(i >> 6) result += float32(i&0x003F) / float32(64.0) return result } // TextRenderData is a structure ...
{ // calculate up to the stopIndex but do not include it if i+charStartIndex >= stopIndex { break } adv, _ := f.face.GlyphAdvance(ch) w += fixedInt26ToFloat(adv) }
conditional_block
font.go
, but get the bounds for the font glyphBounds := ttfData.Bounds(scale) // width and height are getting +2 here since the glyph will be buffered by a // pixel in the texture glyphDimensions := glyphBounds.Max.Sub(glyphBounds.Min) glyphWidth := fixedInt26ToFloat(glyphDimensions.X) glyphHeight := fixedInt26ToFloat(...
} // OffsetForIndex returns the width offset that will fit just before the `stopIndex` // number character in the msg. func (f *Font) OffsetForIndex(msg string, stopIndex int) float32 { return f.OffsetForIndexAdv(msg, 0, stopIndex) } // OffsetForIndexAdv returns the width offset that will fit just before the `stopIn...
return w * fontScale
random_line_split
component_catalog.py
server process (if running) can detect the manifest file update and send the request to the update queue. Note that any calls to ComponentCache.refresh() from non-server processes will still perform the refresh, but via the update queue rather than the refresh queue. We could, instead...
"""Dispatches delete and modification events pertaining to the manifest filename""" if "elyra-component-manifest" in event.src_path: super().dispatch(event)
identifier_body
component_catalog.py
CacheUpdateWorker( self._component_cache, self._refresh_queue if self._check_refresh_queue else self._update_queue, catalog, action, ) updater_thread.start() queue_clause = "refreshing" if self._check_refresh_queue else...
else: self.log.debug(f"CacheUpdateWorker completed for catalog: '{thread.name}', action: '{thread.action}'.") # Thread has been joined and can be removed from the list self._threads.remove(thread) # Mark cache task as complete ...
outstanding_threads = True # Report on a long-running thread if CATALOG_UPDATE_TIMEOUT is exceeded time_since_last_check = int(time.time() - thread.last_warn_time) if time_since_last_check > CATALOG_UPDATE_TIMEOUT: thread.last_warn_time = time.time() ...
conditional_block
component_catalog.py
parent"].__class__.__name__ in app_names: is_server_process = True elif emulate_server_app: # Used in unittests is_server_process = True return is_server_process def load(self): """ Completes a series of actions during system startup, such as creating ...
load_jinja_template
identifier_name
component_catalog.py
timed out) outstanding_threads = True # Report on a long-running thread if CATALOG_UPDATE_TIMEOUT is exceeded time_since_last_check = int(time.time() - thread.last_warn_time) if time_since_last_check > CATALOG_UPDATE_TIMEOUT: thread.l...
# Proceed only if singleton instance has been created if self.initialized: # The cache manager will work on manifest and cache tasks on an # in-process basis as load() is only called during startup from # the server process.
random_line_split
run.py
def process_clients(): """ Check each client, if client.cmd_ready == True then there is a line of input available via client.get_command(). """ for client in state.CLIENT_LIST: if client.active and client.cmd_ready: logging.debug("Found a message, processing...") ms...
""" lost, or disconnected clients """ logging.info("Lost connection to %s" % client.addrport() ) state.prune_client_state(client) state.prune_client_list(client) #broadcast('%s leaves the conversation.\n' % client.addrport() )
identifier_body
run.py
) state.prune_client_list(client) #broadcast('%s leaves the conversation.\n' % client.addrport() ) def process_clients(): """ Check each client, if client.cmd_ready == True then there is a line of input available via client.get_command(). """ for client in state.CLIENT_LIST: if clie...
logging.debug(str(state.CLIENT_STATE)) logging.debug(str(AUTH_DB)) logging.debug(str(state.CLIENT_LIST)) return
conditional_block
run.py
_STATE[client]['auth_status'] = 'enroll_user' def enroll_pass(): CLIENT_STATE[client]['pass1'] = msg client.send("Please type your password again: ") CLIENT_STATE[client]['auth_status'] = 'enroll_pass2' def enroll_pass2(): if CLIENT_STATE[client]['pass1'] == msg: cl...
# elif cmd == 'shutdown': # SERVER_RUN = False #------------------------------------------------------------------------------
random_line_split
run.py
""" lost, or disconnected clients """ logging.info("Lost connection to %s" % client.addrport() ) state.prune_client_state(client) state.prune_client_list(client) #broadcast('%s leaves the conversation.\n' % client.addrport() ) def process_clients(): """ Check each client, if client.cmd_...
(): if not AUTH_DB.has_key(msg): CLIENT_STATE[client]['user_id'] = msg CLIENT_STATE[client]['auth_status'] = 'enroll_pass' client.send("New password: ") client.password_mode_on() else: client.send("%s already taken, try something else: " % msg)...
enroll_user
identifier_name
editorBrowser.ts
; removeContentWidget(widgetData: IContentWidgetData): void; addOverlayWidget(widgetData: IOverlayWidgetData): void; layoutOverlayWidget(widgetData: IOverlayWidgetData): void; removeOverlayWidget(widgetData: IOverlayWidgetData): void; } /** * @internal */ export interface IViewZoneData { viewZoneId: number; p...
*/ position: editorCommon.IPosition; /** * Placement preference for position, in order of preference. */ preference: ContentWidgetPositionPreference[]; } /** * A content widget renders inline with the text and can be easily placed 'near' an editor position. */ export interface IContentWidget { /** * Rende...
* Desired position for the content widget. * `preference` will also affect the placement.
random_line_split
dag_abm_catalogo_ubm.js
tipoimg == '.PNG' || tipoimg == '.BMP' || tipoimg == '.GIF') { $scope.archotro = true; $scope.archpdf = false; $scope.archivoP=fum; $('#imgSalida').attr("src",fum); } else{ document.location = fum;} } } }; //////////////////////////////////////////////////////////////////////////////...
}; // adicionar nodo en el arbol $scope.addNode = function() { if ($scope.agregado == "false") { var nameNode = $scope.datos.DAG_CAT_PRESUP_ITEM; var idNode = parseInt($scope.nodoAr.children.length) + 1; var padreNode = parseInt($scope.nodoAr.id); //console.log(nameNode, " ", idNode); $('#tree1').t...
ode is null // a node was deselected // e.previous_node contains the deselected node } } } );
conditional_block
dag_abm_catalogo_ubm.js
scope.obtArbol); //console.log(obtArbol); var parametros = { "NODOS" : obtArbol, "TARBOL" : "dataCatalogo.json" }; $.ajax({ data: parametros, //url: 'http://192.168.17.144:88/dreamfactory/dist/generaArbolAjaxDAG.php', url: 'http://192.168.5.248/dreamfactory/dist/dag/generaArbolAjaxDAG.ph...
$scope.item.push({ id: DetItem[j].id, partida: $scope.partida, nombre: DetItem[j].nombre, caracteristicas: nodo_carac,
random_line_split
Buy.js
class Buy extends React.Component { constructor(props) { super(props); this.state = { productEmail: "", }; } obtainProductsLocalStorage() { let productLS; if (localStorage.getItem("productos") === null) { productLS = []; } else { productLS = JSON.parse(localStorage.getI...
else { const loadingGif = document.querySelector("#load"); loadingGif.style.display = "block"; const send = document.createElement("img"); send.src = "../images/mail.gif"; send.id = "mailImage"; let productsLS, product; productsLS = JSON.parse(localStorage.getItem("productos")...
{ window.alert("Por favor, diligencie todos los campos"); }
conditional_block
Buy.js
class Buy extends React.Component { constructor(props) { super(props); this.state = { productEmail: "", }; } obtainProductsLocalStorage() { let productLS; if (localStorage.getItem("productos") === null) { productLS = []; } else { productLS = JSON.parse(localStorage.getI...
productsLS.map((productLS, i) => { product += "\n" + JSON.stringify( `Plato: ${productLS.titulo} Precio: ${productLS.precio} Cantidad: ${productLS.cantidad}` ); }); product = product.replace("undefined", ""); emailjs .send( "ser...
{ e.preventDefault(); if (this.obtainProductsLocalStorage().length === 0) { window.alert( "No se puede realizar la compra porque no hay productos seleccionados" ); window.location.href = "/menu"; } else if ( document.getElementById("client").value === "" || document.get...
identifier_body
Buy.js
"; class Buy extends React.Component { constructor(props) { super(props); this.state = { productEmail: "", }; } obtainProductsLocalStorage() {
productLS = JSON.parse(localStorage.getItem("productos")); } return productLS; } totalCalculate() { let productLS; let total = 0, subtotal = 0, igv = 0; productLS = this.obtainProductsLocalStorage(); for (let i = 0; i < productLS.length; i++) { let element = Number(p...
let productLS; if (localStorage.getItem("productos") === null) { productLS = []; } else {
random_line_split
Buy.js
"; class Buy extends React.Component { constructor(props) { super(props); this.state = { productEmail: "", }; } obtainProductsLocalStorage() { let productLS; if (localStorage.getItem("productos") === null) { productLS = []; } else { productLS = JSON.parse(localStorage.g...
() { let productLS; let total = 0, subtotal = 0, igv = 0; productLS = this.obtainProductsLocalStorage(); for (let i = 0; i < productLS.length; i++) { let element = Number(productLS[i].precio * productLS[i].cantidad); total = total + element; } igv = parseFloat(total * 0.1...
totalCalculate
identifier_name
message.pb.go
func (m *VectorClock) XXX_Merge(src proto.Message) { xxx_messageInfo_VectorClock.Merge(m, src) } func (m *VectorClock) XXX_Size() int { return m.Size() } func (m *VectorClock) XXX_DiscardUnknown() { xxx_messageInfo_VectorClock.DiscardUnknown(m) } var xxx_messageInfo_VectorClock proto.InternalMessageInfo func (m *...
{ if deterministic { return xxx_messageInfo_VectorClock.Marshal(b, m, deterministic) } else { b = b[:cap(b)] n, err := m.MarshalToSizedBuffer(b) if err != nil { return nil, err } return b[:n], nil } }
identifier_body
message.pb.go
0x14, 0x77, 0xe1, 0xa1, 0x1c, 0xc3, 0x8d, 0x87, 0x72, 0x0c, 0x1f, 0x1e, 0xca, 0x31, 0x36, 0x3c, 0x92, 0x63, 0x5c, 0xf1, 0x48, 0x8e, 0xf1, 0xc4, 0x23, 0x39, 0xc6, 0x0b, 0x8f, 0xe4, 0x18, 0x1f, 0x3c, 0x92, 0x63, 0x7c, 0xf1, 0x48, 0x8e, 0xe1, 0xc3, 0x23, 0x39, 0xc6, 0x09, 0x8f, 0xe5, 0x18, 0x2e, 0x3c, 0x96, 0x63, 0xb8...
{ return io.ErrUnexpectedEOF }
conditional_block
message.pb.go
if m != nil { return m.ShardId } return 0 } func (m *VectorClock) GetClock() int64 { if m != nil { return m.Clock } return 0 } func (m *VectorClock) GetClusterId() int64 { if m != nil { return m.ClusterId } return 0 } func init() { proto.RegisterType((*VectorClock)(nil), "temporal.server.api.clock.v1...
0xff, 0xff, 0xc4, 0x11, 0xe0, 0xe1, 0x11, 0x01, 0x00, 0x00, } func (this *VectorClock) Equal(that interface{}) bool { if that == nil { return this == nil } that1, ok := that.(*VectorClock) if !ok { that2, ok := that.(VectorClock) if ok { that1 = &that2 } else { return false } } if that1 == nil ...
0x2e, 0x3c, 0x96, 0x63, 0xb8, 0xf1, 0x58, 0x8e, 0x21, 0x4a, 0x23, 0x3d, 0x5f, 0x0f, 0xee, 0xea, 0xcc, 0x7c, 0x6c, 0x9e, 0xb4, 0x06, 0x33, 0x92, 0xd8, 0xc0, 0x7e, 0x34, 0x06, 0x04, 0x00, 0x00,
random_line_split
message.pb.go
if m != nil { return m.ShardId } return 0 } func (m *VectorClock) GetClock() int64 { if m != nil { return m.Clock } return 0 } func (m *VectorClock)
() int64 { if m != nil { return m.ClusterId } return 0 } func init() { proto.RegisterType((*VectorClock)(nil), "temporal.server.api.clock.v1.VectorClock") } func init() { proto.RegisterFile("temporal/server/api/clock/v1/message.proto", fileDescriptor_86d20c4676353367) } var fileDescriptor_86d20c4676353367 = [...
GetClusterId
identifier_name
scripts.py
lines_all if l[0]=='#'] inputLines = [l.split('\t') for l in lines_all if l not in headerLines+['']] if '\t' in headerLines[-1]: headerLines = headerLines[:-1] headerLines.append(self.header) ## for l in inputLines: ## print([l]) self.convertCDLICoNLLtoCoNLLU(inputLines) #print(self.o...
return None command = self.CoNLLRDFFormatter_command() + ['-conll'] \ + columns (CONLLstr, errors) = self.run( command, cwd_path=f_path, stdin_str=stdin_str, decode_stdout=True) CONLLstr = CONLLstr.replace(' #', ' \n#') \ .replace('\t#', '\n#').repl...
if f_path==None and stdin_str==None: print('rdf2conll wrapper: specify path OR string.')
random_line_split
scripts.py
lines_all if l[0]=='#'] inputLines = [l.split('\t') for l in lines_all if l not in headerLines+['']] if '\t' in headerLines[-1]: headerLines = headerLines[:-1] headerLines.append(self.header) ## for l in inputLines: ## print([l]) self.convertCDLICoNLLtoCoNLLU(inputLines) #print(self.o...
(self, filename): ''' Convert CDLI-CoNLL to CoNLL-U from file. ''' sp.run(['cdliconll2conllu', '-i', filename, '-v'], print_stdout=False) cdli_conll_u = CC2CU() #---/ CONLL-U <> CONLL-RDF /--------------------------------------------------- # class CoNLL2RDF(common_functions): ''' Wrapper around C...
convert_from_file
identifier_name
scripts.py
lines_all if l[0]=='#'] inputLines = [l.split('\t') for l in lines_all if l not in headerLines+['']] if '\t' in headerLines[-1]: headerLines = headerLines[:-1] headerLines.append(self.header) ## for l in inputLines: ## print([l]) self.convertCDLICoNLLtoCoNLLU(inputLines) #print(self.o...
def conll2rdf(self, f_path, columns_typ): ''' Run Java CoNNL2RDF script to convert CoNLL file to RDF. ''' #self.define_columns(columns_typ) command = self.CoNLLStreamExtractor_command() + ['../data/'] \ + self.columns self.dump_rdf(rdf_str, f_path) def rdf2conll(self, column...
''' Run Java compiler with command. ''' self.run([r'%s' %self.JAVAC_PATH, '-d', r'%s' %target_path, '-g', '-cp', r'%s' %cp_path, ]+[r'%s' %f for f in src_files_lst], cwd_path=cwd_path)
identifier_body
scripts.py
lines_all if l[0]=='#'] inputLines = [l.split('\t') for l in lines_all if l not in headerLines+['']] if '\t' in headerLines[-1]: headerLines = headerLines[:-1] headerLines.append(self.header) ## for l in inputLines: ## print([l]) self.convertCDLICoNLLtoCoNLLU(inputLines) #print(self.o...
stdout_lst = [b for b in stdout.split(b'\n') if b not in shell_lst] if typ==bytes: errors = b'\n'.join(shell_lst) stdout = b'\n'.join(stdout_lst) ## print(stdout.decode('utf-8')) ## print(errors.decode('utf-8')) elif typ==str: errors = b'\n'.join(shell_lst).decode('utf-8') ...
for m in shell_markers: if m in b: shell_lst.append(b) break
conditional_block
imp.rs
Literal> }, } impl LiteralSearcher { /// Returns a matcher that never matches and never advances the input. pub fn empty() -> Self { Self::new(Literals::empty(), Matcher::Empty) } /// Returns a matcher for literal prefixes from the given set. pub fn prefixes(lits: Literals) -> Self { ...
let pats = lits.literals().to_owned(); let is_aho_corasick_fast = sset.dense.len() <= 1 && sset.all_ascii; if lits.literals().len() <= 100 && !is_aho_corasick_fast { let mut builder = packed::Config::new() .match_kind(packed::MatchKind::LeftmostFirst) ...
{ if lits.literals().is_empty() { return Matcher::Empty; } if sset.dense.len() >= 26 { // Avoid trying to match a large number of single bytes. // This is *very* sensitive to a frequency analysis comparison // between the bytes in sset and the comp...
identifier_body
imp.rs
Literal> }, } impl LiteralSearcher { /// Returns a matcher that never matches and never advances the input. pub fn empty() -> Self { Self::new(Literals::empty(), Matcher::Empty) } /// Returns a matcher for literal prefixes from the given set. pub fn prefixes(lits: Literals) -> Self { ...
(&self, haystack: &[u8]) -> Option<(usize, usize)> { for lit in self.iter() { if lit.len() > haystack.len() { continue; } if lit == &haystack[0..lit.len()] { return Some((0, lit.len())); } } None } /// Like ...
find_start
identifier_name
imp.rs
<Literal> }, } impl LiteralSearcher { /// Returns a matcher that never matches and never advances the input. pub fn empty() -> Self { Self::new(Literals::empty(), Matcher::Empty) } /// Returns a matcher for literal prefixes from the given set. pub fn prefixes(lits: Literals) -> Self { ...
} } fn prefixes(lits: &Literals) -> SingleByteSet { let mut sset = SingleByteSet::new(); for lit in lits.literals() { sset.complete = sset.complete && lit.len() ==
complete: true, all_ascii: true,
random_line_split
imp.rs
Literal> }, } impl LiteralSearcher { /// Returns a matcher that never matches and never advances the input. pub fn empty() -> Self { Self::new(Literals::empty(), Matcher::Empty) } /// Returns a matcher for literal prefixes from the given set. pub fn prefixes(lits: Literals) -> Self { ...
else { let next = &one[..]; *one = &[]; Some(next) } } LiteralIter::AC(ref mut lits) => { if lits.is_empty() { None } else { let next = &lits[0]; ...
{ None }
conditional_block
GetOutput.py
.time() self.getOutput() stop = time.time() common.logger.debug( "GetOutput Time: "+str(stop - start)) pass def checkBeforeGet(self): # should be in this way... but a core dump appear... waiting for solution #self.up_task = common.scheduler.queryEverything(1) ...
for f in os.listdir(self.logDir): if f.find('_'+str(id)+'.') != -1 and f.find('Submission_'+str(id)) == -1: self.moveOutput(id, self.max_id, self.logDir, f) pass pass ...
""" Untar Output """ listCode = [] job_id = [] success_ret = 0 size = 0 # in kB for id in list_id: runningJob = task.getJob( id ).runningJob if runningJob.isError() : continue file = 'out_files_'+ str(id)+'.tgz' ...
identifier_body
GetOutput.py
from %d requested.\n'%(len(self.jobs)) msg += '\t(for details: crab -status)' common.logger.info(msg) if not os.path.isdir(self.logDir) or not os.path.isdir(self.outDir): msg = ' Output or Log dir not found!! check '+self.logDir+' and '+self.outDir ...
if common.scheduler.name().upper() not in ['LSF', 'CAF', 'PBS', 'PBSV2'] and codeValue["wrapperReturnCode"] == 60308: pfns.append(os.path.dirname(aFile['SurlForGrid'])+'/') else: pfns.append(os.path.dirname(aFile['PFN'])+'/') ##...
conditional_block
GetOutput.py
.time() self.getOutput() stop = time.time() common.logger.debug( "GetOutput Time: "+str(stop - start)) pass def checkBeforeGet(self): # should be in this way... but a core dump appear... waiting for solution #self.up_task = common.scheduler.queryEverything(1) ...
(self): """ Get output for a finished job with id. """ self.checkBeforeGet() # Get first job of the list if not self.dontCheckSpaceLeft and not has_freespace(self.outDir, 10*1024): # First check for more than 10 Mb msg = "You have LESS than 10 MB of free space...
getOutput
identifier_name
GetOutput.py
(Failed)']: list_id_done_not_term.append(job['jobId']) self.all_id.append(job['jobId']) check = -1 if self.jobs != 'all': check = len( set(self.jobs).intersection(set(list_id_done)) ) if len(list_id_done)==0 or ( check == 0 ) : msg='' l...
codeValue.pop("applicationReturnCodeOrig")
random_line_split
connect_four.py
empty lists... Index 0 corresponds to the TOP ROW of the printed board!!! board = [[], [], [], [], [], [], []] for x1 in range(0,len(board)): single_row = [' '*20,'| ', spaces[(42-x1*7+0)],' | ', spaces[(42-x1*7+1)], ' | ', spaces[(42-x1*7+2)],' | ', spaces[(42-x1*7+3)], ' | ', spaces[(42-x...
def vertical_win(marker): for x2 in range(0,7): # Iterate up a columns checking for four-in-a-row. Run this check on spaces in first four rows (x3) of the # to avoid going off the board (an indexing error). for x3 in range(0,4): if marker == space...
for x2 in [0,7,14,21,28,35,42]: for x3 in range(0,4): # Can't be 7 if marker == spaces[x2+x3] == spaces[x2+x3+1] == spaces[x2+x3+2] == spaces[x2+x3+3]: return [True, x2+x3, x2+x3+1, x2+x3+2, x2+x3+3] #return True, and the first winning horizontal ...
identifier_body
connect_four.py
(): ''' Module to assign X or O to the two players. Returns a list with two elements, where index 0 is player 1's marker, index 1 is player 2's marker. ''' import string plyr1 = input("Player 1, choose X or O as your marker: ") plyr1_mkr = plyr1.lower() while True: ...
pick_markers
identifier_name
connect_four.py
''' Uses the the contents of spaces (list variable) to construct/update the gameboard on the console. ''' clear() while len(spaces) < 49: spaces.append(' ') # Start with 7 empty lists... Index 0 corresponds to the TOP ROW of the printed board!!! board = [[], [], [], [], []...
clear = lambda: os.system('cls') import colorama # This module constructs the intitial, and print the updated board throughout the game. def print_board(spaces):
random_line_split
connect_four.py
top). return (False, 0) def ascending_diagonal_win(marker): # Check for an ascending left-right diagonal four-in-a-row. Left-right ascending diagonals are 8 indeces apart. # Iterate on first four columns. for x2 in range(0,4): # Iterate on first four...
ConnectFour()
conditional_block
ctrl_server.py
msgs from bot.driver.mec_driver import MecDriver def is_api_method(obj, name): """Tests whether named method exists in obj and is flagged for API export. :param obj: API-exported object to search for the given method on. :type ojb: string :param name: Name of method to check for. :type name: st...
reply = msgs.exit_reply() # Need to actually send reply here as we're about to exit self.logger.debug("Sending: {}".format(reply)) self.ctrl_sock.send_json(reply) self.clean_up() sys.exit(0) else: err_msg = "Unrecognized message...
self.logger.info("Received message to die. Bye!")
random_line_split
ctrl_server.py
from bot.driver.mec_driver import MecDriver def is_api_method(obj, name): """Tests whether named method exists in obj and is flagged for API export. :param obj: API-exported object to search for the given method on. :type ojb: string :param name: Name of method to check for. :type name: string ...
callables[name] = methods return msgs.list_reply(callables) def call_method(self, name, method, params): """Call a previously registered subsystem method by name. Only methods tagged with the @api_call decorator can be called. :param name: Assigned name of the register...
methods.append(member[0])
conditional_block
ctrl_server.py
from bot.driver.mec_driver import MecDriver def is_api_method(obj, name): """Tests whether named method exists in obj and is flagged for API export. :param obj: API-exported object to search for the given method on. :type ojb: string :param name: Name of method to check for. :type name: string ...
(self): """Raise a test exception which will be returned to the caller.""" raise Exception("Exception test") @lib.api_call def spawn_pub_server(self): """Spawn publisher
exception
identifier_name
ctrl_server.py
msgs from bot.driver.mec_driver import MecDriver def is_api_method(obj, name): """Tests whether named method exists in obj and is flagged for API export. :param obj: API-exported object to search for the given method on. :type ojb: string :param name: Name of method to check for. :type name: st...
obj_name = msg["obj_name"] method = msg["method"] params = msg["params"] reply = self.call_method(obj_name, method, params) except KeyError as e: return msgs.error(e) elif msg_type == "exit_req": self.logger....
"""Generic message handler. Hands-off based on type of message. :param msg: Message, received via ZMQ from client, to handle. :type msg: dict :returns: An appropriate message reply dict, from lib.messages. """ self.logger.debug("Received: {}".format(msg)) try: ...
identifier_body
synchronizer.rs
certs ... for cert in &genesis { // let bytes: Vec<u8> = bincode::serialize(&cert)?; let digest_in_store = PartialCertificate::make_digest(&cert.digest, 0, cert.primary_id); let _ = store .write(digest_in_store.0.to_vec(), digest_in_store.0.to_vec()) //digest_in_store.0.to_vec()...
warn!("Exiting DagSynchronizer::start()."); break; } } res = rollback_fut => { if let Err(e) = res{ error!("rollback_headers returns error: {:?}", e); } else{ ...
random_line_split
synchronizer.rs
... for cert in &genesis { // let bytes: Vec<u8> = bincode::serialize(&cert)?; let digest_in_store = PartialCertificate::make_digest(&cert.digest, 0, cert.primary_id); let _ = store .write(digest_in_store.0.to_vec(), digest_in_store.0.to_vec()) //digest_in_store.0.to_vec() --> b...
( mut dag_synchronizer: DagSynchronizer, digest: Digest, rollback_stop_round: RoundNumber, sq: SyncNumber, ) -> Result<Option<Vec<Digest>>, DagError> { //TODO: issue: should we try the processor first? we need concurrent access to it... if let Ok(dbvalue) = dag_synchronizer.store.read(digest.to...
handle_header_digest
identifier_name
synchronizer.rs
... for cert in &genesis { // let bytes: Vec<u8> = bincode::serialize(&cert)?; let digest_in_store = PartialCertificate::make_digest(&cert.digest, 0, cert.primary_id); let _ = store .write(digest_in_store.0.to_vec(), digest_in_store.0.to_vec()) //digest_in_store.0.to_vec() --> b...
}); } } debug!( "[DEP] GOT H {:?} D {}", (header.round, header.author), header.transactions_digest.len() ); Ok(signed_header) } pub async fn dag_synchronizer_process( mut get_from_dag: Receiver<SyncMessage>, dag_synchronizer: DagSynchronizer, ) { ...
{ debug!( "[DEP] ASK H {:?} D {}", (header.round, header.author), header.transactions_digest.len() ); //Note: we now store different digests for header and certificates to avoid false positive. for (other_primary_id, digest) in &header.parents { let digest_in_store = ...
identifier_body
timeseriesrdd.py
each univariate series, observations are not distributed. The time dimension is conformed in the sense that a single DateTimeIndex applies to all the univariate series. Each univariate series within the RDD has a String key to identify it. """ def __init__(self, dt_index, rdd, jtsrdd = None, sc = None...
Returns a TimeSeriesRDD rebased on top of a new index. Any timestamps that exist in the new index but not in the existing index will be filled in with NaNs. Parameters ---------- new_index : DateTimeIndex """ return TimeSeriesRDD(None, None, self._jtsrdd...
return TimeSeriesRDD(None, None, self._jtsrdd.returnRates(), self.ctx) def with_index(self, new_index): """
random_line_split
timeseriesrdd.py
univariate series, observations are not distributed. The time dimension is conformed in the sense that a single DateTimeIndex applies to all the univariate series. Each univariate series within the RDD has a String key to identify it. """ def __init__(self, dt_index, rdd, jtsrdd = None, sc = None): ...
(self, method): """ Returns a TimeSeriesRDD with missing values imputed using the given method. Parameters ---------- method : string "nearest" fills in NaNs with the closest non-NaN value, using the closest previous value in the case of a tie. "...
fill
identifier_name
timeseriesrdd.py
jvm.com.cloudera.sparkts.BytesToKeyAndSeries()) self._jtsrdd = jvm.com.cloudera.sparkts.TimeSeriesRDD( \ dt_index._jdt_index, jrdd.rdd()) RDD.__init__(self, rdd._jrdd, rdd.ctx) else: # Construct from a py4j.JavaObject pointing to a TimeSeriesRD...
stream.write(struct.pack('!d', value))
conditional_block
timeseriesrdd.py
univariate series, observations are not distributed. The time dimension is conformed in the sense that a single DateTimeIndex applies to all the univariate series. Each univariate series within the RDD has a String key to identify it. """ def __init__(self, dt_index, rdd, jtsrdd = None, sc = None): ...
def fill(self, method): """ Returns a TimeSeriesRDD with missing values imputed using the given method. Parameters ---------- method : string "nearest" fills in NaNs with the closest non-NaN value, using the closest previous value in the cas...
""" Returns a TimeSeriesRDD where each time series is differenced with the given order. The new RDD will be missing the first n date-times. Parameters ---------- n : int The order of differencing to perform. """ return TimeSeriesRDD(N...
identifier_body
CLQ_search_new.py
'][xmax,0]))) gmag2.append((22.5 - 2.5*np.log10(ndata['SPECTROFLUX'][xmax,1]))) rmag2.append((22.5 - 2.5*np.log10(ndata['SPECTROFLUX'][xmax,2]))) imag2.append((22.5 - 2.5*np.log10(ndata['SPECTROFLUX'][xmax,3]))) zmag2.append((22.5 - 2.5*np.log10(ndata['SPECTROFLUX'][xmax,...
specdir = 'CLQsearch_spectra' linelist = np.genfromtxt('/Users/vzm83/Proposals/linelist_speccy.txt',usecols=(0,1,2),dtype=('|S10',float,'|S5'),names=True) out = open('CLQsearch_deltamgs_sn1700gt6.txt','w')
random_line_split
CLQ_search_new.py
PLATE_2'][xmin]) mjd1.append(ndata['MJD_2'][xmin]) fiber1.append(ndata['FIBERID_2'][xmin]) plate2.append(ndata['PLATE_2'][xmax]) mjd2.append(ndata['MJD_2'][xmax]) fiber2.append(ndata['FIBERID_2'][xmax]) umag1.append((22.5 - 2.5*np.log10(ndata['SP...
plot_spectra
identifier_name
CLQ_search_new.py
#print uname[i],len(xx),xx,data['PLATE_1'][xx[0]],data['MJD_1'][xx[0]],data['FIBERID_1'][xx[0]],data['PLATE_2'][xx[0]],data['MJD_2'][xx[0]],data['FIBERID_2'][xx[0]],data['PLATE_2'][xx[-1]],data['MJD_2'][xx[-1]],data['FIBERID_2'][xx[-1]],data['FIBERMAG'][xx[0],1],data['FIBER2MAG'][xx[-1],1],data['FIBERFLUX']...
redux= '/uufs/chpc.utah.edu/common/home/sdss/ebosswork/eboss/spectro/redux/v5_13_0/spectra/lite' data=fits.open('CrossMatch_DR12Q_spAll_v5_13_0.fits')[1].data uname = np.unique(data['SDSS_NAME']) count = 0 gcount = 0 out=open('Candidate_CLQ_search_DR16.txt','w') name = [] ; ra=[] ; dec=[];zvi=[]...
identifier_body
CLQ_search_new.py
= '{0:04d}-{1:05d}-{2:04d}'.format(data['PLATE_2'][xx[-1]],data['MJD_2'][xx[-1]],data['FIBERID_2'][xx[-1]]) #data1 = fits.open(os.path.join(redux,plate1,'spec-'+pmf1+'.fits'))[1].data gdiff.append((22.5 - 2.5*np.log10(ndata['SPECTROFLUX'][xmin,1])) - (22.5 - 2.5*np.log10(ndata['SPECTROFLUX'][xm...
if not print_cmd: if not ((os.path.isfile(FITS_FILENAME)) | (os.path.isfile(os.path.join(specdir,FITS_FILENAME)))): download_spectra(plates[j],mjds[j],fibers[j],specdir) else : print 'Spectrum already downloaded' if print...
FITS_FILENAME = 'spec-{0:04d}-{1:05d}-{2:04d}.fits'.format(plates[j],mjds[j],fibers[j])
conditional_block
lib.rs
str, depth: usize, ) -> Box<dyn Iterator<Item = String> + 'a> { if depth == 0 { // If we've reached depth 0, we don't go futher. Box::new(std::iter::empty()) } else { // Generate all possible mutations on the current depth Box::new( ...
SymbolTable::from_str("ab").unwrap(); let result = table.mudder_one("a", "b").unwrap(); assert_eq!(result, "ab"); let table = SymbolTable::from_str("0123456789").unwrap(); let result = table.mudder_one("1", "2").unwrap(); assert_eq!(result, "15"); } #[test] fn o
identifier_body
lib.rs
// SymbolTable::mudder() returns a Vec containing `amount` Strings. let result = table.mudder_one("a", "z").unwrap(); // These strings are always lexicographically placed between `start` and `end`. let one_str = result.as_str(); assert!(one_str > "a"); assert!(one_str < "z"); // You can also define your own symbol tab...
// so you cannot pass in an invalid value. use std::num::NonZeroUsize; // You can use the included alphabet table let table = SymbolTable::alphabet();
random_line_split
lib.rs
. ensure! { a != b, MatchingStrings(a.to_string()) } // In any other case, keep the order (a, b) }; // TODO: Check for lexicographical adjacency! //ensure! { !lex_adjacent(a, b), LexAdjacentStrings(a.to_string(), b.to_string()) } // Count the charact...
comp_amount = computed_amount(), b_factor = branching_factor, depth = depth, pool = pool, pool_len = pool.len(), ) } Ok(if amount.get() == 1 { pool.get(pool.len() / 2) .map(|item| vec...
// We still don't have enough items, so bail panic!( "Internal error: Failed to calculate the correct tree depth! This is a bug. Please report it at: https://github.com/Follpvosten/mudders/issues and make sure to include the following information: Symbols in table: {symbols:?} G...
conditional_block
lib.rs
-> Self { Self::new(&('a' as u8..='z' as u8).collect::<Box<[_]>>()).unwrap() } /// Generate `amount` strings that lexicographically sort between `start` and `end`. /// The algorithm will try to make them as evenly-spaced as possible. /// /// When both parameters are empty strings, `amount`...
phabet()
identifier_name
Search.py
at # Output: The nodes that are created and stored in a dictionary or an error flag def getNodes(Filename, start, end): # flags to validate that nodes exist in the given graph foundStart = 0 foundEnd = 0 # validation for opening the file try: inFile = open(Filename, 'r') except IOErro...
alternate = distance[cur[1]] + pair[1] # if the distance is shorter it replaces in the algorithm if alternate < distance[pair[0]]: distance[pair[0]] = alternate previous[pair[0]] = cur[1] # finds if the nodes are in the open queue and...
# list of nodes that are in open that need to be updated openNodes = [] # Adds each of the neighbors of the node and compares their length for pair in sorted(nodeDict[cur[1]]): # distance of current path is saved and compared with distance
random_line_split
Search.py
# Output: The nodes that are created and stored in a dictionary or an error flag def
(Filename, start, end): # flags to validate that nodes exist in the given graph foundStart = 0 foundEnd = 0 # validation for opening the file try: inFile = open(Filename, 'r') except IOError as e: print ("I/O error({0}): {1} \"{2}\"".format(e.errno, e.strerror, Filename),) ...
getNodes
identifier_name
Search.py
at # Output: The nodes that are created and stored in a dictionary or an error flag def getNodes(Filename, start, end): # flags to validate that nodes exist in the given graph foundStart = 0 foundEnd = 0 # validation for opening the file try: inFile = open(Filename, 'r') except IOErro...
# gets the least valued piece from the queue cur = Open.get() # checks if reached the end if cur[1] == end: temp = end finalPath = [temp] # loops backwards through the found path until reaches start while temp != start: ...
Open = PriorityQueue(10000) # creates dictionaries to keep track of distance and previous node of each element distance = {} previous = {} # Initializes each node to have infinity length and no previous for node in nodeDict.keys(): # gives the initial node 0 distance to be chosen first ...
identifier_body
Search.py
# Output: The nodes that are created and stored in a dictionary or an error flag def getNodes(Filename, start, end): # flags to validate that nodes exist in the given graph foundStart = 0 foundEnd = 0 # validation for opening the file try: inFile = open(Filename, 'r') except IOError a...
# repopulates Open with updated values for node in newOpen: Open.put(node) # end while loop # returns blank string if no output found return "" # writePath() writes the final path it takes to search from start to end to a new file # Input: outFile - the filename of the fil...
newOpen.append(node)
conditional_block
session.rs
stream::StreamManager; use util::{self, SpotifyId, FileId, ReadSeek}; use version; use stream; pub enum Bitrate { Bitrate96, Bitrate160, Bitrate320, } pub struct Config { pub application_key: Vec<u8>, pub user_agent: String, pub device_name: String, pub bitrate: Bitrate, } pub struct Se...
pub struct Session(pub Arc<SessionInternal>); impl Session { pub fn new(config: Config, cache: Box<Cache + Send + Sync>) -> Session { let device_id = { let mut h = Sha1::new(); h.input_str(&config.device_name); h.result_str() }; Session(Arc::new(SessionI...
} #[derive(Clone)]
random_line_split
session.rs
stream::StreamManager; use util::{self, SpotifyId, FileId, ReadSeek}; use version; use stream; pub enum Bitrate { Bitrate96, Bitrate160, Bitrate320, } pub struct Config { pub application_key: Vec<u8>, pub user_agent: String, pub device_name: String, pub bitrate: Bitrate, } pub struct Se...
{ config: Config, device_id: String, data: RwLock<SessionData>, cache: Box<Cache + Send + Sync>, mercury: Mutex<MercuryManager>, metadata: Mutex<MetadataManager>, stream: Mutex<StreamManager>, audio_key: Mutex<AudioKeyManager>, rx_connection: Mutex<Option<CipherConnection>>, tx...
SessionInternal
identifier_name
session.rs
rx_connection: Mutex::new(None), tx_connection: Mutex::new(None), cache: cache, mercury: Mutex::new(MercuryManager::new()), metadata: Mutex::new(MetadataManager::new()), stream: Mutex::new(StreamManager::new()), audio_key: Mutex::new(A...
{ self.0.mercury.lock().unwrap().subscribe(self, uri) }
identifier_body
option.rs
StreamFilter = sys::rs2_option_RS2_OPTION_STREAM_FILTER as i32, /// Select a stream format to process. StreamFormatFilter = sys::rs2_option_RS2_OPTION_STREAM_FORMAT_FILTER as i32, /// Select a stream index to process. StreamIndexFilter = sys::rs2_option_RS2_OPTION_STREAM_INDEX_FILTER as i32, /// Wh...
{ continue; }
conditional_block
option.rs
{ /// The requested option is not supported by this sensor. #[error("Option not supported on this sensor.")] OptionNotSupported, /// The requested option is read-only and cannot be set. #[error("Option is read only.")] OptionIsReadOnly, /// The requested option could not be set. Reason is r...
OptionSetError
identifier_name
option.rs
/// - Off /// - 50Hz /// - 60Hz /// - Auto PowerLineFrequency = sys::rs2_option_RS2_OPTION_POWER_LINE_FREQUENCY as i32, /// Get the current Temperature of the ASIC. AsicTemperature = sys::rs2_option_RS2_OPTION_ASIC_TEMPERATURE as i32, /// Enable/disable error handling. ErrorPollingEn...
/// Enable/disable the maximum usable depth sensor range given the amount of ambient light in the scene. EnableMaxUsableRange = sys::rs2_option_RS2_OPTION_ENABLE_MAX_USABLE_RANGE as i32, /// Enable/disable the alternate IR, When enabling alternate IR, the IR image is holding the amplitude of the depth corre...
random_line_split
option.rs
2_option_RS2_OPTION_STREAM_FORMAT_FILTER as i32, /// Select a stream index to process. StreamIndexFilter = sys::rs2_option_RS2_OPTION_STREAM_INDEX_FILTER as i32, /// When supported, this option make the camera to switch the emitter state every frame. /// 0 for disabled, 1 for enabled. EmitterOnOff =...
{ let deprecated_options = vec![ sys::rs2_option_RS2_OPTION_ZERO_ORDER_POINT_X as i32, sys::rs2_option_RS2_OPTION_ZERO_ORDER_POINT_Y as i32, sys::rs2_option_RS2_OPTION_ZERO_ORDER_ENABLED as i32, sys::rs2_option_RS2_OPTION_AMBIENT_LIGHT as i32, sys::rs2...
identifier_body
mixture.rs
mix. pub fn partial_heat_capacity(&self, idx: GasIDX) -> f32 { self.moles .get(idx) .filter(|amt| amt.is_normal()) .map_or(0.0, |amt| amt * with_specific_heats(|heats| heats[idx])) } /// The total mole count of the mixture. Moles. pub fn total_moles(&self) -> f32 { self.moles.iter().sum() } /// Pres...
} /// Gets all of the reactions this mix should do. pub fn all_reactable(&self) -> Vec<ReactionIdentifier> { with_reactions(|reactions| {
random_line_split
mixture.rs
_heat_capacity = self.heat_capacity(); let other_heat_capacity = giver.heat_capacity(); self.maybe_expand(giver.moles.len()); for (a, b) in self.moles.iter_mut().zip(giver.moles.iter()) { *a += b; } let combined_heat_capacity = our_heat_capacity + other_heat_capacity; if combined_heat_capacity > MINIMUM_...
{ if self.temperature > oxidation.temperature() { let amount = amt * (1.0 - oxidation.temperature() / self.temperature) .max(0.0); acc.0 += amount * oxidation.power(); } }
conditional_block
mixture.rs
self, size: usize) { if self.moles.len() < size { self.moles.resize(size, 0.0); } } /// If mix is not immutable, sets the gas at the given `idx` to the given `amt`. pub fn set_moles(&mut self, idx: GasIDX, amt: f32) { if !self.immutable && idx < total_num_gases() && (idx <= self.moles.len() || (amt >...
/// Merges one gas mixture into another. pub fn merge(&mut self, giver: &Self) { if self.immutable { return; } let our_heat_capacity = self.heat_capacity(); let other_heat_capacity = giver.heat_capacity(); self.maybe_expand(giver.moles.len()); for (a, b) in self.moles.iter_mut().zip(giver.moles.iter()...
{ self.heat_capacity() * self.temperature }
identifier_body
mixture.rs
{ self.remove_ratio(amount / self.total_moles()) } /// Copies from a given gas mixture, if we're mutable. pub fn copy_from_mutable(&mut self, sample: &Self) { if self.immutable { return; } self.moles = sample.moles.clone(); self.temperature = sample.temperature; self.cached_heat_capacity .set(samp...
adjust_heat
identifier_name
object.rs
c, types::{ZendClassObject, ZendStr, Zval}, zend::{ce, ClassEntry, ExecutorGlobals, ZendObjectHandlers}, }; /// A PHP object. /// /// This type does not maintain any information about its type, for example, /// classes with have associated Rust structs cannot be accessed through this /// type. [`ZendClassObjec...
(zval: &'a Zval) -> Option<Self> { zval.object() } } impl<'a> FromZvalMut<'a> for &'a mut ZendObject { const TYPE: DataType = DataType::Object(None); fn from_zval_mut(zval: &'a mut Zval) -> Option<Self> { zval.object_mut() } } impl IntoZval for ZBox<ZendObject> { const TYPE: DataT...
from_zval
identifier_name
object.rs
c, types::{ZendClassObject, ZendStr, Zval}, zend::{ce, ClassEntry, ExecutorGlobals, ZendObjectHandlers}, }; /// A PHP object. /// /// This type does not maintain any information about its type, for example, /// classes with have associated Rust structs cannot be accessed through this /// type. [`ZendClassObjec...
.as_ref() } .ok_or(Error::InvalidScope)?; T::from_zval(zv).ok_or_else(|| Error::ZvalConversion(zv.get_type())) } /// Attempts to set a property on the object. /// /// # Parameters /// /// * `name` - The name of the property. /// * `value` - The value to ...
&mut rv, )
random_line_split
object.rs
memory inside Zend arena. Casting `ce` to // `*mut` is valid as the function will not mutate `ce`. unsafe { let ptr = zend_objects_new(ce as *const _ as *mut _); ZBox::from_raw( ptr.as_mut() .expect("Failed to allocate memory for Zend object")...
{ // TODO: become an error let class_name = obj.get_class_name(); panic!( "{}::__toString() must return a string", class_name.expect("unable to determine class name"), ); }
conditional_block
object.rs
c, types::{ZendClassObject, ZendStr, Zval}, zend::{ce, ClassEntry, ExecutorGlobals, ZendObjectHandlers}, }; /// A PHP object. /// /// This type does not maintain any information about its type, for example, /// classes with have associated Rust structs cannot be accessed through this /// type. [`ZendClassObjec...
} impl FromZendObject<'_> for String { fn from_zend_object(obj: &ZendObject) -> Result<Self
{ zv.set_object(self); Ok(()) }
identifier_body
provider.go
pid-<GUID>...", v) return nil, nil } // Check for straight UUID if _, err := validation.IsUUID(v, ""); err != nil { return nil, []error{fmt.Errorf("expected %q to be a valid UUID", k)} } else { debugLog("[DEBUG] %q partner_id is an un-prefixed UUID...", v) return nil, nil } } func azureProvider(supportL...
resources[key] = resource } } // then handle the untyped services for _, service := range SupportedUntypedServices() { debugLog("[DEBUG] Registering Data Sources for %q..", service.Name()) for k, v := range service.SupportedDataSources() { if existing := dataSources[k]; existing != nil { panic(fmt....
{ panic(fmt.Errorf("creating Wrapper for Resource %q: %+v", key, err)) }
conditional_block
provider.go
// Check for straight UUID if _, err := validation.IsUUID(v, ""); err != nil { return nil, []error{fmt.Errorf("expected %q to be a valid UUID", k)} } else { debugLog("[DEBUG] %q partner_id is an un-prefixed UUID...", v) return nil, nil } } func azureProvider(supportLegacyTestSuite bool) *schema.Provider { /...
}
random_line_split
provider.go
() *schema.Provider { return azureProvider(true) } func ValidatePartnerID(i interface{}, k string) ([]string, []error) { // ValidatePartnerID checks if partner_id is any of the following: // * a valid UUID - will add "pid-" prefix to the ID if it is not already present // * a valid UUID prefixed with "pid-" // ...
TestAzureProvider
identifier_name
provider.go
func ValidatePartnerID(i interface{}, k string) ([]string, []error) { // ValidatePartnerID checks if partner_id is any of the following: // * a valid UUID - will add "pid-" prefix to the ID if it is not already present // * a valid UUID prefixed with "pid-" // * a valid UUID prefixed with "pid-" and suffixed w...
{ return azureProvider(true) }
identifier_body
feature_extraction.py
0] == "MOTIF": if lines[i+1].strip() == "": desc = lines[i+2].strip().split() flag = True else: desc = lines[i+1].strip().split() flag = False try: motifLength = int(desc[5]) except: print (desc) i = i+1 continue if flag: myString = "\n".join(map(lambda x...
set_col_names
identifier_name
feature_extraction.py
r in SeqIO.parse(f, "fasta"): my_dict[r.id] = str(r.seq).upper() return my_dict def read_motif(meme_file): revcomp_file = "/tmp/"+str(uuid.uuid4()) os.system("meme-get-motif -rc -all %s > %s"%(meme_file,revcomp_file)) original_motif_label = "++original++" revcomp_motif_label = "--revcomp--" dic...
------ pos, value list """
random_line_split
feature_extraction.py
ForestClassifier from sklearn.model_selection import cross_val_score from sklearn.model_selection import GridSearchCV from sklearn.metrics.scorer import make_scorer from sklearn.model_selection import train_test_split from sklearn.base import TransformerMixin from sklearn.datasets import make_regression from skl...
i = i+1 return myDict def motif_scan(s,m): ## s, m are numpy array ## s.shape = L*4 ## m.shape = 4*W L = s.shape[0] W = m.shape[1] score_list = [] for i in range(L-W): sub = np.matmul(s[i:i+W,:],m) # if i < 3: # print ("DNA seq",s[i:i+W,:]) # print ("motif",m) # print ("mapping...
myString = "\n".join(map(lambda x:"\t".join(x.strip().split()),lines[i+2:i+2+motifLength])).replace(" "," ") df = pd.read_csv(StringIO(myString), sep="\t",header=None) df.columns=['A','C','G','T'] myDict[myList[1]+label] = df i = i+2+motifLength if df.shape[0] != motifLength or df.shape[1] !=...
conditional_block
feature_extraction.py
Classifier from sklearn.model_selection import cross_val_score from sklearn.model_selection import GridSearchCV from sklearn.metrics.scorer import make_scorer from sklearn.model_selection import train_test_split from sklearn.base import TransformerMixin from sklearn.datasets import make_regression from sklearn.p...
## Define parameters # high_hbf = 50 high_hbf = 0 low_hbf = 0 input = "Editable_A_scores.combined.scores.csv" flank = 100 refgenome="/home/yli11/Data/Human/hg19/fasta/hg19.fa" bw_file="/home/yli11/Projects/Li_gRNA/footprint/H1_H2_GM12878_Tn5_bw/Hudep2.bw" meme_file = "selected_motifs.meme" top_n=5 # numb...
df = pd.DataFrame(roi) df[1] = df[1]-flank df[2] = df[2]+flank df.to_csv("tmp.bed",sep="\t",header=False,index=False) os.system("bedtools getfasta -fi %s -fo tmp.fa -bed tmp.bed -s -name"%(genome_fa)) seq = read_fasta("tmp.fa") os.system("rm tmp.fa tmp.bed") return seq
identifier_body
public_key.rs
pub struct SshPublicKey { pub inner_key: SshBasePublicKey, pub comment: String, } impl SshPublicKey { pub fn to_string(&self) -> Result<String, SshPublicKeyError> { let mut buffer = Vec::with_capacity(1024); self.encode(&mut buffer)?; Ok(String::from_utf8(buffer)?) } } impl Fro...
random_line_split
public_key.rs
7, 111, 140, 200, 79, 204, 41, 199, 53, 47, 139, 209, 230, 243, 123, 7, 30, 114, 198, 57, 174, 216, 48, 251, 160, 97, 23, 7, 89, 26, 17, 65, 126, 39, 245, 255, 171, 61, 171, 188, 187, 251, 193, 158, 222, 21, 8, 18, 162, 221, 136, 192, 195, 207, 23, 58, 235, 50...
decode_ssh_rsa_2048_public_key
identifier_name
public_key.rs
, 229, 127, 166, 90, 128, 1, 154, 46, 143, 63, 240, 0, 176, 227, 18, 152, 82, 196, 5, 28, 1, 31, 173, 226, 45, 133, 223, 211, 218, 239, 83, 18, 115, 126, 200, 244, 189, 244, 207, 125, 109, 113, 182, 181, 95, 186, 29, 238, 28, 235, 84, 201, 125, 138, 234, 228, ...
{ let public_key = SshPublicKey::from_str(key_str).unwrap(); let ssh_public_key_after = public_key.to_string().unwrap(); assert_eq!(key_str, ssh_public_key_after.as_str()); }
identifier_body
CallCenterHome.js
/callCenterEdit/CallCenterEdit"; const intlPrefix = 'organization.callCenter'; const { Sidebar } = Modal; @inject('AppState') @observer class CallCenterHome extends Component{ state = this.getInitState();
() { return{ dataSource: [], pagination: { current: 1, pageSize: 25, total: '', pageSizeOptions: ['25', '50', '100', '200'], }, visible: false, submitting: false, edit: false, isLoading: true, Id: '', nickname: '', sort: 'is...
getInitState
identifier_name
CallCenterHome.js
/callCenterEdit/CallCenterEdit"; const intlPrefix = 'organization.callCenter'; const { Sidebar } = Modal; @inject('AppState') @observer class CallCenterHome extends Component{ state = this.getInitState(); getInitState() { return{ dataSource: [], pagination: { current: 1, pageSize:...
} this.queryInfo(pagination, sorter.join(','), filters, params); } /** * 呼叫中心标题 * @returns {*} */ renderSideTitle() { if (this.state.edit) { return CallCenterStore.languages[`${intlPrefix}.editCallCenter`]; } else { return CallCenterStore.languages[`${intlPrefix}.createCallCe...
random_line_split
CallCenterHome.js
allCenterEdit/CallCenterEdit"; const intlPrefix = 'organization.callCenter'; const { Sidebar } = Modal; @inject('AppState') @observer class CallCenterHome extends Component{ state = this.getInitState(); getInitState() { return{ dataSource: [], pagination: { current: 1, pageSize: 2...
} handleAble = (record) => { const body = { id: record.id, enabled: !record.enabled } CallCenterStore.handleEdit(body).then((data) => { if (data.success) { this.queryInfo(); } }) } render() { const { pagination, visible, dataSource, edit, submitting } =...
} else { return `${values}`; }
conditional_block
CallCenterHome.js
allCenterEdit/CallCenterEdit"; const intlPrefix = 'organization.callCenter'; const { Sidebar } = Modal; @inject('AppState') @observer class CallCenterHome extends Component{ state = this.getInitState(); getInitState()
componentWillMount() { this.fetch(this.props); } componentDidMount() { this.loadLanguage(); this.queryInfo(); } fetch() { CallCenterStore.getIsEnabled(); } loadLanguage=() => { const { AppState } = this.props; CallCenterStore.queryLanguage(0, AppState.currentLanguage); } ...
{ return{ dataSource: [], pagination: { current: 1, pageSize: 25, total: '', pageSizeOptions: ['25', '50', '100', '200'], }, visible: false, submitting: false, edit: false, isLoading: true, Id: '', nickname: '', sort: 'isEna...
identifier_body