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
transport.go
transportState = iota closing draining ) // ServerConfig consists of all the configurations to establish a server transport. type ServerConfig struct { MaxStreams uint32 AuthInfo credentials.AuthInfo InTapHandle tap.ServerInHandle StatsHandler stats.Handler KeepaliveP...
{ return e }
conditional_block
transport.go
"golang.org/x/net/context" "google.golang.org/grpc/codes" "google.golang.org/grpc/credentials" "google.golang.org/grpc/keepalive" "google.golang.org/grpc/metadata" "google.golang.org/grpc/stats" "google.golang.org/grpc/status" "google.golang.org/grpc/tap" ) // state of transport type transportState int const ...
// if it fails. func NewServerTransport(protocol string, conn net.Conn, config *ServerConfig) (ServerTransport, error) { return newHTTP2Server(conn, config) } // ConnectOptions covers all relevant options for communicating with the server. type ConnectOptions struct { // UserAgent is the application user agent. Use...
} // NewServerTransport creates a ServerTransport with conn or non-nil error
random_line_split
transport.go
"golang.org/x/net/context" "google.golang.org/grpc/codes" "google.golang.org/grpc/credentials" "google.golang.org/grpc/keepalive" "google.golang.org/grpc/metadata" "google.golang.org/grpc/stats" "google.golang.org/grpc/status" "google.golang.org/grpc/tap" ) // state of transport type transportState int const (...
() string { return fmt.Sprintf("connection
Error
identifier_name
transport.go
"golang.org/x/net/context" "google.golang.org/grpc/codes" "google.golang.org/grpc/credentials" "google.golang.org/grpc/keepalive" "google.golang.org/grpc/metadata" "google.golang.org/grpc/stats" "google.golang.org/grpc/status" "google.golang.org/grpc/tap" ) // state of transport type transportState int const (...
// Options provides additional hints and information for message // transmission. type Options struct { // Last indicates whether this write is the last piece for // this stream. Last bool // Delay is a hint to the transport implementation for whether // the data could be buffered for a batching write. The // ...
{ return newHTTP2Client(connectCtx, ctx, target, opts, onSuccess) }
identifier_body
assignment.go
json:"position" yaml:"position" meddler:"position"` // the sorting order of the assignment in the group // the types of submissions allowed for this assignment list containing one or // more of the following: 'discussion_topic', 'online_quiz', 'on_paper', 'none', // 'external_tool', 'online_tex...
shAssignment(d
identifier_name
assignment.go
containing one or // more of the following: 'discussion_topic', 'online_quiz', 'on_paper', 'none', // 'external_tool', 'online_text_entry', 'online_url', 'online_upload' // 'media_recording' SubmissionTypes []string `json:"submission_types" yaml:"submission_types" meddler:"submission_types"` // Allowed file exte...
return err }
conditional_block
assignment.go
ToolTagAttributes `json:"external_tool_tag_attributes" yaml:"external_tool_tag_attributes" meddler:"external_tool_tag_attributes"` // The number of submission attempts a student can make for this assignment. -1 // is considered unlimited. AllowedAttempts int `json:"allowed_attempts" yaml:"allowed_attempts" meddler:...
return pullComponent(db, assignmentPath, assignment.CanvasId, assignment) }
identifier_body
assignment.go
// the maximum points possible for the assignment Position int `json:"position" yaml:"position" meddler:"position"` // the sorting order of the assignment in the group // the types of submissions allowed for this assignment list containing one or // more of the following: 'discussion...
// the unlock date as it applies to the user requesting information from the // API. UnlockAt string `json:"unlock_at" yaml:"unlock_at" meddler:"unlock_at"` // the lock date (assignment is locked after this date). returns null if not // present. NOTE: If this assignment has assignment overrides, this field will ...
// the unlock date (assignment is unlocked after this date) returns null if not // present NOTE: If this assignment has assignment overrides, this field will be
random_line_split
home.ts
//Get the sql that was set by the constructor private get_sql_():string { return ' select `school`.`logo`, ' + ' `school`.`id`, ' + ' `school`.`name`, ' + ' `school`.`address`, ' + ' `school`.`location` ' + ' from `general_school`.`school` '; } // set sql(s: stri...
else { await this.Fuel.activate(Ifuel, offset); this.Fuel.paint(this.target!,offset) } } // //This is the search event listener //Filters the schools displayed on the market pannel and to a selected //shool public async show_school(evt: Event): Promise<void>{ // //Throw...
{ // this.Fuel = new show(Ifuel, this.sql, this, offset); // //Activate the fuel await this.Fuel.activate(); // //Paint this labels to make them visible. await this.Fuel.paint(this.target!); }
conditional_block
home.ts
//Get the sql that was set by the constructor private get_sql_():string { return ' select `school`.`logo`, ' + ' `school`.`id`, ' + ' `school`.`name`, ' + ' `school`.`address`, ' + ' `school`.`location` ' + ' from `general_school`.`school` '; } // set sql(s: stri...
// //Modify the sql this.host.sql = sql + modify; // //Get the ifuel for this const ifuel = await this.host.query(0, 1); // //Expand this repository with the given information. this.expand(-1, ifuel) // //Return the newly created accademy if it ...
const sql = this.host.original_sql === undefined ? this.sql : this.host.original_sql; this.host.original_sql = sql; // //The modifying where clause const modify = ` where school.name= ${selection}`;
random_line_split
home.ts
`, ' + ' `school`.`address`, ' + ' `school`.`location` ' + ' from `general_school`.`school` '; } // set sql(s: string) { this.sql_=s } get sql(){return this.sql_} // // //Paint this market place from the first selection in a lable format. async continue_paint() { // ...
open_school
identifier_name
main.py
得数据加载器 self.train_loader = DataLoader(self.train_set, batch_size=self.batch_size, shuffle=True, num_workers=8) self.test_loader = DataLoader(self.test_set, batch_size=self.batch_size, num_workers=8) # 定义训练和测试网络结构 ...
:param word_vocab: 当前数据集的词典,['ship',...] :param pretrained_vocab:GloVe中预训练的词向量
random_line_split
main.py
# 获取训练、测试数据集及其词典 self.train_set = data.get_dataset(data.train_dir, self.vocab_data) self.test_set= data.get_dataset(data.test_dir, self.vocab_data) print('训练数据大小:{}'.format(len(self.train_set))) print('测试数据大小:{}'.format(len(self.test_set))) # 获得数据加载器 self.train_...
it__(self): # 定义相关参数 self.batch_size = 64 # 批次大小 self.num_workers = 8 # 线程数量 self.embedded_size = 100 # 词向量大小 self.num_hiddens = 100 # 隐藏层数量 self.num_layers = 2 # 堆叠LSTM的层数 self.num_classes = 2 # 类别数量 self.name_classes = ['neg', 'pos'] # 类别名称 ...
identifier_body
main.py
self.pretrained = True # 是否使用预训练的词向量 self.lr = 0.01 # 学习率 self.num_epochs = 20 # 批次数量 self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') # 设备 self.checkpoints = 'text.pth' # 定义处理对象的实体类 data = ProcessACLData() # 获得词典 se...
rmat(epoch, self.num_epochs - 1)) print('-' * 20) # 调成训练模式 net.train() # 定义准确率变量,损失值,批次数量,样本总数量;最好精确率 train_acc = 0.0 train_loss = 0.0 num_batch = 0 num_samples = 0 best_acc = 0 # 进行每周期的网络的训练 ...
evice=self.device) self.optimizer.zero_grad() # 周期遍历 for epoch in range(self.num_epochs): print('Epoch {}/{}'.fo
conditional_block
main.py
self.optimizer = torch.optim.Adam(filter(lambda p:p.requires_grad, net.parameters()), lr=self.lr) else: self.optimizer = torch.optim.Adam(net.parameters(), lr=self.lr) self.criterion = torch.nn.CrossEntropyLoss() print('training ...
identifier_name
list.go
whoCanUsage, Long: whoCanLong, Example: whoCanExample, SilenceUsage: true, RunE: func(cmd *cobra.Command, args []string) error { clientConfig := configFlags.ToRawKubeConfigLoader() restConfig, err := clientConfig.ClientConfig() if err != nil { return fmt.Errorf("getting rest ...
getClusterRolesFor
identifier_name
list.go
who can list every resource in the namespace "baz" kubectl who-can list '*' -n baz # List who can read pod logs kubectl who-can get pods --subresource=log # List who can access the URL /logs/ kubectl who-can get /logs` ) const ( // RoleKind is the RoleRef's Kind referencing a Role. RoleKind = "Role" //...
action, err := ActionFrom(clientConfig, cmd.Flags(), args) if err != nil { return err } o, err := NewWhoCan(restConfig, mapper) if err != nil { return err } warnings, err := o.CheckAPIAccess(action) if err != nil { return err } output, err := cmd.Flags().GetString(outputFlag...
{ var configFlags *clioptions.ConfigFlags cmd := &cobra.Command{ Use: whoCanUsage, Long: whoCanLong, Example: whoCanExample, SilenceUsage: true, RunE: func(cmd *cobra.Command, args []string) error { clientConfig := configFlags.ToRawKubeConfigLoader() restConfig, err := clientCon...
identifier_body
list.go
), accessChecker: NewAccessChecker(client.AuthorizationV1().SelfSubjectAccessReviews()), policyRuleMatcher: NewPolicyRuleMatcher(), }, nil } // NewWhoCanCommand constructs the WhoCan command with the specified IOStreams. func NewWhoCanCommand(streams clioptions.IOStreams) (*cobra.Command, error) { var conf...
return nil, err } roleNames := make(map[string]struct{}, 10)
random_line_split
list.go
. type clusterRoles map[string]struct{} type WhoCan struct { clientNamespace clientcore.NamespaceInterface clientRBAC clientrbac.RbacV1Interface namespaceValidator NamespaceValidator resourceResolver ResourceResolver accessChecker AccessChecker policyRuleMatcher PolicyRuleMatcher } // NewWhoCan co...
{ return nil, err }
conditional_block
main.rs
tokio::fs::write(outfile, toml::to_string(&inv)?).await?; } SubCommand::PushFile(push_opts) => { let label = generate_label(&push_opts.path, push_opts.name, push_opts.media_type).await?; println!("Uploading file {} to server", push_opts.path.display()); ...
.into_inner(), ) .await?; }
random_line_split
main.rs
); let out = toml::to_string(&keyring).map_err(|e| ClientError::Other(e.to_string()))?; println!("{}", out); } SubCommand::CreateKey(create_opts) => { let dir = match create_opts.secret_file { Some(dir) => dir, None => ensure_config_dir...
{ match name.as_str() { "c" | "creator" => Ok(SignatureRole::Creator), "h" | "host" => Ok(SignatureRole::Host), "a" | "approver" => Ok(SignatureRole::Approver), "p" | "proxy" => Ok(SignatureRole::Proxy), _ => Err(ClientError::Other("Unknown role".to_owned())), } }
identifier_body
main.rs
::to_string(&inv)?).await?; } SubCommand::PushFile(push_opts) => { let label = generate_label(&push_opts.path, push_opts.name, push_opts.media_type).await?; println!("Uploading file {} to server", push_opts.path.display()); bindle_client ...
load_keyring
identifier_name
fsevents.rs
ventStreamContext { version: c_int, info: *mut c_void, retain: *const c_void, release: *const c_void, desc: *const c_void, } type callback_t = extern "C" fn( stream: *const c_void, info: *const c_void, size: c_int, paths: *const *const i8, events: *const u32, ids: *const u64...
data: events, len: size as uint, }) }; let ids: &[u64] = unsafe { mem::transmute(Slice { data: ids, len: size as uint, }) }; let paths: &[*const i8] = unsafe { mem::transmute(Slice { data: paths, le...
let events: &[u32] = unsafe { mem::transmute(Slice {
random_line_split
fsevents.rs
StreamContext { version: c_int, info: *mut c_void, retain: *const c_void, release: *const c_void, desc: *const c_void, } type callback_t = extern "C" fn( stream: *const c_void, info: *const c_void, size: c_int, paths: *const *const i8, events: *const u32, ids: *const u64 ); ...
Exit => { debug!("Received watcher exit event - performing graceful shutdown"); break } } } } }); watcher } pub fn watch(&mut self, path: &Pa...
{ debug!("Updating watcher loop with {}", paths); *stream.lock() = recreate_stream(*eventloop.lock(), &context, paths); CFRunLoopRun(); }
conditional_block
fsevents.rs
{ Create(String), Remove(String), //ModifyMeta, Modify(String), RenameOld(String), RenameNew(String), } enum Control { Update(HashSet<String>), Exit, } #[repr(C)] struct FSEventStreamContext { version: c_int, info: *mut c_void, retain: *const c_void, release: *const c_...
Event
identifier_name
fsevents.rs
: u64 = 0xFFFFFFFFFFFFFFFF; fn has_flag(event: u32, expected: FSEventStreamEventFlags) -> bool { event & expected as u32 == expected as u32 } extern "C" fn callback(_stream: *const c_void, info: *const c_void, size: c_int, paths: *const *const i8, events: *const u32...
{ super::Unknown }
identifier_body
kmodules.rs
_cycle: Vec<fn()>, } #[allow(dead_code)] /// Stored structure of a given module struct Module { start_point: u32, symbol_table: Box<SymbolTable>, mod_return: ModReturn, alloc_table: AllocTable, } /// Main implementation impl KernelModules { pub fn new() -> Self { Self { dummy: ...
(s: &str) { eprint!("{}", s); } /// Just used for a symbol list test #[no_mangle] #[link_section = ".kernel_exported_functions"] pub fn symbol_list_test() { log::info!("symbol_list_test function sucessfully called by a module !"); } #[no_mangle] #[link_section = ".kernel_exported_functions"] pub fn add_syslog...
emergency_write
identifier_name
kmodules.rs
s, None => { log::error!("No Symtab for that Module"); return Err(Errno::EINVAL); } }; // Launch the module with his particulary context let start_point: u32 = eip as u32; let p: fn(SymbolList) -> ModResult = unsafe { core::mem::t...
// With BSS (so a NOBITS section), the memsz value exceed the filesz. Setting next bytes as 0 segment[h.filez as usize..h.memsz as usize]
random_line_split
kmodules.rs
_cycle: Vec<fn()>, } #[allow(dead_code)] /// Stored structure of a given module struct Module { start_point: u32, symbol_table: Box<SymbolTable>, mod_return: ModReturn, alloc_table: AllocTable, } /// Main implementation impl KernelModules { pub fn new() -> Self { Self { dummy: ...
ModConfig::Keyboard(KeyboardConfig { enable_irq, disable_irq, callback: push_message, }), ), "syslog" => ( &mut self.kernel_modules.syslog, "/turbofish/mod/syslog.mod", ...
{ let (module_opt, module_pathname, mod_config) = match modname { "dummy" => ( &mut self.kernel_modules.dummy, "/turbofish/mod/dummy.mod", ModConfig::Dummy, ), "rtc" => ( &mut self.kernel_modules.rtc, ...
identifier_body
Taguchi_Final_v0.0.py
84,7.00,1.74,3.70,60.59], [19.66,23.15,21.35,22.75,7.00,2.37,3.71,61.51]] #test_data1 = [[6,15,0.5,0,0,0,10,0.57], # [6,15,0.5,3,5,5,13,0.43], # [6,25,2.5,0,0,5,13,0.51], # [6,25,2.5,3,5,0,10,0.51], # [10,15,2.5,0,5,0,13,0.51], # ...
### Printing h values #print(hn) #print("") ### Printing rounded off h values #for i in hn: # print(round(i,3), end=" ") #print("") #rounding off #for i in range(n): # bn[i] = round(bn[i],3) # hn[i] = round(hn[i],3) ...
og_hn = hn
conditional_block
Taguchi_Final_v0.0.py
og_hn = [] sn_level_table = [] sn_change_table = [] Mt_o_table = [] useful_parameters = [] sn_case_table = [] predict_data = [] dataset = [] #def reset_values(): # n = 0 # t = 0 # us = [] # sn = [] # og_n = 0 # og_t = 0 # og_bn = [] # og_hn = [] # sn_level_table = [] # sn_change_table = ...
us = [] sn = [] og_n = 0 og_t = 0 og_bn = []
random_line_split
Taguchi_Final_v0.0.py
### Printing Level Table (SN Ratio Change) for i in range(n): for j in range(2): sn_level_table[i+1][j+1]=round(sn_level_table[i+1][j+1],2) for i in sn_level_table: print(i) ### CASE 1 # Printing SN ( h ) Values when all materials used #print(og_hn) #global...
data_details.withdraw() global n n = parameter_entry.get() global t t = testcase_entry.get() #print(n,t) input_data = Toplevel(data_details) input_data.title("Input Data") #indentation run func def edit_details(): MsgBox = tkinter.me...
identifier_body
Taguchi_Final_v0.0.py
sbn[i]>ven[i]: h = (sbn[i]-ven[i])/(r*ven[i]) else: h = 0 hn.append(h) #print(hn) global og_hn if n == og_n: og_hn = hn ### Printing h values #print(hn) #print("") ### Printing rounded off h...
predict
identifier_name
mail.py
: return addr return name + " " + addr def clean_link(text): return re.sub(r'\s+', ' ', strip_newlines(text)).strip() class LinkParser(HTMLParser): curr = None links = [] def handle_starttag(self, tag, attrs): if tag == "a": for a in attrs: ...
(object): """ EmailProcessor extract attachments from emails in an s3 bucket """ def __init__(self, rules_file, s3_base_url=None, s3_atch_dir=None, aws_access_key_id=None, aws_secret_access_key=None): with open(rules_file, "rb") as file_handle: self.rules = json.loads(file_ha...
EmailProcessor
identifier_name
mail.py
name: return addr return name + " " + addr def clean_link(text): return re.sub(r'\s+', ' ', strip_newlines(text)).strip() class LinkParser(HTMLParser): curr = None links = [] def handle_starttag(self, tag, attrs): if tag == "a": for a in attrs: ...
def handle_data(self, data): if self.curr is not None: self.links.append([clean_link(data), self.curr]) class Email(object): def __init__(self, key, msg, original_date=None): self.key = key self.text = "" self.html = "" self.attachments = [] ...
self.curr = None
identifier_body
mail.py
: return addr return name + " " + addr def clean_link(text): return re.sub(r'\s+', ' ', strip_newlines(text)).strip() class LinkParser(HTMLParser): curr = None links = [] def handle_starttag(self, tag, attrs): if tag == "a": for a in attrs: ...
fmt("Attachments :", atch_names), ] if include_links: lines.append(fmt("Links :", self.links)) if self.errors: for error in self.errors: lines.append(fmt("ERROR :", error)) else: lines.append(fmt("OKAY...
fmt("Date :", self.date),
random_line_split
mail.py
if len(forwarded) > 1: # NOTE: all emails should be placed with the 'Forward as # Attachment' option in outlook. so there should only be a single # attachment containing the forwarded email raise Error("expected 1 forwarded attachment. got", len(forwarded)) return forwarde...
raise Error("forwarded attachment expected but missing")
conditional_block
mod.rs
/// Links given graph node with specified rigid body. pub fn bind( &mut self, node: Handle<Node>, rigid_body: Handle<RigidBody>, ) -> Option<Handle<RigidBody>> { self.node_rigid_body_map.insert(node, rigid_body) } /// Unlinks given graph node from its associated rigid b...
{ // Re-use of body handle is fine here because physics copy bodies // directly and handles from previous pool is still suitable for copy. physics_binder.bind(new_node, body); }
conditional_block
mod.rs
Handle<RigidBody>>, } impl Default for PhysicsBinder { fn default() -> Self { Self { node_rigid_body_map: Default::default(), } } } impl PhysicsBinder { /// Links given graph node with specified rigid body. pub fn bind( &mut self, node: Handle<Node>, ...
pub(in crate) fn resolve(&mut self) { Log::writeln("Starting resolve...".to_owned()); self.graph.resolve(); self.animations.resolve(&self.graph); Log::writeln("Resolve succeeded!".to_owned()); } /// Tries to set new lightmap to scene. pub fn set_lightmap(&mut self, lig...
{ for descendant in self.graph.traverse_handle_iter(handle) { // Remove all associated animations. self.animations.retain(|animation| { for track in animation.get_tracks() { if track.get_node() == descendant { return false; ...
identifier_body
mod.rs
Handle<RigidBody>>, } impl Default for PhysicsBinder { fn default() -> Self { Self { node_rigid_body_map: Default::default(), } } } impl PhysicsBinder { /// Links given graph node with specified rigid body. pub fn bind( &mut self, node: Handle<Node>, ...
impl Scene { /// Creates new scene with single root node. /// /// # Notes /// /// This method differs from Default trait implementation! Scene::default() creates /// empty graph with no nodes. #[inline] pub fn new() -> Self { Self { // Graph must be created with `new`...
}
random_line_split
mod.rs
node } /// Returns handle of rigid body associated with given node. It will return /// Handle::NONE if given node isn't linked to a rigid body. pub fn body_of(&self, node: Handle<Node>) -> Handle<RigidBody> { self.node_rigid_body_map .get(&node) .copied() .u...
add
identifier_name
extractor.py
er/extractor.py') # %% pprint( dics_arr[4] ) # %% fpath = [ f for f in fpaths if str(f).find('israellaguan') >= 0 ][0] # %% doc = BeautifulSoup( html, features='html.parser' ) # %% _extract_accomplishments(doc) # %% def _extract_accomplishments( doc: BeautifulSoup ) -> Dict[str, Li...
def _extract_about( doc ) -> Optional[str]: about_section = doc.find('section', {'class': 'pv-about-section'}) if about_section is None: return None parts = about_section.find_all("p") return (" ".join( part.text.replace('\n', ' ').strip() for part in parts ) .replace( '... ver más...
some metrics on the whole profile text""" text = doc.find('main', {'class': 'core-rail'}).text.strip() words = text.split() eng_ratio = sum(1 for word in words if word in COMMON_ENGLISH) * 10/ (len(words) + 0.001) return { 'length': len( text ), 'eng_ratio': np.round( eng_ratio, 2)} # %...
identifier_body
extractor.py
dics[fpath] = dic dics_arr = list(dics.values()) # %% del dics # %% with (CFG.profiles_yamls_path / 'all_profiles.json').open('wt') as f_out: json.dump( dics_arr, f_out, cls=DateTimeEncoder, indent=4 ) # %% with (CFG.profiles_yamls_path / 'all_profiles.yaml').open('wt') as ...
# pprint(dic['work_stats'])
random_line_split
extractor.py
ch = re.match(r'(\d+) contactos', num_contacts_text) if mch: return int(mch.group(1)) mch2 = re.search(r'Más de 500 contactos', num_contacts_text) if mch2: return 501 def _parse_experiences(doc: BeautifulSoup) -> List[Dict]: # %% xp_section = doc.find( 'section', {'id': 'experience...
ecords: Lis
identifier_name
extractor.py
== 'Fechas de empleo': xp_record['period_raw'] = value period = _extract_period( value ) xp_record['period'] = period # print( period ) xp_record['duration'] = np.round( (period[1] - period[0]).total_seconds() / S...
if len(texts) >= 3: mch = re.match(r'(\d+)', texts[2]) if mch: ret[key] = int( mch.group(1)) else: print( f"skills {len(texts)} spans: {texts}") ret[key] = None elif len(texts) == 1: ...
conditional_block
index.rs
fn deref(&self) -> &Self::Target { &self.pos } } /** Wrapper type indicating a one-hot encoding of a bit mask for an element. This type is produced by [`BitOrder`] implementations to speed up access to the underlying memory. It ensures that masks have exactly one set bit, and can safely be used as a mask for read...
l::<M>::new_unchecked(self) } } fn pos<M>(self)
identifier_body
index.rs
zero in the next element lower in memory, repeating /// until arrival. Positive values move upwards in memory: towards index /// `M::MASK`, then counting from index zero to index `M::MASK` in the /// next element higher in memory, repeating until arrival. /// /// # Returns /// /// - `.0`: The number of el...
se, downshift the bit distance to compute the number of elements moved in either direction, and mask to compute the absolute bit index in the destination element. */ else { (far >> M::INDX, (far as u8 & M::MASK).idx()) } } else { /* Overflowing `isize` addition happens to produce ordinary `usi...
as u8).idx()) } /* Otherwi
conditional_block
index.rs
where M: BitMemory { /// The termination index. pub const END: Self = Self { end: M::BITS, _ty: PhantomData, }; /// Mark that `end` is a tail index for a type. /// /// # Parameters /// /// - `end` must be in the range `0 ..= M::BITS`. pub(crate) unsafe fn new_unchecked(end: u8) -> Self { debug_assert!( ...
&Self
identifier_name
index.rs
index zero in the next element lower in memory, repeating /// until arrival. Positive values move upwards in memory: towards index /// `M::MASK`, then counting from index zero to index `M::MASK` in the /// next element higher in memory, repeating until arrival. /// /// # Returns /// /// - `.0`: The number...
{ /// The termination index. pub const END: Self = Self { end: M::BITS, _ty: PhantomData, }; /// Mark that `end` is a tail index for a type. /// /// # Parameters /// /// - `end` must be in the range `0 ..= M::BITS`. pub(crate) unsafe fn new_unchecked(end: u8) -> Self { debug_assert!( end <= M::BITS, ...
random_line_split
transaction.rs
, // joinsplit_verifier: groth16::Verifier, } impl<ZS> Verifier<ZS> where ZS: Service<zs::Request, Response = zs::Response, Error = BoxError> + Send + Clone + 'static, ZS::Future: Send + 'static, { // XXX: how should this struct be constructed? pub fn new(network: Network, script_verifier: script::...
transaction, known_utxos, upgrade, } => (transaction, known_utxos, upgrade), }; let mut spend_verifier = primitives::groth16::SPEND_VERIFIER.clone(); let mut output_verifier = primitives::groth16::OUTPUT_VERIFIER.clone(); let ...
{ let is_mempool = match req { Request::Block { .. } => false, Request::Mempool { .. } => true, }; if is_mempool { // XXX determine exactly which rules apply to mempool transactions unimplemented!(); } let (tx, known_utxos, upgrade...
identifier_body
transaction.rs
, // joinsplit_verifier: groth16::Verifier, } impl<ZS> Verifier<ZS> where ZS: Service<zs::Request, Response = zs::Response, Error = BoxError> + Send + Clone + 'static, ZS::Future: Send + 'static, { // XXX: how should this struct be constructed? pub fn new(network: Network, script_verifier: script::...
// https://zips.z.cash/protocol/protocol.pdf#sproutnonmalleability // https://zips.z.cash/protocol/protocol.pdf#txnencodingandconsensus let rsp = ed25519_verifier .ready_and() .await? ...
// adding the resulting future to our collection of // async checks that (at a minimum) must pass for the // transaction to verify. //
random_line_split
transaction.rs
, // joinsplit_verifier: groth16::Verifier, } impl<ZS> Verifier<ZS> where ZS: Service<zs::Request, Response = zs::Response, Error = BoxError> + Send + Clone + 'static, ZS::Future: Send + 'static, { // XXX: how should this struct be constructed? pub fn new(network: Network, script_verifier: script::...
{ /// Verify the supplied transaction as part of a block. Block { /// The transaction itself. transaction: Arc<Transaction>, /// Additional UTXOs which are known at the time of verification. known_utxos: Arc<HashMap<transparent::OutPoint, zs::Utxo>>, /// The height of th...
Request
identifier_name
ReservoirChainGen.py
t in range(0, T)} for t in range(T): for l in range(1, lag + 1): for i in range(num_reservoirs): for j in range(up_stream_dep + 1): if i - j >= 0: if (t < season): #var = 0.2 if i>num_reservoirs/2 else 0.6 ...
else: R_matrices[t][l][i][i - j] = R_matrices[t - season][l][i][i - j] print(R_matrices[2][1]) np.random.seed(1234) inflow_t0 = [[np.around(np.random.uniform(0, 30), 3) for i in range(num_reservoirs)] for l in range(lag + 1)] print(np.array(inflo...
R_matrices[t][l][i][i - j] = np.round(np.random.normal(1.0, 0.3), 3) #for nr=30 experiments R_matrices[t][l][i][i - j] = 0.5 + 0.5 * np.sin(t) #for nr=30 experiments #R_matrices[t][l][i][i-j]=np...
conditional_block
ReservoirChainGen.py
t in range(0, T)} for t in range(T): for l in range(1, lag + 1): for i in range(num_reservoirs): for j in range(up_stream_dep + 1): if i - j >= 0: if (t < season): #var = 0.2 if i>num_reservoirs/2 else 0.6 ...
# RHS_noise[i] = np.random.lognormal(mu_s[i],sig_s[i],num_outcomes) #nr 10 and nr 100 # #RHS_noise[i] = np.sort(np.random.lognormal(mu_s[i],0.5,num_outcomes)) # print(np.max(RHS_noise, 1)) #=========================================================================== RHS_noise = np.zeros(shape...
# #RHS_noise[i] = np.random.uniform(-5,10, num_outcomes) # #RHS_noise[i] = np.random.normal(8,np.log(num_reservoirs-i)+1, num_outcomes)
random_line_split
ReservoirChainGen.py
#R_matrices[t][l][i][i-j]=np.random.normal(0.1, (1.0/(lag*up_stream_dep+1))) #R_matrices[t][l][i][i-j]=np.random.uniform(0,0.3) #R_matrices[t][l][i][i-j]=np.random.uniform(-1/(up_stream_dep+lag),1/(up_stream_dep+lag)) #for nr=100 ...
''' Generate a random instance consisting of: - Autoregresive matrices (stored as dictionaries) - Initial inflow vector (matrix for lag > 0) - Innovations of the autoregressive process ''' np.random.seed(0) season = 12 R_matrices = {t: {l: {i: {} for i in range(num_reservoirs...
identifier_body
ReservoirChainGen.py
][i][i-j]=np.random.uniform(0,0.3) #R_matrices[t][l][i][i-j]=np.random.uniform(-1/(up_stream_dep+lag),1/(up_stream_dep+lag)) #for nr=100 #=================================================== # if t>0: # R_...
read_instance
identifier_name
main.rs
2 % 3 == 0 { //println!("white"); } else { //println!("purple"); y +=1; if cord2 %3 != 0 { x +=1; } } } //println!("x:{}, y:{}", x, y); HexAddr{x:x, y:y} } fn note_to_color(note: u8, config: &Config) -> Color { ...
let window = video_subsystem.window("Isomidi", screen_width, screen_height) .position_centered() .opengl() .resizable()
random_line_split
main.rs
, then figures out which hexagon that triangle belongs in. fn get_hex_address(xo:f32, yo:f32, hexagon:&HexagonDescription) -> HexAddr { let hex_height = hexagon.half_height as f32; let plane1 = yo / hex_height; let incangle = INCREMENT_ANGLE * -2.0; // -120 degrees //let x = xo * incangle.cos(...
{ if addr != old_addr { self.start_note(addr, keyboard); self.end_note(old_addr, keyboard); } }
conditional_block
main.rs
of /// the triangle clicked, then figures out which hexagon that triangle belongs in. fn
(xo:f32, yo:f32, hexagon:&HexagonDescription) -> HexAddr { let hex_height = hexagon.half_height as f32; let plane1 = yo / hex_height; let incangle = INCREMENT_ANGLE * -2.0; // -120 degrees //let x = xo * incangle.cos() + yo * incangle.sin(); let y = xo * incangle.sin() + yo * incangle.cos(...
get_hex_address
identifier_name
main.rs
fn translate_hexagon(xlist:[i16;6], ylist:[i16;6], x:i16, y:i16) -> ([i16;6], [i16;6]) { let mut xs: [i16;6] = [0; 6]; let mut ys: [i16;6] = [0; 6]; for i in 0..6 { xs[i] = xlist[i] + x; ys[i] = ylist[i] + y; } return (xs, ys) } /// Given the x and y locations of a click, return ...
{ // TODO this function needs to be broken up into a calculate and translate section, we don't // need to redo the sin math every time. let r:f32 = radius as f32; let mut angle:f32 = INCREMENT_ANGLE/2.0; let mut xs: [i16;6] = [0; 6]; let mut ys: [i16;6] = [0; 6]; for i in 0..6 { let...
identifier_body
render.rs
use crate::{ html::{Attribute, Children, Element, EventListener, EventToMessage, Html}, program::Program, }; use itertools::{EitherOrBoth, Itertools}; use std::fmt::Debug; use std::rc::Rc; use wasm_bindgen::prelude::*; use wasm_bindgen::JsCast; pub struct Renderer<Model, Msg> { program: Rc<Program<Model, M...
node_et .add_event_listener_with_callback(&type_, closure.as_ref().unchecked_ref())?; let ret = js_closure.0.replace(Some(closure)); if ret.is_some() { log::warn!("to_message did already have a closure???"); } ...
let node_et: &web_sys::EventTarget = &node;
random_line_split
render.rs
use crate::{ html::{Attribute, Children, Element, EventListener, EventToMessage, Html}, program::Program, }; use itertools::{EitherOrBoth, Itertools}; use std::fmt::Debug; use std::rc::Rc; use wasm_bindgen::prelude::*; use wasm_bindgen::JsCast; pub struct Renderer<Model, Msg> { program: Rc<Program<Model, M...
( &mut self, parent: &web_sys::Node, new: Option<&Html<Msg>>, old: Option<&Html<Msg>>, index: u32, ) -> Result<(), JsValue> { match (old, new) { (None, Some(new_html)) => { // Node is added parent.append_child(&self.create_n...
update_element
identifier_name
render.rs
use crate::{ html::{Attribute, Children, Element, EventListener, EventToMessage, Html}, program::Program, }; use itertools::{EitherOrBoth, Itertools}; use std::fmt::Debug; use std::rc::Rc; use wasm_bindgen::prelude::*; use wasm_bindgen::JsCast; pub struct Renderer<Model, Msg> { program: Rc<Program<Model, M...
} Ok(()) }
{ if let Some(closure) = js_closure.0.replace(None) { let node_et: &web_sys::EventTarget = &node; node_et.remove_event_listener_with_callback( &type_, closure.as_ref().unchecked_ref(), )?; } else { ...
conditional_block
main.rs
[0; 16]; for (&src, dst) in self.datagram[index..index + 16] .iter() .zip(rdata.iter_mut()) { *dst = src; } let addr = IpAddr::V6(Ipv6Addr::from(rdata)); ...
// 128 is just a conservative value rounded down.
random_line_split
main.rs
1 { log::error!("Problem parsing qname, qclass is not 1: {}", qclass); return Err(FormatError); } index += 2; } // index is now at the aname section for aname in 0..ancount { log::trace!("parsing aname{}, index {}", aname, index...
} pub struct Resolver { /// DnsServerManager is a service of the Net crate that automatically updates the DNS server list mgr: net::protocols::DnsServerManager, socket: UdpSocket, buf: [u8; DNS_PKT_MAX_LEN], trng: trng::Trng, freeze: bool, } impl Resolver { pub fn new(xns: &xous_names::Xou...
{ match (self.header() >> 11) & 0xF { 0 => DnsResponseCode::NoError, 1 => DnsResponseCode::FormatError, 2 => DnsResponseCode::ServerFailure, 3 => DnsResponseCode::NameError, 4 => DnsResponseCode::NotImplemented, 5 => DnsResponseCode::Refuse...
identifier_body
main.rs
1 { log::error!("Problem parsing qname, qclass is not 1: {}", qclass); return Err(FormatError); } index += 2; } // index is now at the aname section for aname in 0..ancount { log::trace!("parsing aname{}, index {}", aname, index...
(&mut self, freeze: bool) { self.freeze = freeze; self.mgr.set_freeze(freeze); } pub fn get_freeze(&self) -> bool { self.freeze } /// this allows us to re-use the TRNG object pub fn trng_u32(&self) -> u32
set_freeze_config
identifier_name
nodes_controller.go
{ r.logger.Info("failed to initialize watcher for updating nodes - disabled", "error", err) chUpdates = make(chan string) } chAll := watchTicks(stop.Done(), 5*time.Minute) for { select { case <-stop.Done(): r.logger.Info("stopping nodes controller") return nil case node := <-chDels: if err := r...
{ oneAgent, err := r.determineOneAgentForNode(node.Name) if err != nil { return err } if oneAgent == nil { return nil } // determineOneAgentForNode only returns a oneagent object if a node instance is present instance := oneAgent.Status.Instances[node.Name] if _, err = c.Get(node.Name); err != nil { if ...
identifier_body
nodes_controller.go
concileNodes) reconcileAll() error { r.logger.Info("reconciling nodes") var oaLst dynatracev1alpha1.OneAgentList if err := r.client.List(context.TODO(), &oaLst, client.InNamespace(r.namespace)); err != nil { return err } oas := make(map[string]*dynatracev1alpha1.OneAgent, len(oaLst.Items)) for i := range oaLs...
updateLastMarkedForTerminationTimestamp
identifier_name
nodes_controller.go
the Manager is Started. func Add(mgr manager.Manager, ns string) error { return mgr.Add(&ReconcileNodes{ namespace: ns, client: mgr.GetClient(), cache: mgr.GetCache(), scheme: mgr.GetScheme(), logger: log.Log.WithName("nodes.controller"), dtClientFunc: utils.BuildDynatraceClien...
r.logger.Error(err, "failed to remove node", "node", node) } } return r.updateCache(c) } func (r *ReconcileNodes) getCache() (*Cache, error) { var cm corev1.ConfigMap err := r.client.Get(context.TODO(), client.ObjectKey{Name: cacheName, Namespace: r.namespace}, &cm) if err == nil { return &Cache{Obj: &cm...
}, name) }); err != nil {
random_line_split
nodes_controller.go
Manager is Started. func Add(mgr manager.Manager, ns string) error { return mgr.Add(&ReconcileNodes{ namespace: ns, client: mgr.GetClient(), cache: mgr.GetCache(), scheme: mgr.GetScheme(), logger: log.Log.WithName("nodes.controller"), dtClientFunc: utils.BuildDynatraceClient, ...
if time.Now().UTC().Sub(nodeInfo.LastSeen).Hours() > 1 { logger.Info("removing stale node") } else if nodeInfo.IPAddress == "" { logger.Info("removing node with unknown IP") } else { oa, err := oaFunc(nodeInfo.Instance) if errors.IsNotFound(err) { logger.Info("oneagent got already deleted") c.Delete(...
{ return err }
conditional_block
recenter_dump.py
(coords, box_size): com = compute_com_pbc(coords, box_size) cob = box_size / 2.0 coords_recenter = coords - com + cob coords_recenter_x = coords_recenter[:,0] coords_recenter_y = coords_recenter[:,1] coords_recenter_z = coords_recenter[:,2] #print coords_recenter coords_recenter_x = np.p...
reposition
identifier_name
recenter_dump.py
position(coords, box_size): com = compute_com_pbc(coords, box_size) cob = box_size / 2.0 coords_recenter = coords - com + cob coords_recenter_x = coords_recenter[:,0] coords_recenter_y = coords_recenter[:,1] coords_recenter_z = coords_recenter[:,2] #print coords_recenter coords_recenter_...
else: snap_index += 1 continue else: snap_index += 1 continue elif args.begin is None and args.terminate is not None: if snap_index <= args.terminate: if snap_index % stride ...
pass
conditional_block
recenter_dump.py
position(coords, box_size): com = compute_com_pbc(coords, box_size) cob = box_size / 2.0 coords_recenter = coords - com + cob coords_recenter_x = coords_recenter[:,0] coords_recenter_y = coords_recenter[:,1] coords_recenter_z = coords_recenter[:,2] #print coords_recenter coords_recenter_...
###################################### velocity_flag = False others_flag = True unwrap_flag = False image_flag = False # First declare several flags parser = argparse.ArgumentParser(description='Convert Lammps custom dump file to output format file.\ IMPORTANT NOTES:Only used for sim...
if s.is_integer(): return str(int(s)) else: return str(s)
identifier_body
recenter_dump.py
reposition(coords, box_size): com = compute_com_pbc(coords, box_size) cob = box_size / 2.0 coords_recenter = coords - com + cob coords_recenter_x = coords_recenter[:,0] coords_recenter_y = coords_recenter[:,1] coords_recenter_z = coords_recenter[:,2] #print coords_recenter coords_recent...
sys.stdout.write('*** No position information found in dump file. Terminated. ***\n') sys.stdout.flush() sys.exit(0) if 'vx' in attribute_info and 'vy' in attribute_info and 'vz' in attribute_info: vx_index = attribute_info.index('vx') vy_index = attribute_info.index('vy') vz_index = attribute_...
x_index = attribute_info.index('x') y_index = attribute_info.index('y') z_index = attribute_info.index('z') else:
random_line_split
sudoku_server_basic.rs
WriteExt; use tokio::io::BufWriter; use tokio::runtime::Builder; use tokio::signal; use tokio::sync::mpsc; use tokio::time; use tokio::{ net::{TcpListener, TcpStream}, sync::broadcast, }; fn main() -> anyhow::Result<()> { let thread_rt = Builder::new_multi_thread() .worker_threads(4) .thread...
(&mut self) -> anyhow::Result<Option<Frame>> { loop { // Attempt to parse a frame from the buffered data. If enough data // has been buffered, the frame is returned. if let Some(frame) = self.parse_frame()? { return Ok(Some(frame)); } ...
read_frame
identifier_name
sudoku_server_basic.rs
port = 9981; let listener = TcpListener::bind(&format!("0.0.0.0:{}", port)).await; info!("sudoku server start listening: {}", port); // if let Ok(listener) = listener { // let _ = run(listener, signal::ctrl_c()).await; // } match listener { Ok(l) => { ...
// the `mpsc` channel will close and `recv()` will return `None`. let _ = shutdown_complete_rx.recv().await; Ok(()) }
random_line_split
sudoku_server_basic.rs
WriteExt; use tokio::io::BufWriter; use tokio::runtime::Builder; use tokio::signal; use tokio::sync::mpsc; use tokio::time; use tokio::{ net::{TcpListener, TcpStream}, sync::broadcast, }; fn main() -> anyhow::Result<()> { let thread_rt = Builder::new_multi_thread() .worker_threads(4) .thread...
self.stream.write_all(ans.as_bytes()).await?; self.stream.write_all(b"\r\n").await?; self.stream.flush().await?; Ok(()) } // frame id:puzzle\r\n or puzzle\r\n fn parse_frame(&mut self) -> anyhow::Result<Option<Frame>> { // let mut buf = Cursor::new(&self.buffer[..]);...
{ self.stream.write_all(id.as_bytes()).await?; self.stream.write_u8(b':').await?; }
conditional_block
sudoku_server_basic.rs
WriteExt; use tokio::io::BufWriter; use tokio::runtime::Builder; use tokio::signal; use tokio::sync::mpsc; use tokio::time; use tokio::{ net::{TcpListener, TcpStream}, sync::broadcast, }; fn main() -> anyhow::Result<()> { let thread_rt = Builder::new_multi_thread() .worker_threads(4) .thread...
} } _ = shutdown => { // The shutdown signal has been received. info!("shutting down"); } } let Listener { mut shutdown_complete_rx, shutdown_complete_tx, notify_shutdown, .. } = server; // When `notify_shutdown...
{ let (notify_shutdown, _) = broadcast::channel(1); let (shutdown_complete_tx, shutdown_complete_rx) = mpsc::channel(1); let mut server = Listener { listener, notify_shutdown, shutdown_complete_tx, shutdown_complete_rx, }; tokio::select! { res = server.run() ...
identifier_body
Amazon.py
5% wszystkie neutral # -100 Negative but Neutral - o # 99 Neutral but Positive o + # 100 Neutral but Negative o - #false match FalseNeg = reviews FalseNeg = FalseNeg[FalseNeg["Difference"]==-1] FalseNeg = FalseNeg[FalseNeg["Polarity"]>0.6] # górna 1/5 bo 5 gwiazdek FalsePos = reviews FalsePos = FalsePos[Fals...
reviews["ReviewBody"] = reviews["ReviewBody"].apply(remove_punctuation) #remove emoji def remove_emoji(a): emojis = re.compile("[" u"\U0001F600-\U0001F64F" # emoticons u"\U0001F300-\U0001F5FF" # symbols & pictographs u"\U0001F68...
= ''.join([i for i in a if i not in frozenset(string.punctuation)]) return ' '+ a
identifier_body
Amazon.py
C:/Users/Natalia/Documents/Python/Amazon/toheadphones.png") plt.figure(figsize=[10,10]) plt.imshow(wordcloud, interpolation='bilinear') plt.axis("off") plt.show() ########### Z podziałem na positive, negative, omijając neutral revpositive = reviews[reviews.Satisfied == 1] revnegative = reviews[reviews.Satisfied ...
plt.savefig("C:/Users/Natalia/Documents/Python/Amazon/plotRF.jpg") #################################### MODEL SVM model = SVC(kernel='linear') model.fit(X_train_vectorized,y_train)
random_line_split
Amazon.py
5% wszystkie neutral # -100 Negative but Neutral - o # 99 Neutral but Positive o + # 100 Neutral but Negative o - #false match FalseNeg = reviews FalseNeg = FalseNeg[FalseNeg["Difference"]==-1] FalseNeg = FalseNeg[FalseNeg["Polarity"]>0.6] # górna 1/5 bo 5 gwiazdek FalsePos = reviews FalsePos = FalsePos[Fals...
): a = ''.join([i for i in a if not i.isdigit()]) return a reviews["ReviewBody"] = reviews["ReviewBody"].apply(remove_numbers) #stopwords stopwords = stopwords.words('english') reviews["ReviewBody"] = reviews["ReviewBody"].apply(lambda x: ' '.join([word for word in x.split() if word not in (stopwords)])) ...
move_numbers(a
identifier_name
Amazon.py
5% wszystkie neutral # -100 Negative but Neutral - o # 99 Neutral but Positive o + # 100 Neutral but Negative o - #false match FalseNeg = reviews FalseNeg = FalseNeg[FalseNeg["Difference"]==-1] FalseNeg = FalseNeg[FalseNeg["Polarity"]>0.6] # górna 1/5 bo 5 gwiazdek FalsePos = reviews FalsePos = FalsePos[Fals...
######## WORDLIST ########## wordlist = pd.Series(np.concatenate([x.split() for x in reviews.ReviewBody])).value_counts() wordlist25 = wordlist.head(25) wordlist25.plot.barh(width=0.5,fontsize=20).invert_yaxis() plt.savefig("C:/Users/Natalia/Documents/Python/Amazon/plt1.jpg") ########## WORDCLOUD ####### fulltex...
int(ps.stem(word))
conditional_block
cliff_walking.py
[randint(0, len(best_q_values) - 1)][0] else: _max_q = np.argmax(self.q_values) return _max_q def get_max_q_value(self): return np.max(self.q_values) def initialize_states(): # This is the set of states, all initialised with default values states = [[State(j, i) fo...
(mistakes_sarsa, mistakes_q_learning): plt.gca().invert_yaxis() legend = [] for mistake_sarsa in mistakes_sarsa: plt.plot(mistake_sarsa[1]) legend.append(r'SARSA $\epsilon={}$'.format(mistake_sarsa[0])) for mistake_q_learning in mistakes_q_learning: plt.plot(mistake_q_learning[1]...
plot_errors
identifier_name
cliff_walking.py
_values[randint(0, len(best_q_values) - 1)][0] else: _max_q = np.argmax(self.q_values) return _max_q def get_max_q_value(self): return np.max(self.q_values) def initialize_states(): # This is the set of states, all initialised with default values states = [[State(j...
current_state = states[N_ROWS-1][0] # iterate until reaching a terminal state epsilon = max(min_epsilon, epsilon * decay) episode_reward = 0 while not current_state.is_terminal(): if random() < epsilon: next_action = randint(0, 3) else: ...
for i in range(N_STEPS): # select a random starting state
random_line_split
cliff_walking.py
[randint(0, len(best_q_values) - 1)][0] else: _max_q = np.argmax(self.q_values) return _max_q def get_max_q_value(self): return np.max(self.q_values) def initialize_states(): # This is the set of states, all initialised with default values states = [[State(j, i) fo...
PLOTS += 1 # plt.savefig('CLIFF_WALKING: {}-{}-{}.png'.format(N_STEPS, epsilon, method)) # plt.show() def display_optimal_policy(states, method, epsilon): print("{}; ε = {}".format(method, epsilon)) print('-' * 60) for i in range(len(states)): line_str = '' for j in range(len(...
str_ = "" for j in range(N_COLUMNS): str_ += str(int(final_grid[i][j])) + ", "
conditional_block
cliff_walking.py
_values[randint(0, len(best_q_values) - 1)][0] else: _max_q = np.argmax(self.q_values) return _max_q def get_max_q_value(self): return np.max(self.q_values) def initialize_states(): # This is the set of states, all initialised with default values states = [[State(j...
def action_to_verbose(action): if action == 0: return 'NORTH' elif action == 1: return 'EAST' elif action == 2: return 'SOUTH' elif action == 3: return 'WEST' def sarsa(state, next_state, action, next_state_action): return reward(state, next_state), state.q_values...
if action == 0: # NORTH return -1, 0 elif action == 1: # EAST return 0, 1 elif action == 2: # SOUTH return 1, 0 elif action == 3: # WEST return 0, -1
identifier_body
rule_builder.rs
OptimizerAspect>, crate visitor: Rc<VisitorAspect>, crate output_model: ModelCell, crate options: Options, crate closure_builder: Rc<ClosureBuilder>, crate closure_interner: Rc<ClosureInterner>, crate dfa_builder: DFABuilder, crate grammar: Option<Rc<Grammar>>, crate reduce_ids: Vec<ReduceId>, crat...
, } } crate fn build_origin_stmts(&mut self, cursor: &mut Cursor) { let stmts = self.origin_stmts.clone(); let stmts = stmts.borrow(); for (k, v) in stmts.iter() { k.build_mir_dyn(&**v, self, cursor); } } pub fn build_set(&mut self, mut cursor: Cursor, closure: Closure) { if clo...
{ let job = BuildJob::BuildSet { cursor, closure: succ_closure }; self.build_queue.push_back(job); }
conditional_block
rule_builder.rs
= self.resolve_closure_seed(seed); let fail_seed = ClosureSeed::default(); let fail_block = self.resolve_closure_seed(fail_seed); self.fail_block = Some(fail_block); } pub fn add_value_map<A: ToNodeId, B: ToNodeId>(&mut self, from: A, to: B) { self.value_map.insert(from.to_top(), to.to_top()); ...
resolve_one
identifier_name
rule_builder.rs
OptimizerAspect>, crate visitor: Rc<VisitorAspect>, crate output_model: ModelCell, crate options: Options, crate closure_builder: Rc<ClosureBuilder>, crate closure_interner: Rc<ClosureInterner>, crate dfa_builder: DFABuilder, crate grammar: Option<Rc<Grammar>>, crate reduce_ids: Vec<ReduceId>, crat...
self.fail_block = Some(fail_block); } pub fn add_value_map<A: ToNodeId, B: ToNodeId>(&mut self, from: A, to: B) { self.value_map.insert(from.to_top(), to.to_top()); } pub fn at_origin(&self) -> bool { self.num_built <= 2 } pub fn build( &mut self, grammar: Rc<Grammar>, rules: &Vec<NodeId...
{ let seed = { let model = self.visitor.input_model.borrow(); let first_rule = model.get::<_, mir::ItemRule>(rules[0]).unwrap(); self.rule_ty = Some(first_rule.rule_ty.clone()); model.iter(rules) .borrow_cast_nodes_to::<mir::ItemRule>() .filter_map(|r| r.blocks.first().clon...
identifier_body
rule_builder.rs
<OptimizerAspect>, crate visitor: Rc<VisitorAspect>, crate output_model: ModelCell, crate options: Options, crate closure_builder: Rc<ClosureBuilder>, crate closure_interner: Rc<ClosureInterner>, crate dfa_builder: DFABuilder, crate grammar: Option<Rc<Grammar>>, crate reduce_ids: Vec<ReduceId>, cra...
crate rule_ty: Option<Link<mir::TypeFn>>, crate iter_locals: Vec<LValLink>, crate locals: Vec<Child<mir::RuleLocal>>, crate blocks: Vec<Child<mir::Block>>, } impl RuleBuilder { pub fn new(comp: &Compiler, options: Options) -> Self { let visitor = comp.aspect_mut::<VisitorAspect>(); let closure_bu...
crate origin_stmts: Rc<RefCell<Vec<GroupPair>>>,
random_line_split
genetic.go
embers []*Member } type Member struct { Id string Score int64 // Advantage or disadvantage in reproducing Fitness float64 Runtime time.Duration Track []tracks.Element ScoreData scoreData } type scoresArray [500]int64 func (a *scoresArray) Len() int { return len(a) } func (a *scoresArray) Swap(i i...
Crossover
identifier_name
genetic.go
(expDir, id) err = os.MkdirAll(expIdDir, 0755) if err != nil { return err
} iterationsDir := path.Join(expIdDir, "iterations") err = os.MkdirAll(iterationsDir, 0755) if err != nil { return err } cmd := exec.Command("git", "rev-parse", "HEAD") cmd.Dir = packageRoot hashb, err := cmd.Output() if err != nil { return err } mtd := ExperimentMetadata{ Hash: strings...
random_line_split
genetic.go
// constants which may be altered to affect the ride runtime const PARENTS = 2 const FIT_PERCENTAGE = 0.2 const MUTATION_RATE = 0.05 // crossover with a probability of 0.6 (taken from the book & De Jong 1975) const CROSSOVER_PROBABILITY = 0.6 const POOL_SIZE = 500 const ITERATIONS = 1000 const PRINT_RESULTS_EVERY = ...
{ directory = flag.String("directory", "/usr/local/rct", "Path to the folder storing RCT experiment data") }
identifier_body
genetic.go
Dir, id) err = os.MkdirAll(expIdDir, 0755) if err != nil { return err } iterationsDir := path.Join(expIdDir, "iterations") err = os.MkdirAll(iterationsDir, 0755) if err != nil { return err } cmd := exec.Command("git", "rev-parse", "HEAD") cmd.Dir = packageRoot hashb, err := cmd.Output() if err != nil { ...
return b } func max(a float64, b float64) float64 { if a > b { return a } return b } // crossPoint1 = splice point in parent1. func crossoverAtPoint(parent1 *Member, parent2 *Member, crossPoint1 int) (*Member, *Member) { // crossPoint2 = splice point in parent2. crossPoint2 := crossPoint1 + 1 foundMatch := ...
{ return a }
conditional_block
msg-send.ts
5,9,20,25 case 5: case 9: case 20: case 25: reqtype = errorCodes.custom.MSG_AppointmentType; this.startTime = '09:00'; this.endTime = '16:00'; this.selectDate = ''; //this.normal = false; break; default: reqtype = errorCodes.custom.MS...
random_line_split
msg-send.ts
语类型 switch (pcsid){ //预约 pcsid 5,9,20,25 case 5: case 9: case 20: case 25: reqtype = errorCodes.custom.MSG_AppointmentType; this.startTime = '09:00'; this.endTime = '16:00'; this.selectDate = ''; //this.normal = false; break; defaul...
this.showAlert('提示','消息发送失败!错误码:' + resp.errCode ); return; } },(err) =>{
conditional_block
msg-send.ts
修改不显示),true显示 public changeback = false; //是否是打回修改的消息 public alcMsgInfoArray: AlcMsgInfo[] = []; //存放oid,name数组 // 是否批量操作 public sendAll = false; /** * MSG_SysMsgType: 0, // 系统消息类型 * MSG_AppointmentType: 1, // 预约消息类型 * MSG_BusinessLetterType: 2, // 商调函消息类型 * MSG_ConfirmHealthCheck: 3, // 体检确...
'primary'}}}); this.http.postJson<any>(config.common.getApiPrefix()+ urls.api.submitPcsDataUrl , JSON.stringify(submitAppointmentMsg)).subscribe( (resp)=>{ this.m.push({id:MODAL_ID, body:{hidden:true}}); if(resp.errCode !== errorCodes.custom.PCS_SUCCESS){ this.showAlert('提示','消息发送失败!...
{}, params:{color:
identifier_name
msg-send.ts
(this.normal === true && this.changeback === false) { //单独发送消息/批量发送消息 console.log('单独或批量发送自定义消息'); this.sendCustomerMsg(); } } //发送普通消息 public sendCustomerMsg(){ const cstMsg: CustomerMsgData = { alcInfo:this.alcMsgInfoArray , Info: this.msgSend }; this.m.push({id...
identifier_body
trainer.rs
.shrinking_factor) as usize; let pruned_size = desired_vocab_size.max(pruned_size); candidates.sort_by(|(_, a), (_, b)| b.partial_cmp(a).unwrap()); for (id, _score) in candidates { if new_pieces.len() == pruned_size { break; } new_pieces.push(...
random_line_split
trainer.rs
#[derive(thiserror::Error, Debug)] pub enum UnigramTrainerError { #[error("The vocabulary is not large enough to contain all chars")] VocabularyTooSmall, } fn to_log_prob(pieces: &mut [SentencePiece]) { let sum: f64 = pieces.iter().map(|(_, score)| score).sum(); let logsum = sum.ln(); for (_, sco...
{ let mut result = 0.0; while x < 7.0 { result -= 1.0 / x; x += 1.0; } x -= 1.0 / 2.0; let xx = 1.0 / x; let xx2 = xx * xx; let xx4 = xx2 * xx2; result += x.ln() + (1.0 / 24.0) * xx2 - 7.0 / 960.0 * xx4 + (31.0 / 8064.0) * xx4 * xx2 - (127.0 / 30720.0) * xx4 * xx4...
identifier_body