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
astutils.py
get_children(cls, node: ast.AST) -> Iterable[ast.AST]: """ Returns the nested nodes in the body of a node. """ body: Optional[Sequence[ast.AST]] = getattr(node, 'body', None) if body is not None: for child in body: yield child class NodeVisitorExt(vi...
(sig: Signature, call: ast.Call) -> BoundArguments: """ Binds the arguments of a function call to that function's signature. @raise TypeError: If the arguments do not match the signature. """ kwargs = { kw.arg: kw.value for kw in call.keywords # When keywords are passed using...
bind_args
identifier_name
astutils.py
get_children(cls, node: ast.AST) -> Iterable[ast.AST]: """ Returns the nested nodes in the body of a node. """ body: Optional[Sequence[ast.AST]] = getattr(node, 'body', None) if body is not None: for child in body: yield child class NodeVisitorExt(vi...
module = ctx.module assert module is not None module.report(f'syntax error in {section}: {ex}', lineno_offset=node.lineno, section=section) return node else: assert isinstance(expr, ast.expr), expr return expr class _AnnotationStringParser(ast.NodeTransformer): "...
""" try: expr = _AnnotationStringParser().visit(node) except SyntaxError as ex:
random_line_split
astutils.py
get_children(cls, node: ast.AST) -> Iterable[ast.AST]: """ Returns the nested nodes in the body of a node. """ body: Optional[Sequence[ast.AST]] = getattr(node, 'body', None) if body is not None: for child in body: yield child class NodeVisitorExt(vi...
# For Python < 3.8: def visit_Str(self, node: ast.Str) -> ast.expr: return ast.copy_location(self._parse_string(node.s), node) TYPING_ALIAS = ( "typing.Hashable", "typing.Awaitable", "typing.Coroutine", "typing.AsyncIterable", "typing.AsyncIterator", "...
value = node.value if isinstance(value, str): return ast.copy_location(self._parse_string(value), node) else: const = self.generic_visit(node) assert isinstance(const, ast.Constant), const return const
identifier_body
lid_shutdown.rs
_event: Option<zx::Event>, system_shutdown_node: Rc<dyn Node>, inspect_root: Option<&'a inspect::Node>, } impl<'a> LidShutdownBuilder<'a> { pub fn new(system_shutdown_node: Rc<dyn Node>) -> Self { LidShutdownBuilder { proxy: None, lid_report_event: None, system_s...
(&self) -> String { "LidShutdown".to_string() } async fn handle_message(&self, _msg: &Message) -> Result<MessageReturn, PowerManagerError> { Err(PowerManagerError::Unsupported) } } struct InspectData { lid_reports: RefCell<BoundedListNode>, read_errors: inspect::UintProperty, l...
name
identifier_name
lid_shutdown.rs
_report_event: Option<zx::Event>, system_shutdown_node: Rc<dyn Node>, inspect_root: Option<&'a inspect::Node>, } impl<'a> LidShutdownBuilder<'a> { pub fn new(system_shutdown_node: Rc<dyn Node>) -> Self { LidShutdownBuilder { proxy: None, lid_report_event: None, s...
/// Reads the report from the lid sensor and sends shutdown signal if lid is closed. async fn check_report(&self) -> Result<(), Error> { let (status, report, _time) = self.proxy.read_report().await?; let status = zx::Status::from_raw(status); if status != zx::Status::OK { ret...
}, }; }
random_line_split
lid_shutdown.rs
self } pub async fn build<'b>( self, futures_out: &FuturesUnordered<LocalBoxFuture<'b, ()>>, ) -> Result<Rc<LidShutdown>, Error> { // In tests use the default proxy. let proxy = match self.proxy { Some(proxy) => proxy, None => Self::find_lid_sensor()...
{ let mut mock_maker = MockNodeMaker::new(); let shutdown_node = mock_maker.make( "Shutdown", vec![( msg_eq!(SystemShutdown(ShutdownRequest::PowerOff)), msg_ok_return!(SystemShutdown), )], ); let event = zx::Event::crea...
identifier_body
lid_shutdown.rs
_event: Option<zx::Event>, system_shutdown_node: Rc<dyn Node>, inspect_root: Option<&'a inspect::Node>, } impl<'a> LidShutdownBuilder<'a> { pub fn new(system_shutdown_node: Rc<dyn Node>) -> Self { LidShutdownBuilder { proxy: None, lid_report_event: None, system_s...
_ => (), } } Err(format_err!("No lid device found")) } /// Opens the sensor's device file. Returns the device if the correct HID /// report descriptor is found. async fn open_sensor(filename: &PathBuf) -> Result<LidProxy, Error> { let path = Path::n...
{ match Self::open_sensor(&msg.filename).await { Ok(device) => return Ok(device), _ => (), } }
conditional_block
generate_random_samples.py
if corruption_type == 'pose' or corruption_type == 'all': # pose_perturbation = np.random.normal(0, pose_sigma[i], (corrupted_flame.shape[0], 3)) # corrupted_flame[:, 150:153] += np.clip(pose_perturbation, -3 * pose_sigma[i], 3 * pose_sigma[i]) pose_perturbation = np.random.normal(0, pose_...
corrupted_flame[:, 100:110] = flm_params[:, 100:110] + \ np.clip(np.random.normal(0, sigma, flm_params[:, 100:110].shape), -3 * sigma, 3 * sigma).astype('float32') # Jaw pose corrupted_flame[:, 153] = flm_params[:, 153] ...
conditional_block
generate_random_samples.py
def corrupt_flame_given_sigma(flm_params, corruption_type, sigma, jaw_sigma, pose_sigma): # import ipdb; ipdb.set_trace() # np.random.seed(2) corrupted_flame = deepcopy(flm_params) if corruption_type == 'shape' or corruption_type == 'all': corrupted_flame[:, :10] = flm_params[:, :10] + \ ...
if normal_map_cond and texture_cond: return torch.cat((textured_rndr, norm_map), dim=1) elif normal_map_cond: return norm_map elif texture_cond: return textured_rndr else: return flm_params
identifier_body
generate_random_samples.py
110].shape), -3 * sigma, 3 * sigma).astype('float32') # Jaw pose corrupted_flame[:, 153] = flm_params[:, 153] + \ np.random.normal(0, jaw_sigma, corrupted_flame.shape[0]) if corruption_type == 'pose' or corruption_type ...
generator_1 = generator_1.eval() params_to_save = {'cam': [], 'shape': [], 'exp': [], 'pose': [], 'light_code': [], 'texture_code': [], 'identity_indices': []} for i, sigma in enumerate(corruption_sigma): images = np.zeros((num_smpl_to_eval_on, 3, resolution, resolution)).ast...
ckpt1 = torch.load(f'{cnst.output_root}checkpoint/{run_idx}/{model_idx}.model') generator_1.load_state_dict(ckpt1['generator_running'])
random_line_split
generate_random_samples.py
(flm_params, textured_rndr, norm_map, normal_map_cond, texture_cond): if normal_map_cond and texture_cond: return torch.cat((textured_rndr, norm_map), dim=1) elif normal_map_cond: return norm_map elif texture_cond: return textured_rndr else: return flm_params def corrup...
ge_gen_in
identifier_name
fpl1617.py
line in prvsCaptains: if(playername in line): count=int(line.split(':')[1].strip()) if(count<7): return True else: return False return True else: return True def isValidViceCaptain(playername): ...
teamscores_path=curr_dir+"\TeamScores\TeamScore_gw"+str(gw)+".txt" results_path=curr_dir+"\Results\Results_gw"+str(gw)+".txt" captain_path=curr_dir+"\Counts\Captains\CaptainCount_gw"+str(gw)+".txt" vicecaptain_path=curr_dir+"\Counts\ViceCaptains\ViceCaptainCount_gw"+str(gw)+".txt" f_teamscores=ope...
os.makedirs("Counts/Captains", exist_ok=True) os.makedirs("Counts/ViceCaptains", exist_ok=True)
random_line_split
fpl1617.py
line in prvsCaptains: if(playername in line): count=int(line.split(':')[1].strip()) if(count<7): return True else: return False return True else: return True def isValidViceCaptain(playername): ...
def Captain_ViceCaptainSetup(teams): for k,v in sorted(teams.items()): team=k print("-------------------\nTeam: %s" %(str(k))) for i in range(0,len(v)): print(str(i+1)+". "+teams[k][i][0]) captain=int(input("Enter Captain number: ")) teams[k].append(captain-...
if(prvsVcFileFound): for line in prvsViceCaptains: if(playername in line): count=int(line.split(':')[1].strip()) if(count<7): return True else: return False return True else: return True
identifier_body
fpl1617.py
line in prvsCaptains: if(playername in line): count=int(line.split(':')[1].strip()) if(count<7): return True else: return False return True else: return True def isValidViceCaptain(playername): ...
return teams def getTeamScoresfromList(TeamList): orignalScore=[] orignalScoreDict=[] multiplierScore=[] multiplierScoreDict=[] for player in TeamList[0:6]: player_score=get_player_score(player[1],gw) orignalScore.append(player_score) orignalScoreDict.append({player...
teams[k][vc-1][2]=1.5
conditional_block
fpl1617.py
line in prvsCaptains: if(playername in line): count=int(line.split(':')[1].strip()) if(count<7): return True else: return False return True else: return True def isValidViceCaptain(playername): ...
(id,gw): url="https://fantasy.premierleague.com/drf/entry/"+str(id)+"/event/"+str(gw)+"/picks" retryCount=0 while True: try: print("\rURL: "+str(url)+" Retry Count: "+str(retryCount),end="") r = requests.get(url) except: print("\nFound exception")...
get_player_score
identifier_name
workspace.go
which modules we care about. If go.work/gopls.mod has changed // we need to either re-read it if it exists or walk the filesystem if it // has been deleted. go.work should override the gopls.mod if both exist. changed, needReinit = handleWorkspaceFileChanges(ctx, result, changes, fs) // Next, handle go.mod changes...
{ return nil, nil, fmt.Errorf("go.work has missing or incomplete go directive") }
conditional_block
workspace.go
} w.wsDirs[span.URIFromPath(r.New.Path)] = struct{}{} } } // Ensure that there is always at least the root dir. if len(w.wsDirs) == 0 { w.wsDirs = map[span.URI]struct{}{ w.root: {}, } } sum, err := buildWorkspaceSumFile(ctx, w.activeModFiles, fs) if err == nil { w.sum = sum } else { event.E...
{ return span.URIFromPath(filepath.Join(root.Filename(), "go.mod")) }
identifier_body
workspace.go
default: ws.moduleSource = legacyWorkspace activeModFiles, err := getLegacyModules(ctx, root, fs) if err != nil { return nil, err } ws.activeModFiles = activeModFiles } return ws, nil } // loadExplicitWorkspaceFile loads workspace information from go.work or // gopls.mod files, setting the active modu...
() map[span.URI]struct{} { return w.knownModFiles } // ActiveModFiles returns the set of active mod files for the current workspace. func (w *workspace) ActiveModFiles() map[span.URI]struct{} { return w.activeModFiles } // criticalError returns a critical error related to the workspace setup. func (w *workspace) cr...
getKnownModFiles
identifier_name
workspace.go
opls.mod has changed we need to either re-read it if it // exists or walk the filesystem if it has been deleted. // go.work should override the gopls.mod if both exist. for _, src := range []workspaceSource{goWorkWorkspace, goplsModWorkspace} { uri := uriForSource(ws.root, ws.explicitGowork, src) // File opens/c...
if err != nil {
random_line_split
lib.rs
.0-alpha.1" //! features = [ "..." ] //! ``` //! //! The crate contains different features for integration with other common crates. //! Check the [feature flags][] section for information about all available features. //! //! # Examples //! //! Annotate your struct or enum to enable the custom de/serializer. //! //! #...
SpaceSeparator
identifier_name
lib.rs
/jonasbb/serde_with/branch/master/graph/badge.svg)](https://codecov.io/gh/jonasbb/serde_with) //! //! --- //! //! This crate provides custom de/serialization helpers to use in combination with [serde's with-annotation][with-annotation] and with the improved [`serde_as`][]-annotation. //! Some common use cases are: //! ...
//! # assert_eq!(json.replace(" ", "").replace("\n", ""), serde_json::to_string(&foo).unwrap()); //! # assert_eq!(foo, serde_json::from_str(&json).unwrap()); //! # } //! ``` //! //! [`DisplayFromStr`]: https://docs.rs/serde_with/*/serde_with/struct.DisplayFromStr.html //! [`serde_as`]: https://docs.rs/serde_with/*/serd...
//! "1": "006fde" //! } //! } //! # "#;
random_line_split
notification_client.rs
&self, room_id: &RoomId, event_id: &EventId, ) -> Result<Option<NotificationItem>, Error> { match self.get_notification_with_sliding_sync(room_id, event_id).await? { NotificationStatus::Event(event) => Ok(Some(event)), NotificationStatus::EventFilteredOut => O...
// The message is still encrypted, and the client is configured to retry // decryption. // // Spawn an `EncryptionSync` that runs two iterations of the sliding sync loop: // - the first iteration allows to get SS events as well as send e2ee requests. // - the second one ...
{ if !self.retry_decryption { return Ok(None); } let event: AnySyncTimelineEvent = raw_event.deserialize().map_err(|_| Error::InvalidRumaEvent)?; let event_type = event.event_type(); let is_still_encrypted = matches!(event_type, ruma::events...
identifier_body
notification_client.rs
&self, room_id: &RoomId, event_id: &EventId, ) -> Result<Option<NotificationItem>, Error> { match self.get_notification_with_sliding_sync(room_id, event_id).await? { NotificationStatus::Event(event) => Ok(Some(event)), NotificationStatus::EventFilteredOut => O...
( &self, room_id: &RoomId, event_id: &EventId, ) -> Result<Option<RawNotificationEvent>, Error> { // Serialize all the calls to this method by taking a lock at the beginning, // that will be dropped later. let _guard = self.sliding_sync_mutex.lock().await; //...
try_sliding_sync
identifier_name
notification_client.rs
&self, room_id: &RoomId, event_id: &EventId, ) -> Result<Option<NotificationItem>, Error> { match self.get_notification_with_sliding_sync(room_id, event_id).await? { NotificationStatus::Event(event) => Ok(Some(event)), NotificationStatus::EventFilteredOut => O...
timeline_event.push_actions } else { room.event_push_actions(timeline_event).await? } } RawNotificationEvent::Invite(invite_event) => { // Invite events can't be encrypted, so they should be in clear text. ...
self.maybe_retry_decryption(&room, timeline_event).await? { raw_event = RawNotificationEvent::Timeline(timeline_event.event.cast());
random_line_split
gateway_bft_test.go
call.SIGTERM) Eventually(peerProcesses.Wait(), network.EventuallyTimeout).Should(Receive()) } if network != nil { network.Cleanup() } for _, ordererInstance := range ordererProcesses { ordererInstance.Signal(syscall.SIGTERM) Eventually(ordererInstance.Wait(), network.EventuallyTimeout).Should(Receiv...
{ By("joining " + o.Name + " to channel as a consenter") channelparticipation.Join(network, o, channel, genesisBlock, expectedChannelInfoPT) channelInfo := channelparticipation.ListOne(network, o, channel) Expect(channelInfo).To(Equal(expectedChannelInfoPT)) }
conditional_block
gateway_bft_test.go
.gz"), Ctor: `{"Args":["init","a","100","b","200"]}`, SignaturePolicy: `AND ('Org1MSP.peer')`, Sequence: "1", InitRequired: true, Label: "gatewaycc_label", } nwo.DeployChaincode(network, channel, orderer, chaincode) }) AfterEach(func() { if peerProcesses != nil { ...
{ sess, err := network.ConfigTxGen(commands.OutputBlock{ ChannelID: channel, Profile: network.Profiles[0].Name, ConfigPath: network.RootDir, OutputBlock: network.OutputBlockPath(channel), }) Expect(err).NotTo(HaveOccurred()) Eventually(sess, network.EventuallyTimeout).Should(gexec.Exit(0)) genesisB...
identifier_body
gateway_bft_test.go
"google.golang.org/grpc/status" ) var _ = Describe("GatewayService with BFT ordering service", func() { var ( testDir string network *nwo.Network ordererProcesses map[string]ifrit.Process peerProcesses ifrit.Process channel = "testchannel1" ) BeforeEach(func() { var err er...
( ctx context.Context, gatewayClient gateway.GatewayClient, signer *nwo.SigningIdentity, channel string, chaincode string, transactionName string, arguments []string, ) *gateway.SubmitRequest { args := [][]byte{} for _, arg := range arguments { args = append(args, []byte(arg)) } proposedTransaction, transa...
prepareTransaction
identifier_name
gateway_bft_test.go
"google.golang.org/grpc/status" ) var _ = Describe("GatewayService with BFT ordering service", func() { var ( testDir string network *nwo.Network ordererProcesses map[string]ifrit.Process peerProcesses ifrit.Process channel = "testchannel1" )
BeforeEach(func() { var err error testDir, err = os.MkdirTemp("", "gateway") Expect(err).NotTo(HaveOccurred()) client, err := docker.NewClientFromEnv() Expect(err).NotTo(HaveOccurred()) networkConfig := nwo.MultiNodeSmartBFT() network = nwo.New(networkConfig, testDir, client, StartPort(), components) ...
random_line_split
db.go
id) return err }) if err != nil { return nil, err } return blob, nil } // SetBlob saves binary value for provided pulse. func (db *DB) SetBlob(ctx context.Context, pulseNumber core.PulseNumber, blob []byte) (*core.RecordID, error) { var ( id *core.RecordID err error ) err = db.Update(ctx, func(tx *Tra...
return db.set( ctx, bytes.Join([][]byte{{scopeIDLocal}, pulse.Bytes(), key}, nil), data, ) }
identifier_body
db.go
nil { *newo = *o } else { *newo = badger.DefaultOptions } return newo } // NewDB returns storage.DB with BadgerDB instance initialized by opts. // Creates database in provided dir or in current directory if dir parameter is empty. func NewDB(conf configuration.Ledger, opts *badger.Options) (*DB, error) { opts...
opts.Dir = dir opts.ValueDir = dir bdb, err := badger.Open(*opts) if err != nil { return nil, errors.Wrap(err, "local database open failed") } db := &DB{ db: bdb, txretiries: conf.Storage.TxRetriesOnConflict, idlocker: NewIDLocker(), nodeHistory: map[core.PulseNumber][]core.Node{}, } ...
{ return nil, err }
conditional_block
db.go
(db *DB) GetDrop(ctx context.Context, pulse core.PulseNumber) (*jetdrop.JetDrop, error) { k := prefixkey(scopeIDJetDrop, pulse.Bytes()) buf, err := db.get(ctx, k) if err != nil { return nil, err } drop, err := jetdrop.Decode(buf) if err != nil { return nil, err } return drop, nil } func (db *DB) waitinfli...
func (db *DB) set(ctx context.Context, key, value []byte) error {
random_line_split
db.go
= tx.SetRecord(ctx, pulseNumber, rec) return err }) if err != nil { return nil, err } return id, nil } // GetObjectIndex wraps matching transaction manager method. func (db *DB) GetObjectIndex( ctx context.Context, id *core.RecordID, forupdate bool, ) (*index.ObjectLifeline, error) { tx := db.BeginTransac...
tActiveNodes(p
identifier_name
strutil.go
{ for i := range prefixes { if strings.HasPrefix(s, prefixes[i]) { return true } } return false } // HasSuffixes `suffixes` 中是否存在 `s` 的后缀 // // HasSuffixes("asd", "ddd", "d") => true // // HasSuffixes("asd", "sd") => true // // HasSuffixes("asd", "iid", "as") => false func HasSuffixes(s string, suffixes ......
.bool) []string { var omitEmpty bool if len(omitEmptyOpt) > 0 && omitEmptyOpt[0] {
conditional_block
strutil.go
.go.tmp"}, ".go", ".tmp") => []string{"test", "test.go"} func TrimSliceSuffixes(ss []string, suffixes ...string) []string { r := make([]string, len(ss)) for i := range ss { r[i] = TrimSuffixes(ss[i], suffixes...) } return r } // TrimSlicePrefixes TrimPrefixes 的 Slice 版本 // // TrimSlicePrefixes([]string{"/tmp/fil...
ool) string { if len(omitEmptyOpt) == 0 || !omitEmptyOpt[0] { return strings.Join(ss, sep) } r := []string{} for i := range ss { if ss[i] != "" { r = append(r, ss[i]) } } return strings.Join(r, sep) } // JoinPath see also filepath.Join func JoinPath(ss ...string) string { return filepath.Join(ss...) } ...
nt) } // Concat 合并字符串 func Concat(s ...string) string { return strings.Join(s, "") } // Join see also strings.Join, // omitEmptyOpt = true 时,不拼接 `ss` 中空字符串 func Join(ss []string, sep string, omitEmptyOpt ...b
identifier_body
strutil.go
n(cutset) == 0 { return strings.TrimLeftFunc(s, unicode.IsSpace) } return strings.TrimLeft(s, cutset[0]) } // TrimRight 裁剪 `s` 右边,如果不指定 `cutset`, 默认cutset=space // // TrimRight("trim ") => "trim" // // TrimRight(" this") => " this" // // TrimRight("athisa", "a") => "athis" func TrimRight(s string, cutset ...string...
{ if le
identifier_name
strutil.go
// // TrimPrefixes("/tmp/file", "/tmp") => "/file" // // TrimPrefixes("/tmp/tmp/file", "/tmp", "/tmp/tmp") => "/tmp/file" func TrimPrefixes(s string, prefixes ...string) string { originLen := len(s) for i := range prefixes { trimmed := strings.TrimPrefix(s, prefixes[i]) if len(trimmed) != originLen { return tr...
} // TrimPrefixes 裁剪 `s` 的前缀
random_line_split
converter.go
} visibleNamespaces.Insert(allowedNamespaces...) break } } if !found && !ignoreUnhandledScopes { errors = append(errors, fmt.Errorf("no scope evaluator found for %q", scope)) } } return visibleNamespaces, kutilerrors.NewAggregate(errors) } const ( UserIndicator = "user:" ClusterRoleI...
ResolveGettableNamespaces
identifier_name
converter.go
.PolicyRule{}, scopeDiscoveryRule) errors := []error{} for _, scope := range scopes { found := false for _, evaluator := range ScopeEvaluators { if evaluator.Handles(scope) { found = true currRules, err := evaluator.ResolveRules(scope, namespace, clusterRoleGetter) if err != nil { errors = a...
{ _, scopeNamespace, _, err := scopemetadata.ClusterRoleEvaluatorParseScope(scope) if err != nil { return nil, err } // if the scope limit on the clusterrole doesn't match, then don't add any rules, but its not an error if !(scopeNamespace == scopesAllNamespaces || scopeNamespace == namespace) { return []rbac...
identifier_body
converter.go
.0.0.pb-v1", "/osapi", "/osapi/", // these cannot be removed until we can drop support for pre 3.1 clients "/.well-known", "/.well-known/*", // we intentionally allow all to here "/", }, } // ScopesToRules takes the scopes and return the rules back. We ALWAYS add the discovery rules and it is possible to ge...
if !found { errors = append(errors, fmt.Errorf("no scope evaluator found for %q", scope)) } } return rules, kutilerrors.NewAggregate(errors) } // ScopesToVisibleNamespaces returns a list of namespaces that the provided scopes have "get" access to. // This exists only to support efficiently list/watch of pr...
{ if evaluator.Handles(scope) { found = true currRules, err := evaluator.ResolveRules(scope, namespace, clusterRoleGetter) if err != nil { errors = append(errors, err) continue } rules = append(rules, currRules...) } }
conditional_block
converter.go
.0.0.pb-v1", "/osapi", "/osapi/", // these cannot be removed until we can drop support for pre 3.1 clients "/.well-known", "/.well-known/*", // we intentionally allow all to here "/", }, } // ScopesToRules takes the scopes and return the rules back. We ALWAYS add the discovery rules and it is possible to ge...
// <indicator><indicator choice> // we have the following formats: // user:<scope name> // role:<clusterrole name>:<namespace to allow the cluster role, * means all> // TODO // cluster:<comma-delimited verbs>:<comma-delimited resources> // namespace:<namespace name>:<comma-delimited verbs>:<comma-delimited resources> ...
// scopes are in the format
random_line_split
bond_monitor.py
False def treeview_sort_column(tv,col,reverse): l = [(tv.set(k,col),k) for k in tv.get_children('')] if is_number(l[0][0]): l.sort(key = lambda x: float(x[0]),reverse=reverse) else: l.sort(reverse = reverse) for index,(val,k) in enumerate(l): tv.move(k,'',index) ...
basedesk(root) root.mainloop()
conditional_block
bond_monitor.py
{} conn = pymssql.connect(host='192.168.8.120', port=14333, user='GuestUser', password='GuestUser', database='JYDB',charset='GBK') with conn.cursor() as cursor: sql = ''' SELECT SecuCode, SecuAbbr,SecuMarket FROM Bond_Code ''' cursor.execute(sql) data = cursor.fetchall() ...
(self, master): self.root = master self.root.title('future monitor') self.root.geometry('1080x720') self.table_init = False self.signal_data = {} self.bond_names = get_bond_names() myclient = pymongo.MongoClient("mongodb://192.168.9.1...
__init__
identifier_name
bond_monitor.py
{} conn = pymssql.connect(host='192.168.8.120', port=14333, user='GuestUser', password='GuestUser', database='JYDB',charset='GBK') with conn.cursor() as cursor: sql = ''' SELECT SecuCode, SecuAbbr,SecuMarket FROM Bond_Code ''' cursor.execute(sql) data = cursor.fetchall() ...
self.target_bond = [] self.signal_list = [] self.get_target_bond() self.db_lookup() def get_target_bond(self): with self.mysql.cursor() as cursor: ##取日常要订的表 sql = ''' SELECT * FROM Bond_list ''' cursor.execute(sql) ...
self.mysql = pymssql.connect(host='192.168.9.85', user='sa', password='lhtzb.123', database='BondMonitor')
random_line_split
bond_monitor.py
= {} conn = pymssql.connect(host='192.168.8.120', port=14333, user='GuestUser', password='GuestUser', database='JYDB',charset='GBK') with conn.cursor() as cursor: sql = ''' SELECT SecuCode, SecuAbbr,SecuMarket FROM Bond_Code ''' cursor.execute(sql) data = cursor.fetchall() ...
else: total = 0.0 if len(self.signal_data[s["code_name"]]["pirce"]) != 15: print("signal cacl error") for i in self.signal_data[s["code_name"]]["pirce"]: total = total + i ...
["time"])[:4] if s["code_name"] not in self.signal_data.keys(): self.signal_data[s["code_name"]] = {} self.signal_data[s["code_name"]]["time"] = minute self.signal_data[s["code_name"]]["pirce"] = [] self.signal_data[s["code_name"]]["pirce"].append(s[...
identifier_body
main.rs
= pm1_boundary[1] - (-1f64 / tangent_line_1_k) * pm1_x; chart.draw_series(LineSeries::new( (tangent_line_low..=tangent_line_high).map(|x| x as f32 / 10f32).map(|x| (x, tangent_line_1_k_vert as f32 * x + tangent_line_1_b_vert as f32)) .filter( |(x, y)| bound_in_axis(*x, *y)) ...
{ let pm0: Vec<f64> = vec![elements[3], elements[4]].iter().filter_map(|e| e.parse::<f64>().ok()).collect(); let pm1: Vec<f64> = vec![elements[5], elements[6]].iter().filter_map(|e| e.parse::<f64>().ok()).collect(); let cp_x: Vec<f64> = elements[7].split(" ").filter_map(|...
conditional_block
main.rs
(tangent_line_low..=tangent_line_high).map(|x| x as f32 / 10f32).map(|x| (x, tangent_line_0_k as f32 * x + tangent_line_0_b as f32)) .filter( |(x, y)| bound_in_axis(*x, *y)) ,&BLACK )).unwrap(); let tangent_line_0_k_vert = -1f64 / tangent_line_0_k; let tangent_line_0_b_vert ...
total_time_ms += now.elapsed().as_micros(); iter += 1; } } }
random_line_split
main.rs
|coord, size, style| { EmptyElement::at(coord) + Circle::new((0, 0), size, style) })).unwrap(); // Plot pupil margins chart.draw_series(PointSeries::of_element(additional_points.iter().map(|v| (v[0] as f32, v[1] as f32)), 3, ShapeStyle::from(&BLUE).filled(), &|coord,...
{ let a = params.get(0); let b = params.get(1); let c = params.get(2); let mut new_points: Vec<Vec<f64>> = Vec::new(); for point in points.iter(){ let k1 = 2f64 * a * point[0] + b; let theta_1 = k1.atan(); let mut theta_2 = 0f64; let mut theta = 0f64; ...
identifier_body
main.rs
(|x| (x, tangent_line_0_k as f32 * x + tangent_line_0_b as f32)) .filter( |(x, y)| bound_in_axis(*x, *y)) ,&BLACK )).unwrap(); let tangent_line_0_k_vert = -1f64 / tangent_line_0_k; let tangent_line_0_b_vert = pm0_boundary[1] - (-1f64 / tangent_line_0_k) * pm0_x; chart.dr...
main
identifier_name
py4_promoter_DCI_scatter.py
=True,label='All genes') plt.scatter(dci_df_x.loc[up_bins,'DCI'],dci_df_y.loc[up_bins,'DCI'],c='tab:red',s=3,alpha=1,rasterized=True,label='Genes w/ DCI$>{}$ in WT/Vector'.format(dci_thre)) plt.scatter(dci_df_x.loc[dn_bins,'DCI'],dci_df_y.loc[dn_bins,'DCI'],c='tab:blue',s=3,alpha=1,rasterized=True,label...
compr_types = [['WT_over_Vector','DEL_over_WT'],['DEL_over_WT','EIF_over_DEL'],['WT_over_Vector','TPR_over_WT']] hm_marks = ['H3K4me3','H3K27ac']
random_line_split
py4_promoter_DCI_scatter.py
ci_file): dci_df = pd.read_csv(dci_file,sep='\t',index_col=4) dci_df.columns=['chr','start','end','IfOverlap','score','strand','DCI'] return dci_df else: return None def scatter_plot_compr_DCI(num_DCI_bins_df,subdir,hm_mark,compr_type,suffix,dci_thre): compr_x = compr_ty...
#print(box_vals) positions = np.arange(len(box_vals)) fig = plt.figure(figsize=(.46*len(box_vals),2.2)) g = plt.boxplot(box_vals,positions=positions,widths = .5,patch_artist=True,\ boxprops=dict(color='k',facecolor='w',fill=None,lw=1),\ me...
test_file='{}/{}/{}_{}{}.csv'.format(DCI_dir,subdir,hm_mark,'WT_over_Vector',suffix) if os.path.isfile(test_file): box_vals = [] xticklabels = [] sig_vals,sig_colors = [],[] for compr_col in ['WT_over_Vector','DEL_over_WT','EIF_over_DEL','TPR_over_WT']: dci_df = r...
identifier_body
py4_promoter_DCI_scatter.py
cellType_labels[control])) plt.legend(fontsize=10.5,borderaxespad=0.1,labelspacing=.1,handletextpad=0.1,\ handlelength=1,loc="upper left",markerscale=3,bbox_to_anchor=[-0.12,1.36],frameon=False) xa,xb = cellType_labels[compr_x.split('_')[0]],cellType_labels[compr_x.split('_')[-1]] ...
for suffix in suffixes[:]: for dci_thre in dci_thres[1:]: for compr_type in compr_types[:]: up_bins,dn_bins = scatter_plot_compr_DCI(num_DCI_bins_df,subdir,hm_mark,compr_type,suffix,dci_thre) # the box plot are ...
conditional_block
py4_promoter_DCI_scatter.py
(DCI_dir,subdir,hm_mark,compr_type,suffix): dci_file = '{}/{}/{}_{}{}.csv'.format(DCI_dir,subdir,hm_mark,compr_type,suffix) if os.path.isfile(dci_file): dci_df = pd.read_csv(dci_file,sep='\t',index_col=4) dci_df.columns=['chr','start','end','IfOverlap','score','strand','DCI'] return dc...
return_dci_df
identifier_name
module.js
if(!this.canRead(req, id, sheet)) throw Msa.FORBIDDEN sheet.editable = this.canWrite(req, id, sheet) return sheet } */ /* MsaSheetPt.getSheet = function(key, args1, args2) { // args if(args2===undefined) var args = {}, next = args1 else var args = args1, next = args2 defArg(args, "checkUserPerms", args.hasOwnP...
params: new SheetParamDict() }
random_line_split
module.js
(ctx) { const id = ctx.sheetParamsArgs.id const dbRow = await ctx.db.getOne("SELECT params FROM msa_sheets WHERE id=:id", { id }) return Sheet.newFromDb(id, dbRow).params } async updateRootParam(ctx, rootParam) { const vals = { id: ctx.sheetParamsArgs.id, params: rootParam.getAsDbS...
getRootParam
identifier_name
module.js
1(callbacks, i+1, len, next) }) fun.apply(null, args) } */ // perms ///////////////////////////////////////////////// /* var checkSheetWritePerm = function(type, key, user, next){ // get sheetType // var typeObj = SheetTypes[type] // if(!typeObj) return next("Unknown sheet type ["+type+"].") // select in DB Sheet...
{ const ctx = Object.create(req) Object.assign(ctx, kwargs) return ctx }
identifier_body
remote_build.go
.savePatch(); err != nil { log.Warnf(ctx, "Unable to save copy of generated patch: %v", err) } } if p.dryRun { log.Infof(ctx, "Dry run ended, build not submitted") return nil } if err := p.submitBuild(ctx, project, target.Tags); err != nil { return fmt.Errorf("unable to submit build: %w", err) } retu...
submitBuild
identifier_name
remote_build.go
3. Generate patch file // 3.1. Comparing every local commits with the one upstream // 3.2. Comparing every unstaged/untracked changes with the one upstream // 3.3. Save the patch and compress it // 4. Submit build! ancestorRef, commitCount, branch, err := fastFindAncestor(ctx, workRepo) if err != nil {...
// This is where the patch is actually generated see #278 p.patchData = []byte(patch.String()) log.Debugf(ctx, "Actual patch generation finished") log.Debugf(ctx, "Reseting worktree to previous state...") // Reset back to HEAD if err := worktree.Reset(&git.ResetOptions{ Commit: headCommit.Hash, }); ...
{ return fmt.Errorf("patch generation failed: %w", err) }
conditional_block
remote_build.go
} defer func() { if !resetDone { log.Debugf(ctx, "Reset failed, restoring...") if err := saver.restore(ctx); err != nil { log.Errorf(ctx, "Unable to restore kept files at %s: %v\n"+ " Please consider unarchiving that package", saver.saveFilePath(), err) } } }() ...
func (p *remoteCmd) fetchProject(ctx context.Context, urls []string) (*apiProject, error) { v := url.Values{} fmt.Println() log.Infof(ctx, "URLs used to search: %s", urls)
random_line_split
remote_build.go
3. Generate patch file // 3.1. Comparing every local commits with the one upstream // 3.2. Comparing every unstaged/untracked changes with the one upstream // 3.3. Save the patch and compress it // 4. Submit build! ancestorRef, commitCount, branch, err := fastFindAncestor(ctx, workRepo) if err != nil {...
if err != nil { return fmt.Errorf("traverse changes: %w", err) } if !ent.Code.IsMissing() { // No need to add deletion to the saver, right? if err = saver.add(ctx, filepath.FromSlash(string(ent.Name))); err != nil { return fmt.Errorf("traverse changes: %w", err) } } } err = g.Add(ctx, addList, ...
{ workTree, err := g.WorkTree(ctx) if err != nil { return fmt.Errorf("traverse changes: %w", err) } status, err := g.Status(ctx, ggit.StatusOptions{ DisableRenames: true, }) if err != nil { return fmt.Errorf("traverse changes: %w", err) } var addList []ggit.Pathspec for _, ent := range status { if ent...
identifier_body
tf_worker.py
# # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ...
name = uid_to_human[val] node_id_to_name[key] = name return node_id_to_name def id_to_string(self, node_id): if node_id not in self.node_lookup: return '' return self.node_lookup[node_id] def create_graph(): """"Creates a graph from saved GraphDef file and returns a saver.""" # ...
tf.logging.fatal('Failed to locate: %s', val)
conditional_block
tf_worker.py
to compute a classification of that image. Please see the tutorial and website for a detailed description of how to use this script to perform image recognition. https://tensorflow.org/tutorials/image_recognition/ """ import os.path import re import sys import tarfile #import argparse from collections import namedt...
"""Download and extract model tar file.""" dest_directory = FLAGS.model_dir if not os.path.exists(dest_directory): os.makedirs(dest_directory) filename = DATA_URL.split('/')[-1] filepath = os.path.join(dest_directory, filename) if not os.path.exists(filepath): def _progress(count, block_size, total_si...
identifier_body
tf_worker.py
#
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Simple image classification with Inception. Run image cl...
# Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS,
random_line_split
tf_worker.py
# # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ...
(): """Download and extract model tar file.""" dest_directory = FLAGS.model_dir if not os.path.exists(dest_directory): os.makedirs(dest_directory) filename = DATA_URL.split('/')[-1
maybe_download_and_extract
identifier_name
blt_engine.py
40 map_width=65 map_height = 40 dialog_width = 50 dialog_height = 35 dialog_pos_x = 68 dialog_pos_y = 1 ##Todo: This is starting to turn into spaghetti code. Probably need to refactor ##soon. def updateui(): ##Switch to layer 4 to update UI terminal.layer(3) terminal.clear_area(dialog_pos_x,dia...
(npc, player, dialog_name): dialog_tree = DialogTree(npc.dialog_dict) text = dialog_tree.get_say(dialog_name) conditions = dialog_tree.get_conditions(dialog_name) responses = dialog_tree.get_responses(dialog_name) target = dialog_tree.get_target_dialog(dialog_name) if not conditions is None: ...
npc_dialog
identifier_name
blt_engine.py
40 map_width=65 map_height = 40 dialog_width = 50 dialog_height = 35 dialog_pos_x = 68 dialog_pos_y = 1 ##Todo: This is starting to turn into spaghetti code. Probably need to refactor ##soon. def updateui(): ##Switch to layer 4 to update UI terminal.layer(3) terminal.clear_area(dialog_pos_x,dia...
if isinstance(get_object, NPC): if not get_object.dialog_dict is None: npc_dialog(get_object, player, "main") elif action == terminal.TK_S: ml.log_message(lorem + " " + str(test_count)) elif action == terminal.T
action = terminal.read() ##1202 AM TODO: ###implement map system in blt engine✅ ###implement NPC and fold in dialog system✅ ##by adding a 'dialog' property to NPC object. ###implement item class and item description ##0118 # TODO: ##implement conditionals✅ 0119 ...
conditional_block
blt_engine.py
40 map_width=65 map_height = 40 dialog_width = 50 dialog_height = 35 dialog_pos_x = 68 dialog_pos_y = 1 ##Todo: This is starting to turn into spaghetti code. Probably need to refactor ##soon. def updateui(): ##Switch to layer 4 to update UI terminal.layer(3) terminal.clear_area(dialog_pos_x,di...
o['char'] = '@' if not 'color' in o: o['color'] = 'black' if not 'type' in o: return GameObject(o['x'], o['y'], o['char'], o['color'], name) elif o.get('type') == 'npc': if 'dialog' in o: dialog = o['dialog'] else: dialog = 'default' r...
random_line_split
blt_engine.py
40 map_width=65 map_height = 40 dialog_width = 50 dialog_height = 35 dialog_pos_x = 68 dialog_pos_y = 1 ##Todo: This is starting to turn into spaghetti code. Probably need to refactor ##soon. def updateui(): ##Switch to layer 4 to update UI terminal.layer(3) terminal.clear_area(dialog_pos_x,dia...
def add_to_inventory(inventory, item_to_add): item_in_inventory = inventory.get(item_to_add.name, None) if item_in_inventory is None: inventory[item_to_add.name] = item_to_add else: item_in_inventory.quantity += item_to_add.quantity def check_inventory_for_item(inventory, item_name, min...
map.switch_map(new_map_index) draw_map(terminal, map) game_map.unblock(player.x, player.y) player.move(dx , dy ) objects.clear() objects.append(player) if map.map_name in map_npc_db: load_objects = map_npc_db[map.map_name] for key in load_objects.keys(): objects.app...
identifier_body
main.py
self.health = health self.ship_img = None self.laser_img = None # keep track of the lasers shoot self.lasers = [] self.cool_down_counter = 0 def draw(self, window): window.blit(self.ship_img, (self.x, self.y)) for laser in self.lasers: ...
def shoot(self): if self.cool_down_counter == 0: laser = Laser(self.x-20, self.y, self.laser_img) self.lasers.append(laser) self.cool_down_counter = 1 def main(): # Flag to track the game status run = True # frame to be rendered per second ...
self.y += vel
identifier_body
main.py
increment of the cool_down_counter elif self.cool_down_counter > 0: self.cool_down_counter += 1 # used to initiate time for new laser def shoot(self): if self.cool_down_counter == 0: laser = Laser(self.x, self.y, self.laser_img) self.lasers.append(la...
enemy = Enemy(random.randrange(50, WIDTH - 100), random.randrange(-1500, -100), random.choice(["red", "blue", "green"])) enemies.append(enemy)
conditional_block
main.py
self.health = health self.ship_img = None self.laser_img = None # keep track of the lasers shoot self.lasers = [] self.cool_down_counter = 0 def
(self, window): window.blit(self.ship_img, (self.x, self.y)) for laser in self.lasers: laser.draw(window) def move_lasers(self, vel, obj): self.cooldown() for laser in self.lasers: laser.move(vel) if laser.off_screen(HEIGHT): ...
draw
identifier_name
main.py
the cool_down_counter elif self.cool_down_counter > 0: self.cool_down_counter += 1 # used to initiate time for new laser def shoot(self): if self.cool_down_counter == 0: laser = Laser(self.x, self.y, self.laser_img) self.lasers.append(laser) ...
random.choice(["red", "blue", "green"])) enemies.append(enemy)
random_line_split
store.ts
List: object[]; @observable typeListTop: object[]; @observable subTypeList: object[]; @observable locationList: object[]; @observable authorityZone: object[]; @observable modalityList: object[] = []; // @observable updateList: {}; @observable updateList: IUpdateState = { ipName: "", ipTypeSuperior...
let _locationList: object[] = []; if (errorCode === "200") { result.forEach((item: any) => { _locationList.push(item); }); this.locationList = _locationList; return _locationList; } } /** * 可授权区 * @param params */ @action async getAuthorityZone(params) { ...
* 国家地区 */ @action async getLocation() { let { errorCode, result }: any = await listCountry();
random_line_split
store.ts
TypeSuperiorNumber: '', ipLocation: '', ipTypeNumber: [], ipTypeName: [], // IP类型 ip二级类型中文名 ipDesc: '', ipFormNumber: [], countryTypes: '', ipPicGuid: '' }, sub: {}, showDate: {}, }; // 切换IP分类时 仅限新增IP 清空参数值 clearSub() { let _updateList: any = JSON.stringi...
} else { return { request: false, message: result.errorMsg, }; // alert(result.errorMsg) } } } @action async setStatus(params) { this.updateList = { ...this.updateList, ...params }; } async setStatus2(params) { this.updateList = { ...this.up...
conditional_block
store.ts
商务资料 prodect: [ { pic: '', title: '' }, { pic: '', title: '' }, { pic: '', title: '' }, { pic: '', title: '' }, ], cooperationCase: [ { pic: '', title: '' }, { pic: '', title: '' }, { pic: '', title: '' }, { pic: '', title: '' }, ], }; @observable bus...
ata[val] === un
identifier_name
unwind.py
self.unwind_table.append((a,b,start+8*i)) i+=1 ver = ramdump.version if re.search('3.0.\d',ver) is not None : self.search_idx = self.search_idx_3_0 else : self.search_idx = self.search_idx_3_4 # index into the table self.origin = self...
unwind_frame
identifier_name
unwind.py
) or (end is None) : print_out_str ("!!! Could not lookup unwinding information") return None # addresses self.start_idx = start self.stop_idx = end self.unwind_table = [] self.ramdump = ramdump i = 0 for addr in range(start,end,8) : ...
def unwind_exec_insn(self, ctrl, trace = False) : insn = self.unwind_get_byte(ctrl) if ((insn & 0xc0) == 0x00) : ctrl.vrs[SP] += ((insn & 0x3f) << 2) + 4 if trace : print_out_str (" add {0} to stack".format(((insn & 0x3f) << 2) + 4)) elif ((insn ...
if (ctrl.entries <= 0) : print_out_str("unwind: Corrupt unwind table") return 0 val = self.ramdump.read_word(ctrl.insn) ret = (val >> (ctrl.byte * 8)) & 0xff if (ctrl.byte == 0) : ctrl.insn+=4 ctrl.entries-=1 ctrl.byte = 3 el...
identifier_body
unwind.py
from struct import unpack from ctypes import * from print_out import * FP = 11 SP = 13 LR = 14 PC = 15 THREAD_SIZE = 8192 class Stackframe () : def __init__(self, fp, sp, lr, pc) : self.fp = fp self.sp = sp self.lr = lr self.pc = pc class UnwindCtrlBlock () : def __init__ (sel...
from optparse import OptionGroup
random_line_split
unwind.py
) or (end is None) : print_out_str ("!!! Could not lookup unwinding information") return None # addresses self.start_idx = start self.stop_idx = end self.unwind_table = [] self.ramdump = ramdump i = 0 for addr in range(start,end,8) : ...
if ctrl.vrs[reg] is None : return -1 vsp+=4 if (insn & 0x80) : if trace : print_out_str (" set LR from the stack") ctrl.vrs[14] = self.ramdump.read_word(vsp) if ctrl.vrs[14] is None :...
print_out_str (" pop r{0} from stack".format(reg))
conditional_block
graph.go
} type allStepsLink struct{} func (_ allStepsLink) SatisfiedBy(_ StepLink) bool { return true } func (_ allStepsLink) UnsatisfiableError() string { return "" } func ExternalImageLink(ref ImageStreamTagReference) StepLink { return &externalImageLink{ namespace: ref.Namespace, name: ref.Name, tag: ...
if !changed && len(waiting) > 0 { errMessages := sets.Set[string]{} for _, node := range waiting { missing := sets.Set[string]{} for _, link := range node.Step.Requires() { if !HasAllLinks([]StepLink{link}, satisfied) { if msg := link.UnsatisfiableError(); msg != "" { missing.Insert(m...
{ for _, child := range node.Children { if _, ok := seen[child.Step]; !ok { waiting = append(waiting, child) } } if _, ok := seen[node.Step]; ok { continue } if !HasAllLinks(node.Step.Requires(), satisfied) { waiting = append(waiting, node) continue } satisfied = append(sat...
conditional_block
graph.go
} type allStepsLink struct{} func (_ allStepsLink) SatisfiedBy(_ StepLink) bool { return true } func (_ allStepsLink) UnsatisfiableError() string { return "" } func ExternalImageLink(ref ImageStreamTagReference) StepLink { return &externalImageLink{ namespace: ref.Namespace, name: ref.Name, tag: ...
node := StepNode{Step: step, Children: []*StepNode{}} allNodes = append(allNodes, &node) } var ret StepGraph for _, node := range allNodes { isRoot := true for _, other := range allNodes { for _, nodeRequires := range node.Step.Requires() { for _, otherCreates := range other.Step.Creates() { if ...
// BuildGraph returns a graph or graphs that include // all steps given. func BuildGraph(steps []Step) StepGraph { var allNodes []*StepNode for _, step := range steps {
random_line_split
graph.go
() string { return l.unsatisfiableError } func AllStepsLink() StepLink { return allStepsLink{} } type allStepsLink struct{} func (_ allStepsLink) SatisfiedBy(_ StepLink) bool { return true } func (_ allStepsLink) UnsatisfiableError() string { return "" } func ExternalImageLink(ref ImageStreamTagReference) Step...
UnsatisfiableError
identifier_name
graph.go
(stream, StableImageStream) } // IsReleasePayloadStream determines if the ImageStream holds // release payload images. func IsReleasePayloadStream(stream string) bool { return stream == ReleaseImageStream } // +k8s:deepcopy-gen=false type StepNode struct { Step Step Children []*StepNode } // GraphConfiguratio...
{ if into.Description == "" { into.Description = from.Description } if into.Dependencies == nil { into.Dependencies = from.Dependencies } if into.StartedAt == nil { into.StartedAt = from.StartedAt } if into.StartedAt == nil { into.StartedAt = from.StartedAt } if into.FinishedAt == nil { into.Finished...
identifier_body
ppapi_generator.py
A base class for ppapi generators. Implementations should set TEMPLATE_NAME to a string containing the name of the template file without its extension. The template will be rendered with the following symbols available: name: A string containing the name of the namespace. enums: A list of enums within th...
def Generate(self): """Generates a Code object for a single namespace.""" return self.Render(self.TEMPLATE_NAME, { 'name': self._namespace.name, 'enums': self._enums, 'types': self._types, 'events': self._namespace.events, 'functions': self._namespace.functions, # TODO(samm...
generated_code.Append(template.render(values)) return generated_code
random_line_split
ppapi_generator.py
base class for ppapi generators. Implementations should set TEMPLATE_NAME to a string containing the name of the template file without its extension. The template will be rendered with the following symbols available: name: A string containing the name of the namespace. enums: A list of enums within the...
while self._dependencies: for name, deps in self._dependencies.items(): if not deps: if (self._required_types[name].property_type == model.PropertyType.ENUM): self._enums.append(self._required_types[name]) else: self._types.append(self._requir...
for typename in sorted(set(self._required_types) - resolved_types): type_ = self._required_types[typename] self._dependencies.setdefault(typename, set()) for member in type_.properties.itervalues(): self._RegisterDependency(member, self._NameComponents(type_)) resolved_types.ad...
conditional_block
ppapi_generator.py
A base class for ppapi generators. Implementations should set TEMPLATE_NAME to a string containing the name of the template file without its extension. The template will be rendered with the following symbols available: name: A string containing the name of the namespace. enums: A list of enums within th...
(self, member, depender): self._RegisterTypeDependency(member.type_, depender, member.optional, False) def _RegisterTypeDependency(self, type_, depender, optional, array): if type_.property_type == model.PropertyType.ARRAY: self._RegisterTypeDependency(type_.item_type, depender, optional, True) eli...
_RegisterDependency
identifier_name
ppapi_generator.py
'templates', 'ppapi'))) self._SetupFilters() self._ResolveTypeDependencies() def _SetupFilters(self): self.jinja_environment.filters.update({ 'ppapi_type': self.ToPpapiType, 'classname': cpp_util.Classname, 'enum_value': self.EnumValue...
return self._generator_factory(namespace).Generate()
identifier_body
statistic_compare.py
, find_best=False): oa = 0 n_trans = 0 percentage = 0 bestlist = [] # try: with open(path, 'r') as f: lines = f.readlines() for line in lines: if '# Task' in line: pbest = float(findall(r"\d+\.?\d*", line.split('Accuracy:')[1])[0]) bestlist.append(pbest) if '# Task 0 #' in line: ...
(): # plt.rcParams['font.sans-serif'] = ['Times'] model = ['densenet121', 'mobilenet_v2', 'squeezenet1_1'] # model = 'mobilenet_v2' # model = 'squeezenet1_1' # datasets = ['UCMerced', 'RSSCN7', 'WHU19', 'AID'] datasets = ['UCMerced', 'OxfordPets', 'RSSCN7'] # datasets = ['AID'] # ntasks = [0, 50, 100, 2...
compare_n
identifier_name
statistic_compare.py
if 'Task 0-rank 0' in line: n_trans = float(findall(r"\d+\.?\d*", line.split('Transfer Count:')[1])[0]) # iters = float(re.findall(r"\d+\.?\d*", line.split('Iter:')[1])[0]) # percentage = n_trans*100/iters if find_best: try: oa = max(bestlist) except ValueError: print('error file is ...
plt.figure() # avg_loss = np.zeros((5,len(ntasks))) # avg_acc = np.zeros((5,len(ntasks))) avg_loss = np.zeros(len(ntasks)) avg_acc = np.zeros(len(ntasks)) for k, m in enumerate(model): files = [] # 1007: 不同交互频率 # 1003_n: STO和MTO的结果 # files.append('../../results/1003_n/{}_single_{}_n1_se...
conditional_block
statistic_compare.py
def get_overall_accuracy(path, find_best=False): oa = 0 n_trans = 0 percentage = 0 bestlist = [] # try: with open(path, 'r') as f: lines = f.readlines() for line in lines: if '# Task' in line: pbest = float(findall(r"\d+\.?\d*", line.split('Accuracy:')[1])[0]) bestlist.append(pbest...
oa_list = [] nt_list = [] count = 0 c_trans = 0 with open(path, 'r') as f: lines = f.readlines() for line in lines: if 'Task 0' in line and '# Iter:' in line: rank_num = int(line.split('rank')[-1].split(',')[0]) if rank_num % 2 == 0: # task_id = int(line.split('Task ')[-1].split(',')[0...
identifier_body
statistic_compare.py
find_best=False): oa = 0 n_trans = 0 percentage = 0 bestlist = [] # try: with open(path, 'r') as f: lines = f.readlines() for line in lines: if '# Task' in line: pbest = float(findall(r"\d+\.?\d*", line.split('Accuracy:')[1])[0]) bestlist.append(pbest) if '# Task 0 #' in line: ...
print('-------------------------') if draw_figure: plt.tight_layout() fig.savefig('{}.pdf'.format(d)) print('============================') def compare_n(): # plt.rcParams['font.sans-serif'] = ['Times'] model = ['densenet121', 'mobilenet_v2', 'squeezenet1_1'] # model = 'mobilenet_v2' # mod...
print('trans percentage {}'.format(avg_trans)) # print('average trans percentage {}'.format(sum(avg_trans)/len(avg_trans)))
random_line_split
kiteworks.go
.Sprintf("%d:%s", S.folder_id, src.String()) uploads := S.db.Table("uploads") if uploads.Get(target, &UploadRecord) { if err := transfer_file(src, UploadRecord.ID); err != nil { Debug("Error attempting to resume file: %s", err.Error()) } else { uploads.Unset(target) return nil } } kw_file_info, e...
}
random_line_split
kiteworks.go
{ folder_path := SplitPath(path) current_id := s.folder_id var current KiteObject for _, f := range folder_path { current, err = s.Folder(current_id).Find(f) if err != nil { if err == ErrNotFound { current, err = s.Folder(current_id).NewFolder(f) if err != nil { return } current_id =...
(params ...interface{}) (children []KiteObject, err error) { if len(params) == 0 { params = SetParams(Query{"deleted": false}) } err = s.DataCall(APIRequest{ Method: "GET", Path: SetPath("/rest/folders/%d/children", s.folder_id), Output: &children, Params: SetParams(params, Query{"with": "(path,currentUs...
Contents
identifier_name
kiteworks.go
: &result, }) return } func (s kw_rest_file) Delete(params ...interface{}) (err error) { err = s.Call(APIRequest{ Method: "DELETE", Path: SetPath("/rest/files/%d", s.file_id), Params: SetParams(params), }) return } func (s kw_rest_file) PermDelete() (err error) { err = s.Call(APIRequest{ Method: "DELE...
{ var user []struct{} if emails != nil && emails[0] != NONE { for _, u := range emails { err = s.DataCall(APIRequest{ Method: "GET", Path: "/rest/admin/users", Params: SetParams(Query{"email": u}, params), Output: &user}, -1, 1000) if err != nil { return } users = len(user) + users...
identifier_body
kiteworks.go
{ folder_path := SplitPath(path) current_id := s.folder_id var current KiteObject for _, f := range folder_path { current, err = s.Folder(current_id).Find(f) if err != nil { if err == ErrNotFound { current, err = s.Folder(current_id).NewFolder(f) if err != nil { return } current_id =...
else if i == folder_len { return } } } if found == false { return result, ErrNotFound } } return result, ErrNotFound } type kw_rest_admin struct { *KWSession } func (s KWSession) Admin() kw_rest_admin { return kw_rest_admin{&s} } // Creates a new user on the system. func (s kw_rest_admin) ...
{ current, err = s.Folder(c.ID).Contents(params) if err != nil { return } found = true break }
conditional_block
run_template.go
= result.Config{} var shootParameters = testrunnerTemplate.Parameters{} var ( testrunNamePrefix string shootPrefix string tmKubeconfigPath string filterPatchVersions bool failOnError bool testrunFlakeAttempts int timeout int64 interval int64 ) // AddCommand adds run-template to a ...
{ logger.Log.Error(err, "mark flag required", "flag", "shoot-name") }
conditional_block
run_template.go
[]string) { var ( err error stopCh = make(chan struct{}) shootFlavors []*shootflavors.ExtendedFlavorInstance ) defer close(stopCh) dryRun, _ := cmd.Flags().GetBool("dry-run") logger.Log.Info("Start testmachinery testrunner") testrunnerConfig.Watch, err = testrunner.StartWatchController(logger...
runCmd.Flags().StringVar(&shootParameters.Landscape, "landscape", "", "Current gardener landscape.") runCmd.Flags().StringArrayVar(&shootParameters.SetValues, "set", make([]string, 0), "setValues additional helm values") runCmd.Flags().StringArrayVarP(&shootParameters.FileValues, "values", "f", make([]string, 0), "...
random_line_split
run_template.go
s.io/controller-runtime/pkg/client" "github.com/gardener/test-infra/pkg/testrunner" "github.com/gardener/test-infra/pkg/testrunner/result" testrunnerTemplate "github.com/gardener/test-infra/pkg/testrunner/template" "github.com/spf13/cobra" ) var testrunnerConfig = testrunner.Config{} var collectConfig = result.Co...
() { // configuration flags runCmd.Flags().StringVar(&tmKubeconfigPath, "tm-kubeconfig-path", "", "Path to the testmachinery cluster kubeconfig") if err := runCmd.MarkFlagRequired("tm-kubeconfig-path"); err != nil { logger.Log.Error(err, "mark flag required", "flag", "tm-kubeconfig-path") } if err := runCmd.Mark...
init
identifier_name
run_template.go
s.io/controller-runtime/pkg/client" "github.com/gardener/test-infra/pkg/testrunner" "github.com/gardener/test-infra/pkg/testrunner/result" testrunnerTemplate "github.com/gardener/test-infra/pkg/testrunner/template" "github.com/spf13/cobra" ) var testrunnerConfig = testrunner.Config{} var collectConfig = result.Co...
runCmd.Flags().IntVar(&testrunnerConfig.BackoffBucket, "backoff-bucket", 0, "Number of parallel created testruns per backoff period") runCmd.Flags().DurationVar(&testrunnerConfig.BackoffPeriod, "backoff-period", 0, "Time to wait between the creation of testrun buckets") runCmd.Flags().StringVar(&collectConfig.Conco...
{ // configuration flags runCmd.Flags().StringVar(&tmKubeconfigPath, "tm-kubeconfig-path", "", "Path to the testmachinery cluster kubeconfig") if err := runCmd.MarkFlagRequired("tm-kubeconfig-path"); err != nil { logger.Log.Error(err, "mark flag required", "flag", "tm-kubeconfig-path") } if err := runCmd.MarkFla...
identifier_body
stat.go
33, "") if err != nil { fmt.Printf("Failed to connect kdb: %s", err.Error()) return } err = con.AsyncCall(".u.sub", &kdb.K{-kdb.KS, kdb.NONE, "response"}, &kdb.K{-kdb.KS, kdb.NONE, ""}) if err != nil { fmt.Println("Subscribe: %s", err.Error()) return } // ignore type print output res, _, e...
算均价", stat.SpaceStk.AvgPrice) //算费用 买是万三 卖是千一加上万三 var stattax float64 if newO
conditional_block
stat.go
stk.orderArray { // fmt.Println("iiiii ", i) if newOrder.Entrustno == order.Entrustno && order.Status != 4 { index = i flag = true break } } if flag { updateArray(stk, index, newOrder) } else { stk.orderArray = append(stk.orderArray, newOrder) } } else if newOrder.Status == 2 ||...
random_line_split