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
ParamEffectsProcessedFCD.py
#!/usr/bin/env python # -*- coding: Latin-1 -*- # Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo # Copyright (C) 2008-2017 German Aerospace Center (DLR) and others. # This program and the accompanying materials # are made available under the terms of the Eclipse Public License v2.0 # which acc...
(vtypeDict): """Collects all vehicles used in the simulation.""" vehSet = set() for timestepList in vtypeDict.values(): for elm in timestepList: vehSet.add(elm[0]) return list(vehSet) def make(source, dependentOn, builder, buildNew=False, *builderParams): """Fills the target (a...
getVehicleList
identifier_name
ParamEffectsProcessedFCD.py
#!/usr/bin/env python # -*- coding: Latin-1 -*- # Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo # Copyright (C) 2008-2017 German Aerospace Center (DLR) and others. # This program and the accompanying materials # are made available under the terms of the Eclipse Public License v2.0 # which acc...
# create mean from all edge speed values which are driven by the # chosen taxis drivenEdgesList = list(drivenEdgesSet) drivenEdgesList.sort() # print "dataSets ",simpleTaxiMeanVList[1] # --edgeDump-- # """ for i in edgeDum...
simpleTaxiMeanVList[0] += tup[2] simpleTaxiMeanVList[1] += 1 drivenEdgesSet.add(tup[1])
conditional_block
ParamEffectsProcessedFCD.py
#!/usr/bin/env python # -*- coding: Latin-1 -*- # Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo # Copyright (C) 2008-2017 German Aerospace Center (DLR) and others. # This program and the accompanying materials # are made available under the terms of the Eclipse Public License v2.0 # which acc...
for quota in qList: print("create output for: period ", period, " quota ", quota) taxis = chooseTaxis(vehList) taxiSum = len(taxis) if mode == U_FCD: vtypeDictR = procFcdDict[(period, quota)] else: vtypeDictR = reduceVty...
if stopByPeriod: yield (period, None, None, None)
random_line_split
activemqartemisaddress_controller.go
package v2alpha2activemqartemisaddress import ( "context" mgmt "github.com/artemiscloud/activemq-artemis-management" "github.com/operator-framework/operator-sdk/pkg/k8sutil" brokerv2alpha2 "github.com/rh-messaging/activemq-artemis-operator/pkg/apis/broker/v2alpha2" "github.com/rh-messaging/activemq-artemis-operat...
(instance *brokerv2alpha2.ActiveMQArtemisAddress, request reconcile.Request, client client.Client) error { reqLogger := log.WithValues("Request.Namespace", request.Namespace, "Request.Name", request.Name) reqLogger.Info("Deleting ActiveMQArtemisAddress") var err error = nil artemisArray := getPodBrokers(instance,...
deleteQueue
identifier_name
activemqartemisaddress_controller.go
package v2alpha2activemqartemisaddress import ( "context" mgmt "github.com/artemiscloud/activemq-artemis-management" "github.com/operator-framework/operator-sdk/pkg/k8sutil" brokerv2alpha2 "github.com/rh-messaging/activemq-artemis-operator/pkg/apis/broker/v2alpha2" "github.com/rh-messaging/activemq-artemis-operat...
else { reqLogger.Info("Statefulset: " + ssNamespacedName.Name + " found") pod := &corev1.Pod{} podNamespacedName := types.NamespacedName{ Name: statefulset.Name + "-0", Namespace: request.Namespace, } // For each of the replicas var i int = 0 var replicas int = int(*statefulset.Spec.Replicas...
{ reqLogger.Info("Statefulset: " + ssNamespacedName.Name + " not found") }
conditional_block
activemqartemisaddress_controller.go
package v2alpha2activemqartemisaddress import ( "context" mgmt "github.com/artemiscloud/activemq-artemis-management" "github.com/operator-framework/operator-sdk/pkg/k8sutil" brokerv2alpha2 "github.com/rh-messaging/activemq-artemis-operator/pkg/apis/broker/v2alpha2" "github.com/rh-messaging/activemq-artemis-operat...
} } } } } return err } func getPodBrokers(instance *brokerv2alpha2.ActiveMQArtemisAddress, request reconcile.Request, client client.Client) []*mgmt.Artemis { reqLogger := log.WithValues("Request.Namespace", request.Namespace, "Request.Name", request.Name) reqLogger.Info("Getting Pod Brokers") var...
reqLogger.Info("No bindings found removing " + instance.Spec.AddressName) a.DeleteAddress(instance.Spec.AddressName) } else { reqLogger.Info("Bindings found, not removing " + instance.Spec.AddressName)
random_line_split
activemqartemisaddress_controller.go
package v2alpha2activemqartemisaddress import ( "context" mgmt "github.com/artemiscloud/activemq-artemis-management" "github.com/operator-framework/operator-sdk/pkg/k8sutil" brokerv2alpha2 "github.com/rh-messaging/activemq-artemis-operator/pkg/apis/broker/v2alpha2" "github.com/rh-messaging/activemq-artemis-operat...
func deleteQueue(instance *brokerv2alpha2.ActiveMQArtemisAddress, request reconcile.Request, client client.Client) error { reqLogger := log.WithValues("Request.Namespace", request.Namespace, "Request.Name", request.Name) reqLogger.Info("Deleting ActiveMQArtemisAddress") var err error = nil artemisArray := getPo...
{ reqLogger := log.WithValues("Request.Namespace", request.Namespace, "Request.Name", request.Name) reqLogger.Info("Creating ActiveMQArtemisAddress") var err error = nil artemisArray := getPodBrokers(instance, request, client) if nil != artemisArray { for _, a := range artemisArray { if nil == a { reqLo...
identifier_body
mod.rs
use std::path::{Path}; use std::fs::{File, PathExt}; use byteorder::{ReadBytesExt, WriteBytesExt, LittleEndian}; use std::ffi::CString; use alsa::{PCM, Stream, Mode, Format, Access, Prepared}; use std::collections::VecDeque; use std; use num; #[derive(Clone)] pub struct Complex<T> { pub i: T, ...
else { self.tapi - ti }; si += self.tapvi[off] * self.taps[ti]; sq += self.tapvq[off] * self.taps[ti]; } self.tapi += 1; if self.tapi >= self.taps.len() { self.tapi = 0; } ...
{ self.taps.len() - (ti - self.tapi)}
conditional_block
mod.rs
use std::path::{Path}; use std::fs::{File, PathExt}; use byteorder::{ReadBytesExt, WriteBytesExt, LittleEndian}; use std::ffi::CString; use alsa::{PCM, Stream, Mode, Format, Access, Prepared}; use std::collections::VecDeque; use std; use num; #[derive(Clone)] pub struct Complex<T> { pub i: T, ...
} pub struct Alsa { sps: u32, pcm: PCM<Prepared>, } impl Alsa { pub fn new(sps: u32) -> Alsa { let pcm = PCM::open("default", Stream::Playback, Mode::Blocking).unwrap(); let mut pcm = pcm.set_parameters(Format::FloatLE, Access::Interleaved, 1, sps as usize).ok().unw...
{ let i = self.i * a.i - self.q * a.q; let q = self.i * a.q + self.q * a.i; self.i = i; self.q = q; }
identifier_body
mod.rs
use std::path::{Path}; use std::fs::{File, PathExt}; use byteorder::{ReadBytesExt, WriteBytesExt, LittleEndian}; use std::ffi::CString; use alsa::{PCM, Stream, Mode, Format, Access, Prepared}; use std::collections::VecDeque; use std; use num; #[derive(Clone)] pub struct Complex<T> { pub i: T, ...
(freq: f64, sps: f64, amp: f32) -> Option<Vec<Complex<f32>>> { // Do not build if too low in frequency. if freq.abs() < 500.0 { return Option::Some(vec![Complex { i: 1.0, q: 0.0 } ]); } if freq * 4.0 > sps { return Option::None; } // How many of our smallest units of time r...
buildsine
identifier_name
mod.rs
use std::path::{Path}; use std::fs::{File, PathExt}; use byteorder::{ReadBytesExt, WriteBytesExt, LittleEndian}; use std::ffi::CString; use alsa::{PCM, Stream, Mode, Format, Access, Prepared}; use std::collections::VecDeque; use std; use num; #[derive(Clone)] pub struct Complex<T> { pub i: T, ...
// let tmp = mem::transmute::<&Vec<i8>, &Vec<u8>>(buf); // fd.write(tmp.as_slice()); //} } pub struct FileSource { fp: File, } impl FileSource { pub fn new(path: String) -> FileSource { FileSource { fp: File::open(path).unwrap(), } } ...
for x in 0..buf.len() { fd.write_f32::<LittleEndian>(buf[x]); } //unsafe {
random_line_split
main.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
{ Overwrite, // str is the extension of the new file NewFile(&'static str), // Write the output to stdout. Display, // Return the result as a mapping from filenames to StringBuffers. Return(&'static Fn(HashMap<String, String>)), } #[derive(Copy, Clone, Eq, PartialEq, Debug)] enum BraceStyl...
WriteMode
identifier_name
main.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
#[cfg(test)] mod test { use std::collections::HashMap; use std::fs; use std::io::Read; use std::sync::atomic; use super::*; use super::run; // For now, the only supported regression tests are idempotent tests - the input and // output must match exactly. // FIXME(#28) would be good ...
random_line_split
main.rs
extern crate chrono; extern crate fastcgi; extern crate htmlescape; extern crate postgres; extern crate quick_xml; extern crate regex; extern crate reqwest; extern crate rss; extern crate serde; extern crate tiny_keccak; extern crate uuid; use std::io; use std::io::Write; type UtcDateTime = chrono::DateTime<chrono::U...
<W: Write>(url: &str, pages: &[Page], out: &mut W) -> Result<(), PagefeedError> { #[derive(serde::Serialize)] #[serde(rename = "opml")] struct Opml<'a> { version: &'a str, head: Head, body: Body<'a>, } #[derive(serde::Serialize)] struct Head {} #[derive(serde::Seria...
build_opml
identifier_name
main.rs
extern crate chrono; extern crate fastcgi; extern crate htmlescape; extern crate postgres; extern crate quick_xml; extern crate regex; extern crate reqwest; extern crate rss; extern crate serde; extern crate tiny_keccak; extern crate uuid; use std::io; use std::io::Write; type UtcDateTime = chrono::DateTime<chrono::U...
fn update_page_changed( conn: &mut postgres::Transaction, page: &Page, new_etag: &Option<String>, new_hash: &Vec<u8>, ) -> Result<(), postgres::error::Error> { let query = " update pages set last_checked = current_timestamp, last_modified = current_timestamp, last_error = null, item_id...
{ let query = " update pages set last_checked = current_timestamp where slug = $1 "; conn.execute(query, &[&page.slug])?; Ok(()) }
identifier_body
main.rs
extern crate chrono; extern crate fastcgi; extern crate htmlescape; extern crate postgres; extern crate quick_xml; extern crate regex; extern crate reqwest; extern crate rss; extern crate serde; extern crate tiny_keccak; extern crate uuid; use std::io; use std::io::Write; type UtcDateTime = chrono::DateTime<chrono::U...
fn describe_page_status(page: &Page) -> String { page.last_error.as_ref().map_or_else( || format!("{} was updated.", page.name), |err| format!("Error while checking {}: {}", page.name, err), ) } fn build_opml<W: Write>(url: &str, pages: &[Page], out: &mut W) -> Result<(), PagefeedError> { #...
random_line_split
main.rs
extern crate chrono; extern crate fastcgi; extern crate htmlescape; extern crate postgres; extern crate quick_xml; extern crate regex; extern crate reqwest; extern crate rss; extern crate serde; extern crate tiny_keccak; extern crate uuid; use std::io; use std::io::Write; type UtcDateTime = chrono::DateTime<chrono::U...
else { handle_feed_request(slug, &mut w) } } fn handle_opml_request<W: Write>(url: &str, out: &mut W) -> Result<(), PagefeedError> { let mut conn = database_connection()?; let mut trans = conn.transaction()?; let pages = get_enabled_pages(&mut trans)?; trans.commit()?; out.write_all(b"...
{ handle_opml_request(&url, &mut w) }
conditional_block
start.go
package start import ( "io" "code.cloudfoundry.org/cfdev/iso" "fmt" "net/url" "os" "strings" "time" "code.cloudfoundry.org/cfdev/config" "code.cloudfoundry.org/cfdev/errors" "code.cloudfoundry.org/cfdev/provision" "code.cloudfoundry.org/cfdev/resource" "github.com/spf13/cobra" "path/filepath" "text/t...
() *cobra.Command { args := Args{} cmd := &cobra.Command{ Use: "start", RunE: func(_ *cobra.Command, _ []string) error { if err := s.Execute(args); err != nil { return errors.SafeWrap(err, "cf dev start") } return nil }, } pf := cmd.PersistentFlags() pf.StringVarP(&args.DepsIsoPath, "file", "f"...
Cmd
identifier_name
start.go
package start import ( "io" "code.cloudfoundry.org/cfdev/iso" "fmt" "net/url" "os" "strings" "time" "code.cloudfoundry.org/cfdev/config" "code.cloudfoundry.org/cfdev/errors" "code.cloudfoundry.org/cfdev/provision" "code.cloudfoundry.org/cfdev/resource" "github.com/spf13/cobra" "path/filepath" "text/t...
NoProvision bool Cpus int Mem int } type Start struct { Exit chan struct{} LocalExit chan string UI UI Config config.Config IsoReader IsoReader Analytics AnalyticsClient AnalyticsToggle Toggle HostNet HostNet ...
random_line_split
start.go
package start import ( "io" "code.cloudfoundry.org/cfdev/iso" "fmt" "net/url" "os" "strings" "time" "code.cloudfoundry.org/cfdev/config" "code.cloudfoundry.org/cfdev/errors" "code.cloudfoundry.org/cfdev/provision" "code.cloudfoundry.org/cfdev/resource" "github.com/spf13/cobra" "path/filepath" "text/t...
{ baseMem := defaultMemory if isoConfig.DefaultMemory > 0 { baseMem = isoConfig.DefaultMemory } availableMem, err := s.Profiler.GetAvailableMemory() if err != nil { return 0, errors.SafeWrap(err, "error retrieving available system memory") } customMemProvided := requestedMem > 0 if customMemProvided { i...
identifier_body
start.go
package start import ( "io" "code.cloudfoundry.org/cfdev/iso" "fmt" "net/url" "os" "strings" "time" "code.cloudfoundry.org/cfdev/config" "code.cloudfoundry.org/cfdev/errors" "code.cloudfoundry.org/cfdev/provision" "code.cloudfoundry.org/cfdev/resource" "github.com/spf13/cobra" "path/filepath" "text/t...
} func (s *Start) parseDockerRegistriesFlag(flag string) ([]string, error) { if flag == "" { return nil, nil } values := strings.Split(flag, ",") registries := make([]string, 0, len(values)) for _, value := range values { // Including the // will cause url.Parse to validate 'value' as a host:port u, err...
{ if err := s.Provisioner.Ping(); err == nil { return } time.Sleep(time.Second) }
conditional_block
Embedding.py
""" General abstraction on the idea of an embedding on a network we should be able to apply this to TNNodes """ from abc import ABC, abstractmethod from util import * from TN import * class Embedder(ABC): """ This is what we will use to annotate TNNodes """ EMBEDDINGS = ['hyperbolic','n-adic','tree'] def __i...
if len(convs) == 1: return n_adic(convs[0].numerator,n,int(np.round(np.log(convs[0].b)/np.log(n)))) #pick the closest one to some a/n^d with d < max_n_exp #this amounts to picking the one whose denom is closest to a power of n #which amounts to picking the one which has log_n(denom) closest to an integer (whic...
return n_adic(convs[0].numerator,n,0)
conditional_block
Embedding.py
""" General abstraction on the idea of an embedding on a network we should be able to apply this to TNNodes """ from abc import ABC, abstractmethod from util import * from TN import * class Embedder(ABC): """ This is what we will use to annotate TNNodes """ EMBEDDINGS = ['hyperbolic','n-adic','tree'] def __i...
def cross(self,l): return Isometry((self.rot * l.rot + l.rot * self.trans * np.conj(l.trans)) / (self.rot * l.trans * np.conj(self.trans) + 1), (self.rot * l.trans + self.trans) / (self.rot * l.trans * np.conj(self.trans) + 1)) def inv(self): a = Isometry(np.conj(self.rot),0) b = Isometry(1,-self.trans...
return (self.rot * arg + self.trans) / (1 + np.conj(self.trans) * self.rot * arg)
identifier_body
Embedding.py
""" General abstraction on the idea of an embedding on a network we should be able to apply this to TNNodes """ from abc import ABC, abstractmethod from util import * from TN import * class Embedder(ABC): """ This is what we will use to annotate TNNodes """ EMBEDDINGS = ['hyperbolic','n-adic','tree'] def __i...
(self,etype,atype,dtype): super().__init__(etype,atype,dtype) def get_adr_child(self,adr,i): self.atype_check(adr) ch = self.__gchld__(adr,i) self.atype_check(ch) return ch def get_root(self): r = self.__grt__() self.atype_check(r) return r @abstractmethod def __gchld__(self,adr,i): pass @ab...
__init__
identifier_name
Embedding.py
""" General abstraction on the idea of an embedding on a network we should be able to apply this to TNNodes """ from abc import ABC, abstractmethod from util import * from TN import * class Embedder(ABC): """ This is what we will use to annotate TNNodes """ EMBEDDINGS = ['hyperbolic','n-adic','tree'] def __i...
for i in range(self.q): didx = (idx+i)%self.q disom = isom.cross(generators[didx]) dcoord = disom.evaluate(0) d_coords.append((dcoord,didx,disom)) return d_coords def __dist__(self,adrx,adry): coordx,_,_ = adrx coordy,_,_ = adry return hyper_dist(coordx,coordy) def __gac__(self,adr): retur...
coords,idx,isom = adr generators = define_generators(self.q) d_coords = []
random_line_split
etcdstatedriver.go
/*** Copyright 2014 Cisco Systems Inc. All rights reserved. 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...
// KeysAPI client.KeysAPI Client *client.Client } // Init the driver with a core.Config. func (d *EtcdStateDriver) Init(instInfo *core.InstanceInfo) error { var err error var endpoint *url.URL if instInfo == nil || len(instInfo.DbURL) == 0 { return errors.New("no etcd config found") } tlsInfo := transport.T...
type EtcdStateDriver struct { // Client client.Client
random_line_split
etcdstatedriver.go
/*** Copyright 2014 Cisco Systems Inc. All rights reserved. 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...
} cfg := client.Config{ Endpoints: instInfo.DbURL, TLS: tlsConfig, } d.Client, err = client.New(cfg) if err != nil { log.Fatalf("error creating etcd client. Err: %v", err) } return nil } // Deinit is currently a no-op. func (d *EtcdStateDriver) Deinit() { d.Client.Close() } // Write state to key wi...
{ return core.Errorf("invalid etcd URL scheme %q", endpoint.Scheme) }
conditional_block
etcdstatedriver.go
/*** Copyright 2014 Cisco Systems Inc. All rights reserved. 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...
// ClearState removes key from etcd func (d *EtcdStateDriver) ClearState(key string) error { ctx, cancel := context.WithTimeout(context.Background(), ctxTimeout) defer cancel() _, err := d.Client.KV.Delete(ctx, key) return err } // ReadState reads key into a core.State with the unmarshaling function. func (d *E...
{ watcher := d.Client.Watch(context.Background(), baseKey, client.WithPrefix()) go d.channelEtcdEvents(watcher, rsps) return nil }
identifier_body
etcdstatedriver.go
/*** Copyright 2014 Cisco Systems Inc. All rights reserved. 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...
(instInfo *core.InstanceInfo) error { var err error var endpoint *url.URL if instInfo == nil || len(instInfo.DbURL) == 0 { return errors.New("no etcd config found") } tlsInfo := transport.TLSInfo{ CertFile: instInfo.DbTLSCert, KeyFile: instInfo.DbTLSKey, TrustedCAFile: instInfo.DbTLSCa, } tlsCon...
Init
identifier_name
deep_consensus.py
''' Distributed Tensorflow 1.12.0 example of using data parallelism and the consensus worker communication scheme. Trains a deep convolutional neural network on MNIST for 10 epochs on n_nodes machines using one parameter server. The goal is to put minimum workload on the parameter server such that all computations are ...
(grads, vars_, learning_rate): mul_grads = [] for grad, var in zip(grads, vars_): mul_grad = tf.scalar_mul(learning_rate, grad) mul_grads.append(mul_grad) return mul_grads with tf.name_scope("softmax"): assign_ops = [] ...
grads_x_lr
identifier_name
deep_consensus.py
''' Distributed Tensorflow 1.12.0 example of using data parallelism and the consensus worker communication scheme. Trains a deep convolutional neural network on MNIST for 10 epochs on n_nodes machines using one parameter server. The goal is to put minimum workload on the parameter server such that all computations are ...
np.random.seed(SEED) rn.seed(SEED) # Raise error if trying to seed after graph construction if len(tf.get_default_graph()._nodes_by_id.keys()) > 0: raise RuntimeError("Seeding is not supported after building part of the graph. " "Please move set_seed to the beginning of your code.") # R...
os.environ['PYTHONHASHSEED'] = '0' SEED = 5 tf.set_random_seed(SEED)
random_line_split
deep_consensus.py
''' Distributed Tensorflow 1.12.0 example of using data parallelism and the consensus worker communication scheme. Trains a deep convolutional neural network on MNIST for 10 epochs on n_nodes machines using one parameter server. The goal is to put minimum workload on the parameter server such that all computations are ...
print("Train-Accuracy: %2.2f" % sess.run(accuracy, feed_dict={x: mnist.train.images, y_: mnist.train.labels})) print("Test-Accuracy: %2.2f" % sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels})) print("Total Time: %3.2fs" % float(time.time() - begin_time)) ...
print("Iteration NO: ", count) batch_x, batch_y = mnist.train.next_batch(batch_size, shuffle=False) # perform the operations we defined earlier on batch _, cost = sess.run([train_op, cross_entropy], feed...
conditional_block
deep_consensus.py
''' Distributed Tensorflow 1.12.0 example of using data parallelism and the consensus worker communication scheme. Trains a deep convolutional neural network on MNIST for 10 epochs on n_nodes machines using one parameter server. The goal is to put minimum workload on the parameter server such that all computations are ...
with tf.name_scope("softmax"): assign_ops = [] for tensor1, tensor2 in zip((W_conv1, W_conv2, W_fc1, W_fc2, b_conv1, b_conv2, b_fc1, b_fc2), worker.vars_): assign_ops.append(tf.assign(tensor1, tensor2)) # This line must be equivalent to the...
mul_grads = [] for grad, var in zip(grads, vars_): mul_grad = tf.scalar_mul(learning_rate, grad) mul_grads.append(mul_grad) return mul_grads
identifier_body
rally.rs
use amethyst::{ assets::{AssetStorage, Handle, Loader}, core::Time, ecs::prelude::{Dispatcher, DispatcherBuilder, Entity}, input::{is_close_requested, is_key_down, BindingTypes}, prelude::*, renderer::{ debug_drawing::{DebugLines, DebugLinesComponent, DebugLinesParams}, ImageForm...
StateEvent::Input(_input) => { //log::info!("Input Event detected: {:?}.", input); Trans::None } } } fn update(&mut self, data: &mut StateData<'_, GameData<'_, '_>>) -> SimpleTrans { if let Some(dispatcher) = self.dispatcher.as_mut() { ...
{ // log::info!( // "[HANDLE_EVENT] You just interacted with a ui element: {:?}", // ui_event // ); Trans::None }
conditional_block
rally.rs
use amethyst::{ assets::{AssetStorage, Handle, Loader}, core::Time, ecs::prelude::{Dispatcher, DispatcherBuilder, Entity}, input::{is_close_requested, is_key_down, BindingTypes}, prelude::*, renderer::{ debug_drawing::{DebugLines, DebugLinesComponent, DebugLinesParams}, ImageForm...
} fn on_resume(&mut self, _data: StateData<'_, GameData<'_, '_>>) { self.paused = false; } fn on_stop(&mut self, data: StateData<'_, GameData<'_, '_>>) { if let Some(root_entity) = self.ui_root { data.world .delete_entity(root_entity) .expect...
fn on_pause(&mut self, _data: StateData<'_, GameData<'_, '_>>) { self.paused = true;
random_line_split
rally.rs
use amethyst::{ assets::{AssetStorage, Handle, Loader}, core::Time, ecs::prelude::{Dispatcher, DispatcherBuilder, Entity}, input::{is_close_requested, is_key_down, BindingTypes}, prelude::*, renderer::{ debug_drawing::{DebugLines, DebugLinesComponent, DebugLinesParams}, ImageForm...
} #[derive(Debug)] pub struct MovementBindingTypes; impl BindingTypes for MovementBindingTypes { type Axis = AxisBinding; type Action = ActionBinding; }
{ write!(f, "{:?}", self) }
identifier_body
rally.rs
use amethyst::{ assets::{AssetStorage, Handle, Loader}, core::Time, ecs::prelude::{Dispatcher, DispatcherBuilder, Entity}, input::{is_close_requested, is_key_down, BindingTypes}, prelude::*, renderer::{ debug_drawing::{DebugLines, DebugLinesComponent, DebugLinesParams}, ImageForm...
(&mut self, data: StateData<'_, GameData<'_, '_>>) { if let Some(root_entity) = self.ui_root { data.world .delete_entity(root_entity) .expect("Failed to remove Game Screen"); } let fetched_game_score = data.world.try_fetch::<GameScore>(); if ...
on_stop
identifier_name
file_header.go
package gitdiff import ( "fmt" "io" "os" "strconv" "strings" "time" ) const ( devNull = "/dev/null" ) // ParseNextFileHeader finds and parses the next file header in the stream. If // a header is found, it returns a file and all input before the header. It // returns nil if no headers are found before the end...
if err == io.EOF { break } return nil, "", err } } return nil, "", nil } func (p *parser) ParseGitFileHeader() (*File, error) { const prefix = "diff --git " if !strings.HasPrefix(p.Line(0), prefix) { return nil, nil } header := p.Line(0)[len(prefix):] defaultName, err := parseGitHeaderName(he...
if err := p.Next(); err != nil {
random_line_split
file_header.go
package gitdiff import ( "fmt" "io" "os" "strconv" "strings" "time" ) const ( devNull = "/dev/null" ) // ParseNextFileHeader finds and parses the next file header in the stream. If // a header is found, it returns a file and all input before the header. It // returns nil if no headers are found before the end...
if err := p.Next(); err != nil { if err == io.EOF { break } return nil, err } if end { break } } if f.OldName == "" && f.NewName == "" { if defaultName == "" { return nil, p.Errorf(0, "git file header: missing filename information") } f.OldName = defaultName f.NewName = defaultN...
{ return nil, p.Errorf(1, "git file header: %v", err) }
conditional_block
file_header.go
package gitdiff import ( "fmt" "io" "os" "strconv" "strings" "time" ) const ( devNull = "/dev/null" ) // ParseNextFileHeader finds and parses the next file header in the stream. If // a header is found, it returns a file and all input before the header. It // returns nil if no headers are found before the end...
(f *File, line, defaultName string) error { const sep = ".." // note that git stops parsing if the OIDs are too long to be valid // checking this requires knowing if the repository uses SHA1 or SHA256 // hashes, which we don't know, so we just skip that check parts := strings.SplitN(line, " ", 2) oids := string...
parseGitHeaderIndex
identifier_name
file_header.go
package gitdiff import ( "fmt" "io" "os" "strconv" "strings" "time" ) const ( devNull = "/dev/null" ) // ParseNextFileHeader finds and parses the next file header in the stream. If // a header is found, it returns a file and all input before the header. It // returns nil if no headers are found before the end...
func parseGitHeaderNewName(f *File, line, defaultName string) error { name, _, err := parseName(line, '\t', 1) if err != nil { return err } if f.NewName == "" && !f.IsDelete { f.NewName = name return nil } return verifyGitHeaderName(name, f.NewName, f.IsDelete, "new") } func parseGitHeaderOldMode(f *File...
{ name, _, err := parseName(line, '\t', 1) if err != nil { return err } if f.OldName == "" && !f.IsNew { f.OldName = name return nil } return verifyGitHeaderName(name, f.OldName, f.IsNew, "old") }
identifier_body
data_helper.py
# -*- coding: utf-8 -*- import configparser as cp import os from hdfs import InsecureClient import pandas as pd import requests from bs4 import BeautifulSoup import numpy as np import itertools import datetime import socket def ConfigSectionMap(config, section): dict_data = {} options = config.options(section...
elif language == 'da': valid_language = 'danish' elif language == 'nl': valid_language = 'dutch' elif language == 'fr': valid_language = 'french' elif language == 'de': valid_language = 'german' elif language == 'el': valid_language = 'greek' elif languag...
valid_language = 'azerbaijani'
conditional_block
data_helper.py
# -*- coding: utf-8 -*- import configparser as cp import os from hdfs import InsecureClient import pandas as pd import requests from bs4 import BeautifulSoup import numpy as np import itertools import datetime import socket def ConfigSectionMap(config, section): dict_data = {} options = config.options(section...
def available_data_semantic_features(): semantic_features = {'Flesch_reading_ease':True, 'Sentence_similarity':True, 'Freq_distribution_coeff':True, 'lexical_coefficient':True, 'Average_syllables_length':True, 'Average_sentences_length':True, 'Number_sentebnes':T...
cols_mfccs = ['MFCSS_' + str(i + 1) for i in range(mfcc[0])] k = [mfcc[1] for i in range(mfcc[0])] audio_features = dict(zip(cols_mfccs, k)) cols_chroma = ['Chroma_' + str(i + 1) for i in range(chromagram[0])] k = [chromagram[1] for i in range(chromagram[0])] audio_features .update(zip(cols_chroma,...
identifier_body
data_helper.py
# -*- coding: utf-8 -*- import configparser as cp import os from hdfs import InsecureClient import pandas as pd import requests from bs4 import BeautifulSoup import numpy as np import itertools import datetime import socket def ConfigSectionMap(config, section): dict_data = {} options = config.options(section...
(s): if s == 'True': return True elif s == 'False': return False else: raise ValueError('Not Valid Input') def build_output(name, task, status): output = {'Service': name, 'Task': task, 'Status': status} return output
str2bool
identifier_name
data_helper.py
# -*- coding: utf-8 -*- import configparser as cp import os from hdfs import InsecureClient import pandas as pd import requests from bs4 import BeautifulSoup import numpy as np import itertools import datetime import socket def ConfigSectionMap(config, section): dict_data = {} options = config.options(section...
'East Asian':links[133:145], 'South & southeast Asian':links[146:164], 'Avant-garde':links[165:169],'Blues':links[170:196], 'Caribbean':links[197:233], 'Comedy':links[234:237], 'Country':links[238:273], 'Ea...
# in this case, all of the links we're in a '<li>' brackets. for i in b.find_all(name = 'li'): links.append(i.text) general_genres = {'African':links[81:127], 'Asian':links[128:132],
random_line_split
Minebot.py
import urllib2 import re import urllib import socket import thread from time import sleep items = [['0', 'Air'], ['1', 'Stone'], ['2', 'Grass'], ['3', 'Dirt'], ['4', 'Cobblestone'], ['5', 'Wooden Plank'], ['6', 'Sapling'], ['6:1', 'Redwood Sapling'], ['6:2', 'Birch Sapling'], ['7', 'Bedrock'], ['8', 'Water'],...
toIRC("{C2}"+g[0][:-1]+"_:{} "+msg,toAdullam) continue login = re.match("^.*INFO] (.*) .* .*logged in$",line) if login: g=login.groups() toIRC("{C2}"+g[0]+" {}logged in.") plist = re.match("^.*INFO] Connected players:(.*)$",li...
random_line_split
Minebot.py
import urllib2 import re import urllib import socket import thread from time import sleep items = [['0', 'Air'], ['1', 'Stone'], ['2', 'Grass'], ['3', 'Dirt'], ['4', 'Cobblestone'], ['5', 'Wooden Plank'], ['6', 'Sapling'], ['6:1', 'Redwood Sapling'], ['6:2', 'Birch Sapling'], ['7', 'Bedrock'], ['8', 'Water'],...
sres = filter(exact,items) if sres or len(res)==1: toMinecraft("ID: "+str(res[0])) return res[0][0] if len(res) > 1: lst = ", ".join(map(lambda x:" ".join(x[1:]),res)) toMinecraft("Multiple matches: "+lst) return None def give(player,name,quant=1): try: ...
toMinecraft("No items found") return
conditional_block
Minebot.py
import urllib2 import re import urllib import socket import thread from time import sleep items = [['0', 'Air'], ['1', 'Stone'], ['2', 'Grass'], ['3', 'Dirt'], ['4', 'Cobblestone'], ['5', 'Wooden Plank'], ['6', 'Sapling'], ['6:1', 'Redwood Sapling'], ['6:2', 'Birch Sapling'], ['7', 'Bedrock'], ['8', 'Water'],...
def TP(src,dst): mc.send("tp {} {}\n".format(src,dst)) def mcThread(args): global running,mc,bot buffer = "" while running: tmp = mc.recv(100) buffer += tmp if not tmp or buffer.count("\n")==0: continue line,buffer=buffer.split("\n",1) ...
print "Lookup:",shorthand mc.send("list\n") resp = mc.recv(1024) if "Connected players:" not in resp: toMinecraft("Something strange happend...") toMinecraft(resp) return shorthand players = resp.split("players:")[1].replace(",","").split() matches = filter(lambda x:shorthand...
identifier_body
Minebot.py
import urllib2 import re import urllib import socket import thread from time import sleep items = [['0', 'Air'], ['1', 'Stone'], ['2', 'Grass'], ['3', 'Dirt'], ['4', 'Cobblestone'], ['5', 'Wooden Plank'], ['6', 'Sapling'], ['6:1', 'Redwood Sapling'], ['6:2', 'Birch Sapling'], ['7', 'Bedrock'], ['8', 'Water'],...
(args): global running,mc,bot buffer = "" while running: tmp = mc.recv(100) buffer += tmp if not tmp or buffer.count("\n")==0: continue line,buffer=buffer.split("\n",1) msg = re.match("^.*INFO] <(.*)> (.*)$",line) if msg: ...
mcThread
identifier_name
judger.rs
use crate::config::Config; use crate::{WsMessage, WsStream}; use heng_utils::container::inject; use heng_protocol::common::JudgeResult; use heng_protocol::error::ErrorCode; use heng_protocol::internal::{ConnectionSettings, ErrorInfo, PartialConnectionSettings}; use heng_protocol::internal::ws_json::{ CreateJudge...
async fn report_status_loop(self: Arc<Self>) -> Result<()> { loop { let delay = self.settings.status_report_interval.load(Relaxed); time::sleep(Duration::from_millis(delay)).await; let result = self .wsrpc(RpcRequest::ReportStatus(ReportStatusArgs { ...
{ info!("starting main loop"); while let Some(frame) = ws_stream.next().await { use tungstenite::Message::*; let frame = frame?; match frame { Close(reason) => { warn!(?reason, "ws session closed"); return Ok((...
identifier_body
judger.rs
use crate::config::Config; use crate::{WsMessage, WsStream}; use heng_utils::container::inject; use heng_protocol::common::JudgeResult; use heng_protocol::error::ErrorCode; use heng_protocol::internal::{ConnectionSettings, ErrorInfo, PartialConnectionSettings}; use heng_protocol::internal::ws_json::{ CreateJudge...
(ws_stream: WsStream) -> Result<()> { let config = inject::<Config>(); let (ws_sink, ws_stream) = ws_stream.split(); let (tx, rx) = mpsc::channel::<WsMessage>(4096); task::spawn( ReceiverStream::new(rx) .map(Ok) .forward(ws_sink) ...
run
identifier_name
judger.rs
use crate::config::Config; use crate::{WsMessage, WsStream}; use heng_utils::container::inject; use heng_protocol::common::JudgeResult; use heng_protocol::error::ErrorCode; use heng_protocol::internal::{ConnectionSettings, ErrorInfo, PartialConnectionSettings}; use heng_protocol::internal::ws_json::{ CreateJudge...
let judger = Arc::new(Self { settings: Settings { status_report_interval: AtomicU64::new(1000), }, session: WsSession { sender: tx, seq: AtomicU32::new(0), callbacks: DashMap::new(), }, c...
ReceiverStream::new(rx) .map(Ok) .forward(ws_sink) .inspect_err(|err| error!(%err, "ws forward error")), );
random_line_split
augment.py
# -*- coding: utf-8 -*- """ @project: 201904_dual_shot @file: augment.py @author: danna.li @time: 2019-06-03 11:33 @description: """ from __future__ import division import cv2 import numpy as np from numpy import random from PIL import Image import math class ConvertFromInts(object): def __call__(self, image, b...
s, labels): if random.randint(5): return image, boxes, labels height, width, depth = image.shape ratio = random.uniform(1, 4) left = random.uniform(0, width * ratio - width) top = random.uniform(0, height * ratio - height) expand_image = np.zeros( ...
elf, image, boxe
identifier_body
augment.py
# -*- coding: utf-8 -*- """ @project: 201904_dual_shot @file: augment.py @author: danna.li @time: 2019-06-03 11:33 @description: """ from __future__ import division import cv2 import numpy as np from numpy import random from PIL import Image import math class ConvertFromInts(object): def __call__(self, image, b...
__init__(self, size=300, mean=(104, 117, 123)): # self.mean = mean # self.size = size # # self.augment = Compose([ # Expand(self.mean), # RandomSSDCrop() # ]) class Augmentation(object): def __init__(self, mean=(104, 117, 123)): self.mean = mean ...
nsform(x, y) xx.append(x_) yy.append(y_) box_rot = [min(xx) + dx, min(yy) + dy, max(xx) + dx, max(yy) + dy] boxes_rot.append(box_rot) img_out,box_out = np.array(img_rotate)/255.0, np.array(boxes_rot) return img_out,box_out, labels # class Augmenta...
conditional_block
augment.py
# -*- coding: utf-8 -*- """ @project: 201904_dual_shot @file: augment.py @author: danna.li @time: 2019-06-03 11:33 @description: """ from __future__ import division import cv2 import numpy as np from numpy import random from PIL import Image import math class ConvertFromInts(object): def
(self, image, boxes=None, labels=None): return image.astype(np.float32), boxes, labels class RandomSaturation(object): def __init__(self, lower=0.5, upper=1.5): self.lower = lower self.upper = upper assert self.upper >= self.lower, "contrast upper must be >= lower." assert ...
__call__
identifier_name
augment.py
# -*- coding: utf-8 -*- """ @project: 201904_dual_shot @file: augment.py @author: danna.li @time: 2019-06-03 11:33 @description: """ from __future__ import division import cv2 import numpy as np from numpy import random from PIL import Image import math class ConvertFromInts(object): def __call__(self, image, b...
def __call__(self, image, boxes, labels=None): angle = self.angle % 360.0 img = Image.fromarray((image*255).astype(np.uint8)) h = img.size[1] w = img.size[0] center_x = int(np.floor(w / 2)) center_y = int(np.floor(h / 2)) img_rotate = img.rotate(angle, expand=...
random_line_split
views.py
# -*- coding: utf-8 -*- import urllib from urllib2 import HTTPError from datetime import datetime from flask.views import MethodView from flask.ext.login import current_user, login_required from flask.ext.paginate import Pagination as PaginationBar from flask import render_template, redirect, url_for, request, jsonify...
': title = data['title'] UserOperation(user_id=current_user.id, operation=Operation.DELETE, title=title).save() query = WaitingQueue.query.filter_by(title=data['title']).first() if query: query.delete() response = jsonify({'result': True}) ...
title = data["title"] env = Env() current_weight = env.get("CUTTING_WEIGHT_INIT") entry = WaitingQueue.query.filter_by(title=title).first() if entry: entry.cutting_weight = current_weight + 1 # FIXME: 即使条目处于权重最高状态亦可增加权限 entry.save() ...
conditional_block
views.py
# -*- coding: utf-8 -*- import urllib from urllib2 import HTTPError from datetime import datetime from flask.views import MethodView from flask.ext.login import current_user, login_required from flask.ext.paginate import Pagination as PaginationBar from flask import render_template, redirect, url_for, request, jsonify...
user_info = User.query.filter_by(username=username, deleted=False).first() if user_info: form = self.admin_form() form.email.data = user_info.email form.about_me.data = user_info.aboutme form.role.data = user_info.role.na...
identifier_name
views.py
# -*- coding: utf-8 -*- import urllib from urllib2 import HTTPError from datetime import datetime from flask.views import MethodView from flask.ext.login import current_user, login_required from flask.ext.paginate import Pagination as PaginationBar from flask import render_template, redirect, url_for, request, jsonify...
identifier_body
views.py
# -*- coding: utf-8 -*- import urllib from urllib2 import HTTPError from datetime import datetime from flask.views import MethodView from flask.ext.login import current_user, login_required from flask.ext.paginate import Pagination as PaginationBar from flask import render_template, redirect, url_for, request, jsonify...
return render_template('main/failed.html', e=result) def fresh_access(self): # config = current_app.config["WEIBO_AUTH_CONFIG"] # callback = config["CALLBACK"] # app_key = config["APP_KEY"] # app_secret_key = config["APP_SECRET"] try: pass ...
return render_template('main/success.html') else:
random_line_split
bfr.py
from copy import deepcopy from pickle import FALSE from re import sub import sys import time import json from pyspark import SparkContext,SparkConf import random from pyspark import StorageLevel from collections import defaultdict import math import os from pathlib import Path # os.environ['PYSPARK_PYTHON'] = '/usr/loc...
for _ in range(k-1): dis = [] for point in points: #calculate tmp_ds = [] for i, c in enumerate(centroid): if point != c: # print("point",point) # print("c",c) tmp_ds.append((eucl...
random_line_split
bfr.py
from copy import deepcopy from pickle import FALSE from re import sub import sys import time import json from pyspark import SparkContext,SparkConf import random from pyspark import StorageLevel from collections import defaultdict import math import os from pathlib import Path # os.environ['PYSPARK_PYTHON'] = '/usr/loc...
(cluster,DIM): _sum = [] _sumq = [] for _ in range(DIM): _sum.append(0) _sumq.append(0) for point in cluster: _sum = point_addition(_sum, point[1],1) _sumq = point_addition(_sumq, point[1],2) lv = len(cluster) res = [lv, _sum, _sumq] return res def merge_list(...
cal_cluster_squ
identifier_name
bfr.py
from copy import deepcopy from pickle import FALSE from re import sub import sys import time import json from pyspark import SparkContext,SparkConf import random from pyspark import StorageLevel from collections import defaultdict import math import os from pathlib import Path # os.environ['PYSPARK_PYTHON'] = '/usr/loc...
#cal nonsample Sample_set = {point[0] for point in sample_points} non_sample = [] for point in POINTS: if point[0] not in Sample_set: non_sample.append(point) new_clusters = kmeans(non_sample, 3*n_clusters) ...
DS.append(cal_cluster_squ(cluster,DIM)) idx = [] for point in cluster: idx.append(point[0]) DS_CLUSTER.append(idx)
conditional_block
bfr.py
from copy import deepcopy from pickle import FALSE from re import sub import sys import time import json from pyspark import SparkContext,SparkConf import random from pyspark import StorageLevel from collections import defaultdict import math import os from pathlib import Path # os.environ['PYSPARK_PYTHON'] = '/usr/loc...
def find_centroid(points): points = list(points) dim = len(points[0][1]) centroid = [] for _ in range(dim): centroid.append(0) for point in points: for i in range(dim): centroid[i] += point[1][i] tmp = [] for x in centroid: tmp.append(x/len(points)) ...
ds = [] # print(point) for i, c in enumerate(centroid): if point != c: # print(c) if c == 0: print(point, centroid) eud = euclidean(point, (0,c)) ds.append((eud,i)) min_ds = min(ds) return (min_ds[1], point)
identifier_body
DoGrouping.py
from ReadSpreadsheets import ReadSpreadsheets import csv import utilities as utils import pickle from LabelClass import * import copy import pySettings as pySet MIN_COSINE = 0.6 class MergeSpreadsheet: def findGrouped(self, labelObj1, lsPossible): global MIN_COSINE # for each label, look for corr...
(self,lsMerged,lsAlone,output_name): print 'writing master spreadsheet' export_file = open(pySet.OUTPUT_PATH + '{}-values.csv'.format(output_name), 'w+') max_num = max([len(x.lsOrigColumnValues) for x in lsMerged] + [len(x.lsOrigColumnValues) for x in lsAlone]) for i in xrange(max_...
writeSpreadsheet
identifier_name
DoGrouping.py
from ReadSpreadsheets import ReadSpreadsheets import csv import utilities as utils import pickle from LabelClass import * import copy import pySettings as pySet MIN_COSINE = 0.6 class MergeSpreadsheet: def findGrouped(self, labelObj1, lsPossible): global MIN_COSINE # for each label, look for corr...
def findMaxGroup(self, lsMatrix, dMapRev): # print lsMatrix # print dMapRev global MIN_COSINE lsGrouping = [] lsGroupingIndex = [] lsGroupingScore = [] for i in range(0, len(lsMatrix)): # get max num in each column lsCol...
rs = ReadSpreadsheets() print 'reading spreadsheets' rs.readSpreadsheets(lsSpreadsheets) dAllCombos = {} # dAll2 = {} print 'comparing spreadsheets' i = 0 for spreadObj in rs.lsSpreadsheetObjs[0:-1]: # print spreadObj for spreadOb...
identifier_body
DoGrouping.py
from ReadSpreadsheets import ReadSpreadsheets import csv import utilities as utils import pickle from LabelClass import * import copy import pySettings as pySet MIN_COSINE = 0.6 class MergeSpreadsheet: def findGrouped(self, labelObj1, lsPossible): global MIN_COSINE # for each label, look for corr...
export_file.write('\n') export_file.close() if __name__ == '__main__': import sys lsSpreadsheets = sys.argv #lsSpreadsheets = ['/Users/lisa/Desktop/AutomaticClusterLabels/Raw2/2010_04_11 Chung 197 CEL clinical_NO ID.csv','/Users/lisa/Desktop/AutomaticClusterLabels/Raw2/Califan...
try: export_file.write('{},,'.format(label.lsOrigColumnValues[i-2])) except: export_file.write(',,')
conditional_block
DoGrouping.py
from ReadSpreadsheets import ReadSpreadsheets import csv import utilities as utils import pickle from LabelClass import * import copy import pySettings as pySet MIN_COSINE = 0.6 class MergeSpreadsheet: def findGrouped(self, labelObj1, lsPossible): global MIN_COSINE # for each label, look for corr...
lsMerged = [list(set(lsObj)) for lsObj in lsMerged] #create new name lsMerged2=[] for ls1 in lsMerged: ls2 = self.findName(ls1) lsMerged2.extend(ls2) return lsMerged2, list(set(lsAlone)) ...
random_line_split
parsers.py
import abc import base64 import logging import os from typing import Dict import exifread import fitparse from app.base.exceptions import PyrTypeError, PyrError from app.data.models import Environment, Physiologic, Activity, DataModel, Gear, TravellerProfile, Unclassified from app.data.geographic.constants import COO...
class VideoParser(Parser): def _parse(self): return {}
f = open(file_path, 'rb') tags = exifread.process_file(f) image_info = {} gps_info = {} thumbnail_info = {} maker_info = {} exit_info = {} other_info = {} for tag in tags: key_array = tag.split(' ') category = key_array[0].lower() ...
identifier_body
parsers.py
import abc import base64 import logging import os from typing import Dict import exifread import fitparse from app.base.exceptions import PyrTypeError, PyrError from app.data.models import Environment, Physiologic, Activity, DataModel, Gear, TravellerProfile, Unclassified from app.data.geographic.constants import COO...
(Parser): def _parse(self): return self.parse_exif(self._file_path) @staticmethod def parse_exif(file_path): f = open(file_path, 'rb') tags = exifread.process_file(f) image_info = {} gps_info = {} thumbnail_info = {} maker_info = {} exit_info...
PhotoParser
identifier_name
parsers.py
import abc import base64 import logging import os from typing import Dict import exifread import fitparse from app.base.exceptions import PyrTypeError, PyrError from app.data.models import Environment, Physiologic, Activity, DataModel, Gear, TravellerProfile, Unclassified from app.data.geographic.constants import COO...
elif category in PHOTO_DATA_IMAGE[1]: image_info.update(item) elif category in PHOTO_DATA_THUMBNAIL[1]: thumbnail_info.update(item) elif category in PHOTO_DATA_MAKER[1]: maker_info.update(item) else: item = ...
gps_info.update(item)
conditional_block
parsers.py
import abc import base64 import logging import os from typing import Dict import exifread import fitparse from app.base.exceptions import PyrTypeError, PyrError from app.data.models import Environment, Physiologic, Activity, DataModel, Gear, TravellerProfile, Unclassified from app.data.geographic.constants import COO...
data_for_store.update(extra_data) return mongodb.insert(collection, data_for_store) class FitParser(Parser): _activity_record: [] = [] _gears: [] = [] _activity: [] = [] _traveller: [] = [] _unclassified: [] = [] def _parse(self): try: fit_file = fitpa...
data_for_store = {'data': self._result, 'path': get_relative_path(self._file_path)} if extra_data is not None:
random_line_split
compile.rs
use std::fs; use std::path::{Path, PathBuf}; use codespan_reporting::diagnostic::{Diagnostic, Label}; use codespan_reporting::term::{self, termcolor}; use termcolor::{ColorChoice, StandardStream}; use typst::diag::{bail, Severity, SourceDiagnostic, StrResult}; use typst::doc::Document; use typst::eval::{eco_format, Tr...
Severity::Warning => Diagnostic::warning(), } .with_message(diagnostic.message.clone()) .with_notes( diagnostic .hints .iter() .map(|e| (eco_format!("hint: {e}")).into()) .collect(), ) .with_l...
for diagnostic in warnings.iter().chain(errors.iter()) { let diag = match diagnostic.severity { Severity::Error => Diagnostic::error(),
random_line_split
compile.rs
use std::fs; use std::path::{Path, PathBuf}; use codespan_reporting::diagnostic::{Diagnostic, Label}; use codespan_reporting::term::{self, termcolor}; use termcolor::{ColorChoice, StandardStream}; use typst::diag::{bail, Severity, SourceDiagnostic, StrResult}; use typst::doc::Document; use typst::eval::{eco_format, Tr...
impl<'a> codespan_reporting::files::Files<'a> for SystemWorld { type FileId = FileId; type Name = String; type Source = Source; fn name(&'a self, id: FileId) -> CodespanResult<Self::Name> { let vpath = id.vpath(); Ok(if let Some(package) = id.package() { format!("{package}...
{ let mut w = match diagnostic_format { DiagnosticFormat::Human => color_stream(), DiagnosticFormat::Short => StandardStream::stderr(ColorChoice::Never), }; let mut config = term::Config { tab_width: 2, ..Default::default() }; if diagnostic_format == DiagnosticFormat::Short { co...
identifier_body
compile.rs
use std::fs; use std::path::{Path, PathBuf}; use codespan_reporting::diagnostic::{Diagnostic, Label}; use codespan_reporting::term::{self, termcolor}; use termcolor::{ColorChoice, StandardStream}; use typst::diag::{bail, Severity, SourceDiagnostic, StrResult}; use typst::doc::Document; use typst::eval::{eco_format, Tr...
(&'a self, id: FileId) -> CodespanResult<Self::Name> { let vpath = id.vpath(); Ok(if let Some(package) = id.package() { format!("{package}{}", vpath.as_rooted_path().display()) } else { // Try to express the path relative to the working directory. vpath ...
name
identifier_name
main.rs
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")] #[macro_use] extern crate error_chain; use std::cell::{Cell, RefCell}; use std::f32; use std::path::PathBuf; use std::rc::Rc; use std::str::FromStr; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex}; use std::time::{Duration, ...
#[cfg(not(feature = "networking"))] /// Always returns false without the `networking` feature. fn check_for_updates() -> bool { false } #[cfg(feature = "networking")] /// Returns true if updates are available. fn check_for_updates() -> bool { let client; match reqwest::blocking::Client::builder().user_agent("emuls...
random_line_split
main.rs
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")] #[macro_use] extern crate error_chain; use std::cell::{Cell, RefCell}; use std::f32; use std::path::PathBuf; use std::rc::Rc; use std::str::FromStr; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex}; use std::time::{Duration, ...
() -> bool { false } #[cfg(feature = "networking")] /// Returns true if updates are available. fn check_for_updates() -> bool { let client; match reqwest::blocking::Client::builder().user_agent("emulsion").build() { Ok(c) => client = c, Err(e) => { println!("Could not build client for version request: {}", e...
check_for_updates
identifier_name
main.rs
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")] #[macro_use] extern crate error_chain; use std::cell::{Cell, RefCell}; use std::f32; use std::path::PathBuf; use std::rc::Rc; use std::str::FromStr; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex}; use std::time::{Duration, ...
if !cache_folder.exists() { std::fs::create_dir_all(&cache_folder).unwrap(); } (config_folder.join("cfg.toml"), cache_folder.join("cache.toml")) } #[cfg(not(feature = "networking"))] /// Always returns false without the `networking` feature. fn check_for_updates() -> bool { false } #[cfg(feature = "networking...
{ std::fs::create_dir_all(&config_folder).unwrap(); }
conditional_block
mod.rs
//! The central Framework struct that ties everything together. // Prefix and slash specific implementation details mod prefix; mod slash; mod builder; pub use builder::*; use crate::serenity::client::{bridge::gateway::ShardManager, Client}; use crate::serenity_prelude as serenity; use crate::*; pub use prefix::di...
else { (self.options.on_error)( err, crate::ErrorContext::Command(crate::CommandErrorContext::Prefix(ctx)), ) .await; } } } Event::...
{ (on_error)(err, ctx).await; }
conditional_block
mod.rs
//! The central Framework struct that ties everything together. // Prefix and slash specific implementation details mod prefix; mod slash; mod builder; pub use builder::*; use crate::serenity::client::{bridge::gateway::ShardManager, Client}; use crate::serenity_prelude as serenity; use crate::*; pub use prefix::di...
(&self) -> &U { // We shouldn't get a Message event before a Ready event. But if we do, wait until // the Ready event does come and the resulting data has arrived. loop { match self.user_data.get() { Some(x) => break x, None => tokio::time::sleep(std::...
get_user_data
identifier_name
mod.rs
//! The central Framework struct that ties everything together. // Prefix and slash specific implementation details mod prefix; mod slash; mod builder; pub use builder::*; use crate::serenity::client::{bridge::gateway::ShardManager, Client}; use crate::serenity_prelude as serenity; use crate::*; pub use prefix::di...
async fn check_required_permissions_and_owners_only<U, E>( ctx: crate::Context<'_, U, E>, required_permissions: serenity::Permissions, owners_only: bool, ) -> bool { if owners_only && !ctx.framework().options().owners.contains(&ctx.author().id) { return false; } if !check_permissions(...
{ if required_permissions.is_empty() { return true; } let guild_id = match ctx.guild_id() { Some(x) => x, None => return true, // no permission checks in DMs }; let guild = match ctx.discord().cache.guild(guild_id) { Some(x) => x, None => return false, // Gu...
identifier_body
mod.rs
//! The central Framework struct that ties everything together. // Prefix and slash specific implementation details mod prefix; mod slash; mod builder; pub use builder::*; use crate::serenity::client::{bridge::gateway::ShardManager, Client}; use crate::serenity_prelude as serenity; use crate::*; pub use prefix::di...
pub fn application_id(&self) -> serenity::ApplicationId { self.application_id } /// Returns the serenity's client shard manager. pub fn shard_manager(&self) -> std::sync::Arc<tokio::sync::Mutex<ShardManager>> { self.shard_manager .lock() .unwrap() .cl...
&self.options } /// Returns the application ID given to the framework on its creation.
random_line_split
plugin.go
package main import ( "errors" "fmt" "log" "net/http" "net/url" "strconv" "strings" "time" "github.com/NoahShen/gotunnelme/src/gotunnelme" "github.com/appleboy/com/random" "github.com/appleboy/drone-facebook/template" "github.com/fatih/color" "github.com/line/line-bot-sdk-go/linebot" "github.com/prometh...
} } } }) mux.HandleFunc("/metrics", func(w http.ResponseWriter, req *http.Request) { promhttp.Handler().ServeHTTP(w, req) }) // Setup HTTP Server for receiving requests from LINE platform mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) { fmt.Fprintln(w, "Welcome to Line webhook p...
{ log.Print(err) }
conditional_block
plugin.go
package main import ( "errors" "fmt" "log" "net/http" "net/url" "strconv" "strings" "time" "github.com/NoahShen/gotunnelme/src/gotunnelme" "github.com/appleboy/com/random" "github.com/appleboy/drone-facebook/template" "github.com/fatih/color" "github.com/line/line-bot-sdk-go/linebot" "github.com/prometh...
func trimElement(keys []string) []string { var newKeys []string for _, value := range keys { value = strings.Trim(value, " ") if len(value) == 0 { continue } newKeys = append(newKeys, value) } return newKeys } func convertImage(value, delimiter string) []string { values := trimElement(strings.Split...
{ // Support metrics m := NewMetrics() prometheus.MustRegister(m) }
identifier_body
plugin.go
package main import ( "errors" "fmt" "log" "net/http" "net/url" "strconv" "strings" "time" "github.com/NoahShen/gotunnelme/src/gotunnelme" "github.com/appleboy/com/random" "github.com/appleboy/drone-facebook/template" "github.com/fatih/color" "github.com/line/line-bot-sdk-go/linebot" "github.com/prometh...
// Bot is new Line Bot clien. func (p Plugin) Bot() (*linebot.Client, error) { if len(p.Config.ChannelToken) == 0 || len(p.Config.ChannelSecret) == 0 { log.Println("missing line bot config") return nil, errors.New("missing line bot config") } return linebot.New(p.Config.ChannelSecret, p.Config.ChannelToken) } ...
}
random_line_split
plugin.go
package main import ( "errors" "fmt" "log" "net/http" "net/url" "strconv" "strings" "time" "github.com/NoahShen/gotunnelme/src/gotunnelme" "github.com/appleboy/com/random" "github.com/appleboy/drone-facebook/template" "github.com/fatih/color" "github.com/line/line-bot-sdk-go/linebot" "github.com/prometh...
() error { bot, err := p.Bot() if err != nil { return err } if len(p.Config.To) == 0 && len(p.Config.ToRoom) == 0 && len(p.Config.ToGroup) == 0 { log.Println("missing line user config") return errors.New("missing line user config") } var message []string if len(p.Config.Message) > 0 { message = p.Co...
Exec
identifier_name
render.rs
extern crate gl; extern crate libc; use vecmath::Vec2; use gl::types::*; use std::ffi::CString; use libc::{c_char, c_int}; use std::mem::{uninitialized, transmute, size_of}; use std::ptr; use std::slice; use std::vec::Vec; use assets; macro_rules! check_error( () => ( match gl::GetError() { gl...
pub fn loaded(&self) -> bool { self.vbo != 0 } pub unsafe fn load(&mut self) { let mut texture = load_texture(self.filename); texture.generate_texcoords_buffer(self.frame_width, self.frame_height, self.texcoords()); self.texture = texture; gl::GenBuffers(1, &mut self.vbo); ...
{ let count_ptr: *mut usize = &mut self.texcoord_count; slice::from_raw_parts_mut::<Texcoords>( transmute(count_ptr.offset(1)), self.texcoord_count ) }
identifier_body
render.rs
extern crate gl; extern crate libc; use vecmath::Vec2; use gl::types::*; use std::ffi::CString; use libc::{c_char, c_int}; use std::mem::{uninitialized, transmute, size_of}; use std::ptr; use std::slice; use std::vec::Vec; use assets; macro_rules! check_error( () => ( match gl::GetError() { gl...
} } /* fn put_texcoord(&mut self, index: usize, texcoord: Texcoords) { self.texcoords_mut()[index] = texcoord; } */ // NOTE this should be properly merged with add_frames. pub fn generate_texcoords_buffer( &mut self, frame_width: usize, frame_height: usize, space: ...
{ gl::Uniform2fv( frames_uniform, frames_len as GLint * 4, transmute(&(&*self.texcoords_space)[0]) ); }
conditional_block
render.rs
extern crate gl; extern crate libc; use vecmath::Vec2; use gl::types::*; use std::ffi::CString; use libc::{c_char, c_int}; use std::mem::{uninitialized, transmute, size_of}; use std::ptr; use std::slice; use std::vec::Vec; use assets; macro_rules! check_error( () => ( match gl::GetError() { gl...
macro_rules! check_log( ($typ:expr, $get_iv:ident | $get_log:ident $val:ident $status:ident $on_error:ident) => ( unsafe { let mut status = 0; gl::$get_iv($val, gl::$status, &mut status); if status == 0 { let mut len = 0; gl::$get_iv($val,...
color = texture(tex, texcoord); } ";
random_line_split
render.rs
extern crate gl; extern crate libc; use vecmath::Vec2; use gl::types::*; use std::ffi::CString; use libc::{c_char, c_int}; use std::mem::{uninitialized, transmute, size_of}; use std::ptr; use std::slice; use std::vec::Vec; use assets; macro_rules! check_error( () => ( match gl::GetError() { gl...
(&mut self) -> &mut [Texcoords] { let count_ptr: *mut usize = &mut self.texcoord_count; slice::from_raw_parts_mut::<Texcoords>( transmute(count_ptr.offset(1)), self.texcoord_count ) } pub fn loaded(&self) -> bool { self.vbo != 0 } pub unsafe fn load(&mut sel...
texcoords
identifier_name
Assignment+2.py
# coding: utf-8 # --- # # _You are currently looking at **version 1.0** of this notebook. To download notebooks and datafiles, as well as get help on Jupyter notebooks in the Coursera platform, visit the [Jupyter Notebook FAQ](https://www.coursera.org/learn/python-text-mining/resources/d9pwm) course resource._ # # -...
# # Each of the recommenders should provide recommendations for the three default words provided: `['cormulent', 'incendenece', 'validrate']`. # In[94]: from nltk.corpus import words correct_spellings = words.words() # ### Question 9 # # For this recommender, your function should provide recommendations for the...
# # *Each of the three different recommenders will use a different distance measure (outlined below).
random_line_split
Assignment+2.py
# coding: utf-8 # --- # # _You are currently looking at **version 1.0** of this notebook. To download notebooks and datafiles, as well as get help on Jupyter notebooks in the Coursera platform, visit the [Jupyter Notebook FAQ](https://www.coursera.org/learn/python-text-mining/resources/d9pwm) course resource._ # # ...
(): return len(set(nltk.word_tokenize(moby_raw))) # or alternatively len(set(text1)) example_two() # ### Example 3 # # After lemmatizing the verbs, how many unique tokens does text1 have? # # *This function should return an integer.* # In[85]: from nltk.stem import WordNetLemmatizer def example_three(...
example_two
identifier_name
Assignment+2.py
# coding: utf-8 # --- # # _You are currently looking at **version 1.0** of this notebook. To download notebooks and datafiles, as well as get help on Jupyter notebooks in the Coursera platform, visit the [Jupyter Notebook FAQ](https://www.coursera.org/learn/python-text-mining/resources/d9pwm) course resource._ # # ...
def answer_ten(entries=['cormulent', 'incendenece', 'validrate']): max_dists, max_words, quadgrams = {}, {}, {} for entry in entries: max_dists[entry] = 1.0 max_words[entry] = None quadgrams[entry] = create_quadgram(entry) def try_correct(correct_spelling, incorrect_spelling): ...
quadgrams = [] for i in range(0, len(w)-3): quadgrams.append(w[i:i+4]) return set(quadgrams)
identifier_body
Assignment+2.py
# coding: utf-8 # --- # # _You are currently looking at **version 1.0** of this notebook. To download notebooks and datafiles, as well as get help on Jupyter notebooks in the Coursera platform, visit the [Jupyter Notebook FAQ](https://www.coursera.org/learn/python-text-mining/resources/d9pwm) course resource._ # # ...
return [max_words[entry] for entry in entries] answer_ten() # ### Question 11 # # For this recommender, your function should provide recommendations for the three default words provided above using the following distance metric: # # **[Edit distance on the two words with transposition...
try_correct(correct_spelling, entry)
conditional_block
vault.rs
// ENV: https://www.vaultproject.io/docs/commands/#environment-variables use std::borrow::Cow; use std::collections::HashMap; use std::fmt::Debug; use log::{debug, info, warn}; use reqwest::{Client as HttpClient, ClientBuilder}; use serde::{Deserialize, Serialize}; /// Vault API Client #[derive(Clone, Debug)] pub str...
() -> Result<(), crate::Error> { let client = Client::new(vault_address(), "vault_token", false, None)?; let request = client.build_nomad_token_request("nomad", "default")?; assert_eq!( format!("{}/v1/nomad/creds/default", vault_address()), request.url().to_string() ...
nomad_token_request_is_built_properly
identifier_name
vault.rs
// ENV: https://www.vaultproject.io/docs/commands/#environment-variables use std::borrow::Cow; use std::collections::HashMap; use std::fmt::Debug; use log::{debug, info, warn}; use reqwest::{Client as HttpClient, ClientBuilder}; use serde::{Deserialize, Serialize}; /// Vault API Client #[derive(Clone, Debug)] pub str...
fn build_nomad_token_request( &self, nomad_path: &str, nomad_role: &str, ) -> Result<reqwest::Request, crate::Error> { let vault_address = url::Url::parse(self.address())?; let vault_address = vault_address.join(&format!("/v1/{}/creds/{}", nomad_path, nomad_...
{ let vault_address = url::Url::parse(self.address())?; let vault_address = vault_address.join("/v1/auth/token/revoke-self")?; Ok(self .client .post(vault_address) .header("X-Vault-Token", self.token.as_str()) .build()?) }
identifier_body
vault.rs
// ENV: https://www.vaultproject.io/docs/commands/#environment-variables use std::borrow::Cow; use std::collections::HashMap; use std::fmt::Debug; use log::{debug, info, warn}; use reqwest::{Client as HttpClient, ClientBuilder}; use serde::{Deserialize, Serialize}; /// Vault API Client #[derive(Clone, Debug)] pub str...
/// List of tokens directly assigned to token pub token_policies: Vec<String>, /// Arbitrary metadata pub metadata: HashMap<String, String>, /// Lease Duration for the token pub lease_duration: u64, /// Whether the token is renewable pub renewable: bool, /// UUID for the entity p...
pub client_token: crate::Secret, /// The accessor for the Token pub accessor: String, /// List of policies for token, including from Identity pub policies: Vec<String>,
random_line_split
controlPanel.go
package main import ( "fmt" "golang.org/x/exp/shiny/gesture" "golang.org/x/exp/shiny/iconvg" "golang.org/x/exp/shiny/materialdesign/icons" "golang.org/x/exp/shiny/screen" "golang.org/x/exp/shiny/unit" "golang.org/x/exp/shiny/widget" "golang.org/x/exp/shiny/widget/node" "golang.org/x/exp/shiny/widget/theme" "...
if open { return "Close all" } else { return "Open all" } }) return button } func (p *ControlPanel) NewNetworkTickers() node.Node { vf := widget.NewFlow(widget.AxisVertical) vf.Insert(p.NewTicker("Total updates:", func() string { return fmt.Sprintf("%d", <-p.world.totalSendsChan) }), nil) queued := ...
{ dest := &p.world.scenario.Destinations[i] if dest.ID == p.world.scenario.Exit.ID { continue } if open { dest.Close() } else { dest.Open() } }
conditional_block
controlPanel.go
package main import ( "fmt" "golang.org/x/exp/shiny/gesture" "golang.org/x/exp/shiny/iconvg" "golang.org/x/exp/shiny/materialdesign/icons" "golang.org/x/exp/shiny/screen" "golang.org/x/exp/shiny/unit" "golang.org/x/exp/shiny/widget" "golang.org/x/exp/shiny/widget/node" "golang.org/x/exp/shiny/widget/theme" "...
func (w *Button) OnInputEvent(e interface{}, origin image.Point) node.EventHandled { switch e := e.(type) { case gesture.Event: if e.Type != gesture.TypeTap { break } if w.onClick != nil { w.uniform.ThemeColor = theme.StaticColor(colornames.Orange) w.uniform.Mark(node.MarkNeedsPaintBase) go w.onCl...
{ w := &Button{ icon: icon, } fn := func() { w.pressed = !w.pressed w.label.Text = fmt.Sprintf("%-30s", onClick()) w.label.Mark(node.MarkNeedsPaintBase) if w.pressed || !toggle { w.uniform.ThemeColor = theme.StaticColor(colornames.Lightgreen) } else { w.uniform.ThemeColor = theme.StaticColor(colorn...
identifier_body
controlPanel.go
package main import ( "fmt" "golang.org/x/exp/shiny/gesture" "golang.org/x/exp/shiny/iconvg" "golang.org/x/exp/shiny/materialdesign/icons" "golang.org/x/exp/shiny/screen" "golang.org/x/exp/shiny/unit" "golang.org/x/exp/shiny/widget" "golang.org/x/exp/shiny/widget/node" "golang.org/x/exp/shiny/widget/theme" "...
node.LeafEmbed icon []byte z iconvg.Rasterizer } func NewIcon(icon []byte) *Icon { w := &Icon{ icon: icon, } w.Wrapper = w return w } func (w *Icon) Measure(t *theme.Theme, widthHint, heightHint int) { px := t.Pixels(unit.Ems(2)).Ceil() w.MeasuredSize = image.Point{X: px, Y: px} } func (w *Icon) PaintB...
type panelUpdate struct { } type Icon struct {
random_line_split