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
keyword_plan.pb.go
(m *KeywordPlan) XXX_DiscardUnknown() { xxx_messageInfo_KeywordPlan.DiscardUnknown(m) } var xxx_messageInfo_KeywordPlan proto.InternalMessageInfo func (m *KeywordPlan) GetResourceName() string { if m != nil { return m.ResourceName } return "" } func (m *KeywordPlan) GetId() *wrappers.Int64Value {...
return nil } // The forecasting period associated with the keyword plan. type KeywordPlanForecastPeriod struct { // Required. The date used for forecasting the Plan. // // Types that are valid to be assigned to Interval: // *KeywordPlanForecastPeriod_DateInterval // *KeywordPlanForecastPeriod_DateRang...
{ return m.ForecastPeriod }
conditional_block
keyword_plan.pb.go
func (m *KeywordPlan) XXX_DiscardUnknown() { xxx_messageInfo_KeywordPlan.DiscardUnknown(m) } var xxx_messageInfo_KeywordPlan proto.InternalMessageInfo func (m *KeywordPlan) GetResourceName() string { if m != nil { return m.ResourceName } return "" } func (m *KeywordPlan) GetId() *wrappers.Int64Val...
() {} func (*KeywordPlanForecastPeriod_DateRange) isKeywordPlanForecastPeriod_Interval() {} func (m *KeywordPlanForecastPeriod) GetInterval() isKeywordPlanForecastPeriod_Interval { if m != nil { return m.Interval } return nil } func (m *KeywordPlanForecastPeriod) GetDateInterval() enums.KeywordPlanFo...
isKeywordPlanForecastPeriod_Interval
identifier_name
keyword_plan.pb.go
xxx_messageInfo_KeywordPlan.Merge(m, src) } func (m *KeywordPlan) XXX_Size() int { return xxx_messageInfo_KeywordPlan.Size(m) } func (m *KeywordPlan) XXX_DiscardUnknown() { xxx_messageInfo_KeywordPlan.DiscardUnknown(m) } var xxx_messageInfo_KeywordPlan proto.InternalMessageInfo func (m *KeywordPlan) Get...
return xxx_messageInfo_KeywordPlan.Marshal(b, m, deterministic) } func (m *KeywordPlan) XXX_Merge(src proto.Message) {
random_line_split
main.go
_workload(workload_path string) bool { return strings.HasSuffix(workload_path, "bda.json") } func is_hpc_workload(workload_path string) bool { return strings.HasSuffix(workload_path, "hpc.json") } func getWorkloadID(id string) string
func recvBatsimMessage(socket *zmq.Socket) ([]byte, BatMessage) { msg, err = socket.RecvBytes(0) if err != nil { panic("Error while receiving Batsim message: " + err.Error()) } // reset message structure jmsg = BatMessage{} if err := json.Unmarshal(msg, &jmsg); err != nil { panic(err) } return msg, jmsg...
{ return strings.Split(id, "!")[0] }
identifier_body
main.go
_workload(workload_path string) bool { return strings.HasSuffix(workload_path, "bda.json") } func is_hpc_workload(workload_path string) bool { return strings.HasSuffix(workload_path, "hpc.json") } func getWorkloadID(id string) string { return strings.Split(id, "!")[0] } func recvBatsimMessage(socket *zmq.Socket) ...
// Inspect Batsim request now = jmsg.Now for _, event := range jmsg.Events { switch event.Type { case "SIMULATION_BEGINS": { fmt.Println("Hello Batsim!") // get workload/scheduler mapping for id, path := range event.Data["workloads"].(map[string]interface{}) { if is_hpc_workload(pat...
{ // clean structures hpc_events = []Event{} bda_events = []Event{} common_events = []Event{} jmsg = BatMessage{} bda_reply = BatMessage{} hpc_reply = BatMessage{} msg, err = bat_sock.RecvBytes(0) if err != nil { panic("Error while receiving Batsim message: " + err.Error()) } if err := json.U...
conditional_block
main.go
_workload(workload_path string) bool { return strings.HasSuffix(workload_path, "bda.json") } func is_hpc_workload(workload_path string) bool { return strings.HasSuffix(workload_path, "hpc.json") } func getWorkloadID(id string) string { return strings.Split(id, "!")[0] } func
(socket *zmq.Socket) ([]byte, BatMessage) { msg, err = socket.RecvBytes(0) if err != nil { panic("Error while receiving Batsim message: " + err.Error()) } // reset message structure jmsg = BatMessage{} if err := json.Unmarshal(msg, &jmsg); err != nil { panic(err) } return msg, jmsg } func removeEvents(to...
recvBatsimMessage
identifier_name
main.go
_workload(workload_path string) bool { return strings.HasSuffix(workload_path, "bda.json") } func is_hpc_workload(workload_path string) bool { return strings.HasSuffix(workload_path, "hpc.json") } func getWorkloadID(id string) string { return strings.Split(id, "!")[0] } func recvBatsimMessage(socket *zmq.Socket) ...
bda_workload = id } } fmt.Println("HPC Workload id is: ", hpc_workload) fmt.Println("BDA Workload id is: ", bda_workload) common_events = append(common_events, event) } case "JOB_SUBMITTED": { // Split message events using workload id switch getWorkloadID(event.Data...
} else if is_bda_workload(path.(string)) {
random_line_split
qutex.rs
derive(Debug)] pub struct Guard<T> { qutex: Qutex<T>, } impl<T> Guard<T> { /// Releases the lock held by a `Guard` and returns the original `Qutex`. pub fn unlock(guard: Guard<T>) -> Qutex<T> { let qutex = unsafe { ::std::ptr::read(&guard.qutex) }; ::std::mem::forget(guard); unsafe ...
(&self) { // TODO: Consider using `Ordering::Release`. self.inner.state.store(0, SeqCst); self.process_queue() } } impl<T> From<T> for Qutex<T> { #[inline] fn from(val: T) -> Qutex<T> { Qutex::new(val) } } // Avoids needing `T: Clone`. impl<T> Clone for Qutex<T> { #...
direct_unlock
identifier_name
qutex.rs
derive(Debug)] pub struct Guard<T> { qutex: Qutex<T>, } impl<T> Guard<T> { /// Releases the lock held by a `Guard` and returns the original `Qutex`. pub fn unlock(guard: Guard<T>) -> Qutex<T> { let qutex = unsafe { ::std::ptr::read(&guard.qutex) }; ::std::mem::forget(guard); unsafe ...
else { panic!("FutureGuard::poll: Task already completed."); } } } impl<T> Drop for FutureGuard<T> { /// Gracefully unlock if this guard has a lock acquired but has not yet /// been polled to completion. fn drop(&mut self) { if let Some(qutex) = self.qutex.take() { ...
{ unsafe { self.qutex.as_ref().unwrap().process_queue() } match self.rx.poll() { Ok(status) => Ok(status.map(|_| Guard { qutex: self.qutex.take().unwrap(), })), Err(e) => Err(e.into()), } }
conditional_block
qutex.rs
derive(Debug)] pub struct Guard<T> { qutex: Qutex<T>, } impl<T> Guard<T> { /// Releases the lock held by a `Guard` and returns the original `Qutex`. pub fn unlock(guard: Guard<T>) -> Qutex<T> { let qutex = unsafe { ::std::ptr::read(&guard.qutex) }; ::std::mem::forget(guard); unsafe ...
let (tx, rx) = oneshot::channel(); unsafe { self.push_request(Request::new(tx)); } FutureGuard::new(self, rx) } /// Pushes a lock request onto the queue. /// // // TODO: Evaluate unsafe-ness. // #[inline] pub unsafe fn push_request(&self, req:...
/// Returns a new `FutureGuard` which can be used as a future and will /// resolve into a `Guard`. pub fn lock(self) -> FutureGuard<T> {
random_line_split
qutex.rs
(Debug)] pub struct Guard<T> { qutex: Qutex<T>, } impl<T> Guard<T> { /// Releases the lock held by a `Guard` and returns the original `Qutex`. pub fn unlock(guard: Guard<T>) -> Qutex<T> { let qutex = unsafe { ::std::ptr::read(&guard.qutex) }; ::std::mem::forget(guard); unsafe { qute...
} #[cfg(test)] // Woefully incomplete: mod tests { use super::*; use futures::Future; #[test] fn simple() { let val = Qutex::from(999i32); println!("Reading val..."); { let future_guard = val.clone().lock(); let guard = future_guard.wait().unwrap(); ...
{ Qutex { inner: self.inner.clone(), } }
identifier_body
projects.py
) extra_top = models.TextField( null=True, blank=True, help_text="Content to inject at the top of the <body> element of HTML served for this project.", ) extra_bottom = models.TextField( null=True, blank=True, help_text="Content to inject at the bottom o...
(self) -> Optional[datetime.datetime]: """ Get the scheduled time for a warning of deletion email to be send to project owner. """ time = self.scheduled_deletion_time return time - Project.TEMPORARY_PROJECT_WARNING if time else None def get_main(self): """ Ge...
scheduled_deletion_warning
identifier_name
projects.py
=True ).order_by("-modified") if len(candidates): return candidates[0] return None def get_theme(self) -> str: """Get the theme for the project.""" return self.theme or self.account.theme def content_url(self, snapshot=None, path=None, live=False) -> str: ...
""" A user or team role within an account. See `get_description` for what each role can do. Some of roles can also be applied to the public. For example, a project might be made public with the `REVIEWER` role allowing anyone to comment. """ READER = "Reader" REVIEWER = "Reviewer" ...
identifier_body
projects.py
null=True, blank=True, help_text="The name of the theme to use as the default when generating content for this project." # See note for the `Account.theme` field for why this is a TextField. ) extra_head = models.TextField( null=True, blank=True, help_tex...
blank=True, help_text="When the image file was last updated (e.g. from image_path).", ) theme = models.TextField(
random_line_split
projects.py
) extra_top = models.TextField( null=True, blank=True, help_text="Content to inject at the top of the <body> element of HTML served for this project.", ) extra_bottom = models.TextField( null=True, blank=True, help_text="Content to inject at the bottom o...
else: # Try to find an image for the project and use the most # recently modified since the image was last updated images = self.files.filter( current=True, mimetype__startswith="image/", **modified_since, ).order_by("-modified") if le...
images = self.files.filter( current=True, path=self.image_path, **modified_since ).order_by("-modified") if len(images) > 0: self.set_image_from_file(images[0])
conditional_block
sbfdinitiator_ef4ed37c4520e95225e35be31ea6dde4.py
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. import sys from ixnetwork_restpy.base import Base from ixnetwork_restpy.files import Fi...
( self, Count=None, DescriptiveName=None, MplsLabelCount=None, Name=None, SessionInfo=None, ): # type: (int, str, int, str, List[str]) -> SbfdInitiator """Finds and retrieves sbfdInitiator resources from the server. All named parameters are ev...
find
identifier_name
sbfdinitiator_ef4ed37c4520e95225e35be31ea6dde4.py
OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. import sys from ixnetwork_restpy.base import Base from ixnetwork_restpy.files import...
Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): Tx Interval in Milli Seconds. Note: Initial transmission interval is set to maximum of 1s and configured Tx Interval. Once session comes up, the timer will auto-transition to the negotiated value i.e. maximum of local Tx Interval and...
# type: () -> 'Multivalue' """
random_line_split
sbfdinitiator_ef4ed37c4520e95225e35be31ea6dde4.py
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. import sys from ixnetwork_restpy.base import Base from ixnetwork_restpy.files import Fi...
return MplsLabelList(self) @property def Active(self): # type: () -> 'Multivalue' """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): Activate/Deactivate Configuration. """ from ixnetwork_restpy.multivalue import Multivalue ...
if self._properties.get("MplsLabelList", None) is not None: return self._properties.get("MplsLabelList")
conditional_block
sbfdinitiator_ef4ed37c4520e95225e35be31ea6dde4.py
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. import sys from ixnetwork_restpy.base import Base from ixnetwork_restpy.files import Fi...
@Name.setter def Name(self, value): # type: (str) -> None self._set_attribute(self._SDM_ATT_MAP["Name"], value) @property def PeerDiscriminator(self): # type: () -> 'Multivalue' """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): ...
""" Returns ------- - str: Name of NGPF element, guaranteed to be unique in Scenario """ return self._get_attribute(self._SDM_ATT_MAP["Name"])
identifier_body
main.go
(&name, "name", "", "name of the server") p.Cmd.Flags().StringVar(&apiToken, "apiToken", "", "API token for global login") p.Cmd.Flags().StringVar(&server, "server", "", "login to the given server") p.Cmd.Flags().StringVar(&kubeConfig, "kubeconfig", "", "path to kubeconfig management cluster. Valid only if user does...
} nameExists, err := config.ServerExists(name) if err != nil { return server, err } if nameExists { err = fmt.Errorf("server %q already exists", name) return } if isGlobalServer(endpoint) { server = &configv1alpha1.Server{ Name: name
return }
conditional_block
main.go
(&name, "name", "", "name of the server") p.Cmd.Flags().StringVar(&apiToken, "apiToken", "", "API token for global login") p.Cmd.Flags().StringVar(&server, "server", "", "login to the given server") p.Cmd.Flags().StringVar(&kubeConfig, "kubeconfig", "", "path to kubeconfig management cluster. Valid only if user does...
serverKeys = append(serverKeys, newServerSelector) servers[newServerSelector] = &configv1alpha1.Server{} err := component.Prompt( &component.PromptConfig{ Message: "Select a server", Options: serverKeys, Default: serverKeys[0], }, &server, promptOpts..., ) if err != nil { return nil, err } ret...
promptOpts := getPromptOpts() servers := map[string]*configv1alpha1.Server{} for _, server := range cfg.KnownServers { ep, err := config.EndpointFromServer(server) if err != nil { return nil, err } s := rpad(server.Name, 20) s = fmt.Sprintf("%s(%s)", s, ep) servers[s] = server } if endpoint == "" {...
identifier_body
main.go
var descriptor = cliv1alpha1.PluginDescriptor{ Name: "login", Description: "Login to the platform", Group: cliv1alpha1.SystemCmdGroup, Aliases: []string{"lo", "logins"}, } var ( stderrOnly, forceCSP, staging bool endpoint, name, apiToken, server, kubeConfig, kubeconte...
"github.com/vmware-tanzu/tanzu-framework/pkg/v1/config" )
random_line_split
main.go
() { p, err := plugin.NewPlugin(&descriptor) if err != nil { log.Fatal(err) } p.Cmd.Flags().StringVar(&endpoint, "endpoint", "", "endpoint to login to") p.Cmd.Flags().StringVar(&name, "name", "", "name of the server") p.Cmd.Flags().StringVar(&apiToken, "apiToken", "", "API token for global login") p.Cmd.Flags(...
main
identifier_name
entity.rs
, } pub type AccountsMap = HashMap<String, Account>; /// Represents the whole config file. #[derive(Debug, Default, Clone, Deserialize)] #[serde(rename_all = "kebab-case")] pub struct Config { // TODO: rename with `from` pub name: String, pub downloads_dir: Option<PathBuf>, pub notify_cmd: Option<Stri...
pub fn run_notify_cmd<S: AsRef<str>>(&self, subject: S, sender: S) -> Result<()> { let subject = subject.as_ref(); let sender = sender.as_ref(); let default_cmd = format!(r#"notify-send "📫 {}" "{}""#, sender, subject); let cmd = self .notify_cmd .as_ref() ...
{ let name = account.name.as_ref().unwrap_or(&self.name); let has_special_chars = "()<>[]:;@.,".contains(|special_char| name.contains(special_char)); if name.is_empty() { format!("{}", account.email) } else if has_special_chars { // so the name has special charac...
identifier_body
entity.rs
HashMap<String, Account>, } impl Config { fn path_from_xdg() -> Result<PathBuf> { let path = env::var("XDG_CONFIG_HOME").context("cannot find `XDG_CONFIG_HOME` env var")?; let mut path = PathBuf::from(path); path.push("himalaya"); path.push("config.toml"); Ok(path) } ...
} // FIXME: tests
random_line_split
entity.rs
, } pub type AccountsMap = HashMap<String, Account>; /// Represents the whole config file. #[derive(Debug, Default, Clone, Deserialize)] #[serde(rename_all = "kebab-case")] pub struct Config { // TODO: rename with `from` pub name: String, pub downloads_dir: Option<PathBuf>, pub notify_cmd: Option<Stri...
() -> Result<PathBuf> { let home_var = if cfg!(target_family = "windows") { "USERPROFILE" } else { "HOME" }; let mut path: PathBuf = env::var(home_var) .context(format!("cannot find `{}` env var", home_var))? .into(); path.push(".hi...
path_from_home
identifier_name
zip.go
// relative path is converted to absolute path by appending function directory if len(includeData) == 1 { i.source = filepath.Join(zw.manifestFilePath, includeData[0]) i.destination = filepath.Join(zw.src, includeData[0]) verboseMsg = wski18n.T(wski18n.ID_VERBOSE_ZIP_INCLUDE_SOURCE_PATH_X_path_X, map[...
{ if i.source != i.destination { // now determine whether the included item is file or dir // it could list something like this as well, "actions/common/*.js" if fileInfo, err = os.Stat(i.source); err != nil { return err } // if the included item is a directory, call a function to copy the // e...
conditional_block
zip.go
} type ZipWriter struct { src string des string include [][]string exclude []string excludedFiles map[string]bool manifestFilePath string zipWriter *zip.Writer } type Include struct { source string destination string } func (zw *ZipWriter) zipFile(p...
(functionPath string, flag bool) error { var err error var files []string var excludedFiles []string var f bool if !strings.HasSuffix(functionPath, PATH_WILDCARD) { functionPath = filepath.Join(functionPath, PATH_WILDCARD) } if excludedFiles, err = filepath.Glob(functionPath); err != nil { return err } fo...
findExcludedIncludedFiles
identifier_name
zip.go
package utils import ( "archive/zip" "io" "os" "path/filepath" "strings" "github.com/apache/openwhisk-wskdeploy/wski18n" "github.com/apache/openwhisk-wskdeploy/wskprint" ) const PATH_WILDCARD = "*" const ONE_DIR_UP = "../" func NewZipWriter(src string, des string, include [][]string, exclude []string, manife...
random_line_split
zip.go
type ZipWriter struct { src string des string include [][]string exclude []string excludedFiles map[string]bool manifestFilePath string zipWriter *zip.Writer } type Include struct { source string destination string } func (zw *ZipWriter) zipFile(pat...
{ zw := &ZipWriter{ src: src, des: des, include: include, exclude: exclude, excludedFiles: make(map[string]bool, 0), manifestFilePath: manifestFilePath, } return zw }
identifier_body
ingress.go
) read(ingress *unstructured.Unstructured, endpoints *unstructured.UnstructuredList, services *unstructured.UnstructuredList) error { iia.processIngressEvent(watchAddedEvent(ingress)) err := services.EachListItem(func(service runtime.Object) error { iia.processServiceEvent(watchAddedEvent(service.(*unstructured.U...
expectedIngressPath
identifier_name
ingress.go
.GroupVersionResource{ Group: "networking.k8s.io", Version: "v1", Resource: "ingresses", }), informers.WithEventChannel(ingressEvents)) if err != nil { return err } go ingressInformer.Informer().Run(stopper) endpointsEvents := make(chan watch.Event) endpointsInformer, err := informers.New(informerFac...
{ continue }
conditional_block
ingress.go
: iia.errorMessages(), } case <-settlementGracePeriodExpired: // If we don't see any endpoint events in the designated time, assume endpoints have settled. // This is to account for the distinct possibility of ingress using a resource reference or non-existent // endpoints - in which case we will never se...
{ messages := make([]string, 0) if _, ready := iia.checkIfEndpointsReady(); !ready { messages = append(messages, "Ingress has at least one rule with an unavailable target endpoint.") } if !iia.ingressReady { messages = append(messages, "Ingress .status.loadBalancer field was not updated with a hostname/IP ...
identifier_body
ingress.go
type ingressInitAwaiter struct { config createAwaitConfig ingress *unstructured.Unstructured ingressReady bool endpointsSettled bool endpointEventsCount uint64 knownEndpointObjects sets.String knownExternalNameServices sets.String } func make...
const ( DefaultIngressTimeoutMins = 10 )
random_line_split
test.py
thread.start() thread.join(timeout) if thread.is_alive(): print(red('ERROR: timeout reached for this process')) self.process.terminate() thread.join() self.process = None def terminate(self): if self.process != None: self....
""" Show the list of tests available """
random_line_split
test.py
self.process = None self.env = env def run(self, timeout): # type: (object) -> object def target(): self.process = subprocess.Popen(self.cmd, shell=True, env=self.env) self.process.communicate() thread = threading.Thread(target=target) thread...
def runCase(self, args, mpi=0, changeDir=False, preruns=None, postruns=None, validate=None, outputs=None, random=False, errorthreshold=0.001): # Retrieve the correct case number from the test name id # We asumme here that 'test_caseXXX' should be in...
""" Run several commands. Params: cmdList: the list of commands to execute. cmdType: either 'preruns' or 'postruns' """ pipe = '>' outDir = self.outputDir for cmd in cmdList: if cmd: cmd = self._parseArgs(cmd) c...
identifier_body
test.py
self.process = None self.env = env def run(self, timeout): # type: (object) -> object def target(): self.process = subprocess.Popen(self.cmd, shell=True, env=self.env) self.process.communicate() thread = threading.Thread(target=target) thread.start(...
else: msg = "Files are not equal:\n output: %s\n gold: %s" % (outFile, fileGoldStd) self.assertTrue(xmippLib.compareTwoFiles(outFile, fileGoldStd, 0), red(msg)) class GTestResult(unittest.TestResult): """ Subclass TestResult to output tests results with c...
outFile = os.path.join(self._testDir, self.outputDir, out) fileGoldStd = os.path.join(self.goldDir, out) # Check the expect output file was produced msg = "Missing expected output file:\n output: %s" % outFile self.assertTrue(os.path.exists(outFile), red(msg...
conditional_block
test.py
self.process = None self.env = env def run(self, timeout): # type: (object) -> object def target(): self.process = subprocess.Popen(self.cmd, shell=True, env=self.env) self.process.communicate() thread = threading.Thread(target=target) thread...
(self): secs = time.time() - self.startTimeAll sys.stderr.write("%s run %d tests (%0.3f secs)\n" % (green("[==========]"), self.numberTests, secs)) if self.testFailed: print >> sys.stderr, red("[ FAILED ]") + " %d tests" % self.testFailed print >> s...
doReport
identifier_name
DLProject_DNN.py
os.chdir(path) cwd = os.getcwd() # 256 neurons in each hidden layers n_hidden_1 = 400 n_hidden_2 = 300 n_hidden_3 = 200 n_hidden_4 = 100 n_hidden_5 = 50 # There are 10 levels, and we consider 40 timestamps and the mid_price # output size input_size = 400 output_size = 3 # Parameters learning_rate = 0.001 trainin...
ile_path = Path
conditional_block
DLProject_DNN.py
L8-AskSize', 'L8-SellNo', 'L9-BidPrice', 'L9-BidSize', 'L9-BuyNo', 'L9-AskPrice', 'L9-AskSize', 'L9-SellNo', 'L10-BidPrice', 'L10-BidSize', 'L10-BuyNo', 'L10-AskPrice', 'L10-AskSize', 'L10-SellNo'] # import tick data from the given path print("Importing the data...") Nrow = input...
x,y,df,my_dict): x_index = my_dict[x] y_index = my_dict[y] vec1 = np.array(df3.iloc[x_index,:df.shape[1]-1]) vec2 = np.array(df3.iloc[y_index,:df.shape[1]-1]) vec_diff = vec2-vec1 return vec_diff # find index of nearest k neighbors from j's row of data def find_neighbors(j,k,my_dict,my_dict2,df...
iff(
identifier_name
DLProject_DNN.py
length) num_neg = max(1,len(df3)-length_neg) # oversample the data with positive mid_price move # initialize a matrix to save the feature difference between 2 feature vectors dist_matrix = np.zeros((length,length)) # 2 dictionary to transform between matrix index and dataframe row index my_dict = {} my_dict2 = {} for...
lobal X_train global y_train global index_in_epoch global epochs_completed start = index_in_epoch index_in_epoch += batch_size # when all trainig data have been already used, it is reorder randomly if index_in_epoch > num_examples: # finished epoch epochs_completed += 1...
identifier_body
DLProject_DNN.py
'L8-AskSize', 'L8-SellNo', 'L9-BidPrice', 'L9-BidSize', 'L9-BuyNo', 'L9-AskPrice', 'L9-AskSize', 'L9-SellNo', 'L10-BidPrice', 'L10-BidSize', 'L10-BuyNo', 'L10-AskPrice', 'L10-AskSize', 'L10-SellNo'] # import tick data from the given path print("Importing the data...") Nrow = inp...
if df3.loc[i,'classification']==-1: temp_list_neg.append(i) temp_list = np.asarray(temp_list) length = len(temp_list) temp_list_neg = np.asarray(temp_list_neg) length_neg = len(temp_list_neg) num_pos = max(1,len(df3)-length) num_neg = max(1,len(df3)-length_neg) # oversample the data with positive mid_pric...
for i in range(len(df3)): if df3.loc[i,'classification']==1: temp_list.append(i)
random_line_split
Notebook_1_DataCleansing_FeatureEngineering.py
id','Categorical_1','Categorical_2','Categorical_3','Categorical_4', 'fault_code_type_1','fault_code_type_2', 'fault_code_type_3','fault_code_type_4', 'problemreported'] features_numeric = list(set(df.columns) -set(features_datetime)-set(features_...
= udf(Cat1, StringType()) df = df.withColumn("cat1", cat1Udf('categorical_1')) def Cat2(num): if num <= 2000: return '0-2000' elif 2000 < num and num <= 3000: return '2000-3000' elif 3000 < num and num <= 4000: return '3000-4000' elif 4000 < num and num <= 5000: return '4000-5000' elif 5000 < num...
= 10: return '0-10' elif 10 < num and num <= 20: return '11-20' elif 20 < num and num <= 30: return '21-30' elif 30 < num and num <= 40: return '31-40' else: return 'morethan40' cat1Udf
identifier_body
Notebook_1_DataCleansing_FeatureEngineering.py
l = df.columns cols = [c.replace(' ','_'). replace('[.]','_'). replace('.','_'). replace('[[:punct:]]','_'). lower() for c in l] return df.toDF(*cols) df = StandardizeNames(df) # remove duplicated rows based on deviceid and date df = df.dropDuplicates([...
izeNames(df):
identifier_name
Notebook_1_DataCleansing_FeatureEngineering.py
1))\ .withColumn("fault_code_type_3_count_per_usage1",F.when(df.usage_count_1==0,0).otherwise(df.fault_code_type_3_count/df.usage_count_1))\ .withColumn("fault_code_type_4_count_per_usage1",F.when(df.usage_count_1==0,0).otherwise(df.fault_code_type_4_count/df.usage_count_1)) # Normalize performance_norma...
# MAGIC # MAGIC
random_line_split
Notebook_1_DataCleansing_FeatureEngineering.py
deviceid','Categorical_1','Categorical_2','Categorical_3','Categorical_4', 'fault_code_type_1','fault_code_type_2', 'fault_code_type_3','fault_code_type_4', 'problemreported'] features_numeric = list(set(df.columns) -set(features_datetime)-set(fea...
= udf(Cat4, StringType()) df = df.withColumn("cat4", cat4Udf('categorical_4')) print(df.select('cat1').distinct().rdd.map(lambda r: r[0]).collect()) print(df.select('cat2').distinct().rdd.map(lambda r: r[0]).collect()) print(df.select('cat3').distinct().rdd.map(lambda r: r[0]).collect()) print(df.select('cat4').dist...
morethan20000' cat4Udf
conditional_block
EffectObject.ts
without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // ...
if(this._playFrame==this._totalframe-1 && this._totalframe>0) { this.dispose(); } } } private drawJson():void { if(egret.getTimer()-this._lastRender<this._spriteSheet.renderTime) return; ...
{ var obj:EffectObject = this.clone(true); obj._sonDeep = --this._sonDeep; obj._posx = this._posx+this._impl.sonSpeed*Math.cos(this._sonAngle); obj._posy = this._posy+this._impl.sonSpeed*Math.sin(this._sonAngle); D5Game....
conditional_block
EffectObject.ts
without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // ...
():void { var target:egret.Point = D5Game.me.map.getScreenPostion(this._posx,this._posy); if(this._monitor) { this._monitor.x = target.x; this._monitor.y = target.y; if(this._spriteSheet) ...
runPos
identifier_name
EffectObject.ts
without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // ...
{ this._res = res; this.onTextureComplete(D5UIResourceData.getData(this._res).getResource(0)); } } private onTextureComplete(data:egret.Texture):void { this._monitor.texture = data; this._totalframe = 5; ...
this._res = res.substr(0,res.length-5); this._loadID++; D5SpriteSheet.getInstance(this._res+'.png',this); } else if(res.indexOf('.png')!=-1)
random_line_split
config.go
Bind string `toml:"bind" mapstructure:"bind" env:"SERVER_BIND"` // https bind address. ":<port>" for all interfaces TLSBind string `toml:"tls-bind" mapstructure:"tls-bind" env:"SERVER_TLS_BIND"` // TLS certificate file path TLSCertFile string `toml:"tls-cert-file" mapstructure:"tls-cert-file" env:"SERVER_TLS_CERT_...
// http bind address. ":<port>" for all interfaces
random_line_split
config.go
toml:"tls-bind" mapstructure:"tls-bind" env:"SERVER_TLS_BIND"` // TLS certificate file path TLSCertFile string `toml:"tls-cert-file" mapstructure:"tls-cert-file" env:"SERVER_TLS_CERT_FILE"` // TLS key file path TLSKeyFile string `toml:"tls-key-file" mapstructure:"tls-key-file" env:"SERVER_TLS_KEY_FILE"` // Maximum...
(v *viper.Viper) error { v.SetConfigType("toml") v.SetConfigFile(c.File) v.SetEnvPrefix(c.EnvPrefix) v.SetEnvKeyReplacer(strings.NewReplacer("-", "_")) if err := v.ReadInConfig(); err != nil { return err } v.AutomaticEnv() return nil } // UnmarshalAppConfig unmarshals the viper's configured config file // i...
ConfigureViper
identifier_name
config.go
toml:"tls-bind" mapstructure:"tls-bind" env:"SERVER_TLS_BIND"` // TLS certificate file path TLSCertFile string `toml:"tls-cert-file" mapstructure:"tls-cert-file" env:"SERVER_TLS_CERT_FILE"` // TLS key file path TLSKeyFile string `toml:"tls-key-file" mapstructure:"tls-key-file" env:"SERVER_TLS_KEY_FILE"` // Maximum...
v = v.Sub(env) if v == nil { return nil, fmt.Errorf("cannot find env section named %s", env) } mappings, err := GetTagMappings(cfg) if err != nil { return nil, errors.Wrap(err, "unable to get tag mappings for config struct") } if c.EnvPrefix != "" { for _, m := range mappings { v.BindEnv(m.chain, st...
{ env = v.GetString("env") }
conditional_block
config.go
DB_DBNAME"` Host string `toml:"host" mapstructure:"host" env:"DB_HOST"` Port int `toml:"port" mapstructure:"port" env:"DB_PORT"` User string `toml:"user" mapstructure:"user" env:"DB_USER"` Pass string `toml:"pass" mapstructure:"pass" env:"DB_PASS"` SSLMode string `toml:"sslmode" mapstructure:"sslmod...
{ flags := &pflag.FlagSet{} // root level flags flags.BoolP("version", "", false, "Display the build version hash") flags.StringP("env", "e", "prod", "The config files environment to load") return flags }
identifier_body
show_alignment.py
60 self.qualitaetsListe = ["AA", "GG", "CC", "TT", "CT", "TC", "AG", "GA", "CA", "AC", "CG", "GC", "TA", "AT", "TG", "GT"] self.qualitaetsListeProteins = self.__qualitaetsListeProteins() # beware: the following variable has coupling with the above # _quali...
if indexOfPair in _guter_match_list: qualitaetsZeile += self.GUTER_MATCH_ZEICHEN if indexOfPair in _kein_guter_match_list: qualitaetsZeile += self.KEIN_GUTER_MATCH_ZEICHEN return(qualitaetsZeile) # bool|ValueError showAlignment(cls...
qualitaetsZeile += self.EXAKTER_MATCH_ZEICHEN
conditional_block
show_alignment.py
_qualitaetsListeProteins function self.AA_EXAKTER_MATCH = range(0, 19) self.AA_GUTER_MATCH = range(19, 60) self.AA_KEIN_GUTER_MATCH = range(60, 529) self.EXAKTER_MATCH_ZEICHEN = "|" self.GUTER_MATCH_ZEICHEN = ":" self.KEIN_GUTER_MATCH_ZEICHEN = "." ...
"""Function checking the consistency of an alignment and generating output of the first section of showAlignment in its behalf. If an inconsistency is detected information about reasons for stopping further processing is given back to the user and a ValueError is raised. In case no incon...
identifier_body
show_alignment.py
0 self.qualitaetsListe = ["AA", "GG", "CC", "TT", "CT", "TC", "AG", "GA", "CA", "AC", "CG", "GC", "TA", "AT", "TG", "GT"] self.qualitaetsListeProteins = self.__qualitaetsListeProteins() # beware: the following variable has coupling with the above # _qualit...
(self): """Private function building and returning a quality list analog to the quality list for dna nucleotides, but based upon the PAM30 Matrix; associated quaity ranges are defined in AA_EXAKTER_MATCH, AA_GUTER_MATCH, AA_KEIN_GUTER_MATCH and correspond for AA_GUTER_MATCH to re...
__qualitaetsListeProteins
identifier_name
show_alignment.py
# "Skelett" des Programs zum Zeigen eines Alignments mit einer # Qualitaetszeile Haltet euch bitte an diese Struktur - dort wo das # "pass" steht muss euer Quelltext kommen. Das pass muss dazu # geloescht werden. # Autor: Alex Finck # Datum der letzten Aenderung: 09.07.2020 # # usage examples from the command line: # ...
until the length of the alignment is reached. """
random_line_split
lib.rs
fn gen_doc_rust(crates_dir: Option<&Path>, manifest_path: Option<&Path>) -> anyhow::Result<()> { let metadata = &cargo_metadata(manifest_path)?; let resolve = metadata.resolve.as_ref().expect("should be present"); let resolve_root = resolve .root .as_ref() .with_context(|| "this is...
( &mut self, path: &[&'cm str], package: &'cm cm::Package, target: &'cm cm::Target, ) { match (self, path) { (Self::Joint(joint), []) => { joint.insert(&target.name, Self::Leaf(&package.id, target)); ...
insert
identifier_name
lib.rs
fn gen_doc_rust(crates_dir: Option<&Path>, manifest_path: Option<&Path>) -> anyhow::Result<()> { let metadata = &cargo_metadata(manifest_path)?; let resolve = metadata.resolve.as_ref().expect("should be present"); let resolve_root = resolve .root .as_ref() .with_context(|| "this is...
env::var_os("CARGO").with_context(|| "missing `$CARGO` environment variable")?, ) .with_file_name("rustfmt") .with_extension(env::consts::EXE_EXTENSION); let tempdir = tempfile::Builder::new() .prefix("qryxip-competitive-programming-library-xtask-") ....
fn apply_rustfmt(code: &str) -> anyhow::Result<String> { let rustfmt_exe = PathBuf::from(
random_line_split
lib.rs
fn gen_doc_rust(crates_dir: Option<&Path>, manifest_path: Option<&Path>) -> anyhow::Result<()> { let metadata = &cargo_metadata(manifest_path)?; let resolve = metadata.resolve.as_ref().expect("should be present"); let resolve_root = resolve .root .as_ref() .with_context(|| "this is...
(Self::Joint(joint), [segment, path @ ..]) => { joint .entry(segment) .or_default() .insert(path, package, target); } _ => panic!(), } } fn expand( ...
{ joint.insert(&target.name, Self::Leaf(&package.id, target)); }
conditional_block
lib.rs
fn gen_doc_rust(crates_dir: Option<&Path>, manifest_path: Option<&Path>) -> anyhow::Result<()> { let metadata = &cargo_metadata(manifest_path)?; let resolve = metadata.resolve.as_ref().expect("should be present"); let resolve_root = resolve .root .as_ref() .with_context(|| "this is...
for (package, target) in library_crates { let markdown = format!( "---\n\ title: \"{} (<code>{}</code>)\"\n\ documentation_of: //{}\n\ ---\n\ {}", package.name, target.name, target .src_path ...
{ let metadata = &cargo_metadata(manifest_path)?; let library_crates = metadata .workspace_members .iter() .flat_map(|ws_member| { let ws_member = &metadata[ws_member]; let target = ws_member.lib_or_proc_macro()?; Some((ws_member, target)) }) ...
identifier_body
Travel.py
the day, the day of the week, and month of the year. In addition, the traffic is usually heavier in Manhattan (downtown of the city) in comparing to the other point of the city. Therefore, if the starting or ending point of the travel is close to the Manhattan we expect higher traffic comparing to the other neighborho...
# Now, we can easily add all of the above features to both traing and test data set. Due to time limtation and calculation power I only used 10% of the traing data. # In[24]: np.random.seed(42) df_train_s = df_train.sample(frac=0.01, replace=False) df_train_s = add_features(df_train_s) df_train_s['velocity'] = np....
DD = df_train_s['start_timestamp'].map(day_of_week) df_train_s['day'] = DD DD = pd.get_dummies( DD,prefix='day', drop_first=True) df_train_s = pd.concat([df_train_s, DD],axis =1 ) # Month, time of the dat, df_train_s df_train_s['month'] = df_train_s['start_timestamp'].map(month) df_trai...
identifier_body
Travel.py
day, the day of the week, and month of the year. In addition, the traffic is usually heavier in Manhattan (downtown of the city) in comparing to the other point of the city. Therefore, if the starting or ending point of the travel is close to the Manhattan we expect higher traffic comparing to the other neighborhoods....
# In[204]: model_sk = LinearRegression() model_sk.fit(X_train, y_train) plt.figure(figsize=(12, 8)) plt.bar(np.arange(model_sk.coef_.shape[0]) - 0.4, model_sk.coef_) plt.xticks(np.arange(model_sk.coef_.shape[0]), cl, rotation='vertical') plt.xlim([-1, model_sk.coef_.shape[0]]) plt.title("Linear model coefficients") ...
# ## Linear Model
random_line_split
Travel.py
df_train_s['pickup_MH'] = df_train_s.apply(pickup_to_MH, axis=1 ) df_train_s['dropoff_MH'] = df_train_s.apply(dropoff_to_MH, axis=1 ) return df_train_s # Now, we can easily add all of the above features to both traing and test data set. Due to time limtation and calculation power I only used 10% of the...
evalute
identifier_name
Travel.py
easily add all of the above features to both traing and test data set. Due to time limtation and calculation power I only used 10% of the traing data. # In[24]: np.random.seed(42) df_train_s = df_train.sample(frac=0.01, replace=False) df_train_s = add_features(df_train_s) df_train_s['velocity'] = np.array(df_train_s...
MAE[kys] = mean_absolute_error(dist,y_true, y_pred ) MAPE[kys] = mean_absolute_percentage_error(dist,y_true, y_pred )
conditional_block
scripts.js
function keyDownHandler(e) { //hit left arrow if(e.key =="Left" || e.key =="ArrowLeft"){ if(loadingCompleted){ keyboardMoveLeft = true; } } //hit right arrow if(e.key =="Right" || e.key =="ArrowRight"){ if(loadingCompleted){ keyboardMoveRight = true; } } if(e.key ==" "){ if(loadingCompleted){ ...
{ timerLength--; console.log(timerLength); updateTimerLine(); if(timerLength<1){ clearTimeout(timer); loseLife(); } }
identifier_body
scripts.js
} //hit right arrow if(e.key =="Right" || e.key =="ArrowRight"){ if(loadingCompleted){ keyboardMoveRight = true; } } if(e.key ==" "){ if(loadingCompleted){ startLevel(); }else{ alert("Please wait until loading complete"); } } } function keyUpHandler(e) { //release left arrow if(e.key =="...
{ keyboardMoveLeft = true; }
conditional_block
scripts.js
Green").drawCircle(0,0, BALL_RADIUS); //circle radius is 8px ball2.x = paddle.x; ball2.y = paddle.y - PADDLE_HEIGHT/2 - BALL_RADIUS; ball2.xSpeed = 3; ball2.ySpeed = 3; ball2.up = true; ball2.right = true; stage.addChild(ball2); } stage.update(); } } stage.update(); } function...
destroyBrick
identifier_name
scripts.js
arrow if(e.key =="Right" || e.key =="ArrowRight"){ keyboardMoveRight = false; } } function addToScore(points) { console.log("score added"); score+=points; if(score > highScore){ highScore = score; } updateStatusLine(); } function updateStatusLine() { scoreText.text = "Score: "+score + " / Lives: "+liv...
// stage.update(); //update the stage manually //move paddle based on left and right key if(keyboardMoveLeft) { console.log("Keyboard- Left"); paddle.x-=5; } if(keyboardMoveRight) { console.log("Keyboard- Right"); paddle.x+=5; } // one fix to make sure paddle not moving through the walls of s...
updateStatusLine(); } function tick(event) //custom tick function {
random_line_split
spp-final.py
g_dir + '\\cache\\spp' + pres_wd + '\\' + dir_wd) for file_name in files_lst: print (os.getcwd() + '\\' + file_name) self.ftp_handle.retrbinary("RETR " + file_name, open(file_name, 'wb').write) self.files_cached.append(os.getcwd() + '\\' + file_name) os.chdir(self.prog_dir + '\\cache\\s...
else: cursor.execute("INSERT INTO offer_base (identifier_1, identifier_2, region_name, market_id) VALUES (%s, %s, %s, %s)", (row[2], '0', "SPP", mkt_id)) ins_perf = True cursor.execute("SELECT offer_id FROM offer_base USE INDEX (IDX_OFFER_BASE_ID1_ID2) WHERE identifier_1 = %s AND identif...
off_id = off_check[0] ins_perf = False
conditional_block
spp-final.py
(self, server, path, start_dt, end_dt, prog_dir): self.files_cached = [] try: self.ftp_handle = ftplib.FTP(server) self.ftp_handle.login() self.path_name = path self.start_dt = datetime.datetime.strptime(start_dt, "%m-%d-%Y") self.end_dt = datetime.datetime.strptime(end_dt, "%m-%d-%Y") sel...
__init__
identifier_name
spp-final.py
g_dir + '\\cache\\spp' + pres_wd + '\\' + dir_wd) for file_name in files_lst: print (os.getcwd() + '\\' + file_name) self.ftp_handle.retrbinary("RETR " + file_name, open(file_name, 'wb').write) self.files_cached.append(os.getcwd() + '\\' + file_name) os.chdir(self.prog_dir + '\\cache\\s...
def etl_file_data(cache_file): try: fread = open(cache_file, 'r') flines = [x.rstrip('\n') for x in fread.readlines() if x.endswith('.csv\n')] fread.close() cnx = MySQLdb.connect(user = 'not-published', passwd = 'not-published', host = 'not-published', db = 'not-published') cursor = cnx.cursor() ...
try: self.ftp_handle.quit() os.chdir(self.prog_dir + '\\cache\\spp') fwrite = open(self.path_name[1:-1].replace('\\', '-') + '.txt', 'w') fwrite.write('File(s) cached are as follows:\n') for file_name in self.files_cached: fwrite.write(file_name + '\n') fwrite.close() os.chdir(self.prog...
identifier_body
spp-final.py
_dir + '\\cache\\spp' + pres_wd + '\\' + dir_wd) for file_name in files_lst: print (os.getcwd() + '\\' + file_name) self.ftp_handle.retrbinary("RETR " + file_name, open(file_name, 'wb').write) self.files_cached.append(os.getcwd() + '\\' + file_name) os.chdir(self.prog_dir + '\\cache\\sp...
ins_perf = True for row in frows: if len(row) > 0 and row[2].strip() != '' and row[3].strip() != '' and row[4].strip() != '': if ins_perf == True: cursor.execute("SELECT offer_id, identifier_1, identifier_2 FROM offer_base USE INDEX (IDX_OFFER_BASE_MARKET_ID) WHERE market_id = %s", (mkt_id,)) ...
next(frows, None) offer_base_rs = []
random_line_split
TypeScriptHelpers.ts
names for late-bound symbols derived from `unique symbol` declarations // which have the form of "__@<variableName>@<symbolId>", i.e. "__@someSymbol@12345". private static readonly _uniqueSymbolNameRegExp: RegExp = /^__@.*@\d+$/; /** * This traverses any symbol aliases to find the original place where an ite...
<T extends ts.Node>( node: ts.Node, kindToMatch: ts.SyntaxKind ): T | undefined { for (const child of node.getChildren()) { if (child.kind === kindToMatch) { return child as T; } const recursiveMatch: T | undefined = TypeScriptHelpers.findFirstChildNode(child, kindToMatch); ...
findFirstChildNode
identifier_name
TypeScriptHelpers.ts
names for late-bound symbols derived from `unique symbol` declarations // which have the form of "__@<variableName>@<symbolId>", i.e. "__@someSymbol@12345". private static readonly _uniqueSymbolNameRegExp: RegExp = /^__@.*@\d+$/; /** * This traverses any symbol aliases to find the original place where an ite...
// If we matched everything, then return the node that matched the last parentKinds item return current as T; } /** * Does a depth-first search of the children of the specified node. Returns the first child * with the specified kind, or undefined if there is no match. */ public static findFir...
{ // (slice(0) clones an array) const reversedParentKinds: ts.SyntaxKind[] = kindsToMatch.slice(0).reverse(); let current: ts.Node | undefined = undefined; for (const parentKind of reversedParentKinds) { if (!current) { // The first time through, start with node current = node; ...
identifier_body
TypeScriptHelpers.ts
names for late-bound symbols derived from `unique symbol` declarations // which have the form of "__@<variableName>@<symbolId>", i.e. "__@someSymbol@12345". private static readonly _uniqueSymbolNameRegExp: RegExp = /^__@.*@\d+$/; /** * This traverses any symbol aliases to find the original place where an ite...
const symbol: ts.Symbol | undefined = TypeScriptInternals.tryGetSymbolForDeclaration( declaration, checker ); if (!symbol) { throw new InternalError( 'Unable to determine semantic information for declaration:\n' + SourceFileLocationFormatter.formatDeclaration(declaration)...
random_line_split
TypeScriptHelpers.ts
names for late-bound symbols derived from `unique symbol` declarations // which have the form of "__@<variableName>@<symbolId>", i.e. "__@someSymbol@12345". private static readonly _uniqueSymbolNameRegExp: RegExp = /^__@.*@\d+$/; /** * This traverses any symbol aliases to find the original place where an ite...
return undefined; } /** * Returns the highest parent node with the specified SyntaxKind, or undefined if there is no match. * @remarks * Whereas findFirstParent() returns the first match, findHighestParent() returns the last match. */ public static findHighestParent<T extends ts.Node>( node...
{ if (current.kind === kindToMatch) { return current as T; } current = current.parent; }
conditional_block
index.js
map.set(data[i].Word, []); } // Get the array of the word and push the date. map.get(data[i].Word).push(data[i].Date); } }); drawScatter(myList); // Set the dimensions and margins of the graph var margin = {top: 10, right: 30, bottom: 30, left: 60}, width = 1100 - margin.left - margin...
} } searchResults = temp; } for (let i = 0; i < searchResults.length; i++) { searchResults[i] = parseTime(searchResults[i]); } } d3.selectAll("g > *").remove(); //console.log(searchResults);...
{ // only push those dates that are already in search result in temp // as the results should be only the tweets that have all the words in the input. temp.push(searchResults[k]); }
conditional_block
index.js
americaResults = []; data.forEach(function(d) { d.Date = parseTime(d.Date); if (d.Word === 'makeamericagreatagain') { americaResults.push(d.Date); } }); d3.selectAll("g > *").remove(); drawScatter(ameri...
{ var newX = d3.event.transform.rescaleX(x); var newY = d3.event.transform.rescaleY(y); xAxis.call(d3.axisBottom(newX).tickFormat(function(date) { if (d3.event.transform.k == 1) { return d3.timeFormat("%b %Y")(date); } else { ...
identifier_body
index.js
map.set(data[i].Word, []); } // Get the array of the word and push the date. map.get(data[i].Word).push(data[i].Date); } }); drawScatter(myList); // Set the dimensions and margins of the graph var margin = {top: 10, right: 30, bottom: 30, left: 60}, width = 1100 - margin.le...
}); //search callback d3.select("#form") .on("submit", function(d) { d3.event.preventDefault(); var input = document.getElementById("input").value; var tokens = input.trim().split(" "); var searchResults = []; let valid = true; let regex = /[^A-Za-z_]/; ...
d3.selectAll("g > *").remove(); drawScatter(americaResults); })
random_line_split
index.js
map.set(data[i].Word, []); } // Get the array of the word and push the date. map.get(data[i].Word).push(data[i].Date); } }); drawScatter(myList); // Set the dimensions and margins of the graph var margin = {top: 10, right: 30, bottom: 30, left: 60}, width = 1100 - margin.left - margin...
(searchResults, errFlag) { d3.csv(csvFile).then(function (data) { // Convert to Date format data.forEach(function (d) { d.Date = parseTime(d.Date); }); if(errFlag){ d3.select("#err") .style("opacity", 1); }else{ d3....
drawScatter
identifier_name
train_k_fold.py
checkpoints/') parser.add_argument('-embed_dim', type=int, default=100) parser.add_argument('-embed_num', type=int, default=100) parser.add_argument('-pos_dim', type=int, default=50) parser.add_argument('-pos_num', type=int, default=100) parser.add_argument('-seg_num', type=int, default=10) parser.add_argument('-kernel...
def train(n_val=50): """ 验证集条数 :param n_val: :return: """ logging.info('Loading vocab,train and val dataset.Wait a second,please') embed = torch.Tensor(np.load(args.embedding)['embedding']) with open(args.word2id) as f: word2id = json.load(f) vocab = summarunner_weather.u...
net.eval() total_loss = 0 batch_num = 0 for batch in data_iter: features, targets, _, doc_lens = vocab.make_features(batch) features, targets = Variable(features), Variable(targets.float()) if use_gpu: features = features.cuda() targets = targets.cuda() ...
identifier_body
train_k_fold.py
points/') parser.add_argument('-embed_dim', type=int, default=100) parser.add_argument('-embed_num', type=int, default=100) parser.add_argument('-pos_dim', type=int, default=50) parser.add_argument('-pos_num', type=int, default=100) parser.add_argument('-seg_num', type=int, default=10) parser.add_argument('-kernel_num'...
o('Total Cost:%f h' % ((t2 - t1) / 3600)) def train_k_fold(log_path='checkpoints/train_k_fold_RNN_RNN_info.txt'): embed = torch.Tensor(np.load(args.embedding)['embedding']) with open(args.word2id) as f: word2id = json.load(f) vocab = summarunner_weather.utils.Vocab(embed, word2id) with open(a...
iter, criterion) if cur_loss < min_loss: min_loss = cur_loss net.save() logging.info('Epoch: %2d Min_Val_Loss: %f Cur_Val_Loss: %f' % (epoch, min_loss, cur_loss)) t2 = time() logging.inf
conditional_block
train_k_fold.py
points/') parser.add_argument('-embed_dim', type=int, default=100) parser.add_argument('-embed_num', type=int, default=100) parser.add_argument('-pos_dim', type=int, default=50) parser.add_argument('-pos_num', type=int, default=100) parser.add_argument('-seg_num', type=int, default=10) parser.add_argument('-kernel_num'...
old_RNN_RNN_info.txt'): embed = torch.Tensor(np.load(args.embedding)['embedding']) with open(args.word2id) as f: word2id = json.load(f) vocab = summarunner_weather.utils.Vocab(embed, word2id) with open(args.train_dir, 'r', encoding='utf-8') as f: examples = [json.loads(line) for line in...
ts/train_k_f
identifier_name
train_k_fold.py
='checkpoints/') parser.add_argument('-embed_dim', type=int, default=100) parser.add_argument('-embed_num', type=int, default=100) parser.add_argument('-pos_dim', type=int, default=50) parser.add_argument('-pos_num', type=int, default=100) parser.add_argument('-seg_num', type=int, default=10) parser.add_argument('-kern...
parser.add_argument('-seed', type=int, default=1) parser.add_argument('-train_dir', type=str, default='../../data/chinese/cont2sum/little/train.json') parser.add_argument('-embedding', type=str, default='../../data/chinese/cont2sum/little/embedding.npz') parser.add_argument('-word2id', type=str, default='../../data/chi...
parser.add_argument('-lr', type=float, default=1e-4) parser.add_argument('-batch_size', type=int, default=16) parser.add_argument('-epochs', type=int, default=30)
random_line_split
roadtrip_compute.py
3e7' #API_KEY = 'cc3bc7b1-4c27-4176-aefd-15017c363178' #API_KEY = '57f195e9-78a9-4fd7-a10c-312f0502d659' #constantes API_NAVITIA = "https://api.sncf.com/v1/coverage/sncf/journeys?key={3}&from=admin:fr:{0}&to=admin:fr:{1}&datetime={2}&count=20" all_waypoints = None def datetime_str_to_datetime_str(datetime_str, fromF...
waypoint2, str(waypoint_co2[frozenset([waypoint1, waypoint2])]), str(int(waypoint_durations[frozenset([waypoint1, waypoint2])]))] db_connector.execute_nonquery(sql.SQL...
with db_connector: for (waypoint1, waypoint2) in waypoint_co2.keys(): waypoint = [waypoint1,
random_line_split
roadtrip_compute.py
e7' #API_KEY = 'cc3bc7b1-4c27-4176-aefd-15017c363178' #API_KEY = '57f195e9-78a9-4fd7-a10c-312f0502d659' #constantes API_NAVITIA = "https://api.sncf.com/v1/coverage/sncf/journeys?key={3}&from=admin:fr:{0}&to=admin:fr:{1}&datetime={2}&count=20" all_waypoints = None def datetime_str_to_datetime_str(datetime_str, fromFo...
onnector, all_waypoints, from_city_insee, to_city_insee, best_travel): """format trip section informations then print & store in db Args: db_connector (psycopg 'connection'): connection instance to the database. Used to keep all requests in the same transaction from_city_insee (str): from city ...
trip_section(db_c
identifier_name
roadtrip_compute.py
e7' #API_KEY = 'cc3bc7b1-4c27-4176-aefd-15017c363178' #API_KEY = '57f195e9-78a9-4fd7-a10c-312f0502d659' #constantes API_NAVITIA = "https://api.sncf.com/v1/coverage/sncf/journeys?key={3}&from=admin:fr:{0}&to=admin:fr:{1}&datetime={2}&count=20" all_waypoints = None def datetime_str_to_datetime_str(datetime_str, fromFo...
route = requests.get(API_NAVITIA.format( int(from_city), int(to_city), travel_date, API_KEY)) response = json.loads(route.text) mid_duration = 0 mid_co2 = 0 for journey in response["journeys"]...
conditional_block
roadtrip_compute.py
e7' #API_KEY = 'cc3bc7b1-4c27-4176-aefd-15017c363178' #API_KEY = '57f195e9-78a9-4fd7-a10c-312f0502d659' #constantes API_NAVITIA = "https://api.sncf.com/v1/coverage/sncf/journeys?key={3}&from=admin:fr:{0}&to=admin:fr:{1}&datetime={2}&count=20" all_waypoints = None def datetime_str_to_datetime_str(datetime_str, fromFo...
save_trip_section(db_connector, all_waypoints, from_city_insee, to_city_insee, best_travel): """format trip section informations then print & store in db Args: db_connector (psycopg 'connection'): connection instance to the database. Used to keep all requests in the same transaction from_city_...
ore trip section information in db Args: db_connector (psycopg 'connection'): connection instance to the database. Used to keep all requests in the same transaction description (str): trip section resume geo_point_from (str): start city coord (lat;long) geo_point_to (float): end cit...
identifier_body
http.go
URL并且解析JSON格式的返回数据 func DoURL(method, url string, body []byte) ([]byte, error) { req, err := http.NewRequest(method, url, bytes.NewBuffer(body)) if err != nil { return nil, err } resp, err := (&http.Client{}).Do(req) if err != nil { return nil, err } defer resp.Body.Close() return ioutil.ReadAll(resp.Body...
urn "" } var ip = strings.TrimSpace(r.Header.Get("X-Real-IP")) if ip == "" { ip, _, _ = net.SplitHostPort(strings.TrimSpace(r.RemoteAddr)) } return ip } // CheckRemoteIP 验证IP // in ips return true func CheckRemoteIP(r *http.Request, ips ...string) bool { if r == nil { return false } var ip = GetRemoteIP(r)...
ibleWithStandardLibrary b, err := json.Marshal(v) if err != nil { return 0, err } return w.Write(b) } // GetRemoteIP 获取IP func GetRemoteIP(r *http.Request) string { if r == nil { ret
identifier_body
http.go
nil, err } defer resp.Body.Close() return ioutil.ReadAll(resp.Body) } // GetURL 请求URL func GetURL(URL string) ([]byte, error) { resp, err := http.Get(URL) if err != nil { return nil, err } defer resp.Body.Close() return ioutil.ReadAll(resp.Body) } // GetURL 请求URL func CtxGetURL(URL string) ([]byte, error...
// IsValidIP
identifier_name
http.go
URL并且解析JSON格式的返回数据 func DoURL(method, url string, body []byte) ([]byte, error) { req, err := http.NewRequest(method, url, bytes.NewBuffer(body)) if err != nil { return nil, err } resp, err := (&http.Client{}).Do(req) if err != nil { return nil, err } defer resp.Body.Close() return ioutil.ReadAll(resp.Body...
// GetURL 请求URL func GetURL(URL string) ([]byte, error) { resp, err := http.Get(URL) if err != nil { return nil, err } defer resp.Body.Close() return ioutil.ReadAll(resp.Body) } // GetURL 请求URL func CtxGetURL(URL string) ([]byte, error) { req := fasthttp.AcquireRequest() defer fasthttp.ReleaseRequest(req) /...
}
random_line_split
http.go
并且解析JSON格式的返回数据 func DoURL(method, url string, body []byte) ([]byte, error) { req, err := http.NewRequest(method, url, bytes.NewBuffer(body)) if err != nil { return nil, err } resp, err := (&http.Client{}).Do(req) if err != nil { return nil, err } defer resp.Body.Close() return ioutil.ReadAll(resp.Body) }...
y) } // GetURL 请求URL func CtxGetURL(URL string) ([]byte, error) { req := fasthttp.AcquireRequest() defer fasthttp.ReleaseRequest(req) // 用完需要释放资源 // 默认是application/x-www-form-urlencoded req.Header.SetMethod("GET") req.SetRequestURI(URL) resp := fasthttp.AcquireResponse() defer fasthttp.ReleaseResponse(resp) ...
outil.ReadAll(resp.Bod
conditional_block
segment.ts
]', options.pathMain, options.novelID); return Promise.resolve(options.files || FastGlob(globPattern, { cwd: CWD_IN, //absolute: true, }) as any as Promise<string[]>) .then(function (ls) { return _doSegmentGlob(ls, options); }) ; } export function _doSegmentGlob(ls: string[], options: IOptions) { ...
let _s_ver: string = String(require("novel-segment").version || '1'); let _d_ver: string = String(require("segment-dict").version || '1'); if (fs.existsSync(_cache_file_segment)) { try { _cache_segment = fs.readJSONSync(_cache_file_segment); } catch (e) { } } // @ts-ignore _cache_segment = _ca...
}, } }, };
random_line_split
segment.ts
]', options.pathMain, options.novelID); return Promise.resolve(options.files || FastGlob(globPattern, { cwd: CWD_IN, //absolute: true, }) as any as Promise<string[]>) .then(function (ls) { return _doSegmentGlob(ls, options); }) ; } export function _doSegmentGlob(ls: string[], options: IOptions) { ...
// 簡轉繁專用 //segment.loadSynonymDic t('zht.synonym.txt'); } let db_dict = segment.getDictDatabase('TABLE', true); db_dict.TABLE = segment.DICT['TABLE']; db_dict.TABLE2 = segment.DICT['TABLE2']; db_dict.options.autoCjk = true; //console.log('主字典總數', db_dict.size()); console.timeEnd(`讀取模組與字典`); if (useCac...
e).toString()); useDefault(segment, { ...options, nodict: true, }); segment.DICT = data.DICT; segment.inited = true; cache_file = null; data = undefined; } } if (!segment.inited) { //console.log(`重新載入分析字典`); segment.autoInit(options);
conditional_block
segment.ts
]', options.pathMain, options.novelID); return Promise.resolve(options.files || FastGlob(globPattern, { cwd: CWD_IN, //absolute: true, }) as any as Promise<string[]>) .then(function (ls) { return _doSegmentGlob(ls, options); }) ; } export function _doSegmentGlob(ls: string[], options: IOptions) { ...
g, list: { [k: string]: { [k: string]: { s_ver?: string, d_ver?: string, last_s_ver?: string, last_d_ver?: string, }, } }, }; let _s_ver: string = String(require("novel-segment").version || '1'); let _d_ver: string = String(require("segment-dict").version || '1'); if (fs.ex...
er?: strin
identifier_name
segment.ts
]', options.pathMain, options.novelID); return Promise.resolve(options.files || FastGlob(globPattern, { cwd: CWD_IN, //absolute: true, }) as any as Promise<string[]>) .then(function (ls) { return _doSegmentGlob(ls, options); }) ; } export function _doSegmentGlob(ls: string[], options: IOptions) { ...
string, last_d_ver?: string, list: { [k: string]: { [k: string]: { s_ver?: string, d_ver?: string, last_s_ver?: string, last_d_ver?: string, }, } }, }; let _s_ver: string = String(require("novel-segment").version || '1'); let _d_ver: string = String(require("segment-dict")....
?: string, d_ver?: string, last_s_ver?:
identifier_body
lib.rs
else { while v != 0 && v % branch_factor as i32 == 0 { v /= branch_factor as i32; layer += 1; } } return layer; } impl<'a> Mast<'a> { pub fn newInMemory() -> Mast<'a> { return Mast { size: 0, height: 0, root_link: Link::Mu...
{ while v != 0 && v & 0xf == 0 { v >>= 4; layer += 1 } }
conditional_block
lib.rs
grow_after_size: default_branch_factor as u64, shrink_below_size: 1, key_order: default_order, key_layer: default_layer, _a: std::marker::PhantomData, // store: InMemoryNodeStore::new(), }; } fn insert(&mut self, key: i32, value: i32) -> Resu...
}; return Ok(res); } if equal { if value == self.value[i] { return Ok(InsertResult::NoChange); } self.value[i] = value; self.dirty = true; return Ok(InsertResult::Updated); } let (left_l...
}; let res = child.insert(key, value, distance - 1, key_order)?; match res { InsertResult::NoChange => (), _ => self.dirty = true,
random_line_split
lib.rs
(v: &i32, branch_factor: u16) -> u8 { let mut layer = 0; let mut v = *v; if branch_factor == 16 { while v != 0 && v & 0xf == 0 { v >>= 4; layer += 1 } } else { while v != 0 && v % branch_factor as i32 == 0 { v /= branch_factor as i32; ...
default_layer
identifier_name