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
combat.rs
pub fn target_tile(tcod: &mut Tcod, objects: &[Object], game: &mut Game, max_range: Option<f32>) -> Option<(i32, i32)> { use tcod::input::KeyCode::Escape; loop { // render the screen. this erases the inventory and shows the names of // objects un...
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
pub fn target_tile(tcod: &mut Tcod, objects: &[Object], game: &mut Game, max_range: Option<f32>) -> Option<(i32, i32)> { use tcod::input::KeyCode::Escape; loop { // render the screen. this erases the inventory and shows the names of // objects un...
} 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
objects: &[Object], game: &mut Game, max_range: Option<f32>) -> Option<(i32, i32)> { use tcod::input::KeyCode::Escape; loop { // render the screen. this erases the inventory and shows the names of // objects under the mouse. tcod.root...
ai_basic
identifier_name
ikdbtest_gl.py
(GLPluginProgram): def __init__(self,world,name): GLPluginProgram.__init__(self,name) self.widgetPlugin = GLWidgetPlugin() self.setPlugin(self.widgetPlugin) self.widgetMaster = self.widgetPlugin.klamptwidgetmaster self.world = world def display...
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
__init__(self,world,name): GLPluginProgram.__init__(self,name) self.widgetPlugin = GLWidgetPlugin() self.setPlugin(self.widgetPlugin) self.widgetMaster = self.widgetPlugin.klamptwidgetmaster self.world = world def display(self): GLPluginPr...
(s,d) = self.view.click_ray(x,y)
conditional_block
ikdbtest_gl.py
PluginProgram): def __init__(self,world,name): GLPluginProgram.__init__(self,name) self.widgetPlugin = GLWidgetPlugin() self.setPlugin(self.widgetPlugin) self.widgetMaster = self.widgetPlugin.klamptwidgetmaster self.world = world def display(se...
(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
PluginProgram): def __init__(self,world,name): GLPluginProgram.__init__(self,name) self.widgetPlugin = GLWidgetPlugin() self.setPlugin(self.widgetPlugin) self.widgetMaster = self.widgetPlugin.klamptwidgetmaster self.world = world def display(se...
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
can // only happen for line numbers; give it no line number (= 0) x = 0 } // encode kind: bits [1..4) x |= SpotInfo(kind) << 1; // encode isIndex: bit 0 if isIndex { x |= 1 } return x; } func (x SpotInfo) Kind() SpotKind { return SpotKind(x >> 1 & 7) } func (x SpotInfo) Lori() int { return int(x >> 4) ...
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
can // only happen for line numbers; give it no line number (= 0) x = 0 } // encode kind: bits [1..4) x |= SpotInfo(kind) << 1; // encode isIndex: bit 0 if isIndex { x |= 1 } return x; } func (x SpotInfo) Kind() SpotKind
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
// ---------------------------------------------------------------------------- // 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
can // only happen for line numbers; give it no line number (= 0) x = 0 } // encode kind: bits [1..4) x |= SpotInfo(kind) << 1; // encode isIndex: bit 0 if isIndex { x |= 1 } return x; } func (x SpotInfo) Kind() SpotKind { return SpotKind(x >> 1 & 7) } func (x SpotInfo) Lori() int { return int(x >> 4) ...
(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
filter
identifier_name
allocator.rs
is an assumption that each worker performs the same channel allocation logic; things go wrong otherwise. pub trait Communicator: 'static { fn index(&self) -> u64; // number out of peers fn peers(&self) -> u64; // number of peers fn new_channel<T:Send+Columnar+Any>(&mut self) -> (Vec<Box<Pushable<T>...
(&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
pub trait Communicator: 'static { fn index(&self) -> u64; // number out of peers fn peers(&self) -> u64; // number of peers fn new_channel<T:Send+Columnar+Any>(&mut self) -> (Vec<Box<Pushable<T>>>, Box<Pullable<T>>); } // TODO : Would be nice if Communicator had associated types for its Pushable an...
sender: sender, receiver: receiver, phantom: PhantomData, buffer: Vec::new(), stack: Default::default(),
random_line_split
load_balancer.rs
may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the ...
} } #[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
may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the ...
{ #[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
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 in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See ...
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
qualified domain whose mappings we want DBPath string // full path to database for Domain ConfigPath string // full path to usher config file } type Entry struct { Code string Url string } type ConfigEntry struct { Type string `yaml:"type"` AWSKey string `yaml:"aws_key,omitempty"` AWSSecret string...
} 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
Dir, "usher") } // Derive domain if not set - check for USHER_DOMAIN in environment if domain == "" { domain = os.Getenv("USHER_DOMAIN") } // Else infer the domain if only one database exists if domain == "" { matches, _ := filepath.Glob(filepath.Join(root, "*.*.yml")) if len(matches) == 1 { // Exactly ...
{ 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
-qualified domain whose mappings we want DBPath string // full path to database for Domain ConfigPath string // full path to usher config file } type Entry struct { Code string Url string } type ConfigEntry struct { Type string `yaml:"type"` AWSKey string `yaml:"aws_key,omitempty"` AWSSecret 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
yml")) if len(matches) == 1 { // Exactly one match - strip .yml suffix to get domain re := regexp.MustCompile(`.yml$`) domain = re.ReplaceAllLiteralString(filepath.Base(matches[0]), "") } } // Else give up with an error if domain == "" { return nil, errors.New("Domain not passed as parameter or set in...
randomCode
identifier_name
forall.rs
self.state; let m = &mut self.max; let mut i = 0; loop { if i == v.len()-1 {
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
self.state; let m = &mut self.max; let mut i = 0; loop { if i == v.len()-1 { return None; } if v[i] > 0 { v[i+1] += 1; v[i] -= 1; if v[i+1] <= m[i+1] { ...
} } } } } 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
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
self.state; let m = &mut self.max; let mut i = 0; loop { if i == v.len()-1 { return None; } if v[i] > 0 { v[i+1] += 1; v[i] -= 1; if v[i+1] <= m[i+1] { ...
{ 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
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
// 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
READY status. This fleet property cannot be changed // later. BuildId *string // Prompts Amazon GameLift to generate a TLS/SSL certificate for the fleet. Amazon // GameLift uses the certificates to encrypt traffic between game clients and the // game servers running on Amazon GameLift. By default, the // Certif...
{ return err }
conditional_block
api_op_CreateFleet.go
(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
] pub trait PolicyHandler { /// Called when a policy client makes a request on the policy API this handler controls. async fn handle_policy_request(&mut self, request: PolicyRequest) -> Response; /// Called when a setting request is intercepted for the setting this policy handler supervises. /// //...
{ 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
Factory}; use crate::message::base::Audience; use crate::policy::response::{Error as PolicyError, Response}; use crate::policy::{ BoxedHandler, Context, GenerateHandlerResult, HasPolicyType, PolicyInfo, PolicyType, Request as PolicyRequest, }; use crate::service; use crate::storage::{self, StorageInfo}; use any...
( &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
Factory}; use crate::message::base::Audience; use crate::policy::response::{Error as PolicyError, Response}; use crate::policy::{ BoxedHandler, Context, GenerateHandlerResult, HasPolicyType, PolicyInfo, PolicyType, Request as PolicyRequest, }; use crate::service; use crate::storage::{self, StorageInfo}; use any...
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
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': r...
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
":"she will", "she's":"she is", "shouldn't":"should not", "shouldn't've":"should not have", "should've":"should have", "somebody's":"somebody is", "someone's":"someone is", "something's":"something is", "that'd":"that would", "that'll":"th...
print(x_valid.shape) print(y_train.shape) print(y_valid.shape) print(combinedFeatures_test.shape)
random_line_split
projectsvmglove.py
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
ata' elif w == 'b': return 'bhi' elif w == 'nai': return 'nahi' elif w == 'f': return 'of' elif w == 'd': return 'the' else: return w ''' Translate word . ''' def translate(word): return translator.translate(word,src='hi' , dest='en')...
(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
msg': 'Requisição enviada para aprovação!'} else: json_ret = {'status': 500, 'msg': msg} else: json_ret = {'status': 500, 'msg': 'Json inválido!'} return json_ret except Exception as err: return {'status': 500, 'msg': 'Erro interno ao processar a requ...
'principalId': '', 'stage': 'dev', 'cognitoPoolClaims': {'sub': ''}, 'enhancedAuthContext': {},
random_line_split
main.py
'msg': 'Erro interno ao processar a requisição'} def request_new_card_handler(event, context): """ POST - Esse código se
print(msg) json_ret = {'status': 200, 'msg': 'Requisição enviada para aprovação!'} else: json_ret = {'status': 500, 'msg': msg} else: json_ret = {'status': 500, 'msg': 'Json inválido!'} return json_ret except Exception as err: ...
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
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
'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. :param event: Event recebido ...
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
created: %v", cfg) return cfg } // EmptyConfig creates a Config with no services or groups func EmptyConfig(workingDir string) Config { log.Printf("Creating empty config\n") cfg := Config{ workingDir: workingDir, } cfg.ServiceMap = make(map[string]*services.ServiceConfig) cfg.GroupMap = make(map[string]*se...
for _, s := range common { commonMap[s] = struct{}{} } var outSlice []string for _, s := range original {
random_line_split
config.go
) if err != nil { return Config{}, errors.WithStack(err) } workingDir := path.Dir(filePath) config, err := loadConfigContents(reader, workingDir) config.FilePath = filePath if err != nil { return Config{}, errors.WithStack(err) } if config.MinEdwardVersion != "" && edwardVersion != "" { // Check that this...
c.Groups = append(c.Groups, grp) } return nil } 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 :...
{ 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
) if err != nil { return Config{}, errors.WithStack(err) } workingDir := path.Dir(filePath) config, err := loadConfigContents(reader, workingDir) config.FilePath = filePath if err != nil { return Config{}, errors.WithStack(err) } if config.MinEdwardVersion != "" && edwardVersion != "" { // Check that this...
(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
{ return errors.WithStack(err) } _, err = writer.Write(content) return errors.WithStack(err) } // NewConfig creates a Config from slices of services and groups func NewConfig(newServices []services.ServiceConfig, newGroups []services.ServiceGroupConfig) Config { log.Printf("Creating new config with %d services ...
{ 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
; case 9: m = "10"; break; case 10: m = "11"; break; case 11: m = "12"; break; } fechaCita = a + "/" + m + "/" + d; //formato año/mes/dia hecho por evelyn document.getElementById('fechaId').value = fechaCita; //document.getElementById('lider').value = fechaCita; ...
or = "Verifique el campo cita, antes de seguir\n" } else { cita.style.background = 'White';
conditional_block
scriptAppoint.js
0); var date = event.data.date; // obtiene la fecha del ultimo dia del mes anterior var mesAc = event.data.mes;// obtiene el mes actual, regresa un num var new_month = $(".month").index(this); // regresa el nuemero del mes seleccionado var ahioSel = date.getFullYear(); var ahioAc= event.data.anio; if (mesA...
"occasion": " Repeated Test Event ", "invited_count": 120, "year": 2017, "month": 5,
random_line_split
scriptAppoint.js
]["occasion"] + ":</div>"); var event_count = $("<div class='event-count'>" + events[i]["invited_count"] + " Invited</div>"); if (events[i]["cancelled"] === true) { $(event_card).css({ "border-left": "10px solid #FF1744" }); event_count = $("<div class='event-cancelled'>Cancelled</div>"); ...
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
para tu cita."); return false; } /*if (ban2 == 0) { window.alert("Antes de, escoge una hora para tu cita."); return false; }*/ if(ban==1){ var date = event.data.date; var a = date.getFullYear(); var m = date.getMonth(); $(".horarios-container").hide(250); $(".events-container").hide(250...
; // var i
identifier_name
example_all.py
, 1.2, (100, 1)), axis=0) train_y = objectiveFunction(train_x) train_data = np.hstack([train_x, train_y]) test_x = np.linspace(-0.5, 1.5, 1000).reshape(-1, 1) # test_x = np.sort(np.random.uniform(-1, 1, (100, 1)), axis=0) test_y = objectiveFunction(test_x) test_data = np.hstack([test_x, test_y])...
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
= datasets.textures_2D(texture_name=datasetName) else: if datasetName == "cosine": objectiveFunction = toy_functions.cosine elif datasetName == "harmonics": objectiveFunction = toy_functions.harmonics elif datasetName == "pattern": objectiveFunction = toy_functions.pattern elif ...
_fun_maximize
identifier_name
example_all.py
"linear", "*", "bbq"] # composition = ["linear", "*", "linear_no_bias", "+", # "linear", "*", "linear_no_bias", "*", "bbq", "+", "bbq"] if basicRBF: # composition = ["rbf" if e == "bbq" else e for e in composition] composition = ["rbf"] qp.paramLow = np.array([-3]) qp.paramHigh...
predImg[idx[0], idx[1]] = y
conditional_block
example_all.py
Algo = nlopt.GN_DIRECT # nlOptAlgo = nlopt.GN_DIRECT_L # nlOptAlgo = nlopt.GN_ISRES # nlOptAlgo = nlopt.GN_ESCH # NLopt Local algotithms (derivative free) nlOptAlgo = nlopt.LN_COBYLA # nlOptAlgo = nlopt.LN_BOBYQA # nlOptAlgo = nlopt.LN_SBPLX """ Generate dataset """ if datasetName == "co2": train_data, test_data ...
""" 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
OneShot%3E%2C%20i16%2C%20CH%3E //! [`set_data_rate()`]: struct.Ads1x1x.html#method.set_data_rate //! [`set_full_scale_range()`]: struct.Ads1x1x.html#method.set_full_scale_range //! [`is_measurement_in_progress()`]: struct.Ads1x1x.html#method.is_measurement_in_progress //! [`set_high_threshold_raw()`]: struct.Ads1x1x.ht...
//! ```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
[`disable_comparator()`]: struct.Ads1x1x.html#method.disable_comparator //! [`use_alert_rdy_pin_as_ready()`]: struct.Ads1x1x.html#method.use_alert_rdy_pin_as_ready //! //! ## The devices //! //! The devices are precision, low power, 12/16-bit analog-to-digital //! converters (ADC) that provide all features necessary t...
gister;
identifier_name
shear_calculation_withoutplot_vasp.py
3)) ####read basis vector from POSCAR print(pos_array) oa=np.array([pos_array[0][0], pos_array[0][1], pos_array[0][2]]) ob=np.array([pos_array[1][0], pos_array[1][1], pos_array[1][2]]) oc=np.array([pos_array[2][0], pos_array[2][1], pos_array[2][2]]) #--------------------------------------------------------------------...
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
, 0] #P0=np.array([1, 1, 1]) #provide the axis before rotation.. P0 is the tensile direction we want to calculate. ###finish to read the input file #Q0=np.array([1, 0, 0]) #after rotation. Q0 is the x axis. Since the x axis will not be optimized as we set in VASP, so Q0 is [1, 0, 0] #--------------------------------...
postrain
identifier_name
shear_calculation_withoutplot_vasp.py
_basis=np.dot(P0_abc,basis) P=P0_abc_basis[0]+P0_abc_basis[1]+P0_abc_basis[2] # the position of the normal of shear plane before rotation Q0_abc=np.array([[Q0[0], 0, 0], [0, Q0[1], 0], [0, 0, Q0[2]]]) Q0_abc_basis=np.dot(Q0_abc,basis) Q=Q0_abc_basis[0]+Q0_abc_basis[1]+Q0_abc_basis[2]...
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
1 -2 \n").split()] if len(Sh_dir)==3: Sh_dir=Sh_dir elif len(Sh_pla)==4: U=Sh_dir[1]+2*Sh_dir[0] V=Sh_dir[0]+2*Sh_dir[1] W=Sh_dir[3] UVW_gcd=gcd(gcd(U,V),W) Sh_dir=np.array([U/UVW_gcd, V/UVW_gcd, W/UVW_gcd]) L0=Sh_dir K0=np.array([0, 0, 1]) #after rotation. K0 is the z axis. Since the x axis ...
os.system("cp POSCAR POSCAR_original") #copy original POSCAR r=[] with open ("POSCAR") as poscar1:
random_line_split
lib.rs
Balance; pub Locks get(fn locks): map T::AccountId => Vec<BalanceLock<T::Balance, T::Moment>>; } add_extra_genesis { config(balances): Vec<(T::AccountId, T::Balance)>; config(vesting): Vec<(T::AccountId, T::BlockNumber, T::BlockNumber, T::Balance)>; // ^^ begin, length, amount liquid at genesis } } decl_mo...
<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
but has an additional /// check that the transfer will not kill the origin account. /// /// # </weight> #[weight = SimpleDispatchInfo::FixedNormal(1_000_000)] pub fn transfer( origin, dest: <T::Lookup as StaticLookup>::Source, #[compact] value: T::Balance ) { let transactor = ensure_signed(...
random_line_split
lib.rs
{ mem::drop(NegativeImbalance::<T>::new(current_reserved - new_reserved)); } Self::set_reserved_balance(&who, new_reserved); } /// Exactly as `transfer`, except the origin must be root and the source account may be /// specified. #[weight = SimpleDispatchInfo::FixedNormal(1_000_000)] pub fn force_...
{ <FreeBalance<T>>::get(who) }
identifier_body
lib.rs
; pub Locks get(fn locks): map T::AccountId => Vec<BalanceLock<T::Balance, T::Moment>>; } add_extra_genesis { config(balances): Vec<(T::AccountId, T::Balance)>; config(vesting): Vec<(T::AccountId, T::BlockNumber, T::BlockNumber, T::Balance)>; // ^^ begin, length, amount liquid at genesis } } decl_module! {...
} 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
链路是否主备线路,0表示备线路,1表示主线路 "over_drop", ##overlay非云网链路丢包率 "over_dropth", ##overlay非云网链路丢包率阈值 "over_sl_drop", ##overlay云网链路丢包率 "over_sl_dropth", ##overlay云网链路丢包率阈值 "over_delay", ##overlay链路时延 "over_shakedelay", ##overlay链路抖动 "over_mindelay", "over_maxdelay", "over_mdev", "und...
random_line_split
query.py
filter": [ {"term": {"pairs.name": "tun_oip"}}, {"term": {"pairs.value.string": "$tunoip"}} ] } } } } ] } }, "size": 10000 } ''' url = 'http://rpc.dsp.chinanetcenter.com:10200/api/console/proxy?path...
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
备线路,1表示主线路 "over_drop", ##overlay非云网链路丢包率 "over_dropth", ##overlay非云网链路丢包率阈值 "over_sl_drop", ##overlay云网链路丢包率 "over_sl_dropth", ##overlay云网链路丢包率阈值 "over_delay", ##overlay链路时延 "over_shakedelay", ##overlay链路抖动 "over_mindelay", "over_maxdelay", "over_mdev", "under_drop", #...
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
filter": [ {"term": {"pairs.name": "tun_oip"}}, {"term": {"pairs.value.string": "$tunoip"}} ] } } } } ] } }, "size": 10000 } ''' url = 'http://rpc.dsp.chinanetcenter.com:10200/api/console/proxy?path...
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
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 = ''; a = 0; salesvalue = 0; min = '2020'; max = '...
this.displayend = this.datePipe.transform(lastdayofmonth, 'dd MMM yyyy'); this.start = first1; this.end = last1; // alert('start: ' + this.start + '\n' + this.end); this.getData(); } ngOnInit() { } share() { // this.getData(); this.createPdf(); } back() { this.router.navigate(...
{ 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
'\n' + this.end); this.getData(); } 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 t...
{ // On a browser simply use download! this.pdfObj.download(); }
conditional_block
day.page.ts
, 'dd MMM yyyy h:mm a'); this.displaystart = this.datePipe.transform(firstdayofmonth, 'dd MMM yyyy'); this.displayend = this.datePipe.transform(lastdayofmonth, 'dd MMM yyyy'); this.start = first1; this.end = last1; // alert('start: ' + this.start + '\n' + this.end); this.getData(); } ngOn...
}); debugger // Save the PDF to the data Directory of our App
random_line_split
day.page.ts
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
def forward(self, x): return self.act(self.bn(self.conv(x))) def fuse_forward(self, x): # 合并后的前向推理,bn和卷积合并 return self.act(self.conv(x)) class Bottleneck(nn.Module): ''' 标准瓶颈层 ''' def __init__(self, in_channel, out_channel, shortcut=True, groups=1, expansion=0.5): # ch_i...
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
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
forward(self, x): return self.act(self.bn(self.conv(x))) def fuse_forward(self, x): # 合并后的前向推理,bn和卷积合并 return self.act(self.conv(x)) class Bottleneck(nn.Module): ''' 标准瓶颈层 ''' def __init__(self, in_channel, out_channel, shortcut=True, groups=1, expansion=0.5): # ch_in, c...
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
forward(self, x): return self.act(self.bn(self.conv(x))) def fuse_forward(self, x): # 合并后的前向推理,bn和卷积合并 return self.act(self.conv(x)) class Bottleneck(nn.Module): ''' 标准瓶颈层 ''' def __init__(self, in_channel, out_channel, shortcut=True, groups=1, expansion=0.5): # ch_in, c...
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
0 exit_group(0) = ?`, } // TestStraceParse1 tests strace level1 parser (joining) by counting and // checking strings. func TestStraceParse1(t *testing.T) { // Count strings that will be parsed away by StraceParser1 n := len(straceout) for _, l := range straceout { if strings.Contains(l, "resum...
{ t.Error(err) }
conditional_block
filetrace_test.go
explain"], [/* 34 vars */]) = -1 ENOENT (No such file or directory)`, `16820 --- SIGCHLD (Child exited) @ 0 (0) ---`, `16820 execve("/usr/bin/tclsh", ["tclsh", "/usr/bin/unbuffer", "scons", "--max-drift=1", "--implicit-cache", "--debug=explain"], [/* 34 vars */]) = 0`, `16820 execve("/usr/bin/tclsh", ["tclsh", "/usr...
TestFiletraceEchocat
identifier_name
filetrace_test.go
} // TestStraceParse2Basic tests strace level2 parser by counting parsed entities. func TestStraceParse2Basic(t *testing.T) { nopen := 0 nexec := 0 for _, l := range straceout { if strings.Contains(l, " open(") { nopen++ } if strings.Contains(l, " execve(") { nexec++ } } syscalls := map[string]int{}...
{ 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
([]string, 0, len(straceout)) for l := range StraceParse1(ChanFromList(straceout)) { if strings.Contains(l, "resumed") || strings.Contains(l, "finished") { t.Error("found invalid string in parsed results: " + l) } parsed = append(parsed, l) } if len(parsed) != n { t.Error("incorrect len of parsed strings"...
if err := os.Remove(f); err != nil { t.Error(err) }
random_line_split
settings.py
return git_hash.rstrip() 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, "postgre...
""" 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
except FileNotFoundError: git_hash = "git_not_available" except subprocess.CalledProcessError: # Ditto git_hash = "no_repository" return git_hash.rstrip() root = environ.Path(__file__) - 2 # two levels back in hierarchy env = environ.Env( DEBUG=(bool, False), DJANGO_LOG_LE...
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
except FileNotFoundError: git_hash = "git_not_available" except subprocess.CalledProcessError: # Ditto git_hash = "no_repository" return git_hash.rstrip() root = environ.Path(__file__) - 2 # two levels back in hierarchy env = environ.Env( DEBUG=(bool, False), DJANGO_LOG_LE...
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
() -> 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
moves` closure which will be invoked with `(el, source, /// handle, sibling)` whenever an element is clicked. If this closure returns /// `false`, a drag event won't begin, and the event won't be prevented /// either. The `handle` element will be the original click target, which /// comes in handy to te...
{ self.invalid_func.clone() }
identifier_body
mod.rs
: &str = "vertical"; const HORIZONTAL: &str = "horizontal"; match self { Direction::Vertical => String::from(VERTICAL), Direction::Horizontal => String::from(HORIZONTAL), } } } /// Used to pass options when activating Dragula /// /// When passed to the [`dragula_opt...
/// 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 web_sys::Element; /// # use wasm_bindgen::JsValue; /// /// # let element = JsValue::TRUE; /// //--snip-- /// /// let options = Options { /// invalid: Box::new(|el, _handle| { /// Element::from(el).tag_name() == String::from("A") /// }), /// copy: CopyValue::Bool(true), /// copy_sort_so...
default
identifier_name
train.py
": [neighbor_features], "features": [NODE_FEATURES], "combined": [neighbor_features, NODE_FEATURES], } return dict(y for x in all_features[feat_type] for y in x.items()) class
: 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
": [neighbor_features], "features": [NODE_FEATURES], "combined": [neighbor_features, NODE_FEATURES], } return dict(y for x in all_features[feat_type] for y in x.items()) class ModelRunner: def __init__(self, products_path, dataset_path, conf, logger...
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
": [neighbor_features], "features": [NODE_FEATURES], "combined": [neighbor_features, NODE_FEATURES], } return dict(y for x in all_features[feat_type] for y in x.items()) class ModelRunner: def __init__(self, products_path, dataset_path, conf, logger...
# 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
": [neighbor_features], "features": [NODE_FEATURES], "combined": [neighbor_features, NODE_FEATURES], } return dict(y for x in all_features[feat_type] for y in x.items()) class ModelRunner: def __init__(self, products_path, dataset_path, conf, logger...
dropout=self.conf["dropout"], layer_type=None) opt3 = optim.Adam(model3.parameters(), lr=self.conf["lr"], weight_decay=self.conf["weight_decay"]) model4 = GCN(nfeat=topo_feat.shape[1], hlayers=self.conf["multi_hidden_layers"], ...
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
_async( CAAPR.CAAPR_Photom.SubpipelinePhotom, args=(source_dict, bands_dict[band], kwargs_dict) ) ) pool.close() pool.join() if kwargs_dict['verbose']: print '['+source_dict['name']+'] Gathering parallel threads.' photom_output_list = [...
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
, source_dict, kwargs_dict) # Record aperture properties to file CAAPR.CAAPR_IO.RecordAperture(aperture_combined, source_dict, kwargs_dict) # Prepare thumbnail images for bands excluded from aperture fitting CAAPR.CAAPR_Aperture.ExcludedThumb(source_dict, bands_dict, kwargs_dict,...
(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
format), or just a single FITS file try: if os.path.isdir(band_dict['band_dir']): in_fitspath = os.path.join( band_dict['band_dir'], source_dict['name']+'_'+band_dict['band_name'] ) elif os.path.isfile(band_dict['band_dir']): in_fitspath = os.path.join( band_dict['band_...
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
, source_dict, kwargs_dict) # Record aperture properties to file CAAPR.CAAPR_IO.RecordAperture(aperture_combined, source_dict, kwargs_dict) # Prepare thumbnail images for bands excluded from aperture fitting CAAPR.CAAPR_Aperture.ExcludedThumb(source_dict, bands_dict, kwargs_dict,...
# 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 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
ifImg = pageQuestion1.querySelector('.gif-img'); var btnQuestion2 = pageQuestion2.querySelector('.bottom-btn img'); var btnRestart = pageFail.querySelector('.bottom-btn img'); var btnZhizhen = pageReward.querySelector('.zhizhen'); var btnAgain = pageAgain.querySelector('.bottom-btn img'); var btnMessages = pa...
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
ifImg = pageQuestion1.querySelector('.gif-img'); var btnQuestion2 = pageQuestion2.querySelector('.bottom-btn img'); var btnRestart = pageFail.querySelector('.bottom-btn img'); var btnZhizhen = pageReward.querySelector('.zhizhen'); var btnAgain = pageAgain.querySelector('.bottom-btn img'); var btnMessages = pa...
系统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
ifImg = pageQuestion1.querySelector('.gif-img'); var btnQuestion2 = pageQuestion2.querySelector('.bottom-btn img'); var btnRestart = pageFail.querySelector('.bottom-btn img'); var btnZhizhen = pageReward.querySelector('.zhizhen'); var btnAgain = pageAgain.querySelector('.bottom-btn img'); var btnMessages = pa...
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
) # timestamp of when image was added # images:ids:timestamps = sorted (ids,timestamp) # all the image ids for the page # images:page_ids:<page_url> (ids) # last time an image was added from page # images:pages:timestamps = sorted (url,timestamp) # images meta...
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
ids:timestamps',image.id) # remove it's hash pipe.delete('images:%s' % image.id) # decriment the count for it's image data pipe.srem('images:datainstances:%s' % image.shahash, image.id) # remove image from the page's id set if image.source_page_url...
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
) # timestamp of when image was added # images:ids:timestamps = sorted (ids,timestamp) # all the image ids for the page # images:page_ids:<page_url> (ids) # last time an image was added from page # images:pages:timestamps = sorted (url,timestamp) # images meta...
# update / set our timestamp da = 0.0 if image.downloaded_at: da = image.downloaded_at else: da = time.time() pipe.zadd('images:ids:timestamps',image.id, da) # add this image to the page's id set if image.source_page_url: pipe....
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
images.py
(object): def __init__(self, redis_host='127.0.0.1'): self.redis_host = redis_host self.rc = Redis(redis_host) self.revent = ReventClient(redis_host=self.redis_host) # redis keys # incr this for the next image id # images:next_id = next_id # all the images ...
ImagesHandler
identifier_name