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
made.py
# Import the PyQt and QGIS libraries from PyQt4.QtCore import * from PyQt4.QtGui import * from qgis.core import * # Initialize Qt resources from file resources.py import resources import locale locale.setlocale(locale.LC_ALL, '') # Import the code for the dialog from dalacalcdialog import DalaCalcDialog class DalaCal...
rect.scale(number * scalefactor) mc.setExtent(rect) mc.refresh() #scalefactor = number / mc.scale() #mc.zoomByFactor(scalefactor) except: print "Tidak ada feature yang terseleksi"
scalefactor = (mc.extent().height() / mc.scale())
conditional_block
made.py
# Import the PyQt and QGIS libraries from PyQt4.QtCore import * from PyQt4.QtGui import * from qgis.core import * # Initialize Qt resources from file resources.py import resources import locale locale.setlocale(locale.LC_ALL, '') # Import the code for the dialog from dalacalcdialog import DalaCalcDialog class DalaCal...
# run method that performs all the real work def run(self): # create and show the dialog flags = Qt.WindowTitleHint | Qt.WindowSystemMenuHint | Qt.WindowMaximizeButtonHint self.dlg = DalaCalcDialog(self.iface.mainWindow(), flags) # show the dialog self.dlg.show() ...
self.iface.removePluginMenu(u"&Hitungan Kerusakan Kerugian", self.action) self.iface.removeToolBarIcon(self.action)
identifier_body
__init__.py
# Copyright (c) 2020 krrr # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, su...
class InMemoryLogHandler(logging.Handler): logs = deque(maxlen=200) def emit(self, record): self.logs.append(self.format(record)) def main_entry(): if not sys.version_info >= (3, 3): die('Python 3.3 or higher required') global config, loop config = load_config() if config.ge...
sha1 = hashlib.sha1() sha1.update(dat) return sha1.digest()
random_line_split
__init__.py
# Copyright (c) 2020 krrr # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, su...
(): import argparse from wstan.autobahn.websocket.protocol import parseWsUrl parser = argparse.ArgumentParser( description='Ver %s | Tunneling TCP in WebSocket' % __version__) # common config parser.add_argument('-g', '--gen-key', help='generate a key and exit', action='store_true') par...
load_config
identifier_name
__init__.py
# Copyright (c) 2020 krrr # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, su...
class InMemoryLogHandler(logging.Handler): logs = deque(maxlen=200) def emit(self, record): self.logs.append(self.format(record)) def main_entry(): if not sys.version_info >= (3, 3): die('Python 3.3 or higher required') global config, loop config = load_config() if config...
sha1 = hashlib.sha1() sha1.update(dat) return sha1.digest()
identifier_body
__init__.py
# Copyright (c) 2020 krrr # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, su...
exceptions = [] sock = None for family, type_, proto, cname, address in infos: try: sock = socket.socket(family=family, type=type_, proto=proto) sock.setblocking(False) await loop.sock_connect(sock, address) except OSError as exc: if sock is ...
raise OSError('getaddrinfo() returned empty list')
conditional_block
fs.rs
// Copyright 2021 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use std::io; use std::os::unix::io::AsRawFd; use std::os::unix::net::UnixListener; use std::path::{Path, PathBuf}; use std::sync::Arc; use anyhow::{an...
fn jail_and_fork( mut keep_rds: Vec<RawDescriptor>, dir_path: PathBuf, uid_map: Option<String>, gid_map: Option<String>, ) -> anyhow::Result<i32> { // Create new minijail sandbox let mut j = Minijail::new()?; j.namespace_pids(); j.namespace_user(); j.namespace_user_disable_setgrou...
{ let egid = unsafe { libc::getegid() }; format!("{} {} 1", egid, egid) }
identifier_body
fs.rs
// Copyright 2021 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use std::io; use std::os::unix::io::AsRawFd; use std::os::unix::net::UnixListener; use std::path::{Path, PathBuf}; use std::sync::Arc; use anyhow::{an...
{ #[argh(option, description = "path to a socket", arg_name = "PATH")] socket: String, #[argh(option, description = "the virtio-fs tag", arg_name = "TAG")] tag: String, #[argh(option, description = "path to a directory to share", arg_name = "DIR")] shared_dir: PathBuf, #[argh(option, descri...
Options
identifier_name
fs.rs
// Copyright 2021 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use std::io; use std::os::unix::io::AsRawFd; use std::os::unix::net::UnixListener; use std::path::{Path, PathBuf}; use std::sync::Arc; use anyhow::{an...
if pid < 0 { bail!("Fork error! {}", std::io::Error::last_os_error()); } Ok(pid) } struct FsBackend { server: Arc<fuse::Server<PassthroughFs>>, tag: [u8; FS_MAX_TAG_LEN], avail_features: u64, acked_features: u64, acked_protocol_features: VhostUserProtocolFeatures, workers...
{ unsafe { libc::prctl(libc::PR_SET_PDEATHSIG, libc::SIGTERM) }; }
conditional_block
fs.rs
// Copyright 2021 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use std::io; use std::os::unix::io::AsRawFd; use std::os::unix::net::UnixListener; use std::path::{Path, PathBuf}; use std::sync::Arc; use anyhow::{an...
/// Starts a vhost-user fs device. /// Returns an error if the given `args` is invalid or the device fails to run. pub fn run_fs_device(program_name: &str, args: &[&str]) -> anyhow::Result<()> { let opts = match Options::from_args(&[program_name], args) { Ok(opts) => opts, Err(e) => { i...
#[argh(option, description = "uid map to use", arg_name = "UIDMAP")] uid_map: Option<String>, #[argh(option, description = "gid map to use", arg_name = "GIDMAP")] gid_map: Option<String>, }
random_line_split
analysis.py
from sklearn.feature_extraction.text import TfidfVectorizer,CountVectorizer from sklearn.metrics.pairwise import cosine_similarity, euclidean_distances from sklearn.decomposition import PCA from scipy.cluster.hierarchy import ward, dendrogram from pandas import DataFrame, Series import pandas as pd import matplotlib im...
umerate(infolist[1]): if title in yeshititles: infolist[2][i] = "野史" ''' if "外史" in title or "逸史" in title or "密史" in title or "野史" in title: priorgenre = infolist[2][i] if priorgenre == "小说": infolist[2][i] = "ny" elif priorgenre == "演义": infolist[2][i] = "yy" elif priorgenre == "志存记录": ...
hoice") # Kill the program exit() for i,title in en
conditional_block
analysis.py
from sklearn.feature_extraction.text import TfidfVectorizer,CountVectorizer from sklearn.metrics.pairwise import cosine_similarity, euclidean_distances from sklearn.decomposition import PCA from scipy.cluster.hierarchy import ward, dendrogram from pandas import DataFrame, Series import pandas as pd import matplotlib im...
infolist = altinfo print("Making vectorizer") # create a vectorizer object to vectorize the documents into matrices. These # vectorizers return sparse matrices. # Calculate using plain term frequency if cnchoice == "tf": vectorizer = TfidfVectorizer(use_idf=False, analyzer='word', token_pattern='\S+', ngram...
nl.append(infolist[i][it]) altinfo.append(nl)
random_line_split
tools.py
import logging import os import shutil import subprocess import sys import click import yaml from yaml.representer import SafeRepresenter from cekit.errors import CekitError try: basestring except NameError: basestring = str LOGGER = logging.getLogger('cekit') class Map(dict): """ Class to enable...
""" External dependency manager. Understands on what platform are we currently running and what dependencies are required to be installed to satisfy the requirements. """ # List of operating system families on which CEKit is known to work. # It may work on other operating systems too, but it wa...
identifier_body
tools.py
import logging import os import shutil import subprocess import sys import click import yaml from yaml.representer import SafeRepresenter from cekit.errors import CekitError try: basestring except NameError: basestring = str LOGGER = logging.getLogger('cekit') class Map(dict): """ Class to enable...
(self): self._handle_dependencies( DependencyHandler.EXTERNAL_CORE_DEPENDENCIES) try: import certifi # pylint: disable=unused-import LOGGER.warning(("The certifi library (https://certifi.io/) was found, depending on the operating " + "sys...
handle_core_dependencies
identifier_name
tools.py
import logging import os import shutil import subprocess import sys import click import yaml from yaml.representer import SafeRepresenter from cekit.errors import CekitError try: basestring except NameError: basestring = str LOGGER = logging.getLogger('cekit') class Map(dict): """ Class to enable...
LOGGER.debug("All dependencies provided!") # pylint: disable=R0201 def _check_for_library(self, library): library_found = False if sys.version_info[0] < 3: import imp try: imp.find_module(library) library_found = True ...
self._check_for_executable(dependency, executable)
conditional_block
tools.py
import logging import os import shutil import subprocess import sys import click import yaml from yaml.representer import SafeRepresenter from cekit.errors import CekitError try: basestring except NameError: basestring = str LOGGER = logging.getLogger('cekit') class Map(dict): """ Class to enable...
# 'BUILDING': 0 # 'COMPLETE': 1 # 'DELETED': 2 # 'FAILED': 3 # 'CANCELED': 4 if build['state'] != 1: raise CekitError( "Artifact with checksum {} was found in Koji metadata but the build is in incorrect state ({}) making " "the ...
#
random_line_split
deploy.go
package cmd import ( "context" "crypto/sha1" "fmt" "io/ioutil" "os" "os/user" "path/filepath" "regexp" "strings" "time" "cuelang.org/go/cue" "cuelang.org/go/cue/build" "github.com/TangoGroup/stx/graph" "github.com/TangoGroup/stx/stx" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awser...
{ fileName, saveErr := saveStackAsYml(stack, buildInstance, stackValue) if saveErr != nil { log.Error(saveErr) } log.Infof("%s %s %s %s:%s\n", au.White("Deploying"), au.Magenta(stack.Name), au.White("⤏"), au.Green(stack.Profile), au.Cyan(stack.Region)) log.Infof("%s", au.Gray(11, " Validating template...")) ...
identifier_body
deploy.go
package cmd import ( "context" "crypto/sha1" "fmt" "io/ioutil" "os" "os/user" "path/filepath" "regexp" "strings" "time" "cuelang.org/go/cue" "cuelang.org/go/cue/build" "github.com/TangoGroup/stx/graph" "github.com/TangoGroup/stx/stx" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awser...
() { rootCmd.AddCommand(deployCmd) deployCmd.Flags().BoolVarP(&flags.DeployWait, "wait", "w", false, "Wait for stack updates to complete before continuing.") deployCmd.Flags().BoolVarP(&flags.DeploySave, "save", "s", false, "Save stack outputs upon successful completion. Implies --wait.") deployCmd.Flags().BoolVarP...
init
identifier_name
deploy.go
package cmd import ( "context" "crypto/sha1" "fmt" "io/ioutil" "os" "os/user" "path/filepath" "regexp" "strings" "time" "cuelang.org/go/cue" "cuelang.org/go/cue/build" "github.com/TangoGroup/stx/graph" "github.com/TangoGroup/stx/stx" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awser...
oySave || flags.DeployWait { log.Infof("%s", au.Gray(11, " Waiting for stack...")) switch changeSetType { case "UPDATE": cfn.WaitUntilStackUpdateCompleteWithContext(context.Background(), &describeStacksInput, waitOption) case "CREATE": cfn.WaitUntilStackCreateCompleteWithContext(context.Background(), &de...
ecuteChangeSetErr) } if flags.Depl
conditional_block
deploy.go
package cmd import ( "context" "crypto/sha1" "fmt" "io/ioutil" "os" "os/user" "path/filepath" "regexp" "strings" "time" "cuelang.org/go/cue" "cuelang.org/go/cue/build" "github.com/TangoGroup/stx/graph" "github.com/TangoGroup/stx/stx" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awser...
} } } }
if flags.DeploySave { saveErr := saveStackOutputs(buildInstance, stack) if saveErr != nil { log.Fatal(saveErr)
random_line_split
http.go
package ostential import ( "ostential/types" "ostential/view" "fmt" "sort" "sync" "os/user" "net/url" "net/http" "html/template" "github.com/rzab/gosigar" "github.com/codegangsta/martini" ) func(s state) InterfacesDelta() []types.DeltaInterface { ifs := make([]types.DeltaInterface, len(s.InterfacesTota...
(disks []diskInfo, seq types.SEQ) []types.DiskData { sort.Stable(diskOrder{ disks: disks, seq: seq, reverse: _DFBIMAP.SEQ2REVERSE[seq], }) var dd []types.DiskData for _, disk := range disks { total, approxtotal := humanBandback(disk.Total) used, approxused := humanBandback(disk.Used) itotal, appr...
orderDisk
identifier_name
http.go
package ostential import ( "ostential/types" "ostential/view" "fmt" "sort" "sync" "os/user" "net/url" "net/http" "html/template" "github.com/rzab/gosigar" "github.com/codegangsta/martini" ) func(s state) InterfacesDelta() []types.DeltaInterface { ifs := make([]types.DeltaInterface, len(s.InterfacesTota...
stateLock.Lock() defer stateLock.Unlock() lastState.PrevInterfacesTotal = []InterfaceTotal{} lastState.PREVCPU.List = []sigar.Cpu{} } func collect() { // state stateLock.Lock() defer stateLock.Unlock() prev_ifstotal := lastState.InterfacesTotal prev_cpu := lastState.RAWCPU ifs, ip := NewInterface...
var stateLock sync.Mutex var lastState state func reset_prev() {
random_line_split
http.go
package ostential import ( "ostential/types" "ostential/view" "fmt" "sort" "sync" "os/user" "net/url" "net/http" "html/template" "github.com/rzab/gosigar" "github.com/codegangsta/martini" ) func(s state) InterfacesDelta() []types.DeltaInterface { ifs := make([]types.DeltaInterface, len(s.InterfacesTota...
func textAttr_colorPercent(p uint) template.HTMLAttr { return template.HTMLAttr(" class=\"text-" + colorPercent(p) + "\"") } func labelAttr_colorPercent(p uint) template.HTMLAttr { return template.HTMLAttr(" class=\"label label-" + colorPercent(p) + "\"") } func colorPercent(p uint) string { if p > 90 { return "d...
{ sum := sigar.Cpu{} cls := s.cpudelta() c := types.CPU{List: make([]types.CPU, len(cls.List))} for i, cp := range cls.List { total := cp.User + cp.Nice + cp.Sys + cp.Idle user := percent(cp.User, total) sys := percent(cp.Sys, total) idle := uint(0) if user + sys < 100 { idle = 100 - user - sys ...
identifier_body
http.go
package ostential import ( "ostential/types" "ostential/view" "fmt" "sort" "sync" "os/user" "net/url" "net/http" "html/template" "github.com/rzab/gosigar" "github.com/codegangsta/martini" ) func(s state) InterfacesDelta() []types.DeltaInterface { ifs := make([]types.DeltaInterface, len(s.InterfacesTota...
return dd } var _DFBIMAP = types.Seq2bimap(DFFS, // the default seq for ordering types.Seq2string{ DFFS: "fs", DFSIZE: "size", DFUSED: "used", DFAVAIL: "avail", DFMP: "mp", }, []types.SEQ{ DFFS, DFMP, }) var _PSBIMAP = types.Seq2bimap(PSPID, // the default seq for ordering types.Se...
{ total, approxtotal := humanBandback(disk.Total) used, approxused := humanBandback(disk.Used) itotal, approxitotal := humanBandback(disk.Inodes) iused, approxiused := humanBandback(disk.Iused) short := "" if len(disk.DevName) > 10 { short = disk.DevName[:10] } dd = append(dd, types.DiskData...
conditional_block
prohack-github.py
# To add a new cell, type '# %%' # To add a new markdown cell, type '# %% [markdown]' # %% [markdown] # Ömer Gözüaçık, 29/05/2020 # %% import pandas as pd import numpy as np from sklearn.metrics import mean_squared_error from sklearn.feature_selection import RFE from sklearn.model_selection import train_test_split fr...
%% print(errors) # [-0.005510409192904806, -0.005474700678841418, -0.005478204236398942, -0.005493891458843025, -0.005485265856592613, -0.005493237060981963, -0.005493713846323645, -0.0055068515842603225] # %% [markdown] # ## Making predictions on the test data # # - Similar methodology is used to fill the missing v...
("cor: ",x) errors.append(loop_train(x)) #
conditional_block
prohack-github.py
# To add a new cell, type '# %%' # To add a new markdown cell, type '# %% [markdown]' # %% [markdown] # Ömer Gözüaçık, 29/05/2020 # %% import pandas as pd import numpy as np from sklearn.metrics import mean_squared_error from sklearn.feature_selection import RFE from sklearn.model_selection import train_test_split fr...
# - That's why, I believe its better to spread the risk for the samples in the bordering regions (400< [rank of p^2] <600). # - I assign 100 energy to top 400 samples and 50 energy to the remaining top 200 samples. # %% index = predictions pot_inc = -np.log(index+0.01)+3 # %% p2= pot_inc**2 # %% ss = pd.DataFrame(...
# # E.g: If the original p^2 value is higher than the predicted p^2, it will increase the error as we are directly giving it 0. #
random_line_split
prohack-github.py
# To add a new cell, type '# %%' # To add a new markdown cell, type '# %% [markdown]' # %% [markdown] # Ömer Gözüaçık, 29/05/2020 # %% import pandas as pd import numpy as np from sklearn.metrics import mean_squared_error from sklearn.feature_selection import RFE from sklearn.model_selection import train_test_split fr...
: errors=[] for gal in tqdm(train_gal): index = train.index[train['galaxy'] == gal] data = train.loc[index] errors.append(cross_validation_loop(data,cor)) return np.mean(errors) # %% [markdown] # #### Checking which correlation threshold gives better value # # The model performs be...
train(cor)
identifier_name
prohack-github.py
# To add a new cell, type '# %%' # To add a new markdown cell, type '# %% [markdown]' # %% [markdown] # Ömer Gözüaçık, 29/05/2020 # %% import pandas as pd import numpy as np from sklearn.metrics import mean_squared_error from sklearn.feature_selection import RFE from sklearn.model_selection import train_test_split fr...
% [markdown] # #### Checking which correlation threshold gives better value # # The model performs best when the threshold is 20 with RMSE of 0.0063 # %% cor=[20,25,30,40,50,60,70,80] errors=[] for x in cor: print("cor: ",x) errors.append(loop_train(x)) # %% print(errors) # [-0.005510409192904806, -0.0054...
s=[] for gal in tqdm(train_gal): index = train.index[train['galaxy'] == gal] data = train.loc[index] errors.append(cross_validation_loop(data,cor)) return np.mean(errors) # %
identifier_body
myRansac.py
#!\usr\bin\env python3 #encoding: utf-8 import csv import codecs import time import numpy import re from configparser import ConfigParser import traceback import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from email.header import Header import os def G...
ations form .config file config = ConfigParser() config.read( CONFIG_FILE ) rs_n = config.getint( 'RANSAC', 'MIN_NUM' ) rs_k = config.getint( 'RANSAC', 'MAX_ITR' ) t_str = config.get( 'RANSAC', 'THRES' ) rs_t = float( t_str ) rs_d = config.getint( 'RANSAC',...
self.to_list = ['sunber.chou@qq.com'] self.cc_list = ['zhousongbo@hanmingtech.com'] self.tag = 'Finally, Ransac get result!' self.doc = None return def send(self): ret = True try: mail_host = smtplib.SMTP_SSL('smtp.exmail.qq.com', port=46...
identifier_body
myRansac.py
#!\usr\bin\env python3 #encoding: utf-8 import csv import codecs import time import numpy import re from configparser import ConfigParser import traceback import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from email.header import Header import os def G...
fw_p.write( 'item[n], name, r_val, r_res, n_fit, f_v, f_dta\r\n') for item in lstResult: fw_p.write( '%s[%d], %s, %.6f, %.6f, %d, %.6f, %.6f\r\n'%( item[0], item[1],item[2],item[3], item[4], item[5], item[6], item[7] )) myMail = qqExmail() myMail.doc = fnList ...
fnList = LOCAL_PATH + 'A_result.txt' with open( fnList, 'w', encoding='utf-8') as fw_p:
random_line_split
myRansac.py
#!\usr\bin\env python3 #encoding: utf-8 import csv import codecs import time import numpy import re from configparser import ConfigParser import traceback import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from email.header import Header import os def G...
ta_x, data_y ): i = 0 j = 0 data_out = [] while i < len( data_x ) and j < len( data_y ): item_x = data_x[i] item_y = data_y[j] tx = time.strptime( item_x[0], '%Y/%m/%d' ) ty = time.strptime( item_y[0], '%Y/%m/%d' ) if tx < ty: i += 1 ...
leanData( da
identifier_name
myRansac.py
#!\usr\bin\env python3 #encoding: utf-8 import csv import codecs import time import numpy import re from configparser import ConfigParser import traceback import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from email.header import Header import os def G...
), 'utf-8') if self.doc: fn = os.path.basename( self.doc ) with open(self.doc,'rb') as f: doc = MIMEText(f.read(), 'base64', 'utf-8') doc["Content-Type"] = 'application/octet-stream' doc["Content-Disposition"] = 'attachment; filename...
message['Cc'] = Header(';'.join(self.cc_list
conditional_block
3DMain.js
/** * User: wyh * Date: 13-4-17 * Time: 上午9:32 * Desc: */ //cy var earthArray = []; var planArr = []; var bollonArr = []; //已看 function unloadEarth() { seearth.Suicide(); } /** * 弹出气泡 */ function onPoiClicked( pVal ){ var htmlObj=parent.htmlBalloon; var posX = parseInt(pVal.substring(pVal.indexOf("<posX...
*/ function setScreen(n, data, projManager, projectId, currentLayerObjList) { planArr = data; if (n == 1) { $("#earthDiv0,#earthDiv1,#earthDiv2").removeClass("s1 s2 s3 s4").addClass("hide"); $("#earthDiv0").removeClass("hide").addClass("s1"); for (var i = parent.earthArray.length - 1; i...
* @param n 屏幕数
random_line_split
3DMain.js
/** * User: wyh * Date: 13-4-17 * Time: 上午9:32 * Desc: */ //cy var earthArray = []; var planArr = []; var bollonArr = []; //已看 function unloadEarth() { seearth.Suicide(); } /** * 弹出气泡 */ function onPoiClicked( pVal ){ var htmlObj=parent.htmlBalloon; var posX = parseInt(pVal.substring(pVal.indexOf("<posX...
minValue = dataValue; } } if(maxValue == null){ maxValue = dataValue; }else{ if(dataValue > maxValue){ maxValue = dataValue; } } } } var chart = new Highcharts.Chart({ chart: { renderTo: '...
se{ if(dataValue < minValue){
conditional_block
3DMain.js
/** * User: wyh * Date: 13-4-17 * Time: 上午9:32 * Desc: */ //cy var earthArray = []; var planArr = []; var bollonArr = []; //已看 function unloadEarth() { seearth.Suicide(); } /** * 弹出气泡 */ function onPoiClicked( pVal ){ var htmlObj=
多屏(方案比选) * @param n 屏幕数 */ function setScreen(n, data, projManager, projectId, currentLayerObjList) { planArr = data; if (n == 1) { $("#earthDiv0,#earthDiv1,#earthDiv2").removeClass("s1 s2 s3 s4").addClass("hide"); $("#earthDiv0").removeClass("hide").addClass("s1"); for (var i = parent...
parent.htmlBalloon; var posX = parseInt(pVal.substring(pVal.indexOf("<posX>")+6, pVal.indexOf("</posX>"))); var posY = parseInt(pVal.substring(pVal.indexOf("<posY>")+6, pVal.indexOf("</posY>"))); var loaclUrl = window.location.href.substring(0, window.location.href.lastIndexOf("/")); var url = loaclUrl + "/res/c...
identifier_body
3DMain.js
/** * User: wyh * Date: 13-4-17 * Time: 上午9:32 * Desc: */ //cy var earthArray = []; var planArr = []; var bollonArr = []; //已看 function unloadEarth() { seearth.Suicide(); } /** * 弹出气泡 */ function onPoiClicked( pVal ){ var htmlObj=parent.htmlBalloon; var posX = parseInt(pVal.substring(pVal.indexOf("<posX...
; earth.classid = "CLSID:EA3EA17C-5724-4104-94D8-4EECBD352964"; earth.style.width = "100%"; earth.style.height = "100%"; div.appendChild(earth); earth.Event.OnCreateEarth = function (searth) { earth.Event.OnCreateEarth = function () {}; parent.earthArray.push(searth); searth....
th.name = id
identifier_name
pygit.py
#! /usr/bin/python3.6 import os import sys import shutil import shelve import argparse import logging from datetime import datetime from subprocess import Popen, PIPE, STDOUT from pathlib import Path, PurePath, PureWindowsPath from send2trash import send2trash BASE_DIR = Path.home() DESKTOP = BASE_DIR / 'Desktop' S...
if __name__ == "__main__": initialize()
"""Write status of all repositories to file in markdown format""" print("Getting repo status.\n\nYou may be prompted for credentials...") os.chdir(STATUS_DIR) attention = "" messages = [] TIME_STAMP = datetime.now().strftime("%a_%d_%b_%Y_%H_%M_%S_%p") fname = "REPO_STATUS_@_{}.md".format(TIME_...
identifier_body
pygit.py
#! /usr/bin/python3.6 import os import sys import shutil import shelve import argparse import logging from datetime import datetime from subprocess import Popen, PIPE, STDOUT from pathlib import Path, PurePath, PureWindowsPath from send2trash import send2trash BASE_DIR = Path.home() DESKTOP = BASE_DIR / 'Desktop' S...
else: process = Popen(['git push'], shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE,) output, _ = process.communicate() return str("Push completed.{}".format(str(output.decode("utf-8")))) def pull(self): """git pull""" if self.git_exec: process = Po...
process = Popen([self.git_exec, ' git push'], stdin=PIPE, stdout=PIPE, stderr=STDOUT,)
conditional_block
pygit.py
#! /usr/bin/python3.6 import os import sys import shutil import shelve import argparse import logging from datetime import datetime from subprocess import Popen, PIPE, STDOUT from pathlib import Path, PurePath, PureWindowsPath from send2trash import send2trash BASE_DIR = Path.home() DESKTOP = BASE_DIR / 'Desktop' S...
(*args, _all=False): for each in load_multiple(*args, _all=_all): s = "*** {} ***\n{}".format(each.name, each.push()) print(s) def all_status(): """Write status of all repositories to file in markdown format""" print("Getting repo status.\n\nYou may be prompted for credentials...") os...
push
identifier_name
pygit.py
#! /usr/bin/python3.6 import os import sys import shutil import shelve import argparse import logging from datetime import datetime from subprocess import Popen, PIPE, STDOUT from pathlib import Path, PurePath, PureWindowsPath from send2trash import send2trash BASE_DIR = Path.home() DESKTOP = BASE_DIR / 'Desktop' S...
i = len(list(INDEX_SHELF.keys())) + 1 folder_paths = [x for x in Path(master).iterdir() if x.is_dir()] for folder_name in folder_paths: path = Path(master) / folder_name directory_absolute_path = Path(path).resolve() if is_git_repo(directory_absolute_path): if sys.platf...
random_line_split
merge.go
// Copyright 2022 Matrix Origin // // 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 ...
w) } if err != nil { m.logger.Warn("failed to read file", logutil.PathField(fp.FilePath), zap.Error(err)) return err } // sql insert if cacheFileData.Size() > 0 { if err = cacheFileData.Flush(m.table); err != nil { return err } cacheFileData.Reset() } // delete empty file or file a...
rse ETL rows failed", logutil.TableField(m.table.GetIdentify()), logutil.PathField(fp.FilePath), logutil.VarsField(SubStringPrefixLimit(fmt.Sprintf("%v", line), 102400)), ) return err } cacheFileData.Put(ro
conditional_block
merge.go
// Copyright 2022 Matrix Origin // // 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 ...
sk task.Task, logger *log.MOLogger, opts ...MergeOption) error { // should init once in/with schema-init. tables := table.GetAllTables() if len(tables) == 0 { logger.Info("empty tables") return nil } var newOptions []MergeOption newOptions = append(newOptions, opts...) newOptions = append(newOptions, WithTa...
ext.Context, ta
identifier_name
merge.go
// Copyright 2022 Matrix Origin // // 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 ...
ize() int64 { return c.size } func LongRunETLMerge(ctx context.Context, task task.Task, logger *log.MOLogger, opts ...MergeOption) error { // should init once in/with schema-init. tables := table.GetAllTables() if len(tables) == 0 { logger.Info("empty tables") return nil } var newOptions []MergeOption newOp...
etCsvStrings()) c.size += r.Size() } func (c *SliceCache) S
identifier_body
merge.go
// Copyright 2022 Matrix Origin // // 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 ...
const LoggerNameContentReader = "ETLContentReader" const MAX_MERGE_INSERT_TIME = 10 * time.Second const defaultMaxFileSize = 32 * mpool.MB // ======================== // handle merge // ======================== // Merge like a compaction, merge input files into one/two/... files. // - NewMergeService init merge as ...
) const LoggerNameETLMerge = "ETLMerge"
random_line_split
pg_v6.x.x.js
declare module pg { // Note: Currently There are some issues in Function overloading. // https://github.com/facebook/flow/issues/2423 // So i temporarily remove the // `((event: string, listener: Function) => EventEmitter );` // from all overloading for EventEmitter.on(). // `any` types exised in this file...
// `Function` types exised in this file, cause of they come from another // untyped npm lib. /* Cause of <flow 0.36 did not support export type very well, // so copy the types from pg-pool // https://github.com/flowtype/flow-typed/issues/16 // https://github.com/facebook/flow/commit/843389f89c69516506213e2...
random_line_split
domaintools.py
#!/usr/bin/env python3 ''' Joshua Lequieu <lequieu@mrl.ucsb.edu> ''' import numpy as np from skimage import measure import pdb #import viztools as viz # Need to increase recursion limit for burning algorithm import sys sys.setrecursionlimit(800000) # class DomainAnalyzer: ''' Class to AnalyzeDomains...
- mesh using marching cubes - calculate volume and area of domains using mesh ''' def __init__(self,coords,fields, density_field_index=0, density_threshold = 0.5): ''' Define and calculate useful variables for DomainAnalysis routines ''' self.__coords = coords ...
random_line_split
domaintools.py
#!/usr/bin/env python3 ''' Joshua Lequieu <lequieu@mrl.ucsb.edu> ''' import numpy as np from skimage import measure import pdb #import viztools as viz # Need to increase recursion limit for burning algorithm import sys sys.setrecursionlimit(800000) # class DomainAnalyzer: ''' Class to AnalyzeDomains...
plt.close() def plotMesh3D(self, verts, faces, filename=None): ''' Plot a mesh from marching cubes ''' import matplotlib.pyplot as plt from mpl_toolkits.mplot3d.art3d import Poly3DCollection # Display resulting triangular mesh using Matplotlib. This can also be done...
plt.show() plt.savefig(filename)
conditional_block
domaintools.py
#!/usr/bin/env python3 ''' Joshua Lequieu <lequieu@mrl.ucsb.edu> ''' import numpy as np from skimage import measure import pdb #import viztools as viz # Need to increase recursion limit for burning algorithm import sys sys.setrecursionlimit(800000) # class DomainAnalyzer: ''' Class to AnalyzeDomains...
(self, area, vol): '''returns isoperimetric coefficient. 1 for perfect circle or sphere, less for other shapes note that in 2d "area" is actually perimeter, and "vol" is actually area This difference didn't seem to warrant a completely different method though ''' if self.__...
calcIQ
identifier_name
domaintools.py
#!/usr/bin/env python3 ''' Joshua Lequieu <lequieu@mrl.ucsb.edu> ''' import numpy as np from skimage import measure import pdb #import viztools as viz # Need to increase recursion limit for burning algorithm import sys sys.setrecursionlimit(800000) # class DomainAnalyzer: ''' Class to AnalyzeDomains...
def updateDisp(self,pos_curr, vol_curr): ''' Given current position of all micelles, update the squared displacement However, there's several things to be careful of: - The number of domains needs to be the same, the threshold will be needed to ignore domains with small volumes ...
''' Returns mean squared displacement (averaged over all micelles) ''' assert(self.__is_init_pos) return np.average(self.__sqdisp)
identifier_body
BackendMapping.ts
/******************************************************************************* * Backend Google Map & ResultList * * Copyright (c) 2015. Code for KORIYAMA. All Rights Reserved. * * @author: Nobuyuki Kondo * @uri: http://koriyama.io/ * @version: 1.0 *************************************************************...
/** * チームデータの格納 * @param data */ setTeamList(data) { var elem = '', count = data.length; $.get(this.template.filterTeam, (template)=> { for (var i = 0, iLen = data.length; i < iLen; i++) { var obj = data[i], data_id = 0, isArr = this.teamSetting.filter((elem...
}); }
identifier_name
BackendMapping.ts
/******************************************************************************* * Backend Google Map & ResultList * * Copyright (c) 2015. Code for KORIYAMA. All Rights Reserved. * * @author: Nobuyuki Kondo * @uri: http://koriyama.io/ * @version: 1.0 *************************************************************...
= '') ? '' : ' hide'; obj.color = this.teamSetting[obj.team_id].color; obj.category = this.category[obj.cat]; obj.cls = visible; obj.created = this.getTimeDiff(obj.created_at); elem += Mustache.render(template, obj); } $(this.target.table).prepend(elem); this...
this.teamData.push(obj); } $('#filter-team').append(elem); this.setMarker(count); this.setList(count); }); } /** * 登録データの表示 * @param count */ setList(count){ var diff = this.teamData.length - count; // 追加データの個数を返却 $.get(this.template.list, (template)=>{ v...
conditional_block
BackendMapping.ts
/******************************************************************************* * Backend Google Map & ResultList * * Copyright (c) 2015. Code for KORIYAMA. All Rights Reserved. * * @author: Nobuyuki Kondo * @uri: http://koriyama.io/ * @version: 1.0 *************************************************************...
} /** * チームデータの格納 * @param data */ setTeamList(data) { var elem = '', count = data.length; $.get(this.template.filterTeam, (template)=> { for (var i = 0, iLen = data.length; i < iLen; i++) { var obj = data[i], data_id = 0, isArr = this.teamSetting.filter(...
} });
random_line_split
BackendMapping.ts
/******************************************************************************* * Backend Google Map & ResultList * * Copyright (c) 2015. Code for KORIYAMA. All Rights Reserved. * * @author: Nobuyuki Kondo * @uri: http://koriyama.io/ * @version: 1.0 *************************************************************...
f (isArr.length === 0) { var len = this.teamSetting.length, //color_code = Math.floor(Math.random() * 16777215).toString(16), color_code = this.getRandomColor(this.teamSetting), team = { name : obj.team, color: color_code, id : le...
** * チームデータの格納 * @param data */ setTeamList(data) { var elem = '', count = data.length; $.get(this.template.filterTeam, (template)=> { for (var i = 0, iLen = data.length; i < iLen; i++) { var obj = data[i], data_id = 0, isArr = this.teamSetting.filter((elem, i...
identifier_body
download_params_and_roslaunch_agent.py
#!/usr/bin/env python3 """script to download yaml param from S3 bucket to local directory and start training/eval ROS launch Example: $ python download_params_and_roslaunch_agent.py s3_region, s3_bucket, s3_prefix, s3_yaml_name, launch_name """ # import argparse import logging from subprocess import Popen import...
(yaml_values, multicar): """ Validate that the parameter provided in the yaml file for configuration is correct. Some of the params requires list of two values. This is mostly checked as part of this function Arguments: yaml_values {[dict]} -- [All the yaml parameter as a list] multicar {[bo...
validate_yaml_values
identifier_name
download_params_and_roslaunch_agent.py
#!/usr/bin/env python3 """script to download yaml param from S3 bucket to local directory and start training/eval ROS launch Example: $ python download_params_and_roslaunch_agent.py s3_region, s3_bucket, s3_prefix, s3_yaml_name, launch_name """ # import argparse import logging from subprocess import Popen import...
def get_yaml_values(yaml_dict, default_vals=None): '''yaml_dict - dict containing yaml configs default_vals - Dictionary of the default values to be used if key is not present ''' try: return_values = dict() default_val_keys = default_vals.keys() if default_vals else [] for...
'''local_yaml_path - path to the local yaml file ''' with open(local_yaml_path, 'r') as stream: try: return yaml.safe_load(stream) except yaml.YAMLError as exc: log_and_exit("yaml read error: {}".format(exc), SIMAPP_SIMULATION_WORKER_EXCEPTION, SI...
identifier_body
download_params_and_roslaunch_agent.py
#!/usr/bin/env python3 """script to download yaml param from S3 bucket to local directory and start training/eval ROS launch Example: $ python download_params_and_roslaunch_agent.py s3_region, s3_bucket, s3_prefix, s3_yaml_name, launch_name """ # import argparse import logging from subprocess import Popen import...
cmd = [''.join(("roslaunch deepracer_simulation_environment {} ".format(launch_name), "local_yaml_path:={} ".format(local_yaml_path), "racecars_with_stereo_cameras:={} ".format(','.join(racecars_with_stereo_cameras)), "racecars_with_lida...
racecars_with_lidars.append(racecar_name)
conditional_block
download_params_and_roslaunch_agent.py
#!/usr/bin/env python3 """script to download yaml param from S3 bucket to local directory and start training/eval ROS launch Example: $ python download_params_and_roslaunch_agent.py s3_region, s3_bucket, s3_prefix, s3_yaml_name, launch_name """ # import argparse import logging from subprocess import Popen import...
for key in default_val_keys: return_values[key] = yaml_dict.get(key, default_vals[key]) return return_values except yaml.YAMLError as exc: log_and_exit("yaml read error: {}".format(exc), SIMAPP_SIMULATION_WORKER_EXCEPTION, SIMAPP_EVENT_E...
default_val_keys = default_vals.keys() if default_vals else []
random_line_split
2_tracking.py
# -*- coding: utf-8 -*- # 15 """ """ import numpy as np import os import cv2 from scipy.optimize import linear_sum_assignment input_dir = "../aic19-track1-mtmc/train" ard_uesd_num_path = "../already_used_number.txt" IMAGE_SIZE = 224 TH_SCORE = 0.3 PAD_SIZE = 10 IOU_TH = 0.7 W_PAD = 0 H_PAD = 0 DISTENCE_TH = 100 WIGH...
def Hungary(task_matrix): b = task_matrix.copy() # 行和列减0 for i in range(len(b)): row_min = np.min(b[i]) for j in range(len(b[i])): b[i][j] -= row_min for i in range(len(b[0])): col_min = np.min(b[:, i]) for j in range(len(b)): b[j][i] -= col_min ...
box = self.boxes[i] print('box', i, ': ', box)
random_line_split
2_tracking.py
# -*- coding: utf-8 -*- # 15 """ """ import numpy as np import os import cv2 from scipy.optimize import linear_sum_assignment input_dir = "../aic19-track1-mtmc/train" ard_uesd_num_path = "../already_used_number.txt" IMAGE_SIZE = 224 TH_SCORE = 0.3 PAD_SIZE = 10 IOU_TH = 0.7 W_PAD = 0 H_PAD = 0 DISTENCE_TH = 100 WIGH...
ottom_line - top_line) return float(intersect) / (sum_area - intersect) class Box(object): """ match_state:一个box是否匹配到一个track中,若没有,应该生成新的track """ def __init__(self, frame_index, id, box, score, gps_coor, feature): self.frame_index = frame_index self.id = id self.box = b...
line) * (b
conditional_block
2_tracking.py
# -*- coding: utf-8 -*- # 15 """ """ import numpy as np import os import cv2 from scipy.optimize import linear_sum_assignment input_dir = "../aic19-track1-mtmc/train" ard_uesd_num_path = "../already_used_number.txt" IMAGE_SIZE = 224 TH_SCORE = 0.3 PAD_SIZE = 10 IOU_TH = 0.7 W_PAD = 0 H_PAD = 0 DISTENCE_TH = 100 WIGH...
.index) + ' : ', "length-" + len(self.boxes)) for i in range(len(self.boxes)): box = self.boxes[i] print('box', i, ': ', box) def Hungary(task_matrix): b = task_matrix.copy() # 行和列减0 for i in range(len(b)): row_min = np.min(b[i]) for j in range(len(b[i])): ...
: print("For frame index-" + str(self
identifier_body
2_tracking.py
# -*- coding: utf-8 -*- # 15 """ """ import numpy as np import os import cv2 from scipy.optimize import linear_sum_assignment input_dir = "../aic19-track1-mtmc/train" ard_uesd_num_path = "../already_used_number.txt" IMAGE_SIZE = 224 TH_SCORE = 0.3 PAD_SIZE = 10 IOU_TH = 0.7 W_PAD = 0 H_PAD = 0 DISTENCE_TH = 100 WIGH...
, x0, y1, x1), which reflects (top, left, bottom, right) :param rec2: (y0, x0, y1, x1) :return: scala value of IoU """ rec1 = [box1[0], box1[1], box1[0] + box1[2], box1[1] + box1[3]] rec2 = [box2[0], box2[1], box2[0] + box2[2], box2[1] + box2[3]] # computing area of each rectangles ...
m rec1: (y0
identifier_name
add-action-form.component.ts
import { Component, OnInit, Input, Output, EventEmitter, OnChanges, SimpleChanges, ViewChild } from '@angular/core'; import { FormBuilder, FormGroup, FormControl, Validators, ValidatorFn } from '@angular/forms'; import { AddActionPageService } from "../page/add-action-page.service"; import { AddActionFormService } from...
rols['checkPassword'].updateValueAndValidity(); }); } getCaptcha(e: MouseEvent) { e.preventDefault(); } // confirmationValidator = (control: FormControl): { [s: string]: boolean } => { // if (!control.value) { // return { required: true }; // } else if (control.value !== this.validateFor...
} updateConfirmValidator() { /** wait for refresh value */ setTimeout(() => { this.validateForm.cont
identifier_body
add-action-form.component.ts
import { Component, OnInit, Input, Output, EventEmitter, OnChanges, SimpleChanges, ViewChild } from '@angular/core'; import { FormBuilder, FormGroup, FormControl, Validators, ValidatorFn } from '@angular/forms'; import { AddActionPageService } from "../page/add-action-page.service"; import { AddActionFormService } from...
changes.action.currentValue; let icon = this.action.icon; if (icon) { this.appIconFile.list = [{ uid: 146, name: 'widgets.png', status: 'done', // url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png', thumbUrl: icon ...
this.action =
identifier_name
add-action-form.component.ts
import { Component, OnInit, Input, Output, EventEmitter, OnChanges, SimpleChanges, ViewChild } from '@angular/core'; import { FormBuilder, FormGroup, FormControl, Validators, ValidatorFn } from '@angular/forms'; import { AddActionPageService } from "../page/add-action-page.service"; import { AddActionFormService } from...
this.userTableFieldParams = params; } onUploadAppIconFile(files: any[]) { if (files.length > 0 && files[0].thumbUrl) { this.resultValue.icon = files[0].thumbUrl; } else { this.resultValue.icon = ""; } } ngOnChanges(changes: SimpleChanges) { this.initValidateForm(); if (...
random_line_split
add-action-form.component.ts
import { Component, OnInit, Input, Output, EventEmitter, OnChanges, SimpleChanges, ViewChild } from '@angular/core'; import { FormBuilder, FormGroup, FormControl, Validators, ValidatorFn } from '@angular/forms'; import { AddActionPageService } from "../page/add-action-page.service"; import { AddActionFormService } from...
() { //监听service里的id值,当编辑时传id if (this.validateForm) { return false; } const that = this; if (this.id) {//当操作为编辑时,添加id值 this.validateForm = this.fb.group({ name: [null, [Validators.required, Validators.minLength(2), Validators.maxLength(100), Validators.pattern(/^\S.*\S$|^\S$/)]...
null; } }; initValidateForm
conditional_block
__init__.py
import ConfigParser import os.path import subprocess class BatchelorException(Exception): def __init__(self, value): self.value = value def __str__(self): return repr(self.value) def runCommand(commandString): commandString = "errHandler() { (( errcount++ )); }; trap errHandler ERR\n" + commandString.rstr...
error = False if system != "" and not config.has_section(system): print("ERROR: System set but corresponding section is missing in config file.") error = True requiredOptions = { "c2pap": [ "group", "notification", "notify_user", "node_usage", "wall_clock_limit", "resources", "job_type", "class" ], ...
print("ERROR: Could not read config file '" + configFileName + "'.") return False
conditional_block
__init__.py
import ConfigParser import os.path import subprocess class BatchelorException(Exception): def __init__(self, value): self.value = value def __str__(self): return repr(self.value) def runCommand(commandString): commandString = "errHandler() { (( errcount++ )); }; trap errHandler ERR\n" + commandString.rstri...
self._config = ConfigParser.RawConfigParser() def bprint(self, msg): self.bprintTicker += ('' if self.bprintTicker == '' else '\n') + msg if self.debug: print(msg) def initialize(self, configFileName, systemOverride = ""): self.bprint("Initializing...") if not self._config.read(os.path.abspath(configFi...
bprintTicker = "" batchFunctions = None def __init__(self):
random_line_split
__init__.py
import ConfigParser import os.path import subprocess class BatchelorException(Exception): def __init__(self, value): self.value = value def __str__(self): return repr(self.value) def runCommand(commandString): commandString = "errHandler() { (( errcount++ )); }; trap errHandler ERR\n" + commandString.rstr...
(self, jobs): # 'jobs' should be a list of arguments as they need to be specified for # 'submitJob', e.g.: # [ [ "command 1", "output file 1", "name 1" ], # [ "command 2", "output file 2", None ], # ... ] # The return value is a list of job IDs in the same order as the jobs. # A job ID of ...
submitJobs
identifier_name
__init__.py
import ConfigParser import os.path import subprocess class BatchelorException(Exception):
def runCommand(commandString): commandString = "errHandler() { (( errcount++ )); }; trap errHandler ERR\n" + commandString.rstrip('\n') + "\nexit $errcount" process = subprocess.Popen(commandString, shell=True, stdout=subprocess.PIPE, ...
def __init__(self, value): self.value = value def __str__(self): return repr(self.value)
identifier_body
clob.rs
//! Содержит типы для работы с большими символьными объектами. use std::io; use {Connection, Result, DbResult}; use types::Charset; use ffi::native::lob::{Lob, LobImpl, LobOpenMode, CharsetForm}; use ffi::types::Piece; use super::{Bytes, Chars, LobPrivate}; //---------------------------------------------------------...
m, buf); self.piece = piece; res } } impl<'lob, 'conn: 'lob> Drop for ClobReader<'lob, 'conn> { fn drop(&mut self) { // Невозможно делать панику отсюда, т.к. приложение из-за этого крашится let _ = self.lob.close(self.piece);//.expect("Error when close CLOB reader"); } }
res, piece) = self.lob.impl_.read(self.piece, self.charset, self.lob.for
conditional_block
clob.rs
//! Содержит типы для работы с большими символьными объектами. use std::io; use {Connection, Result, DbResult}; use types::Charset; use ffi::native::lob::{Lob, LobImpl, LobOpenMode, CharsetForm}; use ffi::types::Piece; use super::{Bytes, Chars, LobPrivate}; //---------------------------------------------------------...
iece; res } } impl<'lob, 'conn: 'lob> Drop for ClobReader<'lob, 'conn> { fn drop(&mut self) { // Невозможно делать панику отсюда, т.к. приложение из-за этого крашится let _ = self.lob.close(self.piece);//.expect("Error when close CLOB reader"); } }
читателем. pub fn lob(&mut self) -> &mut Clob<'conn> { self.lob } } impl<'lob, 'conn: 'lob> io::Read for ClobReader<'lob, 'conn> { #[inline] fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { let (res, piece) = self.lob.impl_.read(self.piece, self.charset, self.lob.form, buf); self.piece = p
identifier_body
clob.rs
//! Содержит типы для работы с большими символьными объектами. use std::io; use {Connection, Result, DbResult}; use types::Charset; use ffi::native::lob::{Lob, LobImpl, LobOpenMode, CharsetForm}; use ffi::types::Piece; use super::{Bytes, Chars, LobPrivate}; //---------------------------------------------------------...
} /// Создает читателя данного символьного объекта. Каждый вызов метода `read` читателя читает очередную порцию данных. /// Данные читаются из CLOB-а в указанной кодировке. /// /// Каждый вызов `read` будет заполнять массив байтами в запрошенной кодировке. Так как стандартные методы Rust для /// работы чита...
/// Данные читаются из CLOB-а в кодировке `UTF-8`. #[inline] pub fn new_reader<'lob>(&'lob mut self) -> Result<ClobReader<'lob, 'conn>> { self.new_reader_with_charset(Charset::AL32UTF8)
random_line_split
clob.rs
//! Содержит типы для работы с большими символьными объектами. use std::io; use {Connection, Result, DbResult}; use types::Charset; use ffi::native::lob::{Lob, LobImpl, LobOpenMode, CharsetForm}; use ffi::types::Piece; use super::{Bytes, Chars, LobPrivate}; //---------------------------------------------------------...
identifier_name
visualization.py
import pymc3 as pm from matplotlib import pyplot as plt import numpy as np from scipy.stats import mode import pandas as pd import seaborn as sns sns.set(font_scale=1) sns.set_style("whitegrid", {'axes.grid' : False}) from mednickdb_pysleep.pysleep_utils import pd_to_xarray_datacube sns.set_palette(sns.color_palette("S...
(x): if '__' in x: return [int(x) for x in x.split('__')[1].split('_')] else: return [0] df['var type'] = df['index'].apply(lambda x: x.split('__')[0]) df = df.loc[df['var type'] == var, :] var_idxs = df['index'].apply(split_fun) indexs = np.stack(var_idxs) i...
split_fun
identifier_name
visualization.py
import pymc3 as pm from matplotlib import pyplot as plt import numpy as np from scipy.stats import mode import pandas as pd import seaborn as sns sns.set(font_scale=1) sns.set_style("whitegrid", {'axes.grid' : False}) from mednickdb_pysleep.pysleep_utils import pd_to_xarray_datacube sns.set_palette(sns.color_palette("S...
def stage_parameters(trace, stage_param_names, stage_map, label_plot=True): stage_map = {v:k for k,v in stage_map.items()} _, axs = model_parameters(trace, stage_param_names) for param in stage_param_names: if trace[param].dtype == np.float64: means = extract_mean_as_array(trace, para...
summary_df = pm.summary(trace, varnames=varnames) print(summary_df) axs = pm.traceplot(trace, varnames=varnames) return summary_df, axs
identifier_body
visualization.py
import pymc3 as pm from matplotlib import pyplot as plt import numpy as np from scipy.stats import mode import pandas as pd import seaborn as sns sns.set(font_scale=1) sns.set_style("whitegrid", {'axes.grid' : False}) from mednickdb_pysleep.pysleep_utils import pd_to_xarray_datacube sns.set_palette(sns.color_palette("S...
x_data = np.linspace(data[x].min(), data[x].max(), samples_per_x_range) df = pd.DataFrame({x:x_data}) for var in mean_sample_vars: var_mean = data[var].mean(skipna=True) var_std = data[var].std(skipna=True) df[var] = var_mean data_points = data_points.loc[(var_mean-va...
else: if truncate_to_percentile: x_data = np.linspace(np.percentile(data[x],truncate_to_percentile), np.percentile(data[x],100-truncate_to_percentile), samples_per_x_range) else:
random_line_split
visualization.py
import pymc3 as pm from matplotlib import pyplot as plt import numpy as np from scipy.stats import mode import pandas as pd import seaborn as sns sns.set(font_scale=1) sns.set_style("whitegrid", {'axes.grid' : False}) from mednickdb_pysleep.pysleep_utils import pd_to_xarray_datacube sns.set_palette(sns.color_palette("S...
df['var type'] = df['index'].apply(lambda x: x.split('__')[0]) df = df.loc[df['var type'] == var, :] var_idxs = df['index'].apply(split_fun) indexs = np.stack(var_idxs) if astype == 'array': sizes = indexs.max(axis=0)+1 var_array = df['mean'].copy().values.reshape(sizes) re...
return [0]
conditional_block
train_ddpg_selfplay.py
import argparse import copy import dataclasses import datetime import os import time import gym import numpy as np import rc_gym import torch.multiprocessing as mp import torch.nn.functional as F import torch.optim as optim import wandb from agents.ddpg_selfplay import (DDPGHP, DDPGActor, DDPGCritic, TargetActor, ...
# Log metrics wandb.log(metrics) if hp.NOISE_SIGMA_DECAY and sigma_m.value > hp.NOISE_SIGMA_MIN \ and n_grads % hp.NOISE_SIGMA_GRAD_STEPS == 0: # This syntax is needed to be process-safe # The noise sigma value is accessed by the pla...
metrics[key] = np.mean([info[key] for info in ep_infos])
conditional_block
train_ddpg_selfplay.py
import argparse import copy import dataclasses import datetime import os import time
import numpy as np import rc_gym import torch.multiprocessing as mp import torch.nn.functional as F import torch.optim as optim import wandb from agents.ddpg_selfplay import (DDPGHP, DDPGActor, DDPGCritic, TargetActor, TargetCritic, data_func) from agents.utils import ReplayBuffer, save_checkp...
import gym
random_line_split
spatialfr.py
import os import time from datetime import datetime, timedelta import yaml from yaml import SafeLoader as SafeLoader import matplotlib.pyplot as plt import csv import numpy as np import run_ionfr import pandas as pd from scipy.interpolate import griddata from scipy.optimize import curve_fit # from mpl_toolkits.mplot3d ...
def resid_overlay(ra, dec, ampscales, stds, grid_sub, beam_lim, obsid, var='median amplitude scales'): print('Using plotly') size = stds fig = go.Figure() fig.add_trace( go.Scatter( x=ra, y=dec, mode='markers', text=ampscales, hover...
fig, ax = plt.subplots(1, 1, figsize=(15, 12)) img1 = ax.imshow(grid_sub, extent=beam_extent, cmap="plasma") ax.set_xlabel("RA [deg]") ax.set_ylabel("Dec [deg]") ax.set_title("Faraday depth residuals after plane surface fit") fig.colorbar(img1, ax=ax, format="%.2f", fraction=0.046, pad=0.04) plt...
identifier_body
spatialfr.py
import os import time from datetime import datetime, timedelta import yaml from yaml import SafeLoader as SafeLoader import matplotlib.pyplot as plt import csv import numpy as np import run_ionfr import pandas as pd from scipy.interpolate import griddata from scipy.optimize import curve_fit # from mpl_toolkits.mplot3d ...
(df): # Determine the radius of the primary beam. # Fit a Gaussian to the distribution of RA and Dec positions. # Use 2x the determined sigma as a cutoff for sources, in steps of 2.5 deg. ra_hist, ra_bins = np.histogram(df.ra, bins=50) dec_hist, dec_bins = np.histogram(df.dec, bins=50) ra_p0 = [...
determine_radius
identifier_name
spatialfr.py
import os import time from datetime import datetime, timedelta import yaml from yaml import SafeLoader as SafeLoader import matplotlib.pyplot as plt import csv import numpy as np import run_ionfr import pandas as pd from scipy.interpolate import griddata from scipy.optimize import curve_fit # from mpl_toolkits.mplot3d ...
np.vstack((ra, dec)).T, fr, (grid_x, grid_y), method=interp_method, fill_value=0)) beam_extent = ( ra_centre+radius, ra_centre-radius, dec_centre-radius, ...
grid_fr = np.fliplr( griddata(
random_line_split
spatialfr.py
import os import time from datetime import datetime, timedelta import yaml from yaml import SafeLoader as SafeLoader import matplotlib.pyplot as plt import csv import numpy as np import run_ionfr import pandas as pd from scipy.interpolate import griddata from scipy.optimize import curve_fit # from mpl_toolkits.mplot3d ...
return fr_value, fr_value_err def get_radec(sources, obsid): ''' Gets the Ra and Dec of a source from the yaml file who's path is given. ''' yaml_file = '/home/chege/Desktop/curtin_work/vega/%s.yaml' % (obsid) ras = [] decs = [] fluxes = [] ampscales = [] stds = [] with op...
print('found the hr, reading its fr value') fr_value = row[3] fr_value_err = row[4]
conditional_block
functions.py
import matplotlib matplotlib.use('Agg') from bs4 import BeautifulSoup import requests import pandas as pd import numpy as np import pickle import re import matplotlib.pyplot as plt from matplotlib.transforms import Affine2D import shap import datetime import os from wordcloud import WordCloud import numpy as np featur...
def get_bs_from_http(link): html = requests.get(link) return BeautifulSoup(html.text, "html.parser") def get_html_request(link): return requests.get(link) def merge_dicts(dic1, dic2): try: dic3 = dict(dic2) for k, v in dic1.items(): dic3[k] = Flatten([dic3[k], v]) if k in...
random_line_split
functions.py
import matplotlib matplotlib.use('Agg') from bs4 import BeautifulSoup import requests import pandas as pd import numpy as np import pickle import re import matplotlib.pyplot as plt from matplotlib.transforms import Affine2D import shap import datetime import os from wordcloud import WordCloud import numpy as np featur...
_main_text(soup): text = soup.find(id="ad_description_text").text text = clean_string2(text) cut_string = "ihr wg gesucht team" try: return text.split(cut_string, 1)[1] except: return text def get_text(link): bs = get_bs_from_http(link) text = get_main_text(bs) return cl...
e.sub(r"[\W\_]|\d+", ' ', liste) liste = " ".join(liste.split()) liste = liste.lower() return liste def get
identifier_body
functions.py
import matplotlib matplotlib.use('Agg') from bs4 import BeautifulSoup import requests import pandas as pd import numpy as np import pickle import re import matplotlib.pyplot as plt from matplotlib.transforms import Affine2D import shap import datetime import os from wordcloud import WordCloud import numpy as np featur...
ct(dict12) dict_list = [dict1, dict2, dict3, dict4, dict5, dict8, dict6, dict7, dict7, dict9, dict10, dict11, dict12] for item in dict_list: dict1.update(item) return dict1 def get_bs_from_html(html): return BeautifulSoup(html.text, "html.parser") def get_bs_from_http(link): html = requ...
g, 0]) dict12 = di
conditional_block
functions.py
import matplotlib matplotlib.use('Agg') from bs4 import BeautifulSoup import requests import pandas as pd import numpy as np import pickle import re import matplotlib.pyplot as plt from matplotlib.transforms import Affine2D import shap import datetime import os from wordcloud import WordCloud import numpy as np featur...
text = soup.find(id="ad_description_text").text text = clean_string2(text) cut_string = "ihr wg gesucht team" try: return text.split(cut_string, 1)[1] except: return text def get_text(link): bs = get_bs_from_http(link) text = get_main_text(bs) return clean_string2(text) ...
text(soup):
identifier_name
agent_sample_stats.py
from textwrap import dedent import os import sys import pickle import numpy as np import pandas as pd from collections import defaultdict from matplotlib import pyplot as plt import indra.tools.assemble_corpus as ac from indra.preassembler import grounding_mapper as gm from indra.util import write_unicode_csv, plot_for...
cats = (['P'], ['F', 'C', 'X'], ['S'], ['B'], ['U'], ['M']) cat_names = ('Protein/gene', 'Family/complex', 'Small molecule', 'Biological process', 'Other/unknown', 'microRNA') def grounding_stats(data, plot=False): rows = [] num_agents = len(data) if plot: plt.figure(figsize=(2.2, 2...
"""Plot the distribution of ungrounded strings in training vs test corpus. """ bin_interval = 1 fracs_total_list = [] bin_starts_list = [] for counts in counts_list: freq_dist = [] bin_starts = list(range(0, len(counts), bin_interval)) bin_starts_list.append(bin_starts) ...
identifier_body
agent_sample_stats.py
from textwrap import dedent import os import sys import pickle import numpy as np import pandas as pd from collections import defaultdict from matplotlib import pyplot as plt import indra.tools.assemble_corpus as ac from indra.preassembler import grounding_mapper as gm from indra.util import write_unicode_csv, plot_for...
width = 0.3 bef_color = pf.ORANGE aft_color = pf.GREEN ax = plt.gca() error_kw = dict(ecolor='black', lw=1, capsize=2, capthick=1) befh = plt.bar(-0.5*width, prot_bef, width=width, yerr=prot_bef_err, color=bef_color, error_kw=error_kw) afth = plt.bar(0.5*width, prot_aft, w...
random_line_split
agent_sample_stats.py
from textwrap import dedent import os import sys import pickle import numpy as np import pandas as pd from collections import defaultdict from matplotlib import pyplot as plt import indra.tools.assemble_corpus as ac from indra.preassembler import grounding_mapper as gm from indra.util import write_unicode_csv, plot_for...
all_ungrounded_ratio = 100 * (all_ungrounded / float(len(stmts))) any_ungrounded_ratio = 100 * (any_ungrounded / float(len(stmts))) return all_ungrounded_ratio, any_ungrounded_ratio def get_agent_counts(stmts): agents = gm.ungrounded_texts(stmts) agent_counts = [t[1] for t ...
agents_ungrounded = [] for ag in stmt.agent_list(): if ag is not None and list(ag.db_refs.keys()) == ['TEXT']: agents_ungrounded.append(True) else: agents_ungrounded.append(False) if all(agents_ungrounded): a...
conditional_block
agent_sample_stats.py
from textwrap import dedent import os import sys import pickle import numpy as np import pandas as pd from collections import defaultdict from matplotlib import pyplot as plt import indra.tools.assemble_corpus as ac from indra.preassembler import grounding_mapper as gm from indra.util import write_unicode_csv, plot_for...
(results): prot_bef, prot_bef_err = results['training'][0][4:6] fam_bef, fam_bef_err = results['training'][1][4:6] prot_aft, prot_aft_err = results['test'][0][4:6] fam_aft, fam_aft_err = results['test'][1][4:6] plt.figure(figsize=(2.8, 2.2), dpi=300) width = 0.3 bef_color = pf.ORANGE aft...
combined_graph
identifier_name
nextbus_test.go
package nextbus import ( "encoding/xml" "fmt" "io/ioutil" "net/http" "net/url" "path/filepath" "reflect" "runtime" "strings" "testing" ) const baseURL = "http://webservices.nextbus.com/service/publicXMLFeed" func makeURL(command string, params ...string) string { if len(params) != 0 && len(params)%2 != 0 ...
func TestGetStopPredictions(t *testing.T) { nb := NewClient(testingClient(t)) found, err := nb.GetStopPredictions("alpha", "11123") ok(t, err) expected := []PredictionData{ PredictionData{ xmlName("predictions"), []PredictionDirection{ PredictionDirection{ xmlName("direction"), []Prediction...
{ nb := NewClient(testingClient(t)) found, err := nb.GetVehicleLocations("alpha") ok(t, err) expected := LocationResponse{ xmlName("body"), []VehicleLocation{ VehicleLocation{ xmlName("vehicle"), "1111", "1", "1_outbound", "37.77513", "-122.41946", "4", "true", "225", ...
identifier_body
nextbus_test.go
package nextbus import ( "encoding/xml" "fmt" "io/ioutil" "net/http" "net/url" "path/filepath" "reflect" "runtime" "strings" "testing" ) const baseURL = "http://webservices.nextbus.com/service/publicXMLFeed" func makeURL(command string, params ...string) string { if len(params) != 0 && len(params)%2 != 0 ...
(t *testing.T) { nb := NewClient(testingClient(t)) found, err := nb.GetAgencyList() ok(t, err) expected := []Agency{ Agency{xmlName("agency"), "alpha", "The First", "What a Transit Agency"}, Agency{xmlName("agency"), "beta", "The Second", "Never never land"}, } equals(t, expected, found) } func TestGetRoute...
TestGetAgencyList
identifier_name
nextbus_test.go
package nextbus import ( "encoding/xml" "fmt" "io/ioutil" "net/http" "net/url" "path/filepath" "reflect" "runtime" "strings" "testing" ) const baseURL = "http://webservices.nextbus.com/service/publicXMLFeed" func makeURL(command string, params ...string) string { if len(params) != 0 && len(params)%2 != 0 ...
"ffffff", "12.3456789", "45.6789012", "-123.4567890", "-456.78901", []Direction{ Direction{ xmlName("direction"), "1out", "Outbound to somewhere", "Outbound", "true", stopMarkers("1123", "1234"), }, Direction{ xmlName("direction"), "1in", "Inbound to somewhere", "I...
"1-first", "660000",
random_line_split
nextbus_test.go
package nextbus import ( "encoding/xml" "fmt" "io/ioutil" "net/http" "net/url" "path/filepath" "reflect" "runtime" "strings" "testing" ) const baseURL = "http://webservices.nextbus.com/service/publicXMLFeed" func makeURL(command string, params ...string) string { if len(params) != 0 && len(params)%2 != 0 ...
url := req.URL.String() xml, ok := fakes[url] if !ok { valid := []string{} for k := range fakes { valid = append(valid, k) } f.t.Fatalf("Unexpected url %q. allowable urls are=%q", url, valid) return nil, nil } res := http.Response{} res.StatusCode = http.StatusOK res.Body = ioutil.NopCloser(stri...
{ req.Body.Close() req.Body = nil }
conditional_block
battle.py
import sys import copy import time class Unit: #Used to uniquely identify combatants (assumes less than 27 of each) goblin_id = 'a' elf_id = 'A' def __init__(self, race, x, y, hp, attack): if race == 'goblin': self.name = Unit.goblin_id Unit.goblin_id = ch...
battle()
start = time.time() round_end = time.time() arena, units = read_arena() initial_arena = copy.deepcopy(arena) initial_units = copy.deepcopy(units) #Loop until no deaths deaths = 1 power = 2 while deaths > 0: #Update elf powers power += 1 arena = co...
identifier_body
battle.py
import sys import copy import time class Unit: #Used to uniquely identify combatants (assumes less than 27 of each) goblin_id = 'a' elf_id = 'A' def __init__(self, race, x, y, hp, attack): if race == 'goblin': self.name = Unit.goblin_id Unit.goblin_id = ch...
return 'no-reachable', {} # If multiple paths exist, pick the starting point using reading order optimal_paths = find_optimal_paths((self.x, self.y), target, paths) choices = sorted([op[0] for op in optimal_paths]) x, y = choices[0] # Update position ...
if target is None:
random_line_split
battle.py
import sys import copy import time class Unit: #Used to uniquely identify combatants (assumes less than 27 of each) goblin_id = 'a' elf_id = 'A' def __init__(self, race, x, y, hp, attack): if race == 'goblin': self.name = Unit.goblin_id Unit.goblin_id = ch...
optimal_paths = [] update_paths(source, target, (), graph, optimal_paths) return optimal_paths def find_next_step(start, end, paths): """ Given initial and final (x,y) coordinates and a dictionary of partial paths, return the next step towards reaching """ def find_paths(...
path = (current,) + path update_paths(source, (x, y), path, graph, optimal_paths)
conditional_block
battle.py
import sys import copy import time class Unit: #Used to uniquely identify combatants (assumes less than 27 of each) goblin_id = 'a' elf_id = 'A' def __init__(self, race, x, y, hp, attack): if race == 'goblin': self.name = Unit.goblin_id Unit.goblin_id = ch...
(start, current, distance, paths, choices): """ Given the start point, and the current point, builds a dictionary indicating the first step and the minimum distance to the end using that step. Distance indicates the distance from current to end. """ # Find all paths...
find_paths
identifier_name
lib.rs
//! See the `Bitmap` type. /// A dense bitmap, intended to store small bitslices (<= width of usize). pub struct Bitmap { entries: usize, width: usize, // Avoid a vector here because we have our own bounds checking, and // don't want to duplicate the length, or panic. data: *mut u8, } #[inline(alw...
(&mut self) { let p = self.data; if p != 0 as *mut _ { self.data = 0 as *mut _; let _ = unsafe { Vec::from_raw_parts(p as *mut u8, 0, self.byte_len()) }; } } } impl Bitmap { /// Create a new bitmap, returning None if the data can't be allocated or /// if the ...
drop
identifier_name