file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
39k
suffix
large_stringlengths
0
36.1k
middle
large_stringlengths
0
29.4k
fim_type
large_stringclasses
4 values
combat.rs
use super::*; use rand::Rng; use crate::r#const::*; use crate::types::*; use crate::types::Tcod; use crate::types::Messages; use crate::func::*; use crate::types::object::Object; use tcod::input::{self, Event, Mouse}; use tcod::colors::{self, Color}; /// returns a clicked monster inside FOV up to a range, or None if r...
game.log.add(format!("The eyes of {} look vacant, as he starts to stumble around!", objects[monster_id].name), colors::LIGHT_GREEN); UseResult::UsedUp } else { // no enemy fonud within maximum range game.log.add("No enemy is close en...
objects[monster_id].ai = Some(Ai::Confused { previous_ai: Box::new(old_ai), num_turns: CONFUSE_NUM_TURNS, });
random_line_split
combat.rs
use super::*; use rand::Rng; use crate::r#const::*; use crate::types::*; use crate::types::Tcod; use crate::types::Messages; use crate::func::*; use crate::types::object::Object; use tcod::input::{self, Event, Mouse}; use tcod::colors::{self, Color}; /// returns a clicked monster inside FOV up to a range, or None if r...
pub fn monster_death(monster: &mut Object, messages: &mut Messages) { // transform it into a nasty corpse! it doesn't block, can't be // attacked and doesn't move // TODO Replace with game.log.add() // message(messages, format!("{} is dead!", monster.name), colors::ORANGE); message(messages, forma...
{ // the game ended! // TODO Replace with game.log.add() message(messages, "You died!", colors::DARK_RED); // for added effect, transform the player into a corpse! player.char = CORPSE; player.color = colors::DARK_RED; }
identifier_body
combat.rs
use super::*; use rand::Rng; use crate::r#const::*; use crate::types::*; use crate::types::Tcod; use crate::types::Messages; use crate::func::*; use crate::types::object::Object; use tcod::input::{self, Event, Mouse}; use tcod::colors::{self, Color}; /// returns a clicked monster inside FOV up to a range, or None if r...
} render_all(tcod, objects, game, false); let (x, y) = (tcod.mouse.cx as i32, tcod.mouse.cy as i32); // accept the target if the player clicked in FOV, and in case a range // is specified, if it's in that range let in_fov = (x < MAP_WIDTH) && (y...
{}
conditional_block
combat.rs
use super::*; use rand::Rng; use crate::r#const::*; use crate::types::*; use crate::types::Tcod; use crate::types::Messages; use crate::func::*; use crate::types::object::Object; use tcod::input::{self, Event, Mouse}; use tcod::colors::{self, Color}; /// returns a clicked monster inside FOV up to a range, or None if r...
(monster_id: usize, game: &mut Game, objects: &mut [Object], fov_map: &FovMap) -> Ai { // a basic monster takes its turn. If you can see it, it can see you let (monster_x, monster_y) = objects[monster_id].pos(); if fov_map.is_in_fov(monster_x, monster_y) { if objects[monster_id].distance_to(&objects...
ai_basic
identifier_name
ikdbtest_gl.py
#Python 2/3 compatibility from __future__ import print_function,division,absolute_import from builtins import input,range from six import iteritems from ikdb import * from ikdb import functionfactory from klampt import * import pkg_resources if pkg_resources.get_distribution('klampt').version >= '0.7': NEW_KLAMPT ...
print ('[space]: tests the current configuration') print ('d: deletes IK constraint') print ('t: adds a new rotation-fixed IK constraint') print ('f: flushes the current database to disk') print ('s: saves the current database to disk') print ('b: ...
print ('HELP:') print ('[right-click]: add a new IK constraint')
random_line_split
ikdbtest_gl.py
#Python 2/3 compatibility from __future__ import print_function,division,absolute_import from builtins import input,range from six import iteritems from ikdb import * from ikdb import functionfactory from klampt import * import pkg_resources if pkg_resources.get_distribution('klampt').version >= '0.7': NEW_KLAMPT ...
else: (s,d) = self.click_ray(x,y) #run the collision tests collided = [] for g in self.collider.geomList: (hit,pt) = g[1].rayCast(s,d) if hit: dist = vectorops.dot(vectorops.sub(pt,s),d) collided.append((dist,g[0])) ...
(s,d) = self.view.click_ray(x,y)
conditional_block
ikdbtest_gl.py
#Python 2/3 compatibility from __future__ import print_function,division,absolute_import from builtins import input,range from six import iteritems from ikdb import * from ikdb import functionfactory from klampt import * import pkg_resources if pkg_resources.get_distribution('klampt').version >= '0.7': NEW_KLAMPT ...
(self,visWorld,planningWorld,name="IK Database visual tester"): GLWidgetProgram.__init__(self,visWorld,name) self.planningWorld = planningWorld self.collider = collide.WorldCollider(visWorld) self.ikdb = ManagedIKDatabase(planningWorld.robot(0)) self.ikWidgets = [] self.i...
__init__
identifier_name
ikdbtest_gl.py
#Python 2/3 compatibility from __future__ import print_function,division,absolute_import from builtins import input,range from six import iteritems from ikdb import * from ikdb import functionfactory from klampt import * import pkg_resources if pkg_resources.get_distribution('klampt').version >= '0.7': NEW_KLAMPT ...
def mousefunc(self,button,state,x,y): #Put your mouse handler here #the current example prints out the list of objects clicked whenever #you right click GLWidgetProgram.mousefunc(self,button,state,x,y) self.reSolve = False dragging = False if NEW_KLAMPT: ...
GLWidgetProgram.__init__(self,visWorld,name) self.planningWorld = planningWorld self.collider = collide.WorldCollider(visWorld) self.ikdb = ManagedIKDatabase(planningWorld.robot(0)) self.ikWidgets = [] self.ikIndices = [] self.ikProblem = IKProblem() self.ikProble...
identifier_body
index.go
// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // This file contains the infrastructure to create an // (identifier) index for a set of Go files. // // Basic indexing algorithm: // - traverse all .go files o...
run := &PakRun{pak, files}; sort.Sort(run); // files were sorted by package; sort them by file now return run; } // ---------------------------------------------------------------------------- // HitList // A HitList describes a list of PakRuns. type HitList []*PakRun // PakRuns are sorted by package. func les...
{ files[k] = h.At(i).(*FileRun); k++; }
conditional_block
index.go
// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // This file contains the infrastructure to create an // (identifier) index for a set of Go files. // // Basic indexing algorithm: // - traverse all .go files o...
func (x SpotInfo) Lori() int { return int(x >> 4) } func (x SpotInfo) IsIndex() bool { return x&1 != 0 } // ---------------------------------------------------------------------------- // KindRun // Debugging support. Disable to see multiple entries per line. const removeDuplicates = true // A KindRun is a run of...
{ return SpotKind(x >> 1 & 7) }
identifier_body
index.go
// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // This file contains the infrastructure to create an // (identifier) index for a set of Go files. // // Basic indexing algorithm: // - traverse all .go files o...
// ---------------------------------------------------------------------------- // RunList // A RunList is a vector of entries that can be sorted according to some // criteria. A RunList may be compressed by grouping "runs" of entries // which are equal (according to the sort critera) into a new RunList of // runs. ...
)
random_line_split
index.go
// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // This file contains the infrastructure to create an // (identifier) index for a set of Go files. // // Basic indexing algorithm: // - traverse all .go files o...
(s string) *AltWords { if len(a.Alts) == 1 && a.Alts[0] == s { // there are no different alternatives return nil } // make a new AltWords with the current spelling removed alts := make([]string, len(a.Alts)); i := 0; for _, w := range a.Alts { if w != s { alts[i] = w; i++; } } return &AltWords{a....
filter
identifier_name
allocator.rs
use std::rc::Rc; use std::cell::RefCell; use std::sync::{Arc, Mutex}; use std::any::Any; use std::sync::mpsc::{Sender, Receiver, channel}; use std::collections::VecDeque; use std::marker::PhantomData; use columnar::{Columnar, ColumnarStack}; use communication::{Pushable, Pullable}; use networking::networking::MessageH...
(&self) -> u64 { 1 } fn new_channel<T:'static>(&mut self) -> (Vec<Box<Pushable<T>>>, Box<Pullable<T>>) { let shared = Rc::new(RefCell::new(VecDeque::<T>::new())); return (vec![Box::new(shared.clone()) as Box<Pushable<T>>], Box::new(shared.clone()) as Box<Pullable<T>>) } } // A specific Communi...
peers
identifier_name
allocator.rs
use std::rc::Rc; use std::cell::RefCell; use std::sync::{Arc, Mutex}; use std::any::Any; use std::sync::mpsc::{Sender, Receiver, channel}; use std::collections::VecDeque; use std::marker::PhantomData; use columnar::{Columnar, ColumnarStack}; use communication::{Pushable, Pullable}; use networking::networking::MessageH...
} } } impl<T:Columnar+'static> Pushable<T> for BinaryPushable<T> { #[inline] fn push(&mut self, data: T) { let mut bytes = if let Some(buffer) = self.receiver.try_recv().ok() { buffer } else { Vec::new() }; bytes.clear(); self.stack.push(data); self.stack.encode(&mu...
sender: sender, receiver: receiver, phantom: PhantomData, buffer: Vec::new(), stack: Default::default(),
random_line_split
load_balancer.rs
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to i...
} } #[test] fn round_robin_load_balancer_policy() { let addresses = vec![ "127.0.0.1:8080".parse().unwrap(), "127.0.0.2:8080".parse().unwrap(), "127.0.0.3:8080".parse().unwrap(), ]; let yaml = " policy: ROUND_ROBIN "; let filter ...
{ assert_eq!(expected, result.unwrap(), "{}", name); }
conditional_block
load_balancer.rs
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to i...
{ #[serde(default)] policy: Policy, } impl TryFrom<ProtoConfig> for Config { type Error = ConvertProtoConfigError; fn try_from(p: ProtoConfig) -> Result<Self, Self::Error> { let policy = p .policy .map(|policy| { map_proto_enum!( valu...
Config
identifier_name
load_balancer.rs
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to i...
policy: Some(PolicyValue { value: ProtoPolicy::Random as i32, }), }, Some(Config { policy: Policy::Random, }), ), ( "RoundRobinPolicy", ...
fn convert_proto_config() { let test_cases = vec![ ( "RandomPolicy", ProtoConfig {
random_line_split
usher.go
/* usher is a tiny personal url shortener. This library provides the maintenance functions for our simple database of code => url mappings (a yaml file in filepath.join(os.UserConfigDir(), "usher")). */ package usher import ( "errors" "fmt" "io/ioutil" "math/rand" "os" "path/filepath" "regexp" "sort" "strin...
} if root == "" { // If root is still unset, default to "os.UserConfigDir()/usher" configDir, err := os.UserConfigDir() if err != nil { return nil, err } root = filepath.Join(configDir, "usher") } // Derive domain if not set - check for USHER_DOMAIN in environment if domain == "" { domain = os.Get...
{ cwd, err := os.Getwd() if err == nil { root = cwd } }
conditional_block
usher.go
/* usher is a tiny personal url shortener. This library provides the maintenance functions for our simple database of code => url mappings (a yaml file in filepath.join(os.UserConfigDir(), "usher")). */ package usher import ( "errors" "fmt" "io/ioutil" "math/rand" "os" "path/filepath" "regexp" "sort" "strin...
// randomCode is a utility function to generate a random code // and check that it doesn't exist in mappings. // Random codes use the following pattern: 1 digit, then 4-7 // lowercase ascii characters. This usually allows them to be // relatively easily distinguished from explicit codes, while // still being easy to ...
{ config, err := ioutil.ReadFile(db.ConfigPath) if err != nil { return err } config = append(config, []byte(data)...) tmpfile := db.ConfigPath + ".tmp" err = ioutil.WriteFile(tmpfile, config, 0600) if err != nil { return err } err = os.Rename(tmpfile, db.ConfigPath) if err != nil { return err } ret...
identifier_body
usher.go
/* usher is a tiny personal url shortener. This library provides the maintenance functions for our simple database of code => url mappings (a yaml file in filepath.join(os.UserConfigDir(), "usher")). */ package usher import ( "errors" "fmt" "io/ioutil" "math/rand" "os" "path/filepath" "regexp" "sort" "strin...
// Compile entries var entries = make([]Entry, len(mappings)) i = 0 for _, code := range codes { entries[i] = Entry{Code: code, Url: mappings[code]} i++ } return entries, nil } // Add a mapping for url and code to the database. // If code is missing, a random code will be generated and returned. func (db *D...
codes[i] = code i++ } sort.Strings(codes)
random_line_split
usher.go
/* usher is a tiny personal url shortener. This library provides the maintenance functions for our simple database of code => url mappings (a yaml file in filepath.join(os.UserConfigDir(), "usher")). */ package usher import ( "errors" "fmt" "io/ioutil" "math/rand" "os" "path/filepath" "regexp" "sort" "strin...
(mappings map[string]string) string { rand.Seed(time.Now().UnixNano()) var b strings.Builder b.WriteByte(digits[rand.Intn(len(digits))]) for i := 1; i < maxRandomCodeLen; i++ { b.WriteByte(chars[rand.Intn(len(chars))]) // If long enough, check if exists in mappings, and return if not if i+1 >= minRandomCodeLe...
randomCode
identifier_name
forall.rs
use itertools::Itertools; use std::collections::HashMap; use std::collections::HashSet; use crate::Line; use crate::Constraint; use crate::Problem; use indicatif::ProgressStyle; use indicatif::ProgressBar; use chrono::prelude::*; struct Comb{ max : Vec<usize>, state : Vec<usize>, first : bool } impl Comb ...
return None; } if v[i] > 0 { v[i+1] += 1; v[i] -= 1; if v[i+1] <= m[i+1] { break; } } i += 1; } let mut res ...
random_line_split
forall.rs
use itertools::Itertools; use std::collections::HashMap; use std::collections::HashSet; use crate::Line; use crate::Constraint; use crate::Problem; use indicatif::ProgressStyle; use indicatif::ProgressBar; use chrono::prelude::*; struct Comb{ max : Vec<usize>, state : Vec<usize>, first : bool } impl Comb...
} } } } } let mut groups = Vec::with_capacity(delta); groups.push(uni.clone()); for (i,(ga,_)) in c1.iter().enumerate() { for (j,(gb,_)) in c2.iter().enumerate() { for _ in 0..x[i].state...
{ let u1 = c1[i1].0.clone() & c2[j1].0.clone(); let u2 = c1[i2].0.clone() & c2[j2].0.clone(); let u3 = c1[i1].0.clone() & c2[j2].0.clone(); let u4 = c1[i2].0.clone() & c2[j1].0.clone(); ...
conditional_block
forall.rs
use itertools::Itertools; use std::collections::HashMap; use std::collections::HashSet; use crate::Line; use crate::Constraint; use crate::Problem; use indicatif::ProgressStyle; use indicatif::ProgressBar; use chrono::prelude::*; struct Comb{ max : Vec<usize>, state : Vec<usize>, first : bool } impl Comb...
fn transform(&mut self, n : usize, max : impl Iterator<Item=usize>) { let mut i = 0; for x in max { self.max[i] = x; i += 1; } assert!(i == self.max.len()); let mut res = n; let mut i = 0; while res > 0 { let cur = std::cm...
{ let mut state = vec![0;max.len()]; let mut res = n; let mut i = 0; while res > 0 { let cur = std::cmp::min(max[i],res); state[i] = cur; res -= cur; i += 1; } Comb { max, state, first:true } }
identifier_body
forall.rs
use itertools::Itertools; use std::collections::HashMap; use std::collections::HashSet; use crate::Line; use crate::Constraint; use crate::Problem; use indicatif::ProgressStyle; use indicatif::ProgressBar; use chrono::prelude::*; struct Comb{ max : Vec<usize>, state : Vec<usize>, first : bool } impl Comb...
{ state : Vec<Comb>, first : bool, v1 : Vec<usize> } impl Matches { fn new(v1 : Vec<usize>, mut v2 : Vec<usize>) -> Self { let mut s = vec![]; for &x in &v1 { let mut c = Comb::new(x,v2.clone()); c.next(); for i in 0..v2.len() { v2[i]...
Matches
identifier_name
api_op_CreateFleet.go
// Code generated by smithy-go-codegen DO NOT EDIT. package gamelift import ( "context" "errors" "fmt" "github.com/aws/aws-sdk-go-v2/aws" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" "github.com/aws/aws-sdk-go-v2/aws/signer/v4" internalauth "github.com/aws/aws-sdk-go-v2/internal/auth" "github.c...
type CreateFleetInput struct { // A descriptive label that is associated with a fleet. Fleet names do not need to // be unique. // // This member is required. Name *string // Amazon GameLift Anywhere configuration options. AnywhereConfiguration *types.AnywhereConfiguration // The unique identifier for a cu...
{ if params == nil { params = &CreateFleetInput{} } result, metadata, err := c.invokeOperation(ctx, "CreateFleet", params, optFns, c.addOperationCreateFleetMiddlewares) if err != nil { return nil, err } out := result.(*CreateFleetOutput) out.ResultMetadata = metadata return out, nil }
identifier_body
api_op_CreateFleet.go
// Code generated by smithy-go-codegen DO NOT EDIT. package gamelift import ( "context" "errors" "fmt" "github.com/aws/aws-sdk-go-v2/aws" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" "github.com/aws/aws-sdk-go-v2/aws/signer/v4" internalauth "github.com/aws/aws-sdk-go-v2/internal/auth" "github.c...
// computing resources for your fleet and provide instructions for running game // servers on each instance. Most Amazon GameLift fleets can deploy instances to // multiple locations, including the home Region (where the fleet is created) and // an optional set of remote locations. Fleets that are created in the follow...
) // Creates a fleet of Amazon Elastic Compute Cloud (Amazon EC2) instances to host // your custom game server or Realtime Servers. Use this operation to configure the
random_line_split
api_op_CreateFleet.go
// Code generated by smithy-go-codegen DO NOT EDIT. package gamelift import ( "context" "errors" "fmt" "github.com/aws/aws-sdk-go-v2/aws" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" "github.com/aws/aws-sdk-go-v2/aws/signer/v4" internalauth "github.com/aws/aws-sdk-go-v2/internal/auth" "github.c...
err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpCreateFleet{}, middleware.After) if err != nil { return err } if err = addlegacyEndpointContextSetter(stack, options); err != nil { return err } if err = addSetLoggerMiddleware(stack, options); err != nil { return err } if err = awsmiddleware.AddClie...
{ return err }
conditional_block
api_op_CreateFleet.go
// Code generated by smithy-go-codegen DO NOT EDIT. package gamelift import ( "context" "errors" "fmt" "github.com/aws/aws-sdk-go-v2/aws" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" "github.com/aws/aws-sdk-go-v2/aws/signer/v4" internalauth "github.com/aws/aws-sdk-go-v2/internal/auth" "github.c...
(ctx context.Context, params *CreateFleetInput, optFns ...func(*Options)) (*CreateFleetOutput, error) { if params == nil { params = &CreateFleetInput{} } result, metadata, err := c.invokeOperation(ctx, "CreateFleet", params, optFns, c.addOperationCreateFleetMiddlewares) if err != nil { return nil, err } out...
CreateFleet
identifier_name
policy_handler.rs
// Copyright 2020 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use crate::base::SettingType; use crate::handler::base::{Payload as HandlerPayload, Request, Response as SettingResponse}; use crate::handler::setting_hand...
}
{ let setting_type = SettingType::Unknown; let service_delegate = service::MessageHub::create_hub(); let (_, mut receptor) = service_delegate .create(MessengerType::Addressable(service::Address::Handler(setting_type))) .await .expect("service receptor create...
identifier_body
policy_handler.rs
// Copyright 2020 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use crate::base::SettingType; use crate::handler::base::{Payload as HandlerPayload, Request, Response as SettingResponse}; use crate::handler::setting_hand...
( &self, policy_info: PolicyInfo, id: ftrace::Id, ) -> Result<UpdateState, PolicyError> { let policy_type = (&policy_info).into(); let mut receptor = self .service_messenger .message( storage::Payload::Request(storage::StorageRequest::W...
write_policy
identifier_name
policy_handler.rs
// Copyright 2020 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use crate::base::SettingType; use crate::handler::base::{Payload as HandlerPayload, Request, Response as SettingResponse}; use crate::handler::setting_hand...
impl ClientProxy { /// Sends a setting request to the underlying setting proxy this policy handler controls. pub(crate) fn send_setting_request( &self, setting_type: SettingType, request: Request, ) -> service::message::Receptor { self.service_messenger .message(...
random_line_split
projectsvmglove.py
# -*- coding: utf-8 -*- """ProjectSVMGlove.ipynb Automatically generated by Colaboratory. Original file is located at https://colab.research.google.com/drive/1oP_lPuxcr0qYni8HvGSS-rCFlUCtfUYE """ import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import warnings ...
''' Translate word . ''' def translate(word): return translator.translate(word,src='hi' , dest='en').text ''' Self defined contractions ''' def load_dict_contractions(): return { "ain't":"is not", "amn't":"am not", "aren't":"are not", "can't":"canno...
if w == 'h': return 'hai' elif w == 'n': return 'na' elif w == 'da': return 'the' elif w == 'wid': return 'with' elif w == 'pr': return 'par' elif w == 'mattt': return 'mat' elif w == 'vo': return 'woh' elif w == 'ki': ...
identifier_body
projectsvmglove.py
# -*- coding: utf-8 -*- """ProjectSVMGlove.ipynb Automatically generated by Colaboratory. Original file is located at https://colab.research.google.com/drive/1oP_lPuxcr0qYni8HvGSS-rCFlUCtfUYE """ import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import warnings ...
# standardization from sklearn.preprocessing import StandardScaler sc = StandardScaler() x_train = sc.fit_transform(x_train) x_valid = sc.transform(x_valid) x_test = sc.transform(combinedFeatures_test) ''' Random Forest Classifer ''' from sklearn.ensemble import RandomForestClassifier from sklearn....
print(x_valid.shape) print(y_train.shape) print(y_valid.shape) print(combinedFeatures_test.shape)
random_line_split
projectsvmglove.py
# -*- coding: utf-8 -*- """ProjectSVMGlove.ipynb Automatically generated by Colaboratory. Original file is located at https://colab.research.google.com/drive/1oP_lPuxcr0qYni8HvGSS-rCFlUCtfUYE """ import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import warnings ...
elif w == 'goood': return 'very good' elif w == 'tera': return 'teraa' elif w == 'cnfsn': return 'confusion' elif w == 'ka': return 'kaa' elif w == 'rkhi': return 'rakhi' elif w == 'thts': return 'thats' elif w == 'cald': ...
return 'bas'
conditional_block
projectsvmglove.py
# -*- coding: utf-8 -*- """ProjectSVMGlove.ipynb Automatically generated by Colaboratory. Original file is located at https://colab.research.google.com/drive/1oP_lPuxcr0qYni8HvGSS-rCFlUCtfUYE """ import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import warnings ...
(sentence): final_sent ="" res = " ".join(long_form_dict.get(ele, ele) for ele in sentence.split()) for word in res.split(): final_sent += (handle_short_forms(word))+ " " return final_sent data.shape l=[] for sent in data.sentence_eng: l.append(expand_sent(sent)) print(l[2:5]) ...
expand_sent
identifier_name
main.py
""" Pensando no uso de micro serviços, esse arquivo contem o conteudo (python) das funções que serão colocadas na AWS utilizando o framework Serverless. O frameWork Serverless é utilizado para fazer o deploy do código na AWS, sua utilização é interessante, pois o framework pode ser utilizado para outros serviços como G...
'headers': {'Accept': '*/*', 'Accept-Encoding': 'gzip, deflate, br', 'CloudFront-Forwarded-Proto': 'https', 'CloudFront-Is-Desktop-Viewer': 'true', 'CloudFront-Is-Mobile-Viewer': 'false', 'CloudFront-Is-SmartTV-Viewer': 'false', 'CloudFront-Is-Tablet-Viewer': 'false', 'CloudFront-Viewer-Countr...
'principalId': '', 'stage': 'dev', 'cognitoPoolClaims': {'sub': ''}, 'enhancedAuthContext': {},
random_line_split
main.py
""" Pensando no uso de micro serviços, esse arquivo contem o conteudo (python) das funções que serão colocadas na AWS utilizando o framework Serverless. O frameWork Serverless é utilizado para fazer o deploy do código na AWS, sua utilização é interessante, pois o framework pode ser utilizado para outros serviços como G...
""" DELETE - Esse código será chamado através de um DELETE para a API que será criada no arquivo serverless. Faz a requisição para apagar uma solicitação de cartão. :param event: Event recebido pela nuvem :param context: Contexto com informações da função :return: JSON contendo informações sobre a ...
rá chamado através de um POST para a API que será criada no arquivo serverless. Faz a requisição de um novo cartão, o Score do candidato será avaliado. :param event: Event recebido pela nuvem :param context: Contexto com informações da função :return: JSON contendo informações sobre a solicitação realiz...
identifier_body
main.py
""" Pensando no uso de micro serviços, esse arquivo contem o conteudo (python) das funções que serão colocadas na AWS utilizando o framework Serverless. O frameWork Serverless é utilizado para fazer o deploy do código na AWS, sua utilização é interessante, pois o framework pode ser utilizado para outros serviços como G...
r: return {'status': 500, 'msg': 'Erro interno ao processar a requisição'} def request_new_card_handler(event, context): """ POST - Esse código será chamado através de um POST para a API que será criada no arquivo serverless. Faz a requisição de um novo cartão, o Score do candidato será avaliado. ...
msg': 'Lista de requisições não encontrada'} except Exception as er
conditional_block
main.py
""" Pensando no uso de micro serviços, esse arquivo contem o conteudo (python) das funções que serão colocadas na AWS utilizando o framework Serverless. O frameWork Serverless é utilizado para fazer o deploy do código na AWS, sua utilização é interessante, pois o framework pode ser utilizado para outros serviços como G...
será criada no arquivo serverless. Recebe o id do solicitante via parametro de URL e retorna as informações referente ao solicitante e seu crédito :param event: Event recebido pela nuvem :param context: Contexto com informações da função :return: informações do solicitante """ try: s3_bu...
ado através de um GET para a API que
identifier_name
config.go
package config import ( "bytes" "encoding/json" "fmt" "io" "log" "os" "path" "path/filepath" "sort" "strings" version "github.com/hashicorp/go-version" "github.com/pkg/errors" "github.com/yext/edward/services" ) // Config defines the structure for the Edward project configuration file type Config struct...
if _, ok := commonMap[s]; !ok { outSlice = append(outSlice, s) } } return outSlice }
for _, s := range common { commonMap[s] = struct{}{} } var outSlice []string for _, s := range original {
random_line_split
config.go
package config import ( "bytes" "encoding/json" "fmt" "io" "log" "os" "path" "path/filepath" "sort" "strings" version "github.com/hashicorp/go-version" "github.com/pkg/errors" "github.com/yext/edward/services" ) // Config defines the structure for the Edward project configuration file type Config struct...
func (c *Config) loadImports() error { log.Printf("Loading imports\n") for _, i := range c.Imports { var cPath string if filepath.IsAbs(i) { cPath = i } else { cPath = filepath.Join(c.workingDir, i) } log.Printf("Loading: %v\n", cPath) r, err := os.Open(cPath) if err != nil { return errors....
{ log.Printf("Adding %d groups.\n", len(groups)) for _, group := range groups { grp := GroupDef{ Name: group.Name, Aliases: group.Aliases, Description: group.Description, Children: []string{}, Env: group.Env, } for _, cg := range group.Groups { if cg != nil { grp.Chil...
identifier_body
config.go
package config import ( "bytes" "encoding/json" "fmt" "io" "log" "os" "path" "path/filepath" "sort" "strings" version "github.com/hashicorp/go-version" "github.com/pkg/errors" "github.com/yext/edward/services" ) // Config defines the structure for the Edward project configuration file type Config struct...
(groups []services.ServiceGroupConfig) error { log.Printf("Adding %d groups.\n", len(groups)) for _, group := range groups { grp := GroupDef{ Name: group.Name, Aliases: group.Aliases, Description: group.Description, Children: []string{}, Env: group.Env, } for _, cg := range ...
AddGroups
identifier_name
config.go
package config import ( "bytes" "encoding/json" "fmt" "io" "log" "os" "path" "path/filepath" "sort" "strings" version "github.com/hashicorp/go-version" "github.com/pkg/errors" "github.com/yext/edward/services" ) // Config defines the structure for the Edward project configuration file type Config struct...
c.ServiceMap = svcs c.GroupMap = groups return nil } func hasChildCycle(parent *services.ServiceGroupConfig, children []*services.ServiceGroupConfig) bool { for _, sg := range children { if parent == sg { return true } if hasChildCycle(parent, sg.Groups) { return true } } return false } func str...
{ var keys []string for k := range orphanNames { keys = append(keys, k) } return errors.New("A service or group could not be found for the following names: " + strings.Join(keys, ", ")) }
conditional_block
scriptAppoint.js
// Setup the calendar with the current date $(document).ready(function () { var date = new Date(); // Date() imprime la fecha actual hora y día. var today = date.getDate(); /* devuelve el dia del mes, hoy 4 */ var mes = date.getMonth(); /* Obtiene el numero indicado del mes */ var anio= date.getFullYear(); ...
} return error; } function validatePhone(tel) { var error = ""; var stripped = tel.value.replace(/[\(\)\.\-\ ]/g, ''); if (tel.value == "" || tel.value==null) { error = "No ingresó un número de teléfono..\n"; tel.style.background = 'red'; } else if (isNaN(parseInt(stripped))) { error = "El...
or = "Verifique el campo cita, antes de seguir\n" } else { cita.style.background = 'White';
conditional_block
scriptAppoint.js
// Setup the calendar with the current date $(document).ready(function () { var date = new Date(); // Date() imprime la fecha actual hora y día. var today = date.getDate(); /* devuelve el dia del mes, hoy 4 */ var mes = date.getMonth(); /* Obtiene el numero indicado del mes */ var anio= date.getFullYear(); ...
"day": 10, "cancelled": true }, { "occasion": " Repeated Test Event ", "invited_count": 120, "year": 2017, "month": 5, "day": 10 }, { "occasion": " Repeated Test Event ", "invited_count": 120, "year": 2017, "month": 5, "day": 10, "cancelled": true }, ...
"occasion": " Repeated Test Event ", "invited_count": 120, "year": 2017, "month": 5,
random_line_split
scriptAppoint.js
// Setup the calendar with the current date $(document).ready(function () { var date = new Date(); // Date() imprime la fecha actual hora y día. var today = date.getDate(); /* devuelve el dia del mes, hoy 4 */ var mes = date.getMonth(); /* Obtiene el numero indicado del mes */ var anio= date.getFullYear(); ...
how(250); //$(".horariosss").show(250); //$(".horariosss").show(250); ban=0; ban2=0; document.getElementById('fechaId').innerHTML = ""; document.getElementById('horaId').innerHTML = ""; document.getElementById('name').innerHTML = ""; document.getElementById('cita').innerHTML = ""; document.getElementB...
identifier_body
scriptAppoint.js
// Setup the calendar with the current date $(document).ready(function () { var date = new Date(); // Date() imprime la fecha actual hora y día. var today = date.getDate(); /* devuelve el dia del mes, hoy 4 */ var mes = date.getMonth(); /* Obtiene el numero indicado del mes */ var anio= date.getFullYear(); ...
llegalChars = /\W/; // permite letras, números y guiones bajos if (nombre.value == "" || nombre.value == null || (/^\s+$/.test(nombre.value))) { nombre.style.background = 'red'; error="La caja para nombre no contiene nada...\n"; nombre.focus(); }else if ((nombre.length < 3) || (nombre.length > 30)) { no...
; // var i
identifier_name
example_all.py
import numpy as np from functools import partial from tqdm import tqdm import nlopt import matplotlib.pylab as plt import bbq.models.rff as ff from bbq.examples.utils import toy_functions from bbq.examples.utils.train_model import train_model from bbq.examples.utils.saveResults import ResultSaver from bbq.utils.enums ...
opt.set_max_objective(_fun_maximize) init_opt = np.random.uniform(0, 1, len(paramLow)) * \ (paramHigh - paramLow) + paramLow opt.optimize(init_opt) pbar.close() """ Saving """ # Compute best quantile imax = np.argmax(score) curParams = allParams[imax, :] if learnBeta: curParams = ...
global i if i == nlOptIter: print("Warning: maximum number of iterations reached.") return float(np.min(score)) allParams[i, :] = _x if learnBeta: global blrBeta blrBeta = 10 ** (allParams[i, 0]) curParams = allParams[i, 1:] els...
identifier_body
example_all.py
import numpy as np from functools import partial from tqdm import tqdm import nlopt import matplotlib.pylab as plt import bbq.models.rff as ff from bbq.examples.utils import toy_functions from bbq.examples.utils.train_model import train_model from bbq.examples.utils.saveResults import ResultSaver from bbq.utils.enums ...
(_x, grad): global i if i == nlOptIter: print("Warning: maximum number of iterations reached.") return float(np.min(score)) allParams[i, :] = _x if learnBeta: global blrBeta blrBeta = 10 ** (allParams[i, 0]) curParams = allParam...
_fun_maximize
identifier_name
example_all.py
import numpy as np from functools import partial from tqdm import tqdm import nlopt import matplotlib.pylab as plt import bbq.models.rff as ff from bbq.examples.utils import toy_functions from bbq.examples.utils.train_model import train_model from bbq.examples.utils.saveResults import ResultSaver from bbq.utils.enums ...
for idx, y in zip(testIdx, pred_test): predImg[idx[0], idx[1]] = y predImgPrcs = np.clip(predImg, -1, 1) rs.save_pred_image(predImgPrcs) if len(paramLow) - 1 * learnBeta == 2: # Plot score map if searchStrategy == "BO" or searchStrategy == "NLopt": plotRes = 64 X, Y = np.mesh...
predImg[idx[0], idx[1]] = y
conditional_block
example_all.py
import numpy as np from functools import partial from tqdm import tqdm import nlopt import matplotlib.pylab as plt import bbq.models.rff as ff from bbq.examples.utils import toy_functions from bbq.examples.utils.train_model import train_model from bbq.examples.utils.saveResults import ResultSaver from bbq.utils.enums ...
""" Search/optimisation for best quantile """ if useARDkernel: paramLow = np.array(D * list(paramLow)) paramHigh = np.array(D * list(paramHigh)) qp.logScaleParams = np.array(D * list(qp.logScaleParams)) if learnBeta: paramLow = np.array([-3] + list(paramLow)) paramHigh = np.array([3] + list(paramHig...
paramLow = qp.paramLow paramHigh = qp.paramHigh
random_line_split
lib.rs
//! This is a platform-agnostic Rust driver for the ADS1013, ADS1014, ADS1015, //! ADS1113, ADS1114, and ADS1115 ultra-small, low-power //! analog-to-digital converters (ADC), based on the [`embedded-hal`] traits. //! //! [`embedded-hal`]: https://github.com/rust-embedded/embedded-hal //! //! This driver allows you to:...
//! ```no_run //! use linux_embedded_hal::I2cdev; //! use ads1x1x::{Ads1x1x, SlaveAddr}; //! //! let dev = I2cdev::new("/dev/i2c-1").unwrap(); //! let (bit1, bit0) = (true, false); // last two bits of address //! let address = SlaveAddr::Alternative(bit1, bit0); //! let adc = Ads1x1x::new_ads1013(dev, address); //! ```...
random_line_split
lib.rs
//! This is a platform-agnostic Rust driver for the ADS1013, ADS1014, ADS1015, //! ADS1113, ADS1114, and ADS1115 ultra-small, low-power //! analog-to-digital converters (ADC), based on the [`embedded-hal`] traits. //! //! [`embedded-hal`]: https://github.com/rust-embedded/embedded-hal //! //! This driver allows you to:...
impl Register { const CONVERSION: u8 = 0x00; const CONFIG: u8 = 0x01; const LOW_TH: u8 = 0x02; const HIGH_TH: u8 = 0x03; } struct BitFlags; impl BitFlags { const OS: u16 = 0b1000_0000_0000_0000; const MUX2: u16 = 0b0100_0000_0000_0000; const MUX1: u16 = 0b0010_0000_0000_0000; const MUX0...
gister;
identifier_name
shear_calculation_withoutplot_vasp.py
# ################################### #2018-04-11 #Jin Zhang@Stony Brook University ###################################### ###For VASP ###----------------------------------Readme------------------------------------------------------------ ###This script is to calculate the Tensile strength and shear strength using VAS...
###### Fourthly, performing VASP calculation for i in np.arange(stra,stra*(times+1),stra): print("****************************") i=round(i,2) print(i) postrain("POSCAR") os.system("cp POSCAR_stra POSCAR") os.system("cp POSCAR_stra POSCAR_"+str(i))#### #os.system("bsub < Job_qsh.sh") os...
t2=[] t3=[] with open (poscar) as poscar2: pos2=poscar2.readlines() length=len(pos2) for i in range(2,5): j=pos2[i] j=j.split() t2.extend(j) for i in range(len(t2)): t3.extend([float(t2[i])]) pos_array3=np.array(t3).reshape((3,3)) ...
identifier_body
shear_calculation_withoutplot_vasp.py
# ################################### #2018-04-11 #Jin Zhang@Stony Brook University ###################################### ###For VASP ###----------------------------------Readme------------------------------------------------------------ ###This script is to calculate the Tensile strength and shear strength using VAS...
(poscar): t2=[] t3=[] with open (poscar) as poscar2: pos2=poscar2.readlines() length=len(pos2) for i in range(2,5): j=pos2[i] j=j.split() t2.extend(j) for i in range(len(t2)): t3.extend([float(t2[i])]) pos_array3=np.array(t3).r...
postrain
identifier_name
shear_calculation_withoutplot_vasp.py
# ################################### #2018-04-11 #Jin Zhang@Stony Brook University ###################################### ###For VASP ###----------------------------------Readme------------------------------------------------------------ ###This script is to calculate the Tensile strength and shear strength using VAS...
u.close() os.system("rm POSCAR_stra")
print("****************************") i=round(i,2) print(i) postrain("POSCAR") os.system("cp POSCAR_stra POSCAR") os.system("cp POSCAR_stra POSCAR_"+str(i))#### #os.system("bsub < Job_qsh.sh") os.system("srun -n 20 /scratch/jin.zhang3_397857/Software/vasp.5.4.4/bin/vasp_std > vasp.out") ...
conditional_block
shear_calculation_withoutplot_vasp.py
# ################################### #2018-04-11 #Jin Zhang@Stony Brook University ###################################### ###For VASP ###----------------------------------Readme------------------------------------------------------------ ###This script is to calculate the Tensile strength and shear strength using VAS...
for line in poscar1: r.append(line) f=open("POSCAR_rota","w") #write POSCAR after rotation as POSCAR_rota for i in range(0,2): f.write(r[i]) for j in range(len(a_LK_rot)): f.write(str(a_LK_rot[j][0])+' ') f.write(str(a_LK_rot[j][1])+' ') f.write(str(a_LK_rot[j][2])) f.write('\n') for x...
os.system("cp POSCAR POSCAR_original") #copy original POSCAR r=[] with open ("POSCAR") as poscar1:
random_line_split
lib.rs
#![cfg_attr(not(feature = "std"), no_std)] #[allow(unused)] #[cfg(all(feature = "std", test))] mod mock; #[cfg(all(feature = "std", test))] mod tests; #[cfg(not(feature = "std"))] use rstd::borrow::ToOwned; use rstd::{cmp, fmt::Debug, mem, prelude::*, result}; use sr_primitives::{ traits::{ Bounded, CheckedAdd, Ch...
<T: Trait>(T::Balance); impl<T: Trait> NegativeImbalance<T> { /// Create a new negative imbalance from a balance. pub fn new(amount: T::Balance) -> Self { NegativeImbalance(amount) } } impl<T: Trait> Imbalance<T::Balance> for PositiveImbalance<T> { type Opposite = NegativeImbalance<T>; fn zero() -> S...
NegativeImbalance
identifier_name
lib.rs
#![cfg_attr(not(feature = "std"), no_std)] #[allow(unused)] #[cfg(all(feature = "std", test))] mod mock; #[cfg(all(feature = "std", test))] mod tests; #[cfg(not(feature = "std"))] use rstd::borrow::ToOwned; use rstd::{cmp, fmt::Debug, mem, prelude::*, result}; use sr_primitives::{ traits::{ Bounded, CheckedAdd, Ch...
impl<T: Trait> Drop for PositiveImbalance<T> { /// Basic drop handler will just square up the total issuance. fn drop(&mut self) { <super::TotalIssuance<T>>::mutate(|v| *v = v.saturating_add(self.0)); } } impl<T: Trait> Drop for NegativeImbalance<T> { /// Basic drop handler will just square up the total...
random_line_split
lib.rs
#![cfg_attr(not(feature = "std"), no_std)] #[allow(unused)] #[cfg(all(feature = "std", test))] mod mock; #[cfg(all(feature = "std", test))] mod tests; #[cfg(not(feature = "std"))] use rstd::borrow::ToOwned; use rstd::{cmp, fmt::Debug, mem, prelude::*, result}; use sr_primitives::{ traits::{ Bounded, CheckedAdd, Ch...
// # <weight> // Despite iterating over a list of locks, they are limited by the number of // lock IDs, which means the number of runtime modules that intend to use and create locks. // # </weight> fn ensure_can_withdraw( who: &T::AccountId, _amount: T::Balance, reasons: WithdrawReasons, new_balance: T::...
{ <FreeBalance<T>>::get(who) }
identifier_body
lib.rs
#![cfg_attr(not(feature = "std"), no_std)] #[allow(unused)] #[cfg(all(feature = "std", test))] mod mock; #[cfg(all(feature = "std", test))] mod tests; #[cfg(not(feature = "std"))] use rstd::borrow::ToOwned; use rstd::{cmp, fmt::Debug, mem, prelude::*, result}; use sr_primitives::{ traits::{ Bounded, CheckedAdd, Ch...
} fn split(self, amount: T::Balance) -> (Self, Self) { let first = self.0.min(amount); let second = self.0 - first; mem::forget(self); (Self(first), Self(second)) } fn merge(mut self, other: Self) -> Self { self.0 = self.0.saturating_add(other.0); mem::forget(other); self } fn subsum...
{ Err(self) }
conditional_block
query.py
import requests import json import csv import datetime import time from collections import defaultdict import sys import os import glob import logging import pandas as pd json_query = ''' { "query": { "bool": { "filter": [ { "terms": { "metricset.name": [ "POP_t...
if __name__ == "__main__": cache() nsid = '1' tunoip = '10.0.1.214->10.0.1.213' # ta = '2019-10-30 13:00:00' # tb = '2019-10-30 14:05:00' # ta = None # df = query(nsid, tunoip, data_dir='/home/monitor/data') # print(proname) # print(data['over_drop']) # print(data['over_drop'].as...
random_line_split
query.py
import requests import json import csv import datetime import time from collections import defaultdict import sys import os import glob import logging import pandas as pd json_query = ''' { "query": { "bool": { "filter": [ { "terms": { "metricset.name": [ "POP_...
if os.path.exists(csv_path): logging.info('Read data from %s'%csv_path) df = pd.read_csv(csv_path) logging.info('Time range: [{}, {}]'.format(df.iloc[0]['timestamp'], df.iloc[-1]['timestamp'])) begin_time = datetime.datetime.fromisoformat(df.iloc[-1]['timestamp']) + datetime.timedelta(...
ime, end_time))
conditional_block
query.py
import requests import json import csv import datetime import time from collections import defaultdict import sys import os import glob import logging import pandas as pd json_query = ''' { "query": { "bool": { "filter": [ { "terms": { "metricset.name": [ "POP_...
cache() nsid = '1' tunoip = '10.0.1.214->10.0.1.213' # ta = '2019-10-30 13:00:00' # tb = '2019-10-30 14:05:00' # ta = None # df = query(nsid, tunoip, data_dir='/home/monitor/data') # print(proname) # print(data['over_drop']) # print(data['over_drop'].astype(float)) # a = df['...
t' logging.basicConfig(level=logging.INFO, format='[%(asctime)s] %(levelname)s: %(message)s', datefmt='%Y-%m-%d %H:%M:%S') if __name__ == "__main__":
identifier_body
query.py
import requests import json import csv import datetime import time from collections import defaultdict import sys import os import glob import logging import pandas as pd json_query = ''' { "query": { "bool": { "filter": [ { "terms": { "metricset.name": [ "POP_...
defaultdict(str) pair_dict['timestamp'] = datetime.datetime.fromtimestamp(float(a['_source']['timestamp'])/1000) if len(a['_source']['tags']) > 0: pair_dict['tags'] = a['_source']['tags'][0]['value'] if len(a['_source']['tags']) > 1: print('Warning:', ...
pair_dict =
identifier_name
day.page.ts
import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { SyncService } from 'src/app/services/sync.service'; import { LoadingController, Platform } from '@ionic/angular'; import { DatePipe, getLocaleDateTimeFormat } from '@angular/common'; import { DatePicker } from '@ionic-...
ngOnInit() { } share() { // this.getData(); this.createPdf(); } back() { this.router.navigate(['/menu/reports']); } onActivate(event) { if (event.type === 'click') { console.log(event.row); } } async getData() { let loading = await this.loadingCtrl.create(); await loading...
{ const last = new Date(new Date().getFullYear(), 11, 31); this.max = this.datePipe.transform(last, 'yyyy'); this.storage.get('COM').then((val) => { this.company = val; }); storage.get('currency').then((val) => { if (val !== null) { this.currency = val.toString(); deb...
identifier_body
day.page.ts
import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { SyncService } from 'src/app/services/sync.service'; import { LoadingController, Platform } from '@ionic/angular'; import { DatePipe, getLocaleDateTimeFormat } from '@angular/common'; import { DatePicker } from '@ionic-...
} }
{ // On a browser simply use download! this.pdfObj.download(); }
conditional_block
day.page.ts
import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { SyncService } from 'src/app/services/sync.service'; import { LoadingController, Platform } from '@ionic/angular'; import { DatePipe, getLocaleDateTimeFormat } from '@angular/common'; import { DatePicker } from '@ionic-...
// this.file.writeFile(this.file.dataDirectory, 'Invoice4.pdf', blob).then(fileEntry => { // this.fileOpener.open(this.file.dataDirectory + 'Invoice.pdf', 'application/pdf'); // }); }); } else { // On a browser simply use download! this.pdfObj.download(); } }...
}); debugger // Save the PDF to the data Directory of our App
random_line_split
day.page.ts
import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { SyncService } from 'src/app/services/sync.service'; import { LoadingController, Platform } from '@ionic/angular'; import { DatePipe, getLocaleDateTimeFormat } from '@angular/common'; import { DatePicker } from '@ionic-...
implements OnInit { style = 'bootstrap'; data = []; items = []; total = []; day = new Date().toString(); start = new Date().setHours(0, 0, 0, 0).toString(); end = new Date().setHours(23, 59, 59, 999).toString(); i = 0; currency = ''; pdfObj = null; company = ''; displaystart = ''; displayend ...
DayPage
identifier_name
models.py
import torch import torch.nn as nn import torch.nn.functional as F import math import yaml import nn_utils from sys_utils import _single_instance_logger as logger def make_divisible(x, divisor): # Returns x evenly divisble by divisor return math.ceil(x / divisor) * divisor def autopad(kernel, padding=None):...
args = [self.parse_string(a) for a in args] module_function = eval(module_name) if repeat_count > 1: repeat_count = max(round(repeat_count * depth_multiple), 1) if module_function in [Conv, Bottleneck, SPP, Focus, BottleneckCSP]: ...
all_layers_channels = [input_channel] all_layers = [] saved_layer_index = [] for layer_index, (from_index, repeat_count, module_name, args) in enumerate(all_layers_cfg_list):
random_line_split
models.py
import torch import torch.nn as nn import torch.nn.functional as F import math import yaml import nn_utils from sys_utils import _single_instance_logger as logger def make_divisible(x, divisor): # Returns x evenly divisble by divisor
def autopad(kernel, padding=None): # kernel, padding # Pad to 'same' if padding is None: padding = kernel // 2 if isinstance(kernel, int) else [x // 2 for x in kernel] # auto-pad return padding class Conv(nn.Module): ''' 标准卷积层 ''' def __init__(self, in_channel, out_channel, ke...
return math.ceil(x / divisor) * divisor
identifier_body
models.py
import torch import torch.nn as nn import torch.nn.functional as F import math import yaml import nn_utils from sys_utils import _single_instance_logger as logger def make_divisible(x, divisor): # Returns x evenly divisble by divisor return math.ceil(x / divisor) * divisor def autopad(kernel, padding=None):...
strides = [8, 16, 32] for head, stride in zip(self.m, strides): bias = head.bias.view(self.num_anchor, -1) bias[:, 4] += math.log(8 / (640 / stride) ** 2) bias[:, 5:] += math.log(0.6 / (self.num_classes - 0.99)) head.bias = nn.Parameter(bias.view(-1), requir...
def init_weight(self):
conditional_block
models.py
import torch import torch.nn as nn import torch.nn.functional as F import math import yaml import nn_utils from sys_utils import _single_instance_logger as logger def make_divisible(x, divisor): # Returns x evenly divisble by divisor return math.ceil(x / divisor) * divisor def autopad(kernel, padding=None):...
d) class Detect(nn.Module): def __init__(self, num_classes, num_anchor, reference_channels): super(Detect, self).__init__() self.num_anchor = num_anchor self.num_classes = num_classes self.num_output = self.num_classes + 5 self.m = nn.ModuleList(nn.Conv2d(input_channel, sel...
m=self.
identifier_name
filetrace_test.go
package libbusyna import ( "io/ioutil" "os" "reflect" "regexp" "strings" "testing" ) // TestStraceRun tests basic strace execution. func TestStraceRun(t *testing.T) { StraceRun("echo asdf > /dev/null", nil, "") } // Example strace file used to test parsers. var straceout = []string{ `16819 stat64("/usr/bin/u...
}() data, err := ioutil.ReadFile("e.txt") if err != nil { t.Fatal(err) } datastr := string(data) if !strings.Contains(datastr, "x=y") { t.Fatalf("environment x=y not found in %s", datastr) } } // TestFiletraceDir tests the dir argument. func TestFiletraceDir(t *testing.T) { os.Mkdir("d", 0755) filetrace...
{ t.Error(err) }
conditional_block
filetrace_test.go
package libbusyna import ( "io/ioutil" "os" "reflect" "regexp" "strings" "testing" ) // TestStraceRun tests basic strace execution. func TestStraceRun(t *testing.T) { StraceRun("echo asdf > /dev/null", nil, "") } // Example strace file used to test parsers. var straceout = []string{ `16819 stat64("/usr/bin/u...
(t *testing.T) { empty := map[string]bool{} filetraceTest(t, "echo asdf > t", "", empty, map[string]bool{"t": true}) defer func() { if err := os.Remove("t"); err != nil { t.Error(err) } }() filetraceTest(t, "cat t > h", "", map[string]bool{"t": true}, map[string]bool{"h": true}) defer func(...
TestFiletraceEchocat
identifier_name
filetrace_test.go
package libbusyna import ( "io/ioutil" "os" "reflect" "regexp" "strings" "testing" ) // TestStraceRun tests basic strace execution. func TestStraceRun(t *testing.T) { StraceRun("echo asdf > /dev/null", nil, "") } // Example strace file used to test parsers. var straceout = []string{ `16819 stat64("/usr/bin/u...
// TestFiletraceChdirPid tests directory chaging in different processes func TestFiletraceChdirPid(t *testing.T) { filetraceTest(t, "(mkdir d; cd d; echo asdf > t); echo asdf > u", "", empty, map[string]bool{"d/t": true, "u": true}) defer func() { for _, f := range []string{`d/t`, `d`, `u`} { if err :=...
{ empty := map[string]bool{} filetraceTest(t, "echo asdf > t; mv t v", "", empty, map[string]bool{"v": true}) defer func() { if err := os.Remove("v"); err != nil { t.Error(err) } }() }
identifier_body
filetrace_test.go
package libbusyna import ( "io/ioutil" "os" "reflect" "regexp" "strings" "testing" ) // TestStraceRun tests basic strace execution. func TestStraceRun(t *testing.T) { StraceRun("echo asdf > /dev/null", nil, "") } // Example strace file used to test parsers. var straceout = []string{ `16819 stat64("/usr/bin/u...
} }() } // TestFiletraceRename tests renaming func TestFiletraceRename(t *testing.T) { empty := map[string]bool{} filetraceTest(t, "echo asdf > t; mv t v", "", empty, map[string]bool{"v": true}) defer func() { if err := os.Remove("v"); err != nil { t.Error(err) } }() } // TestFiletraceChdirPid t...
if err := os.Remove(f); err != nil { t.Error(err) }
random_line_split
settings.py
""" Django settings for hauki project. """ import logging import os import subprocess import environ import sentry_sdk from django.conf.global_settings import LANGUAGES as GLOBAL_LANGUAGES from django.core.exceptions import ImproperlyConfigured from sentry_sdk.integrations.django import DjangoIntegration CONFIG_FILE...
root = environ.Path(__file__) - 2 # two levels back in hierarchy env = environ.Env( DEBUG=(bool, False), DJANGO_LOG_LEVEL=(str, "INFO"), CONN_MAX_AGE=(int, 0), SYSTEM_DATA_SOURCE_ID=(str, "hauki"), LANGUAGES=(list, ["fi", "sv", "en"]), DATABASE_URL=(str, "postgres:///hauki"), TEST_DATABA...
""" Retrieve the git hash for the underlying git repository or die trying We need a way to retrieve git revision hash for sentry reports I assume that if we have a git repository available we will have git-the-comamand as well """ try: # We are not interested in gits complaints ...
identifier_body
settings.py
""" Django settings for hauki project. """ import logging import os import subprocess import environ import sentry_sdk from django.conf.global_settings import LANGUAGES as GLOBAL_LANGUAGES from django.core.exceptions import ImproperlyConfigured from sentry_sdk.integrations.django import DjangoIntegration CONFIG_FILE...
MIDDLEWARE = [ # CorsMiddleware should be placed as high as possible and above WhiteNoiseMiddleware # in particular "corsheaders.middleware.CorsMiddleware", # Ditto for securitymiddleware "django.middleware.security.SecurityMiddleware", "whitenoise.middleware.WhiteNoiseMiddleware", "django.c...
ntry_sdk.init( dsn=env("SENTRY_DSN"), environment=env("SENTRY_ENVIRONMENT"), release=get_git_revision_hash(), integrations=[DjangoIntegration()], )
conditional_block
settings.py
""" Django settings for hauki project. """ import logging import os import subprocess import environ import sentry_sdk from django.conf.global_settings import LANGUAGES as GLOBAL_LANGUAGES from django.core.exceptions import ImproperlyConfigured from sentry_sdk.integrations.django import DjangoIntegration CONFIG_FILE...
STATIC_ROOT = env("STATIC_ROOT") MEDIA_ROOT = env("MEDIA_ROOT") # Whether to trust X-Forwarded-Host headers for all purposes # where Django would need to make use of its own hostname # fe. generating absolute URLs pointing to itself # Most often used in reverse proxy setups # https://docs.djangoproject.com/en/3.0/ref/...
STATIC_URL = env("STATIC_URL") MEDIA_URL = env("MEDIA_URL")
random_line_split
settings.py
""" Django settings for hauki project. """ import logging import os import subprocess import environ import sentry_sdk from django.conf.global_settings import LANGUAGES as GLOBAL_LANGUAGES from django.core.exceptions import ImproperlyConfigured from sentry_sdk.integrations.django import DjangoIntegration CONFIG_FILE...
() -> str: """ Retrieve the git hash for the underlying git repository or die trying We need a way to retrieve git revision hash for sentry reports I assume that if we have a git repository available we will have git-the-comamand as well """ try: # We are not interested in gits comp...
get_git_revision_hash
identifier_name
mod.rs
use crate::closure; use wasm_bindgen::prelude::*; /// Since the `copy` option can be either a function or a boolean, this enum /// encapsulates the possible values for the copy option. /// /// The closure signature is `(el, handle)`, the element to check and the /// element that was directly clicked on. pub enum CopyV...
#[wasm_bindgen(setter = invalid)] pub fn set_invalid_func(&mut self, val: JsValue) { self.invalid_func = val; } #[wasm_bindgen(getter = copy)] pub fn copy_func_or_bool(&self) -> JsValue { self.copy_func_or_bool.clone() } #[wasm_bindgen(setter = copy)] pub fn set_copy_...
{ self.invalid_func.clone() }
identifier_body
mod.rs
use crate::closure; use wasm_bindgen::prelude::*; /// Since the `copy` option can be either a function or a boolean, this enum /// encapsulates the possible values for the copy option. /// /// The closure signature is `(el, handle)`, the element to check and the /// element that was directly clicked on. pub enum CopyV...
/// for this particular [`Drake`](crate::Drake) instance. /// /// This closure will be invoked with the element that is being checked for /// whether it is a container. pub is_container: Box<dyn FnMut(JsValue) -> bool>, /// You can define a `moves` closure which will be invoked with `(el, source...
/// Besides the containers that you pass to [`dragula`](crate::dragula()), /// or the containers you dynamically add, you can also use this closure to /// specify any sort of logic that defines what is a container
random_line_split
mod.rs
use crate::closure; use wasm_bindgen::prelude::*; /// Since the `copy` option can be either a function or a boolean, this enum /// encapsulates the possible values for the copy option. /// /// The closure signature is `(el, handle)`, the element to check and the /// element that was directly clicked on. pub enum CopyV...
() -> Self { OptionsImpl::from(Options::default()) } } #[wasm_bindgen] #[doc(hidden)] impl OptionsImpl { #[wasm_bindgen(getter = isContainer)] pub fn is_container_func(&self) -> JsValue { self.is_container_func.clone() } #[wasm_bindgen(setter = isContainer)] pub fn set_is_conta...
default
identifier_name
train.py
# from __future__ import division # from __future__ import print_function import argparse import logging import pickle import random import time from itertools import chain import numpy as np import torch import torch.nn.functional as functional import torch.optim as optim from torch.autograd import Variable import ...
: def __init__(self, products_path, dataset_path, conf, logger, data_logger=None): self.conf = conf self._logger = logger self._data_logger = EmptyLogger() if data_logger is None else data_logger self.products_path = products_path self.loader = GraphLoader(dataset_path, is_m...
ModelRunner
identifier_name
train.py
# from __future__ import division # from __future__ import print_function import argparse import logging import pickle import random import time from itertools import chain import numpy as np import torch import torch.nn.functional as functional import torch.optim as optim from torch.autograd import Variable import ...
val_list = sorted(vals.items(), key=lambda x: x[0], reverse=True) logger.info("*" * 15 + "%s mean: %s", name, ", ".join("%s=%3.4f" % (key, np.mean(val)) for key, val in val_list)) logger.info("*" * 15 + "%s std: %s", name, ", ".join("%s=%3.4f" % (key, np.std(val)) for key, va...
random_line_split
train.py
# from __future__ import division # from __future__ import print_function import argparse import logging import pickle import random import time from itertools import chain import numpy as np import torch import torch.nn.functional as functional import torch.optim as optim from torch.autograd import Variable import ...
# Testing test_idx = self.loader.test_idx for name, model_args in models.items(): meter = meters[name] self._test(name, model_args, test_idx, meter) self._data_logger.log_info( model_name=name, loss=meter.last_val("loss_test")...
self._train(epoch, name, model_args, train_idx, val_idx, meters[name])
conditional_block
train.py
# from __future__ import division # from __future__ import print_function import argparse import logging import pickle import random import time from itertools import chain import numpy as np import torch import torch.nn.functional as functional import torch.optim as optim from torch.autograd import Variable import ...
def run(self, train_p, feat_type): features_meta = get_features(feat_type, is_directed=self.loader.is_graph_directed) self.loader.split_train(train_p, features_meta) models = self._get_models() if self.conf["cuda"] is not None: [model["model"].cuda(self.conf["cuda"]) ...
bow_feat = self.loader.bow_mx topo_feat = self.loader.topo_mx model1 = GCN(nfeat=bow_feat.shape[1], hlayers=[self.conf["kipf"]["hidden"]], nclass=self.loader.num_labels, dropout=self.conf["kipf"]["dropout"]) opt1 = optim.Adam(model1...
identifier_body
CAAPR_Pipeline.py
# Import smorgasbord import os import sys sys.path.append( str( os.path.join( os.path.split( os.path.dirname(os.path.abspath(__file__)) )[0], 'CAAPR', 'CAAPR_AstroMagic', 'PTS') ) ) import gc import pdb import time import re import copy import warnings import numbers import random import shutil import nump...
# Define function that fits and subtracts polynomial background filter from map def PolySub(pod, mask_semimaj_pix, mask_axial_ratio, mask_angle, poly_order=5, cutoff_sigma=2.0, instant_quit=False): if pod['verbose']: print '['+pod['id']+'] Determining if (and how) background is significnatly variable....
if pod['verbose']: print '['+pod['id']+'] Determining properties of map.' # Check if x & y pixel sizes are meaningfully different. If so, panic; else, treat as same pix_size = 3600.0 * pod['in_wcs'].wcs.cdelt if float(abs(pix_size.max()))/float(abs(pix_size.min()))>(1+1E-3): raise Exceptio...
identifier_body
CAAPR_Pipeline.py
# Import smorgasbord import os import sys sys.path.append( str( os.path.join( os.path.split( os.path.dirname(os.path.abspath(__file__)) )[0], 'CAAPR', 'CAAPR_AstroMagic', 'PTS') ) ) import gc import pdb import time import re import copy import warnings import numbers import random import shutil import nump...
(source_dict, band_dict, kwargs_dict): # Determine whether the user is specificing a directroy full of FITS files in this band (in which case use standardised filename format), or just a single FITS file try: if os.path.isdir(band_dict['band_dir']): in_fitspath = os.path.join( band...
FilePrelim
identifier_name
CAAPR_Pipeline.py
# Import smorgasbord import os import sys sys.path.append( str( os.path.join( os.path.split( os.path.dirname(os.path.abspath(__file__)) )[0], 'CAAPR', 'CAAPR_AstroMagic', 'PTS') ) ) import gc import pdb import time import re import copy import warnings import numbers import random import shutil import nump...
clip_sub = ChrisFuncs.SigmaClip(image_sub, tolerance=0.005, median=True, sigma_thresh=sigma_thresh) bg_sub = image_sub[ np.where( image_sub<clip_sub[1] ) ] spread_sub = np.mean( np.abs( bg_sub - clip_sub[1] ) ) spread_diff = spread_in / spread_sub # If the filter made significant difference, a...
spread_in = np.mean( np.abs( bg_in - clip_in[1] ) ) # How much reduction in background variation there was due to application of the filter image_sub = pod['cutout'] - poly_full
random_line_split
CAAPR_Pipeline.py
# Import smorgasbord import os import sys sys.path.append( str( os.path.join( os.path.split( os.path.dirname(os.path.abspath(__file__)) )[0], 'CAAPR', 'CAAPR_AstroMagic', 'PTS') ) ) import gc import pdb import time import re import copy import warnings import numbers import random import shutil import nump...
# Return result if True not in bands_check: return False elif True in bands_check: return True # Define function that does basic initial handling of band parameters def BandInitiate(band_dict): # Make sure band has content if band_dict==None: retu...
print '['+source_id+'] No data found in target directory for current source.' # Make null entries in tables, as necessary if kwargs_dict['fit_apertures']==True: null_aperture_combined = [np.NaN, np.NaN, np.NaN, np.NaN] CAAPR.CAAPR_IO.RecordAperture(null_aperture_combined, s...
conditional_block
index.js
var pageIndex = document.getElementById('index'); var pageRule = document.getElementById('rule'); var pageQuestion1 = document.getElementById('question1'); var pageQuestion2 = document.getElementById('question2'); var pageFail = document.getElementById('fail'); var pageReward = document.getElementById('reward...
var btnRule = pageRule.querySelector('.bottom-btn img'); var btnQuestion1 = pageQuestion1.querySelector('.bottom-btn img'); var btnGifPlay = pageQuestion1.querySelector('.btn-play'); var btnGifImg = pageQuestion1.querySelector('.gif-img'); var btnQuestion2 = pageQuestion2.querySelector('.bottom-btn img'); v...
var yun1Left = 0; var yun2Left = parseInt(window.getComputedStyle(yun2).left); var btnStart = pageIndex.querySelector('.bottom-btn img');
random_line_split
index.js
var pageIndex = document.getElementById('index'); var pageRule = document.getElementById('rule'); var pageQuestion1 = document.getElementById('question1'); var pageQuestion2 = document.getElementById('question2'); var pageFail = document.getElementById('fail'); var pageReward = document.getElementById('rew...
yun1Left++; yun1.style.left = -yun1Left+'px'; yun2.style.left = (yun2Left-yun1Left)+'px'; if(yun1Left > yun2Left){ yun1Left = 0; } requestAnimationFrame(yunduo); } //隐藏系统alerturl window.alert = function(name){ var iframe = document.createElement("IFRAME"); iframe.style.disp...
{
identifier_name
index.js
var pageIndex = document.getElementById('index'); var pageRule = document.getElementById('rule'); var pageQuestion1 = document.getElementById('question1'); var pageQuestion2 = document.getElementById('question2'); var pageFail = document.getElementById('fail'); var pageReward = document.getElementById('rew...
系统alerturl window.alert = function(name){ var iframe = document.createElement("IFRAME"); iframe.style.display="none"; iframe.setAttribute("src", 'data:text/plain,'); document.documentElement.appendChild(iframe); window.frames[0].window.alert(name); iframe.parentNode.removeChild(ifr...
n1Left++; yun1.style.left = -yun1Left+'px'; yun2.style.left = (yun2Left-yun1Left)+'px'; if(yun1Left > yun2Left){ yun1Left = 0; } requestAnimationFrame(yunduo); } //隐藏
identifier_body
index.js
var pageIndex = document.getElementById('index'); var pageRule = document.getElementById('rule'); var pageQuestion1 = document.getElementById('question1'); var pageQuestion2 = document.getElementById('question2'); var pageFail = document.getElementById('fail'); var pageReward = document.getElementById('rew...
uestAnimationFrame(yunduo); } //隐藏系统alerturl window.alert = function(name){ var iframe = document.createElement("IFRAME"); iframe.style.display="none"; iframe.setAttribute("src", 'data:text/plain,'); document.documentElement.appendChild(iframe); window.frames[0].window.alert(name); ...
yun1Left = 0; } req
conditional_block
images.py
from tgen.images import Images, ttypes as o from lib.blobby import Blobby, o as bo from lib.discovery import connect from redis import Redis import time from lib.imgcompare.avg import average_hash from cStringIO import StringIO from PIL import Image # events we will fire: # image_added : source_page_url, source_url,...
return image def get_image(self, image_id): """ returns Image for given id or blank Image """ # see if we have an image image = self._get_from_redis(image_id) if not image: raise o.ImageNotFound('Could not get image', image_id) # pull the actual image...
with connect(Blobby) as c: image.shahash = c.set_data(image.data)
conditional_block
images.py
from tgen.images import Images, ttypes as o from lib.blobby import Blobby, o as bo from lib.discovery import connect from redis import Redis import time from lib.imgcompare.avg import average_hash from cStringIO import StringIO from PIL import Image # events we will fire: # image_added : source_page_url, source_url,...
try: b = StringIO(image_data) img = Image.open(b) except Exception, ex: raise o.Exception('Exception getting PIL img: %s' % ex) try: ti.xdim, ti.ydim = img.size except Exception, ex: raise o.Exception('Exception getting dimensi...
raise o.Exception('oException getting shahash: %s' % ex.msg) except Exception, ex: raise o.Exception('Exception getting shahash: %s' % ex)
random_line_split
images.py
from tgen.images import Images, ttypes as o from lib.blobby import Blobby, o as bo from lib.discovery import connect from redis import Redis import time from lib.imgcompare.avg import average_hash from cStringIO import StringIO from PIL import Image # events we will fire: # image_added : source_page_url, source_url,...
def _get_from_redis(self, image_id): # if the image id is in the id set than pull it's details if self.rc.zrank('images:ids:timestamps',image_id) is not None: # get the image data from redis key = 'images:%s' % image_id image_data = self.rc.hgetall(key) ...
pipe = self.rc.pipeline() # if our image doesn't have an id, set it up w/ one if not image.id: print 'got new image: %s' % image.shahash image.id = self.rc.incr('images:next_id') pipe.sadd('images:datainstances:%s' % image.shahash, image.id) ...
identifier_body