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
ParseEssential.py
.miRNA_=False self.lcRNA_=False self.encode_=False self.viability_=False #functional and viability info self.ppi_=False self.regflag=False self.seqflag=False self.OOGE_added=False ##Collections from excel spreadsheets are put into data-fram...
##Viability information from impc with open(os.path.join(self.prefix,"Viability.csv")) as vb: for line in vb: data=line.strip().split(",") if data[-1] not in ['Viable','Subviable','Lethal']: continue ...
try: ##We have to convert from uid to mgi (our chosen ID) first mtch=re.search("lethal|fatal|dead|viable|essential",data[-1]) #print mtch.group(0),data[-1].split() ant=mtch.group(0) ...
conditional_block
ParseEssential.py
and not self.reannotate: print "Gene info exists, retrieving it..." self.genes=load(open(filename,'rb')) if len(self.genes) < len(self.genelist): print "We need to add more" else: self.link_ids_=True return ...
Gene
identifier_name
ParseEssential.py
self.viability_=False #functional and viability info self.ppi_=False self.regflag=False self.seqflag=False self.OOGE_added=False ##Collections from excel spreadsheets are put into data-frames ##Will be reconciled/normalized later self.lncRNA...
self.miRNA_=False self.lcRNA_=False self.encode_=False
random_line_split
ParseEssential.py
.miRNA_=False self.lcRNA_=False self.encode_=False self.viability_=False #functional and viability info self.ppi_=False self.regflag=False self.seqflag=False self.OOGE_added=False ##Collections from excel spreadsheets are put into data-fram...
with open(os.path.join(self.prefix,"Homo_sapiens_OOGE.csv")) as deg: ##no header here for line in deg: data=line.strip().split(",") #print data symbol,gclass=data[1],data[-2] symbol=symbol.capitalize() ...
line=split.strip("\"") cleanline=line.split(",") classes=list(set(cleanline)) if len(set(classes)) == 1: if classes[0] == "NE": return 0 elif classes[0] == "E": return 1 else: ...
identifier_body
main.go
`json:"emailName"` EmailAddress string `json:"emailAddress"` } type report struct { TransportID int ActionFlag string JobNo string Customer string Department string JobDescription string TransportDate string DateDiff int ServiceType string } type data s...
err := rows.Scan(&r.TransportID, &r.ActionFlag, &r.JobNo, &r.Customer, &r.Department, &r.JobDescription, &r.TransportDate, &r.ServiceType) if err != nil { log.Fatal(err) } if r.ActionFlag == "C" { r.ActionFlag = "Collect" } else if r.ActionFlag == "D" { r.ActionFlag = "Deliver" } else {...
{ var output data sql1 := `SELECT transport_id, action_flag, job_no, customer, department, job_description, COALESCE(CONVERT(NVARCHAR(11), transport_date, 106), '-'), service_type FROM transport WHERE is_active = 'Y' ORDER BY transport_date DESC` rows, err := db.Query(sql1) if err != nil { ...
identifier_body
main.go
`json:"emailName"` EmailAddress string `json:"emailAddress"` } type report struct { TransportID int ActionFlag string JobNo string Customer string Department string JobDescription string TransportDate string DateDiff int ServiceType string } type data s...
} func createGetJobDetails(w http.ResponseWriter, r *http.Request, p httprouter.Params) { JobNo := p.ByName("jobno") if len(JobNo) > 10 { fmt.Println("Job number greater than 10 characters") } else if len(JobNo) < 5 { fmt.Println("Job number less than 5 characters") } else { var output job...
{ log.Fatal(err) }
conditional_block
main.go
`json:"emailName"` EmailAddress string `json:"emailAddress"` } type report struct { TransportID int ActionFlag string JobNo string Customer string Department string JobDescription string TransportDate string DateDiff int ServiceType string } type data s...
sql2 := `UPDATE transport SET is_active = 'N' WHERE transport_id = ?` _, err := db.Exec(sql2, TransportID) if err != nil { log.Fatal(err) } http.Redirect(w, r, "/transport/complete", 303) } func editJob(w http.ResponseWriter, r *http.Request, p httprouter.Params) { TransportID := p.B...
func completeJob(w http.ResponseWriter, r *http.Request, p httprouter.Params) { TransportID := p.ByName("transportid")
random_line_split
main.go
`json:"emailName"` EmailAddress string `json:"emailAddress"` } type report struct { TransportID int ActionFlag string JobNo string Customer string Department string JobDescription string TransportDate string DateDiff int ServiceType string } type data s...
(w http.ResponseWriter, r *http.Request, _ httprouter.Params) { var output validation t, _ := template.ParseFiles("assets/templates/create.tpl") output.ActionFlag = "C" if r.Method == "POST" { output.ActionFlag = r.FormValue("action_flag") output.Department = r.FormValue("department") output....
transportCreate
identifier_name
mod.rs
redundancy even if all validators have //! roughly the same entries in their queues. By selecting a random fraction of the first _B_ //! entries, any two nodes will likely make almost disjoint contributions instead of proposing //! the same transaction multiple times. use std::marker::PhantomData; use std::{cmp, iter...
<R>(self, rng: R) -> QueueingHoneyBadgerWithStep<T, N, Q> where R: 'static + Rng + Send + Sync, { self.build_with_transactions(None, rng) .expect("building without transactions cannot fail") } /// Returns a new Queueing Honey Badger instance that starts with the given transa...
build
identifier_name
mod.rs
std::{cmp, iter}; use crypto::PublicKey; use derivative::Derivative; use failure::Fail; use rand::{Rand, Rng}; use serde::{de::DeserializeOwned, Serialize}; use dynamic_honey_badger::{self, Batch as DhbBatch, DynamicHoneyBadger, Message}; use transaction_queue::TransactionQueue; use {util, Contribution, DistAlgorith...
{ self.apply(|dyn_hb| dyn_hb.handle_message(sender_id, message)) }
identifier_body
mod.rs
redundancy even if all validators have //! roughly the same entries in their queues. By selecting a random fraction of the first _B_ //! entries, any two nodes will likely make almost disjoint contributions instead of proposing //! the same transaction multiple times. use std::marker::PhantomData; use std::{cmp, iter...
self.dyn_hb.our_id() } } impl<T, N, Q> QueueingHoneyBadger<T, N, Q> where T: Contribution + Serialize + DeserializeOwned + Clone, N: NodeIdT + Serialize + DeserializeOwned + Rand, Q: TransactionQueue<T>, { /// Returns a new `QueueingHoneyBadgerBuilder` configured to use the node IDs and cry...
fn our_id(&self) -> &N {
random_line_split
install_plans.go
.PkgType) plan.Resource { b := plan.NewBuilder() if criSpec.Kind != "docker" { log.Fatalf("Unknown CRI - %s", criSpec.Kind) } IsDockerOnCentOS := false // Docker runtime switch pkgType { case resource.PkgTypeRHEL: b.AddResource("install:container-selinux", &resource.Run{ Script: object.String("...
(pkgType resource.PkgType, f *eksd.EKSD) (func(string, string) plan.Resource, error) { if f != nil { log.Debugf("Using flavor %+v", f) return func(binName, version string) plan.Resource { // TODO (Mark) logic for the architecture binURL, sha256, err := f.KubeBinURL(binName) if err != nil { log.Fatalf(...
BinInstaller
identifier_name
install_plans.go
// BuildCRIPlan creates a plan for installing a CRI. Currently, Docker is the only supported CRI func BuildCRIPlan(ctx context.Context, criSpec *existinginfrav1.ContainerRuntime, cfg *envcfg.EnvSpecificConfig, pkgType resource.PkgType) plan.Resource { b := plan.NewBuilder() if criSpec.Kind != "docker" { log.Fat...
{ b := plan.NewBuilder() b.AddResource( "install-cni:apply-manifests", &resource.KubectlApply{Manifest: manifests[0], Filename: object.String(cni + ".yaml")}, ) if len(manifests) == 2 { b.AddResource( "install-cni:apply-manifests-ds", &resource.KubectlApply{Manifest: manifests[1], Filename: object.Stri...
identifier_body
install_plans.go
.PkgType) plan.Resource { b := plan.NewBuilder() if criSpec.Kind != "docker"
IsDockerOnCentOS := false // Docker runtime switch pkgType { case resource.PkgTypeRHEL: b.AddResource("install:container-selinux", &resource.Run{ Script: object.String("yum install -y http://mirror.centos.org/centos/7/extras/x86_64/Packages/container-selinux-2.107-1.el7_6.noarch.rpm || true"), U...
{ log.Fatalf("Unknown CRI - %s", criSpec.Kind) }
conditional_block
install_plans.go
resource.PkgType) plan.Resource { b := plan.NewBuilder() if criSpec.Kind != "docker" { log.Fatalf("Unknown CRI - %s", criSpec.Kind) } IsDockerOnCentOS := false
&resource.Run{ Script: object.String("yum install -y http://mirror.centos.org/centos/7/extras/x86_64/Packages/container-selinux-2.107-1.el7_6.noarch.rpm || true"), UndoScript: object.String("yum remove -y container-selinux || true")}) b.AddResource("install:docker", &resource.RPM{Name: criSpec.Pack...
// Docker runtime switch pkgType { case resource.PkgTypeRHEL: b.AddResource("install:container-selinux",
random_line_split
outputs.js
}); } } // Output strings for now require a field for every language, so this is a // helper function to generate one for literal numbers. const numberToOutputString = (n) => { const str = n.toString(); return { en: str, de: str, fr: str, ja: str, cn: str, ko: str, }; }; // Genera...
{ this.obj = obj; if ('toJSON' in obj) throw new Error('Cannot have toJSON property.'); return new Proxy(this, { set(target, property, value) { throw new Error('Cannot set readonly object.'); }, get(target, name) { if (name === 'toJSON') return JSON.strin...
identifier_body
outputs.js
getLeftAndWest: { en: '<= Get Left/West', de: '<= Nach Links/Westen', fr: '<= Allez à Gauche/Ouest', ja: '<= 左/西へ', cn: '<= 去左/西边', ko: '<= 왼쪽으로', }, getRightAndEast: { en: 'Get Right/East =>', de: 'Nach Rechts/Osten =>', fr: 'Allez à Droite/Est =>', ja: '右/東へ =>', cn: ...
ko: '서쪽', }, northwest: { en: 'Northwest', de: 'Nordwesten',
random_line_split
outputs.js
{ constructor(obj) { this.obj = obj; if ('toJSON' in obj) throw new Error('Cannot have toJSON property.'); return new Proxy(this, { set(target, property, value) { throw new Error('Cannot set readonly object.'); }, get(target, name) { if (name === 'toJSON') ...
ThrowOnInvalidProxy
identifier_name
lib.rs
the contained value. pub fn unwrap(self) -> T { assert_eq!(self.internal_error, None); self.value } } } // ============== // === Parser === // ============== /// Enso parser. See the module documentation to learn more about how it works. #[allow(missing_docs)] #[derive(D...
parse_argument_definition
identifier_name
lib.rs
//! # Splitting the token stream by the macro segments. //! The input token stream is being iterated and is being split based on the segments of the //! registered macros. For example, for the input `if a b then c d else e f`, the token stream will //! be split into three segments, `a b`, `c d`, and `e f`, which will b...
//! in case these segments were found. For example, let's consider two macros: `if ... then ...`, //! and `if ... then ... else ...`. In such a case, the macro registry will contain only one entry, //! "if", and two sets of possible resolution paths: ["then"], and ["then", "else"], each associated //! with the correspo...
random_line_split
lib.rs
use syntax::tree::*; match &*tree.variant { Variant::Ident(_) => true, Variant::OprApp(OprApp { lhs: Some(lhs), opr: Ok(opr), rhs: Some(rhs) }) if matches!(&*rhs.variant, Variant::Ident(_)) && opr.properties.is_dot() => is_qualified_name(lhs), _ => false, } } ...
{ str.push_str("* "); }
conditional_block
lib.rs
#![allow(clippy::let_and_return)] // === Non-Standard Linter Configuration === #![allow(clippy::option_map_unit_fn)] #![allow(clippy::precedence)] #![allow(dead_code)] #![deny(unconditional_recursion)] #![warn(missing_copy_implementations)] #![warn(missing_debug_implementations)] #![warn(missing_docs)] #![warn(trivial_...
{ let mut args = vec![]; let first = unroll_arguments(tree, &mut args); args.push(parse_argument_definition(first)); args.reverse(); args }
identifier_body
scan.py
init__(self, cfg, bbox_proposal_model=None): super(SCAN, self).__init__() if cfg.MODEL.RPN_ONLY: raise ValueError("SCAN model can't operate in RPN_ONLY regime, " "since it requires an object detection head") if bbox_proposal_model: self.img_d...
for _ in range(world_size)] dist.all_gather(batch_size_full, batch_size) # cutting all data to min batch size across all GPUs min_bs = min([bs.item() for bs in batch_size_full]) if min_bs < batch_size: ...
# batch size across all processes batch_size = torch.tensor(img_emb.shape[0], device=self.device) batch_size_full = [torch.zeros_like(batch_size)
random_line_split
scan.py
__(self, cfg, bbox_proposal_model=None): super(SCAN, self).__init__() if cfg.MODEL.RPN_ONLY: raise ValueError("SCAN model can't operate in RPN_ONLY regime, " "since it requires an object detection head") if bbox_proposal_model: self.img_dim =...
predictions = [pred.get_field('box_features') for pred in predictions] self.bbox_proposal_model.force_boxes = force_boxes_model self.bbox_proposal_model.roi_heads.box.force_boxes = force_boxes_box self.bbox_proposal_model.roi_heads.box.post_processor.force_boxes = force...
backbone_training = self.bbox_proposal_model.backbone.training self.bbox_proposal_model.eval() if self.training: self.bbox_proposal_model.backbone.train() self.bbox_proposal_model.roi_heads.box.feature_extractor.train() predictions ...
conditional_block
scan.py
class SCAN(nn.Module): def __init__(self, cfg, bbox_proposal_model=None): super(SCAN, self).__init__() if cfg.MODEL.RPN_ONLY: raise ValueError("SCAN model can't operate in RPN_ONLY regime, " "since it requires an object detection head") if bbox_pr...
cast_img_emb = self.img_emb.to(*args, **kwargs) cast_cap_emb = self.cap_emb.to(*args, **kwargs) cast_img_length = self.img_length.to(*args, **kwargs) cast_cap_length = self.cap_length.to(*args, **kwargs) return SCANEmbedding(cast_img_emb, cast_img_length, cas...
identifier_body
scan.py
Returns: contrastive_loss in the training regime and tuple of image and caption embeddings in the test/evaluation regime. """ images = [image.to(self.device) for image in images] if self.use_precomputed_boxes: targets_transposed = list(zip(*targets)) ...
unused_params
identifier_name
youtube_tops_en_US_.py
def parse_page(self, response): # print response.url body_instance = response.body_as_unicode() tree = lxml.html.fromstring(body_instance) raw = {} # title_selector = '//*[@id="page-container"]/div[2]/div/div/div[1]/div/div/div/div[@class="ProfileHeaderCard"]/h1[@class="Pro...
channel_url = self.channel_list.pop(0) yield Request( channel_url, headers=self.hd, dont_filter=True, callback=self.parse_page )
identifier_body
youtube_tops_en_US_.py
= '//*[@id="watch7-main-container"]/div[@id="watch7-main"]/div[@id="watch7-content"]/span[@itemprop="thumbnail"]/link/@href' duration_raw_selector = '//*[@id="watch7-main-container"]/div[@id="watch7-main"]/div[@id="watch7-content"]/meta[@itemprop="duration"]/@content' video_id_selector = '//*[@id="watc...
if bracket_count == 0: break
random_line_split
youtube_tops_en_US_.py
'/html/body/div[2]/div/div[1]/table/tbody/tr[3]/td[3]/button/a/@href' raw = dict() raw.update(response.meta) raw['video'] = tree.xpath(video_selector)[0] self.logger.warning("parse_video_from_other!!") for request in self.parse_raw(raw): yield request def parse...
return hashlib.
identifier_name
youtube_tops_en_US_.py
"]/div/a/text()' thumbnails_selector = '//*[@id="watch7-main-container"]/div[@id="watch7-main"]/div[@id="watch7-content"]/span[@itemprop="thumbnail"]/link/@href' duration_raw_selector = '//*[@id="watch7-main-container"]/div[@id="watch7-main"]/div[@id="watch7-content"]/meta[@itemprop="duration"]/@content...
video(self, response): def _parse_stream_map(text): videoinfo = { "itag": [], "url": [], "quality": [], "fallback_host": [], "s": [], "type": [] } videos = text.split(",") ...
def parse_
conditional_block
generate_go_schema.go
= (props[s[i]]).(map[string]interface{}) } else { schema, found = (schema[s[i]]).(map[string]interface{}) } if !found { fmt.Printf("schema[s[i]] called %s looks like: %+v\n", objName, schema[s[i]]) fmt.Printf("** ERR ** getObject illegal selector %s at ...
aMap, isMap := obj.(map[string]interface{})
random_line_split
generate_go_schema.go
.(string))) } else { oArr[k] = replaceReferences(schema, v) } } else { //fmt.Printf("** WARN ** array member not a map object [%d:%+v]\n", k, v) } } return oArr c...
generateGoSampleFile
identifier_name
generate_go_schema.go
// retrieves a subschema object via the reference path; handles root node references and // references starting after definitions; does not handle external file references yet func getObject (schema map[string]interface{}, objName string) (map[string]interface{}) { // return a copy of the selected object ...
{ syntax, ok := err.(*json.SyntaxError) if !ok { fmt.Println("*********** ERR trying to get syntax error location **************\n", err) return } start, end := strings.LastIndex(js[:syntax.Offset], "\n")+1, len(js) if idx := strings.Index(js[start:], "\n"); idx >= 0 { end = start + idx } ...
identifier_body
generate_go_schema.go
start], "\n"), int(syntax.Offset) - start -1 fmt.Printf("Error in line %d: %s \n", off[line]+1, err) fmt.Printf("%s\n%s^\n\n", js[start:end], strings.Repeat(" ", pos)) } // retrieves a subschema object via the reference path; handles root node references and // references starting after definitions; does n...
// if nothing else ... return "carpe noctem" case "null" : return nil case "boolean" : return true case "array" : var items, found = o["items"].(map[string]interface{}) if (!found) { fmt.Printf("**...
{ return desc }
conditional_block
assistant.py
secode(cmds[1:]) else: print("I don't know that command... Yet? Teach me machine learning so I can learn it!") def dictionnary(): """ Sets the chosen file as a dictionnary, allowing word search """ try: file = open(file_name,"r") ex...
'-.-.'),("D",'
conditional_block
assistant.py
achu(): #Does it really need an explanation? print("█▀▀▄░░░░░░░░░░░▄▀▀█") print("░█░░░▀▄░▄▄▄▄▄░▄▀░░░█") print('░░▀▄░░░▀░░░░░▀░░░▄▀') print('░░░░▌░▄▄░░░▄▄░▐▀▀') print('░░░▐░░█▄░░░▄█░░▌▄▄▀▀▀▀█ ')#Pikachu print('░░░▌▄▄▀▀░▄░▀▀▄▄▐░░░░░░█') print('▄▀▀▐▀▀░▄▄▄▄▄░▀▀▌▄▄▄░░░█') print('█░░░▀▄░█░░░█░...
,'---...'),("/",'-..-.'),("-",'-....-'),("=",'-...-'),("""'""",'.----.'),("()",'-.--.-'),("_",'..--.-')] morse_code += [("!",'-.-.--'),("&",'.-...'),('''"''','.-..-.')] sentence = "" translation = "" for word in stripped_sentence: for letter in word: translated_letter = conversion(le...
identifier_body
assistant.py
avg(cmds[1:]) elif cmds[0] == "avg" and len(cmds) == 1: print("""Argument needed! Expected syntax: Numbers separated by spaces""") elif cmds[0] == "help" and len(cmds) == 1: help() elif cmds[0] == "product" and len(cmds) == 1: print("""Argument needed! Expected syntax: Numbers se...
def list_every_word(file_name): #considers file_name is valid """ return a sorted list of all the words contained in a file """ file = open(file_name,"r") words = [] lines = file.readlines() for line in lines: line = line.strip() line = line.split(" ") for word in li...
random_line_split
assistant.py
avg(cmds[1:]) elif cmds[0] == "avg" and len(cmds) == 1: print("""Argument needed! Expected syntax: Numbers separated by spaces""") elif cmds[0] == "help" and len(cmds) == 1: help() elif cmds[0] == "product" and len(cmds) == 1: print("""Argument needed! Expected syntax: Numbers se...
): #Counts characters counter = 0 file = open(file_name,"r") for line in file: for x in line.strip(): counter +=1 file.close() return counter def pikachu(): #Does it really need an explanation? print("█▀▀▄░░░░░░░░░░░▄▀▀█") print("░█░░░▀▄░▄▄▄▄▄░▄▀░░░█") print('░░...
har_count(
identifier_name
main.py
, help_command=None, case_insensitive=True ) THEME_COLOR = discord.Colour.blue() # Add Cogs bot.add_cog(Miscellaneous(bot, THEME_COLOR))
bot.add_cog(ServerSettings(bot, THEME_COLOR)) bot.add_cog(Moderator(bot, THEME_COLOR)) bot.add_cog(AutoMod(bot, THEME_COLOR)) bot.add_cog(Fun(bot, THEME_COLOR)) bot.add_cog(Google(bot, THEME_COLOR)) #bot.add_cog(Hangman(bot, THEME_COLOR)) #bot.add_cog(RockPaperScissors(bot, THEME_COLOR)) previous_msg_sender_id = None ...
random_line_split
main.py
, help_command=None, case_insensitive=True ) THEME_COLOR = discord.Colour.blue() # Add Cogs bot.add_cog(Miscellaneous(bot, THEME_COLOR)) bot.add_cog(ServerSettings(bot, THEME_COLOR)) bot.add_cog(Moderator(bot, THEME_COLOR)) bot.add_cog(AutoMod(bot, THEME_COLOR)) bot.add_cog(Fun(bot, THEME_COLOR)) bot.add_cog(...
# Welcome Message if data["welcome_msg"] is None: server_wlcm_msg = f"Welcome, {member.mention}, to the Official **{guild.name}** Server" else: server_wlcm_msg = data["welcome_msg"] server_wlcm_msg = server_wlcm_msg.replace( "[mention]", f"{member.mention}") # Welc...
await member.add_roles(join_role)
conditional_block
main.py
ents, help_command=None, case_insensitive=True ) THEME_COLOR = discord.Colour.blue() # Add Cogs bot.add_cog(Miscellaneous(bot, THEME_COLOR)) bot.add_cog(ServerSettings(bot, THEME_COLOR)) bot.add_cog(Moderator(bot, THEME_COLOR)) bot.add_cog(AutoMod(bot, THEME_COLOR)) bot.add_cog(Fun(bot, THEME_COLOR)) bot.add_...
elif type(error) is discord.ext.commands.errors.BadUnionArgument: pass elif type(error) is discord.ext.commands.errors.BotMissingPermissions: pass elif type(error) is discord.errors.Forbidden: error = "I don't have permission to do that!" else: print(f"Error {type(error)}...
try: error = error.original except Exception: pass if type(error) is discord.ext.commands.errors.CommandNotFound: return elif type(error) is discord.ext.commands.errors.BadArgument: pass elif type(error) is discord.ext.commands.errors.MissingRequiredArgument: pass...
identifier_body
main.py
, help_command=None, case_insensitive=True ) THEME_COLOR = discord.Colour.blue() # Add Cogs bot.add_cog(Miscellaneous(bot, THEME_COLOR)) bot.add_cog(ServerSettings(bot, THEME_COLOR)) bot.add_cog(Moderator(bot, THEME_COLOR)) bot.add_cog(AutoMod(bot, THEME_COLOR)) bot.add_cog(Fun(bot, THEME_COLOR)) bot.add_cog(...
(member): guild: discord.Guild = member.guild channels = guild.channels if str(guild.id) not in Data.server_data: Data.server_data[str(guild.id)] = Data.create_new_data() data = Data.server_data[str(guild.id)] print(f"{member} has joined {guild} server...") join_role = guild.get_role(...
on_member_join
identifier_name
lib.rs
upto the /// client to decide what should be cloned/copied and what should be shared. For example, /// counters are always per thread and cant be shared, a new set of counters need to be /// made per thread fn clone(&self, _counters: &mut Counters, _log: Arc<Logger>) -> Box<dyn Gclient<T>>; /// Thi...
/// Queue one packet to another node pub fn push(&mut self, node: usize, pkt: BoxPkt) -> bool { let node = self.nodes[node]; if self.vectors[node].capacity() >= 1 { self.vectors[node].push_back(pkt); if node <= self.node { self.work = true; ...
{ self.vectors[self.node].pop_front() }
identifier_body
lib.rs
upto the /// client to decide what should be cloned/copied and what should be shared. For example, /// counters are always per thread and cant be shared, a new set of counters need to be /// made per thread fn clone(&self, _counters: &mut Counters, _log: Arc<Logger>) -> Box<dyn Gclient<T>>; /// Thi...
else { self.work = true; self.wakeup = wakeup; } } } /// The parameters each feature/client node needs to specify if it wants to be added /// to the graph pub struct GnodeInit { /// A unique name for the node pub name: String, /// Names of all the nodes this node will h...
{ if wakeup < self.wakeup { self.wakeup = wakeup; } }
conditional_block
lib.rs
upto the /// client to decide what should be cloned/copied and what should be shared. For example, /// counters are always per thread and cant be shared, a new set of counters need to be /// made per thread fn clone(&self, _counters: &mut Counters, _log: Arc<Logger>) -> Box<dyn Gclient<T>>; /// Thi...
<T> { // The thread this graph belongs to thread: usize, // The graph nodes nodes: Vec<Gnode<T>>, // Graph node performance info perf: Vec<Perf>, // A per node packet queue, to hold packets from other nodes to this node vectors: Vec<VecDeque<BoxPkt>>, // Generic enq/deq/drop counters...
Graph
identifier_name
lib.rs
upto the /// client to decide what should be cloned/copied and what should be shared. For example, /// counters are always per thread and cant be shared, a new set of counters need to be /// made per thread fn clone(&self, _counters: &mut Counters, _log: Arc<Logger>) -> Box<dyn Gclient<T>>; /// Thi...
next_nodes: Vec::new(), } } fn clone(&self, counters: &mut Counters, log: Arc<Logger>) -> Self { Gnode { client: self.client.clone(counters, log), name: self.name.clone(), next_names: self.next_names.clone(), next_nodes: self.next_node...
random_line_split
mysql_connector.go
:= db.D().WithSchema("") dialect := db.Dialect() prevDB, err := dbFromInformationSchema(db) if err != nil { return err } exec := func(expr builder.SqlExpr) error { if expr == nil || expr.IsNil() { return nil } if output != nil { _, _ = io.WriteString(output, builder.ResolveExpr(expr).Query()) ...
} for _, name := range d.Tables.TableNames() { table := d.Tables.Table(name) prevTable := prevDB.Table(name) if prevTable == nil { for _, expr := range dialect.CreateTableIsNotExists(table) { if err := exec(expr); err != nil { return err } } continue } exprList := table.Diff(prevTa...
{ return err }
conditional_block
mysql_connector.go
:= db.D().WithSchema("") dialect := db.Dialect() prevDB, err := dbFromInformationSchema(db) if err != nil { return err } exec := func(expr builder.SqlExpr) error { if expr == nil || expr.IsNil() { return nil } if output != nil { _, _ = io.WriteString(output, builder.ResolveExpr(expr).Query()) ...
func (c MysqlConnector) IsErrorConflict(err error) bool { if mysqlErr, ok := sqlx.UnwrapAll(err).(*mysql.MySQLError); ok && mysqlErr.Number == 1062 { return true } return false } func quoteString(name string) string { if len(name) < 2 || (name[0] == '`' && name[len(name)-1] == '`') { return name } retur...
{ if mysqlErr, ok := sqlx.UnwrapAll(err).(*mysql.MySQLError); ok && mysqlErr.Number == 1049 { return true } return false }
identifier_body
mysql_connector.go
:= db.D().WithSchema("") dialect := db.Dialect() prevDB, err := dbFromInformationSchema(db) if err != nil { return err } exec := func(expr builder.SqlExpr) error { if expr == nil || expr.IsNil() { return nil } if output != nil { _, _ = io.WriteString(output, builder.ResolveExpr(expr).Query()) ...
for _, expr := range dialect.CreateTableIsNotExists(table) { if err := exec(expr); err != nil { return err } } continue } exprList := table.Diff(prevTable, dialect) for _, expr := range exprList { if err := exec(expr); err != nil { return err } } } return nil } func (c *Mys...
random_line_split
mysql_connector.go
:= db.D().WithSchema("") dialect := db.Dialect() prevDB, err := dbFromInformationSchema(db) if err != nil { return err } exec := func(expr builder.SqlExpr) error { if expr == nil || expr.IsNil() { return nil } if output != nil { _, _ = io.WriteString(output, builder.ResolveExpr(expr).Query()) ...
() driver.Driver { return (&MySqlLoggingDriver{}).Driver() } func (MysqlConnector) DriverName() string { return "mysql" } func (MysqlConnector) PrimaryKeyName() string { return "primary" } func (c MysqlConnector) IsErrorUnknownDatabase(err error) bool { if mysqlErr, ok := sqlx.UnwrapAll(err).(*mysql.MySQLError);...
Driver
identifier_name
model_evaluation.py
(model_list, X, y, kf): ''' Takes a list of models (at same scale) and performs KFolds cross-validation on each Inputs: * list of models to be evaluated * X, y training data * KFolds parameters Returns: * Scoring metrics for each CV Round Metr...
multi_model_eval
identifier_name
model_evaluation.py
Folds cross-validation on each Inputs: * list of models to be evaluated * X, y training data * KFolds parameters Returns: * Scoring metrics for each CV Round Metrics: Accuracy, Precision, Recall, F1, ROC AUC ''' for model in mode...
Inputs: * Classification Model * X, y training data * KFold parameters * Model Alias (for plot) ''' # sets up the figure plt.figure(figsize=(6, 6), dpi=100) # sets up the X, y for KFolds X_kf, y_kf = np.array(X), np.array(y) # to return mean an...
Plots ROC Curve with AUC score for each fold in KFold cross-validation for a provided model.
random_line_split
model_evaluation.py
olds cross-validation on each Inputs: * list of models to be evaluated * X, y training data * KFolds parameters Returns: * Scoring metrics for each CV Round Metrics: Accuracy, Precision, Recall, F1, ROC AUC ''' for model in model...
for train_ind, val_ind in kf.split(X, y): # Data split X_train, y_train = X_kf[train_ind], y_kf[train_ind] X_val, y_val = X_kf[val_ind], y_kf[val_ind] # Fit model and make predictions model.fit(X_train, y_train) pred = model.predict(X_val) proba = model.pre...
''' Plots Precision-Recall Curves for each fold in KFold cross-validation for a provided model. Inputs: * Classification Model * X, y training data * KFold parameters * Model Alias (for plot) ''' # sets up the figure plt.figure(figsize=(6, 6), dpi=1...
identifier_body
model_evaluation.py
(accuracy_score(y_val, pred)) prec_scores.append(precision_score(y_val, pred)) recall_scores.append(recall_score(y_val, pred)) f1_scores.append(f1_score(y_val, pred)) roc_auc_scores.append(roc_auc_score(y_val, model.predict_proba(X_val)[:,1])) print(f'Model: {mod...
plt.text(j, i, "{:0.4f}".format(cm[i, j]), horizontalalignment="center", color="white" if cm[i, j] > thresh else "black")
conditional_block
zocket.py
else: import traceback import socket import json from time import sleep def micropython_only(fn): def wrapper(*args, **kwargs): if MICROPYTHON: return fn(*args, **kwargs) return wrapper class _Peer: def __init__( self, port, *, ...
mport usocket as socket import ujson as json import network from utime import sleep ap_if = network.WLAN(network.AP_IF) sta_if = network.WLAN(network.STA_IF)
conditional_block
zocket.py
def wrapper(*args, **kwargs): if MICROPYTHON: return fn(*args, **kwargs) return wrapper class _Peer: def __init__( self, port, *, ssid: str = None, passwd: str = None, enable_ap: bool = False, namespace: ...
def _send(self, msg: bytes): while True: try: return self.data_sock.sendall(msg) except OSError: self.disconnect() self.connect() def _recv(self) -> tuple: data, addr = self.data_sock.recvfrom(self.chunksize) if data =...
().connect() self.peer_sock.settimeout(1) self.data_sock.connect(self.find_server())
identifier_body
zocket.py
def wrapper(*args, **kwargs): if MICROPYTHON: return fn(*args, **kwargs) return wrapper class _Peer: def __init__( self, port, *, ssid: str = None, passwd: str = None, enable_ap: bool = False, namespace: ...
@micropython_only def network_connected(self): return ap_if.isconnected() or sta_if.isconnected() @micropython_only def _configure_network(self): if self.enable_ap: ap_if.active(True) if self.ssid is not None: sta_if.active(True) sta_if.scan()...
random_line_split
zocket.py
wrapper(*args, **kwargs): if MICROPYTHON: return fn(*args, **kwargs) return wrapper class _Peer: def __init__( self, port, *, ssid: str = None, passwd: str = None, enable_ap: bool = False, namespace: str ...
self, exc=None): print(LOG_PREFIX + "\nCrash report:") if MICROPYTHON: sys.print_exception(exc) else: traceback.print_exc() print(LOG_PREFIX + "Retrying in %d sec…\n" % self.retry_delay) sleep(self.retry_delay) @property @micropython_only de...
handle_error(
identifier_name
claim_name.rs
_v2::prelude::{CountryCode, GameMode, OsuError, UserHighestRank, Username}; use time::{OffsetDateTime, Time}; use twilight_interactions::command::{CommandModel, CreateCommand}; use crate::{ core::Context, embeds::ClaimNameEmbed, embeds::EmbedData, manager::redis::{osu::UserArgs, RedisData}, util::{...
{ match user { RedisData::Original(user) => Self::from(user), RedisData::Archive(user) => Self::from(user.deref()), } }
identifier_body
claim_name.rs
OnceCell; use rkyv::{ with::{DeserializeWith, Map}, Archived, Infallible, }; use rosu_v2::prelude::{CountryCode, GameMode, OsuError, UserHighestRank, Username}; use time::{OffsetDateTime, Time}; use twilight_interactions::command::{CommandModel, CreateCommand}; use crate::{ core::Context, embeds::Claim...
(user: RedisData<User>) -> Self { match user { RedisData::Original
from
identifier_name
claim_name.rs
::OnceCell; use rkyv::{ with::{DeserializeWith, Map}, Archived, Infallible, }; use rosu_v2::prelude::{CountryCode, GameMode, OsuError, UserHighestRank, Username}; use time::{OffsetDateTime, Time}; use twilight_interactions::command::{CommandModel, CreateCommand}; use crate::{ core::Context, embeds::Cla...
pub user_id: u32, } impl From<User> for ClaimNameUser { #[inline] fn from(user: User) -> Self { Self { avatar_url: user.avatar_url, country_code: user.country_code, has_badges: !user.badges.is_empty(), has_ranked_mapsets: user.ranked_mapset_count > 0,...
pub username: Username,
random_line_split
createVm.go
Info { return hyper_proto.VmInfo{ ConsoleType: consoleType, DestroyProtection: *destroyProtection, DisableVirtIO: *disableVirtIO, Hostname: *vmHostname, MemoryInMiB: uint64(memory >> 20), MilliCPUs: *milliCPUs, OwnerGroups: ownerGroups, OwnerUsers: ...
{ if *overlayDirectory == "" { return nil, nil } overlayFiles := make(map[string][]byte) err := filepath.Walk(*overlayDirectory, func(path string, info os.FileInfo, err error) error { if err != nil { return err } if info.IsDir() { return nil } data, err := ioutil.ReadFile(path) if err ...
identifier_body
createVm.go
!= nil { return fmt.Errorf("error encoding request: %s", err) } // Stream any required data. if imageReader != nil { logger.Debugln(0, "uploading image") startTime := time.Now() if nCopied, err := io.CopyN(conn, imageReader, imageSize); err != nil { return fmt.Errorf("error uploading image: %s got %d of ...
request.OverlayFiles = overlayFiles } secondaryFstab.Write(request.OverlayFiles["/etc/fstab"]) if secondaryFstab.Len() > 0 { if request.OverlayFiles == nil { request.OverlayFiles = make(map[string][]byte) } request.OverlayFiles["/etc/fstab"] = secondaryFstab.Bytes() } } else if *imageURL != "" ...
request.ImageTimeout = *imageTimeout request.SkipBootloader = *skipBootloader if overlayFiles, err := loadOverlayFiles(); err != nil { return err } else {
random_line_split
createVm.go
{ if vmTags == nil { vmTags = make(tags.Tags) } vmTags["Name"] = *vmHostname } } if hypervisor, err := getHypervisorAddress(); err != nil { return err } else { logger.Debugf(0, "creating VM on %s\n", hypervisor) return createVmOnHypervisor(hypervisor, logger) } } func createVmInfoFromFlags() ...
{ return nil, nil }
conditional_block
createVm.go
Users, Tags: vmTags, SecondarySubnetIDs: secondarySubnetIDs, SubnetId: *subnetId, VirtualCPUs: *virtualCPUs, } } func createVmOnHypervisor(hypervisor string, logger log.DebugLogger) error { request := hyper_proto.CreateVmRequest{ DhcpTimeout: *dhcpTimeout, EnableNetboo...
processCreateVmResponses
identifier_name
altConversion.ts
); } else if ( node.type === "FRAME" || node.type === "INSTANCE" || node.type === "COMPONENT" ) { let altNode; const iconToRect = iconToRectangle(node, altParent); if (iconToRect != null) { altNode = prepareTag(iconToRect, node); } else { ...
notEmpty
identifier_name
altConversion.ts
.imageHash) { altNode.bgImage.hash = f.imageHash; altNode.bgImage.size = f.scaleMode; } } } const tagName = node.getPluginData("tagName"); if (tagName) { altNode.tagName = tagName; } else { altNode.tagName = "div"; } altNode.raster = (node.getPluginData("raster") || "") a...
} else { altNode.hasChildren = false; altNode.renderChildren = "n"; } } else { altNode.isInstance = false; } } return altNode; }; export const convertIntoAltNodes = ( sceneNode: ReadonlyArray<SceneNode>, altParent: AltFrameNode | AltGroupNode | null = null, hasSingl...
altNode.props.children = children.characters.trim(); } altNode.hasChildren = true; altNode.renderChildren = "y";
random_line_split
altConversion.ts
" ) { let altNode; const iconToRect = iconToRectangle(node, altParent); if (iconToRect != null) { altNode = prepareTag(iconToRect, node); } else { altNode = prepareTag( frameNodeToAlt(node, altParent, hasSingleChildren), node )...
{ return value !== null && value !== undefined; }
identifier_body
altConversion.ts
.imageHash) { altNode.bgImage.hash = f.imageHash; altNode.bgImage.size = f.scaleMode; } } } const tagName = node.getPluginData("tagName"); if (tagName) { altNode.tagName = tagName; } else { altNode.tagName = "div"; } altNode.raster = (node.getPluginData("raster") || "") a...
convertBlend(altNode, node); // width, x, y convertLayout(altNode, node); // Vector support is still missing. Meanwhile, add placeholder. altNode.cornerRadius = 0; altNode.strokes = []; altNode.strokeWeight = 0; altNode.strokeMiterLimit = 0; altNode.strokeAlign = "CENTER"; a...
{ altNode.parent = altParent; }
conditional_block
file_generator.py
(self.lar_const): if func[:1] in ("s", "v") and func[1:4].isdigit()==True: self.constraints.append(func) #lar_validator checks a dataframe and returns a JSON with #edit pass/fail results. print("rules engine loading") self.lar_validator = rules_engine(geo_config_file=self.geo_config_file) #tracts=...
row_base = row.copy() #Creates an edit report based on the validation. res = pd.DataFrame(self.validation(row, ts_row)) #debugging print section print("*"*25) print("iterations:", iters) #print(logging.info(res[res.status=="failed"])) print(len(res[res.status=="failed"]), "row fails") ...
"""Uses the lar_gen object and a TS row to create a LAR row that passes syntax and validity edits according to the FIG.""" #Stores the stop condition and the initial number of iterations. #stop = False iters = 1 #Makes a new row using the lar generator. row = self.lar_gen.make_row(lei=self.clean_config...
identifier_body
file_generator.py
.lar_const): if func[:1] in ("s", "v") and func[1:4].isdigit()==True: self.constraints.append(func) #lar_validator checks a dataframe and returns a JSON with #edit pass/fail results. print("rules engine loading") self.lar_validator = rules_engine(geo_config_file=self.geo_config_file) #tracts=tract...
else: new_row = self.make_clean_lar_row(ts_row=self.ts_row) new_row = pd.DataFrame(new_row, index=[1]) lar_frame = pd.concat([lar_frame, new_row], axis=0) #Writes the file to a clean filepath specified in the test_filepaths #configuration. out_file_path = self.filepaths['clean_filepat...
first_row = self.make_clean_lar_row(ts_row=self.ts_row) lar_frame = pd.DataFrame(first_row, index=[1])
conditional_block
file_generator.py
.lar_const): if func[:1] in ("s", "v") and func[1:4].isdigit()==True: self.constraints.append(func) #lar_validator checks a dataframe and returns a JSON with #edit pass/fail results. print("rules engine loading") self.lar_validator = rules_engine(geo_config_file=self.geo_config_file) #tracts=tract...
(self, kind): """Creates a clean file or a set of edit files specified by the function call""" #Creates TS row data. self.ts_row = self.lar_gen.make_ts_row() #Creates a TS row dataframe. ts_df = pd.DataFrame(self.ts_row, index=[1]) #The following produces a clean file. if kind == 'clean_file': ...
create_files
identifier_name
file_generator.py
results. for func in dir(self.lar_validator): if func[:1] in ("s", "v") and func[1:4].isdigit()==True: getattr(self.lar_validator, func)(row) #Returns edit check results. return self.lar_validator.results def make_clean_lar_row(self, ts_row): """Uses the lar_gen object and a TS row to create a LA...
#Creates a new list to store the ULI's without nested brackets. new_list = []
random_line_split
main.py
{"london": datetime.date(11,1,1), "tokyo": datetime.date(6,1,1), "barcelona": datetime.date(5,1,1)} destinations = {"rome": "Rome, Italy", "rio": "Rio De Janiero, Brazil", "paris": "Paris, France", "london": "London, England", "tokyo": "T...
def post(self): confirmation = self.request.get('confirmation') flights = get_flights_from_confirmation(confirmation) if flights: self.render("check_flights.html", confirmation=confirmation, flights=flights) else: self.render("check_flights.html", error=True, confirmation=con...
identifier_body
main.py
import json import random import string import logging import hashlib import datetime import time from google.appengine.ext import db template_dir = os.path.join(os.path.dirname(__file__), 'templates') jinja_env = jinja2.Environment(loader = jinja2.FileSystemLoader(template_dir), autoescape = True) # autoescape escap...
import jinja2
random_line_split
main.py
# parent = vacation # confirm from vacation # global variables tours = {"london": datetime.date(11,1,1), "tokyo": datetime.date(6,1,1), "barcelona": datetime.date(5,1,1)} destinations = {"rome": "Rome, Italy", "rio": "Rio De Janiero, Brazil", "paris": "Pari...
self.render("check_flights.html", confirmation=confirmation, flights=flights)
conditional_block
main.py
_dir = os.path.join(os.path.dirname(__file__), 'templates') jinja_env = jinja2.Environment(loader = jinja2.FileSystemLoader(template_dir), autoescape = True) # autoescape escapes html from user text automatically class Handler(webapp2.RequestHandler): def write(self, *a, **kw): self.response.out.write(*a, ...
(flight_number): flight = get_flight(flight_number) html = "<div class='ticket'><p><span>Flight Number: %s</span><span>Confirmation Number: %s</span></p><img src='images/jquery_QR.png' alt='QR_Code' /></div>" % (flight.flight_number, flight.confirm) return html def get_flights_from_confirmation(confirmati...
generate_ticket_html
identifier_name
binarize.py
(img): # 边缘用平均值填充,而不是用255填充 subwindows = [] positions = [] height = img.shape[0] width = img.shape[1] if not img.shape[0] % PATCH_SIZE == 0: height = img.shape[0] - img.shape[0] % PATCH_SIZE + PATCH_SIZE if not img.shape[1] % PATCH_SIZE == 0: width = img.shape[1] - img.shape...
get_subwindows
identifier_name
binarize.py
windows(img): # 边缘用平均值填充,而不是用255填充 subwindows = [] positions = [] height = img.shape[0] width = img.shape[1] if not img.shape[0] % PATCH_SIZE == 0: height = img.shape[0] - img.shape[0] % PATCH_SIZE + PATCH_SIZE
for row in range(height): for col in range(width): if row >= img.shape[0] or col >= img.shape[1]: if col == img.shape[1] and row < img.shape[0]: average = [0, 0, 0] for c in range(3): for i in range(col-5, col): ...
if not img.shape[1] % PATCH_SIZE == 0: width = img.shape[1] - img.shape[1] % PATCH_SIZE + PATCH_SIZE expanded_img = np.zeros((height, width, 3))
random_line_split
binarize.py
): # 边缘用平均值填充,而不是用255填充 subwindows = [] positions = [] height = img.shape[0] width = img.shape[1] if not img.shape[0] % PATCH_SIZE == 0: height = img.shape[0] - img.shape[0] % PATCH_SIZE + PATCH_SIZE if not img.shape[1] % PATCH_SIZE == 0: width = img.shape[1] - img.shape[1] ...
print('shape:', window.shape) else: pass patchs.append(window.astype(np.float32)) patch_names.append(str(pos[0])+'-'+str(pos[1])+'@'+os.path.basename(image_file)) yield np.array(patchs), patch_names #----------------------------------------...
read(image_file) _, subwindows = get_subwindows(image) batch_count = 0 for each in subwindows: window = each[0] pos = each[1] patchs = [] # 每个batch只有一张图片 patch_names = [] batch_count += 1 if auto_scale: score = thickness_score(window, name=str(ba...
identifier_body
binarize.py
(img): # 边缘用平均值填充,而不是用255填充 subwindows = [] positions = [] height = img.shape[0] width = img.shape[1] if not img.shape[0] % PATCH_SIZE == 0: height = img.shape[0] - img.sh
CH_SIZE == 0: width = img.shape[1] - img.shape[1] % PATCH_SIZE + PATCH_SIZE expanded_img = np.zeros((height, width, 3)) for row in range(height): for col in range(width): if row >= img.shape[0] or col >= img.shape[1]: if col == img.shape[1] and row < img.shape[0]...
ape[0] % PATCH_SIZE + PATCH_SIZE if not img.shape[1] % PAT
conditional_block
proxy.go
} return sessions } } var s *session // if msg arrived from the main interface, then send to matching upstreams for _, upstream := range upstreams { if upstream.ruleNet.Contains(target) { vlog.Printf("session not found when handling solicit for target %s. Creating new session...\n", net.IP(n....
case layers.ICMPv6TypeNeighborSolicitation: // source link-layer address opt type, opt length n.payload = append(n.payload[:16], 0x01, 0x01)
random_line_split
proxy.go
, 0, 0, 0, 0, 0, 0, 0, 0x01, 0xff, 0, 0, 0} func Proxy(wg *sync.WaitGroup, ifname string, rules []string) { defer wg.Done() var err error upstreams := make(map[string]*listener) // shared channels upstreams send to errChan := make(chan error) intChan := make(chan ndp) mainExtChan := make(chan ndp) tickRouteCh...
func refreshRoutes(rules []string, intChan chan ndp, errChan chan error, upstreams map[string]*listener) error { vlog.Println("refreshing routes...") for _, rule := range rules { _, ruleNet, err := net.ParseCIDR(rule) if err != nil { return fmt.Errorf("invalid rule '%s', %s", rule, err) } routes, err :=...
{ for i := len(sessions) - 1; i >= 0; i-- { if sessions[i].expiry.After(time.Now()) { continue } switch sessions[i].status { case waiting: vlog.Printf("set waiting session %d to invalid, target %s", i, sessions[i].target) sessions[i].status = invalid sessions[i].expiry = time.Now().Add(ttl) def...
identifier_body
proxy.go
, 0, 0, 0, 0, 0, 0, 0, 0x01, 0xff, 0, 0, 0} func Proxy(wg *sync.WaitGroup, ifname string, rules []string) { defer wg.Done() var err error upstreams := make(map[string]*listener) // shared channels upstreams send to errChan := make(chan error) intChan := make(chan ndp) mainExtChan := make(chan ndp) tickRouteCh...
} func proxyPacket(n ndp, extChan chan ndp, upstreams map[string]*listener, sessions []session) []session { var target net.IP // IPv6 bounds check if len(n.payload) >= 16 { target = net.IP(n.payload[:16]) } else { return sessions } switch n.icmp.TypeCode.Type() { case layers.ICMPv6TypeNeighborAdvertisemen...
{ select { case err = <-errChan: fmt.Printf("%s\n", err) return case n := <-intChan: sessions = proxyPacket(n, mainExtChan, upstreams, sessions) case <-tickSessChan: sessions = updateSessions(sessions) case <-tickRouteChan: err := refreshRoutes(rules, intChan, errChan, upstreams) if err != n...
conditional_block
proxy.go
, 0, 0, 0, 0, 0, 0, 0, 0x01, 0xff, 0, 0, 0} func Proxy(wg *sync.WaitGroup, ifname string, rules []string) { defer wg.Done() var err error upstreams := make(map[string]*listener) // shared channels upstreams send to errChan := make(chan error) intChan := make(chan ndp) mainExtChan := make(chan ndp) tickRouteCh...
() { var err error var handle *pcap.Handle log.Printf("spawning listener for if %s\n", l.ifname) l.Lock() l.started = true l.Unlock() defer func() { if err != nil { l.errChan <- err } l.Lock() l.finished = true l.Unlock() log.Printf("exiting listener for if %s\n", l.ifname) }() // open interfa...
handler
identifier_name
piston.rs
mut self, batch : &Batch, params : &Params) { self.graphics.draw(batch, params, &self.frame); } pub fn render_tile(&mut self, p : Point, c : Color, elevate : bool) { let (px, py) = point_to_coordinate(p); let params = self.render_params(px, py, if elevate {WALL_HEIGHT} else {0.0}, 0.0, ...
self.player_pos = pos; let front = pos.p + pos.dir;
random_line_split
piston.rs
.render_batch(&batch, &params); } } /// linearly interpolate between two values fn mix<F : FloatMath> (x : F, y : F, a : F) -> F { assert!(a >= zero()); assert!(a <= one()); y * a + x * (one::<F>() - a) } struct SmoothMovement<T> { speed : f32, destination: T, pub current: T, } impl<V :...
date_movement(&
identifier_name
piston.rs
Color = [0.3f32, 0.2, 0.0, 1.0]; static GLASSWALL_COLOR : Color = [0.7f32, 0.7, 0.95, 1.0]; static SAND_COLOR : Color = [1.0f32, 1.0, 0.8, 1.0]; static FLOOR_COLOR : Color = [1.0f32, 0.9, 0.9, 1.0]; static SCOUT_COLOR : Color = [0.0f32, 0.8, 0.0, 1.0]; static GRUNT_COLOR : Color = [0.0f32, 0.6, 0.0, 1.0]; static HEAVY...
pub fn finish_immediately(&mut self) { self.current = self.destination.clone(); } } pub struct PistonUI { renderer : Renderer<GlCommandBuffer, GlDevice>, render_controller
self.destination = dest; }
identifier_body
piston.rs
: false, ctrl_pressed: false, is_running: true, action_queue: RingBuf::new(), } } fn move_or_run(&self, dir : Direction) -> Action { if self.is_running { Run(dir) } else { Move(dir) } } fn push_move_or_run(&mut...
conditional_block
EnaRest.py
.apps.web_copo.utils.EnaUtils as u from dal.broker_da import BrokerDA from dal.copo_da import DataFile from web.apps.web_copo.rest.models import CopoChunkedUpload class CopoChunkedUploadCompleteView(ChunkedUploadCompleteView): do_md5_check = False def get_response_data(self, chunked_upload, request): ...
def hash_upload(request): # utility method to create an md5 hash of a given file path # open uploaded file file_id = request.GET['file_id'] print('hash started ' + file_id) file_obj = ChunkedUpload.objects.get(pk=file_id) file_name = os.path.join(settings.MEDIA_ROOT, file_obj.file.name) ...
return HttpResponse(jsonpickle.encode(''))
conditional_block
EnaRest.py
.apps.web_copo.utils.EnaUtils as u from dal.broker_da import BrokerDA from dal.copo_da import DataFile from web.apps.web_copo.rest.models import CopoChunkedUpload class CopoChunkedUploadCompleteView(ChunkedUploadCompleteView): do_md5_check = False def get_response_data(self, chunked_upload, request): ...
def hash_upload(request): # utility method to create an md5 hash of a given file path # open uploaded file file_id = request.GET['file_id'] print('hash started ' + file_id) file_obj = ChunkedUpload.objects.get(pk=file_id) file_name = os.path.join(settings.MEDIA_ROOT, file_obj.file.name) ...
user_id = request.user.id d = ChunkedUpload.objects.filter(completed_on__isnull=True, user_id=user_id).order_by('created_on') if d: out = serializers.serialize('json', d) return HttpResponse(jsonpickle.encode(out)) else: return HttpResponse(jsonpickle.encode(''))
identifier_body
EnaRest.py
.apps.web_copo.utils.EnaUtils as u from dal.broker_da import BrokerDA from dal.copo_da import DataFile from web.apps.web_copo.rest.models import CopoChunkedUpload class CopoChunkedUploadCompleteView(ChunkedUploadCompleteView): do_md5_check = False def get_response_data(self, chunked_upload, request): ...
# update record in mongo record_object = DataFile().get_by_file_id(file_id) auto_fields = dict() auto_fields[DataFile().get_qualified_field("file_hash")] = file_obj.hash profile_id = request.session['profile_id'] component = "datafile" BrokerDA(target_id=str(record_object.get("_id", str())...
file_obj.hash = md5.hexdigest() file_obj.save() output_dict = {'output_hash': md5.hexdigest(), 'file_id': file_id}
random_line_split
EnaRest.py
.apps.web_copo.utils.EnaUtils as u from dal.broker_da import BrokerDA from dal.copo_da import DataFile from web.apps.web_copo.rest.models import CopoChunkedUpload class CopoChunkedUploadCompleteView(ChunkedUploadCompleteView): do_md5_check = False def get_response_data(self, chunked_upload, request): ...
(HttpResponse): """ An HttpResponse that renders its content into JSON. """ def __init__(self, data, **kwargs): content = JSONRenderer().render(data) kwargs['content_type'] = 'application/json' super(JSONResponse, self).__init__(content, **kwargs) def receive_data_file(reques...
JSONResponse
identifier_name
context.rs
(&self) -> &Context { self.0.as_ref() } } impl std::borrow::Borrow<Context> for CtxRef { fn borrow(&self) -> &Context { self.0.borrow() } } impl std::cmp::PartialEq for CtxRef { fn eq(&self, other: &CtxRef) -> bool { Arc::ptr_eq(&self.0, &other.0) } } impl Default for CtxR...
as_ref
identifier_name
context.rs
} impl Default for CtxRef { fn default() -> Self { Self(Arc::new(Context { // Start with painting an extra frame to compensate for some widgets // that take two frames before they "settle": repaint_requests: AtomicU32::new(1), ..Context::default() }))...
random_line_split
context.rs
} impl std::borrow::Borrow<Context> for CtxRef { fn borrow(&self) -> &Context { self.0.borrow() } } impl std::cmp::PartialEq for CtxRef { fn eq(&self, other: &CtxRef) -> bool { Arc::ptr_eq(&self.0, &other.0) } } impl Default for CtxRef { fn default() -> Self { Self(Arc::n...
{ self.0.as_ref() }
identifier_body
flash.go
-1)) ekf := moscommon.ExpandPlaceholders(opts.ESP32EncryptionKeyFile, "?", mac) common.Reportf("Flash encryption key: %s", ekf) esp32EncryptionKey, err = ioutil.ReadFile(ekf) if err != nil { return errors.Annotatef(err, "failed to read encryption key") } } else { return errors.E...
{ return errors.Errorf("Images 0x%x and 0x%x overlap", prevImageBegin, imageBegin) }
conditional_block
flash.go
(ct esp.ChipType, fw *fwbundle.FirmwareBundle, opts *esp.FlashOpts) error { if opts.KeepFS && opts.EraseChip { return errors.Errorf("--keep-fs and --esp-erase-chip are incompatible") } cfr, err := ConnectToFlasherClient(ct, opts) if err != nil { return errors.Trace(err) } defer cfr.rc.Disconnect() if ct =...
Flash
identifier_name
flash.go
.Reportf("Flash size: %d, params: %s", cfr.flashParams.Size(), cfr.flashParams) encryptionEnabled := false secureBootEnabled := false var esp32EncryptionKey []byte var fusesByName map[string]*esp32.Fuse kcs := esp32.KeyEncodingSchemeNone if ct == esp.ChipESP32 { // TODO(rojer): Flash encryption support for ESP32...
{ sysParamsAddr := uint32(flashSize - sysParamsAreaSize) for _, p := range fw.Parts { if p.Type != sysParamsPartType { continue } if p.Addr != sysParamsAddr { glog.Infof("Sys params image moved from 0x%x to 0x%x", p.Addr, sysParamsAddr) p.Addr = sysParamsAddr } } }
identifier_body
flash.go
...") if err = cfr.fc.EraseChip(); err != nil { return errors.Annotatef(err, "failed to erase chip") } } else if opts.MinimizeWrites { common.Reportf("Deduping...") imagesToWrite, err = dedupImages(cfr.fc, images) if err != nil { return errors.Annotatef(err, "failed to dedup images") } } if len(im...
Type: im.Type, Addr: uint32(newAddr), Data: im.Data[newAddr-imAddr : newAddr-imAddr+newLen], ESP32Encrypt: im.ESP32Encrypt, }
random_line_split