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
_typecheck.py
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. # ============================================================================== """Minimal runtime type checking library....
""" def check_returns(f): """Check the types.""" if not types: raise TypeError("A return type annotation must contain at least one type") @functools.wraps(f) def new_f(*args, **kwds): """A helper function.""" return_value = f(*args, **kwds) if len(types) == 1:
random_line_split
_typecheck.py
"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. # ============================================================================== """Minimal runtime type checking library. T...
if spec.defaults: num_defaults = len(spec.defaults) for (name, a, t) in zip(spec.args[-num_defaults:], spec.defaults, types[-num_defaults:]): allowed_type = _replace_forward_references(t, f.__globals__) if not isinstance(a, al...
raise Error( "Function %r has %d arguments but only %d types were provided in the " "annotation." % (f, num_function_arguments, len(types)))
conditional_block
_typecheck.py
"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. # ============================================================================== """Minimal runtime type checking library. T...
(self): tpe, = self._types # pylint: disable=unbalanced-tuple-unpacking return tpe class _TwoArgumentType(Type): """Use this subclass for parametric types that accept two arguments.""" def __init__(self, first_type, second_type): super(_TwoArgumentType, self).__init__(first_type, second_type) clas...
_type
identifier_name
game.go
(xInt int, zInt int, dir bool, offset mgl32.Vec2) []float32 { x := float32(xInt) z := float32(zInt) var xAxis, zAxis float32 if dir { xAxis = 1 zAxis = 0 } else { xAxis = 0 zAxis = 1 } return []float32{ -0.5*xAxis + x + offset.X(), 0, -0.5*zAxis + z + offset.Y(), 1, 0, 0.5*xAxis + x + offset.X(), 0, ...
WallTile
identifier_name
game.go
, 1, -0.5*xAxis + x + offset.X(), 1, -0.5*zAxis + z + offset.Y(), 1, 1, } } func check(e error) { if e != nil { panic(e) } } var screenWidth = 800 var screenHeight = 600 var vertexArray []float32 var numFloorTiles, numWallTiles int var fov float64 var projection mgl32.Mat4 const ( FOG_DISTANCE float32 = 8.0...
mouseSensitivity := 0.75 mouseX, mouseY := window.GetCursorPos() window.SetCursorPos(float64(screenWidth/2), float64(screenHeight/2)) ratio := float64(screenWidth) / float64(screenHeight) mouseDeltaX := float64(screenWidth/2) - mouseX mouseDeltaY := float64(screenHeight/2) - mouseY player
{ fmt.Println("FPS is ", fps) lastFPS = time fps = 0 }
conditional_block
game.go
, 1, -0.5*xAxis + x + offset.X(), 1, -0.5*zAxis + z + offset.Y(), 1, 1, } } func check(e error)
var screenWidth = 800 var screenHeight = 600 var vertexArray []float32 var numFloorTiles, numWallTiles int var fov float64 var projection mgl32.Mat4 const ( FOG_DISTANCE float32 = 8.0 ) func init() { runtime.LockOSThread() } func main() { keys = map[glfw.Key]bool{} rand.Seed(time.Now().Unix()) player := &Pl...
{ if e != nil { panic(e) } }
identifier_body
game.go
0.6, 0, 1, 0, 0.3, 0.6, 0, 0, 0, -0.3, 0.0, 0, 1, 1, 0.3, 0.6, 0, 0, 0, 0.3, 0.0, 0, 0, 1, -0.3, 0.0, 0, 1, 1, // Blood Sprite -0.5, 0, -0.5, 0, 0, 0.5, 0, -0.5, 1, 0, -0.5, 0, 0.5, 0, 1, 0.5, 0, -0.5, 1, 0, 0.5, 0, 0.5, 1, 1, -0.5, 0, 0.5, 0, 1, } numFloorTiles = 0 numWallTiles = 0 for y...
sin := float32(math.Sin(player.Yaw - math.Pi/2)) rotated := mgl32.Vec2{
random_line_split
service_map.py
-level: 4; indent-tabs-mode: nil -*- # ex: set expandtab softtabstop=4 shiftwidth=4: # # Copyright (C) 2008,2009,2010,2011,2012,2013,2014,2015,2016 Contributor # # 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 ...
@property def object_priority(self): if self.personality: return _TARGET_PERSONALITY elif self.host_environment: return _TARGET_ENVIRONMENT else: return _TARGET_GLOBAL @property def priority(self): return (self.object_priority, self....
if self.network: return _NETWORK_PRIORITY else: try: return _LOCATION_PRIORITY[type(self.location)] except KeyError: # pragma: no cover raise InternalError("The service map is not prepared to handle " "locat...
identifier_body
service_map.py
-level: 4; indent-tabs-mode: nil -*- # ex: set expandtab softtabstop=4 shiftwidth=4: # # Copyright (C) 2008,2009,2010,2011,2012,2013,2014,2015,2016 Contributor # # 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 ...
(self, service_instance, network=None, location=None, personality=None, host_environment=None): if network and location: # pragma: no cover raise AquilonError("A service can't be mapped to a Network and a " "Location at the same time") if net...
__init__
identifier_name
service_map.py
-level: 4; indent-tabs-mode: nil -*- # ex: set expandtab softtabstop=4 shiftwidth=4: # # Copyright (C) 2008,2009,2010,2011,2012,2013,2014,2015,2016 Contributor # # 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 ...
return instances @staticmethod def get_mapped_instance_cache(dbservices, dbstage, dblocation, dbnetwork=None): """Returns dict of requested services to closest mapped instances.""" session = object_session(dblocation) location_ids = [loc.id ...
si = map.service_instance if min_seen_priority > map.priority: instances = [si] min_seen_priority = map.priority elif min_seen_priority == map.priority: instances.append(si)
conditional_block
service_map.py
-indent-level: 4; indent-tabs-mode: nil -*- # ex: set expandtab softtabstop=4 shiftwidth=4: # # Copyright (C) 2008,2009,2010,2011,2012,2013,2014,2015,2016 Contributor # # 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 ...
elif self.host_environment: return _TARGET_ENVIRONMENT else: return _TARGET_GLOBAL @property def priority(self): return (self.object_priority, self.scope_priority) @property def scope(self): if self.location: return self.location ...
return _TARGET_PERSONALITY
random_line_split
app.js
var stud2 =parseInt(prompt("Enter second student marks")); var stud3 =parseInt(prompt("Enter third student marks")); var obtMarks = stud1+stud2+stud3; var total= 300; function Mainfunction(){ console.log("student"+" "+stud1+" " +"student"+" "+ stud2+" " +"student"+" "+ stud3) ...
var str = "Pleases read this application and give me gratuity"; var count = 0; switch (str) { case 'a': count++; case 'A': count++ case 'e': case 'E': case 'i': case 'I': ...
rrences() {
identifier_name
app.js
var stud2 =parseInt(prompt("Enter second student marks")); var stud3 =parseInt(prompt("Enter third student marks")); var obtMarks = stud1+stud2+stud3; var total= 300; function Mainfunction(){ console.log("student"+" "+stud1+" " +"student"+" "+ stud2+" " +"student"+" "+ stud3) ...
var centimeter= dist*100000 console.log(centimeter) } centimeter(); /* . A cashier has currency notes of denominations 10, 50 and /* 100. If the amount to be withdrawn is input through the /* keyboard in hundreds, find the total number of currency notes /* of each ...
inches() function centimeter(){
random_line_split
app.js
var stud2 =parseInt(prompt("Enter second student marks")); var stud3 =parseInt(prompt("Enter third student marks")); var obtMarks = stud1+stud2+stud3; var total= 300; function Mainfunction(){ console.log("student"+" "+stud1+" " +"student"+" "+ stud2+" " +"student"+" "+ stud3) ...
delVowel() /* 7. Write a function with switch statement to count the number of /* occurrences of any two vowels in succession in a line of text. /* For example, in the sentence*/ function findOccurrences() { var str = "Pleases read this application and give me gr...
var strings = ["That which does not kill us makes us stronger.” "]; strings = strings.map(function (string) { return string.replace(/[aeiou]/g, ''); }); console.log(strings); }
identifier_body
app.js
console.log(answer); } leapYear(); /* 3. If the lengths of the sides of a triangle are denoted by a, b, and /* c, then area of triangle is given by /* area = S(S − a)(S − b)(S − c) /* where, S = ( a + b + c ) / 2 /* Calculate area of triangle using 2 functions...
{ answer = "not a leap year"; }
conditional_block
lib.rs
as the error type, which means that it //! doesn't store any information about the error. //! This can be changed by using `#[logos(error = T)]` attribute on the enum. //! The type `T` can be any type that implements `Clone`, `PartialEq`, //! `Default` and `From<E>` for each callback's error type. //! //! ## Token dis...
{ Skip }
identifier_body
lib.rs
| `Option<T>` | `Ok(Token::Value(T))` **or** `Err(<Token as Logos>::Error::default())` | //! | `Result<T, E>` | `Ok(Token::Value(T))` **or** `Err(<Token as Logos>::Error::from(err))` | //! |...
FilterResult
identifier_name
lib.rs
&mut Lexer<Token>) -> Option<u64> { //! let slice = lex.slice(); //! let n: u64 = slice[..slice.len() - 1].parse().ok()?; // skip 'm' //! Some(n * 1_000_000) //! } //! //! #[derive(Logos, Debug, PartialEq)] //! #[logos(skip r"[ \t\n\f]+")] //! enum Token { //! // Callbacks can use closure syntax, or re...
random_line_split
environment.py
.ps: p.daemon = ( True ) # if the main process crashes, we should not cause things to hang p.start() for remote in self.work_remotes: remote.close() self.remotes[0].send(("get_spaces", None)) self.observation_space, self.action_sp...
def make_single_env(env_name, **kwargs): env = gym.make(env_name) env = AddEpisodeStats(env) if "NoFrameskip" in env_name: env = wrap_deepmind(make_atari(env, env_name), **kwargs) return env def make_atari(env, env_id, max_episode_steps=4500): env._max_episode_steps = max_episode_steps ...
if hasattr(env, "unwrapped"): return env.unwrapped elif hasattr(env, "env"): return unwrap(env.env) elif hasattr(env, "leg_env"): return unwrap(env.leg_env) else: return env
identifier_body
environment.py
env = env_fn() while True: cmd, data = remote.recv() if cmd == "step": ob, reward, done, info = env.step(data) if done: ob = env.reset() remote.send((ob, reward, done, info)) elif cmd == "reset": ob = env.reset() ...
cv2.ocl.setUseOpenCL(False) def worker(remote, parent_remote, env_fn): parent_remote.close()
random_line_split
environment.py
.ps: p.daemon = ( True ) # if the main process crashes, we should not cause things to hang p.start() for remote in self.work_remotes: remote.close() self.remotes[0].send(("get_spaces", None)) self.observation_space, self.action_sp...
else: raise NotImplementedError class ClipRewardEnv(gym.RewardWrapper): def __init__(self, env): gym.RewardWrapper.__init__(self, env) def reward(self, reward): """Bin reward to {+1, 0, -1} by its sign.""" return float(np.sign(reward)) class WarpFrame(gym.Observ...
return bigimg
conditional_block
environment.py
.ps: p.daemon = ( True ) # if the main process crashes, we should not cause things to hang p.start() for remote in self.work_remotes: remote.close() self.remotes[0].send(("get_spaces", None)) self.observation_space, self.action_sp...
(self, specific_env=None): if specific_env is not None: self.remotes[specific_env].send(("reset", None)) return self.remotes[specific_env].recv() for remote in self.remotes: remote.send(("reset", None)) return np.stack([remote.recv() for remote in self.remot...
reset
identifier_name
messages.d.ts
init({ entity, offsetId, minId, maxId, fromUser, offsetDate, addOffset, filter, search, replyTo, }: MessageIterParams): Promise<false | undefined>; _loadNextChunk(): Promise<true | undefined>; _messageInRange(message: Message): boolean; [Symbol.asyncIterator](): AsyncIterator<Message, any, undefined>; _...
extends RequestIter { _ids?: Api.TypeInputMessage[]; _offset?: number; _ty: number | undefined; private _entity; _init({ entity, ids }: IDsIterInterface): Promise<void>; [Symbol.asyncIterator](): AsyncIterator<Message, any, undefined>; _loadNextChunk(): Promise<false | undefined>; } /** * ...
_IDsIter
identifier_name
messages.d.ts
_init({ entity, offsetId, minId, maxId, fromUser, offsetDate, addOffset, filter, search, replyTo, }: MessageIterParams): Promise<false | undefined>; _loadNextChunk(): Promise<true | undefined>; _messageInRange(message: Message): boolean; [Symbol.asyncIterator](): AsyncIterator<Message, any, undefined>; ...
schedule?: DateLike; } /** Interface for editing messages */ export interface EditMessageParams { /** The ID of the message (or Message itself) to be edited. If the entity was a Message, then this message will be treated as the new text. */ message: Api.Message | number; /** The new text of the message....
fromPeer: EntityLike; /** Whether the message should notify people with sound or not.<br/> * Defaults to false (send with a notification sound unless the person has the chat muted). Set it to true to alter this behaviour. */ silent?: boolean; /** If set, the message(s) won't forward immediately, an...
random_line_split
inferred_modules.go
the default value. // > 0 -> set the value. MinimumModuleSize int // The number of items in a longer prefix needed to break out into it's own prefix. // // For example, with the tokens `pkg_mod_sub1_a`, `pkg_mod_sub2_b`, `pkg_mod_sub2_c`, // `pkg_mod_sub3_d`: // // MinimumSubmoduleSize = 3 will result in: // ...
contract.Assertf(tree.tfToken == "", "We don't expect a resource called '%s'", opts.TfPkgPrefix) output := map[string]tokenInfo{} // Collapse the segment tree via a depth first traversal. tree.dfs(func(parent func(int) *node, n *node) { if parent(0) == tree { // Inject each path as a node if n.len() < opts...
{ contract.Assertf(opts.TfPkgPrefix != "", "TF package prefix not provided or computed") tree := &node{segment: opts.TfPkgPrefix} // Build segment tree: // // Expand each item (resource | datasource) into it's segments (divided by "_"), then // insert each token into the tree structure. The tree is defined by se...
identifier_body
inferred_modules.go
the default value. // > 0 -> set the value. MinimumModuleSize int // The number of items in a longer prefix needed to break out into it's own prefix. // // For example, with the tokens `pkg_mod_sub1_a`, `pkg_mod_sub2_b`, `pkg_mod_sub2_c`, // `pkg_mod_sub3_d`: // // MinimumSubmoduleSize = 3 will result in: // ...
for _, child := range n.children { i += child.len() } return i } // A depth first search of child nodes. // // parent is a function that returns parent nodes, with the immediate parent starting at 0 // and each increment increasing the indirection. 1 yields the grandparent, 2 the // great-grandparent, etc. paren...
{ i++ }
conditional_block
inferred_modules.go
the default value. // > 0 -> set the value. MinimumModuleSize int // The number of items in a longer prefix needed to break out into it's own prefix. // // For example, with the tokens `pkg_mod_sub1_a`, `pkg_mod_sub2_b`, `pkg_mod_sub2_c`, // `pkg_mod_sub3_d`: // // MinimumSubmoduleSize = 3 will result in: // ...
(parentStack *[]*node, iter func(parent func(int) *node, node *node)) { // Pop this node onto the parent stack so children can access it *parentStack = append(*parentStack, n) // Iterate over children by key, making sure that newly added keys are iterated over fullIter(n.children, func(k string, v *node) { v.dfsI...
dfsInner
identifier_name
inferred_modules.go
apply the default value. // > 0 -> set the value. MinimumModuleSize int // The number of items in a longer prefix needed to break out into it's own prefix. // // For example, with the tokens `pkg_mod_sub1_a`, `pkg_mod_sub2_b`, `pkg_mod_sub2_c`, // `pkg_mod_sub3_d`: // // MinimumSubmoduleSize = 3 will result in...
// // Expand each item (resource | datasource) into it's segments (divided by "_"), then // insert each token into the tree structure. The tree is defined by segments, where // each node represents a segment and each path a token. mapProviderItems(info, func(s string, _ shim.Resource) bool { segments := strings....
random_line_split
worker.go
:"error"` } func (r RuleEval) Work() { promql := strings.TrimSpace(r.rule.PromQl) if promql == "" { logger.Errorf("rule_eval:%d promql is blank", r.RuleID()) return } var value model.Value var err error if r.rule.Algorithm == "" { var warnings prom.Warnings value, warnings, err = reader.Client.Query(con...
func (r RuleEval) judge(vectors []conv.Vector) { // 有可能rule的一些配置已经发生变化,比如告警接收人、callbacks等 // 这些信息的修改是不会引起worker restart的,但是确实会影响告警处理逻辑 // 所以,这里直接从memsto.AlertRuleCache中获取并覆盖 curRule := memsto.AlertRuleCache.Get(r.rule.Id) if curRule == nil { return } r.rule = curRule count := len(vectors) alertingKeys := m...
if _, has := Workers.recordRules[hash]; has { // already exists continue } re := RecordingRuleEval{ rule: rules[hash], quit: make(chan struct{}), } go re.Start() Workers.recordRules[hash] = re } }
conditional_block
worker.go
= target.Note // 对于包含ident的告警事件,check一下ident所属bg和rule所属bg是否相同 // 如果告警规则选择了只在本BG生效,那其他BG的机器就不能因此规则产生告警 if r.rule.EnableInBG == 1 && target.GroupId != r.rule.GroupId { continue } } } event := &models.AlertCurEvent{ TriggerTime: vectors[i].Timestamp, TagsMap: tagsMap, GroupId: ...
nd(), promql, time.Now()) if err != nil { logger.Errorf("recording_rule_eval
identifier_body
worker.go
{ logger.Infof("rule_eval:%d started", r.RuleID()) for { select { case <-r.quit: // logger.Infof("rule_eval:%d stopped", r.RuleID()) return default: r.Work() logger.Debugf("rule executed,rule_id=%d", r.RuleID()) interval := r.rule.PromEvalInterval if interval <= 0 { interval = 10 } ...
art()
identifier_name
worker.go
:"error"` } func (r RuleEval) Work() { promql := strings.TrimSpace(r.rule.PromQl) if promql == "" { logger.Errorf("rule_eval:%d promql is blank", r.RuleID()) return } var value model.Value var err error if r.rule.Algorithm == "" { var warnings prom.Warnings value, warnings, err = reader.Client.Query(con...
numLabels := len(m) labelStrings := make([]string, 0, numLabels) for label, value :=
func labelMapToArr(m map[string]string) []string {
random_line_split
event_test.go
false, "name": "Value", "type": "uint256" }], "name": "MixedCase", "type": "event" }`) // 1000000 var transferData1 = "00000000000000000000000000000000000000000000000000000000000f4240" // "0x00Ce0d46d924CC8437c806721496599FC3FFA268", 2218516807680, "usd" var pledgeData1 = "00000000000000000000000000ce0d46d924cc...
for name, event := range abi.Events { if event.Id() != test.expectations[name] { t.Errorf("expected id to be %x, got %x", test.expectations[name], event.Id()) } } } } // TestEventMultiValueWithArrayUnpack verifies that array fields will be counted after parsing array. func TestEventMultiValueWithArrayUn...
random_line_split
event_test.go
test := range table { abi, err := JSON(strings.NewReader(test.definition)) if err != nil { t.Fatal(err) } for name, event := range abi.Events { if event.Id() != test.expectations[name] { t.Errorf("expected id to be %x, got %x", test.expectations[name], event.Id()) } } } } // TestEventMultiVal...
{ val, _ := intType.pack(reflect.ValueOf(tc.want.Value2)) b.Write(val) }
conditional_block
event_test.go
, "name": "Value", "type": "uint256" }], "name": "MixedCase", "type": "event" }`) // 1000000 var transferData1 = "00000000000000000000000000000000000000000000000000000000000f4240" // "0x00Ce0d46d924CC8437c806721496599FC3FFA268", 2218516807680, "usd" var pledgeData1 = "00000000000000000000000000ce0d46d924cc8437c8...
Value2 *big.Int `abi:"value"` } type BadEventTransferWithEmptyTag struct { Value *big.Int `abi:""` } type EventPledge struct { Who common.Address Wad *big.Int Currency [3]byte } type BadEventPledge struct { Who string Wad int Currency [3]byte } type EventMixedCase struct ...
{ type EventTransfer struct { Value *big.Int } type EventTransferWithTag struct { // this is valid because `value` is not exportable, // so value is only unmarshalled into `Value1`. value *big.Int Value1 *big.Int `abi:"value"` } type BadEventTransferWithSameFieldAndTag struct { Value *big.Int Va...
identifier_body
event_test.go
type" : "event", "name" : "check", "inputs": [{ "name" : "t", "type": "address" }, { "name": "b", "type": "uint256" }] } ]`, expectations: map[string]common.Hash{ "balance": crypto.Keccak256Hash([]byte("balance(uint256)")), "check": crypto.Keccak256Hash([]byte("check(address,uint256)")), }, }, } ...
encoded
identifier_name
PolicyEditForm.js
= forwardRef((props, ref) => { useImperativeHandle(ref, () => ({ form, handleSubmit })); // 判断策略名称是否存在 const asyncValidatePolicyNameRepeat = (rule, value, callback) => { debouncedCheckPolicyName(() => { props.actions.existPolicyName({ username: value }).then(({ data }) => { if (data...
specialAccountRules, whiteList } = props.form.getFieldsValue([ 'specialAccountRules', 'whiteList.accountList' ]) let r1 = specialAccountRules.map(rule => { let newRule = { ...rule } newRule.accountList = clear ? [] : newRule.accountList.filter(item => item.platformId !=...
({ title: "特殊账号或白名单中设置了该平台的账号,若删除该平台,账号将一起删除,是否确认此操作?", onOk: () => { // 删除平台 confirm() // 删除账号 const {
identifier_body
PolicyEditForm.js
forwardRef((props, ref) => { useImperativeHandle(ref, () => ({ form, handleSubmit })); // 判断策略名称是否存在 const asyncValidatePolicyNameRepeat = (rule, value, callback) => { debouncedCheckPolicyName(() => { props.actions.existPolicyName({ username: value }).then(({ data }) => { if (data.i...
// 处理 accountList -> accountIds newValue.specialAccountRules = specialAccountRules.map((rule, index) => { let newRule = { ...rule } newRule.ruleId = index + 1 newRule.accountIds = newRule.accountList.map(item => item.accountId) delete newRule.uuid delete newRule.accountList ...
rebateRatio: percentage[index] }) } if (_rebateStepRules.length > 0) { newValue.globalAccountRule.rebateRule.rebateStepRules = _rebateStepRules; } }
conditional_block
PolicyEditForm.js
= forwardRef((props, ref) => { useImperativeHandle(ref, () => ({ form, handleSubmit })); // 判断策略名称是否存在 const asyncValidatePolicyNameRepeat = (rule, value, callback) => { debouncedCheckPolicyName(() => { props.actions.existPolicyName({ username: value }).then(({ data }) => { if (data...
irm({ title: "特殊账号或白名单中设置了该平台的账号,若删除该平台,账号将一起删除,是否确认此操作?", onOk: () => { // 删除平台 confirm() // 删除账号 const { specialAccountRules, whiteList } = props.form.getFieldsValue([ 'specialAccountRules', 'whiteList.accountList' ]) let r1 = specialAc...
Modal.conf
identifier_name
PolicyEditForm.js
AccountRules.reduce((result, item) => { return result.concat(item.accountList) }, []) result = result.concat(whiteList.accountList, list) return { ids: result.map(item => item.accountId), items: result } } // 判断政策下是否包含返点 const hasRebate = (values) => { const { specia...
>
random_line_split
grid.rs
} if child.0.row_end - child.0.row > 1 { dim.row_spans += 1; } } self.dim = dim; } /// Construct via a builder pub fn build<F: FnOnce(GridBuilder<W>)>(f: F) -> Self { let mut grid = Self::default(); let _ = grid.edit(f); grid ...
ListIter
identifier_name
grid.rs
-> Option<&W> { self.widgets.get(index).map(|t| &t.1) } /// Returns a mutable reference to the child, if any pub fn get_mut(&mut self, index: usize) -> Option<&mut W> { self.widgets.get_mut(index).map(|t| &mut t.1) } /// Iterate over childern pub fn iter(&self) -> impl Iterato...
{ self.list = rest; Some(first) }
conditional_block
grid.rs
data: DynGridStorage, dim: GridDimensions, on_messages: Option<Box<dyn Fn(&mut EventCx, usize)>>, } impl Widget for Self { type Data = W::Data; fn for_child_node( &mut self, data: &W::Data, index: usize, closure: Box<dyn F...
for (info, child) in &mut self.widgets { solver.for_child(&mut self.data, *info, |axis| { child.size_rules(sizer.re(), axis) }); } solver.finish(&mut self.data) } fn set_rect(&mut self, cx: &mut ConfigCx, rect: Rect...
} fn size_rules(&mut self, sizer: SizeCx, axis: AxisInfo) -> SizeRules { let mut solver = GridSolver::<Vec<_>, Vec<_>, _>::new(axis, self.dim, &mut self.data);
random_line_split
hypermodel.js
iator { constructor(options) { super(); // get dom ref // resource url // create ajax object // essentially the constructor binds to a resource // can return a JSON model, another reason for calling it 'Hyper' // check all events on itemprop, itemscope etc wh...
tml) { return $.parseHTML(html, document, true); } $html(html) { return $(this.parseHTML(html)); } _extractContainer(data, xhr, options) { let obj = {}; let isPjaxSnippet = false; // Prefer X-PJAX-URL header if it was set, otherwise fallback to // using ...
rseHTML(h
identifier_name
hypermodel.js
Mediator { constructor(options) { super(); // get dom ref // resource url // create ajax object // essentially the constructor binds to a resource // can return a JSON model, another reason for calling it 'Hyper' // check all events on itemprop, itemscope et...
// Scroll to top by default // $(window).scrollTop options.scrollTo if typeof options.scrollTo is "number" // If the URL has a hash in it, make sure the browser // knows to navigate to the hash. // if @_hash isnt "" // Avoid using simple hash set...
random_line_split
hypermodel.js
Mediator { constructor(options) { super(); // get dom ref // resource url // create ajax object // essentially the constructor binds to a resource // can return a JSON model, another reason for calling it 'Hyper' // check all events on itemprop, itemscope et...
_extractContainer(data, xhr, options) { let obj = {}; let isPjaxSnippet = false; // Prefer X-PJAX-URL header if it was set, otherwise fallback to // using the original requested url. obj.url = this._strip
return $(this.parseHTML(html)); }
identifier_body
hypermodel.js
Mediator { constructor(options) { super(); // get dom ref // resource url // create ajax object // essentially the constructor binds to a resource // can return a JSON model, another reason for calling it 'Hyper' // check all events on itemprop, itemscope et...
xhr = this._xhr = $.ajax(options); if (xhr.readyState > 0) { this._fire("pjax:start", [xhr, options]); this._fire("pjax:send", [xhr, options]); } return this._xhr; } _setCallbacks(options) { this._successCb = options.success || function () { }; ...
xhr.onreadystatechange = function () { }; xhr.abort(); }
conditional_block
gosmonaut.go
() } else { nProcs = conf.NumProcessors } // Create decoder dec, header, err := newDecoder(file, nProcs, conf.Decoder) if err != nil { return nil, err } return &Gosmonaut{ dec: dec, header: header, debugMode: conf.DebugMode, printWarnings: conf.PrintWarnings, }, nil } // Head...
return p.i, p.e } func (g *Gosmonaut) entityNeeded(t OSMType, tags OSMTags) bool { if !g.types.Get(t) { return false } return g.funcEntityNeeded(t, tags) } func (g *Gosmonaut) scanRelationDependencies() error { return g.scan(RelationType, func(id int64, tags OSMTags, v entityParser) error { // Needed by cac...
{ return nil, io.EOF }
conditional_block
gosmonaut.go
g.wayTags = nil g.nodeTags = nil g.printDebugInfo("Deleted entity caches") if g.debugMode { fmt.Println("Elapsed time:", time.Since(g.timeStarted)) } } func (g *Gosmonaut) streamError(err error) { g.stream <- osmPair{nil, err} } func (g *Gosmonaut) streamEntity(i OSMEntity) { g.stream <- osmPair{i, nil} } ...
{ rn, ok := g.nodeCache.get(id) if !ok { return Node{}, fmt.Errorf("Node #%d in not in file", id) } return Node{ ID: rn.id, Lat: rn.lat.float(), Lon: rn.lon.float(), Tags: g.nodeTags[id], }, nil }
identifier_body
gosmonaut.go
() } else { nProcs = conf.NumProcessors } // Create decoder dec, header, err := newDecoder(file, nProcs, conf.Decoder) if err != nil { return nil, err } return &Gosmonaut{ dec: dec, header: header, debugMode: conf.DebugMode, printWarnings: conf.PrintWarnings, }, nil } // Head...
lat, lon, err := d.coords() if err != nil { return err } // Add to cache if rc { g.nodeCache.add(rawNode{ id: id, lat: newCoordinate(lat), lon: newCoordinate(lon), }) // Add tags if tags.Len() != 0 { g.nodeTags[id] = tags } } // Send to output stream if rs { g.st...
return fmt.Errorf("got invalid node parser (%T)", v) } // Get properties
random_line_split
gosmonaut.go
() } else { nProcs = conf.NumProcessors } // Create decoder dec, header, err := newDecoder(file, nProcs, conf.Decoder) if err != nil { return nil, err } return &Gosmonaut{ dec: dec, header: header, debugMode: conf.DebugMode, printWarnings: conf.PrintWarnings, }, nil } // Head...
(i OSMEntity) { g.stream <- osmPair{i, nil} } // Next returns the next decoded entity (x)or an error. // If the error is io.EOF the file has successfully been decoded. // If the error is not EOF decoding has been stopped due to another error. func (g *Gosmonaut) Next() (OSMEntity, error) { p, ok := <-g.stream if !o...
streamEntity
identifier_name
initializer.ts
MMMMMMN/ +NMMMN- /yyyyyys d. dMMMMNo` dNy-+ymmmho-+NN- dMMMMMMMMN/ yMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM MMMMMMMNyNMMMMN+::::::::::m+/mMMMMMMd: dMMNho///+ymMMN+/mMMMMMMMMNs/hMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM MMMMMMMMNMMMMMMMMMMMMMMMMMMMMMMMMMMMMNsmMMMMMMMMMMMMMMNNNNMMNNNMMNNNNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM MMMMMMMMMMMMMMMMM...
{ return true; }
conditional_block
initializer.ts
NhmNNMmmNMNNmmmmdmmdyhhoyddddoo++yoyysooossyhsmMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM MMMNNNmmNNNmdNdNmmddhhhdNNhsmNssdooo/dso++osyyysoymMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM MMNNNNmNNNNNmddmmNhshNmmmNmNMdhNsh/ohho++/:++MMNNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM MNNNMMNNNNmmmhhhhdyosd...
{ let session = 'session'; if ( typeof sessionOrOption === 'string' && sessionOrOption.replace(/\s/g, '').length ) { session = sessionOrOption.replace(/\s/g, ''); } else if (typeof sessionOrOption === 'object') { session = sessionOrOption.session || session; catchQR = sessionOrOption.catchQ...
identifier_body
initializer.ts
MMMMMMMMMMMMMMMMMMMMMM NMMMNmhNdNMNMNMMNmNNNmmmdyoohmhoyo::hsooo++oooydhymMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM MMMNNNhmNNMmmNMNNmmmmdmmdyhhoyddddoo++yoyysooossyhsmMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM MMMNNNmmNNNmdNdNmmddhhhdNNhsmNssdooo/dso++osyyysoymMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM...
( sessionOrOption: string | CreateOptions, catchQR?: CatchQR, statusFind?: StatusFind, options?: CreateConfig, browserSessionToken?: tokenSession, browserInstance?: BrowserInstance ): Promise<Whatsapp> { let session = 'session'; if ( typeof sessionOrOption === 'string' && sessionOrOption.replac...
create
identifier_name
initializer.ts
mMMMMMMMMMNNNmmNNNMMNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM mmNMMNMMMMNNNNNmmmddhdddNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM mddNMMNy:/odNmmddmmNNmdhhddmNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM NmmdNMNd:--+dNmmd...
MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
random_line_split
main.rs
.push(name_string); } target_names } pub fn u8_to_string(u: &[u8]) -> String { String::from_utf8(u.to_vec()).unwrap() } pub fn dna_vec(u: &[u8]) -> (Vec<char>) { let mut v: Vec<char> = Vec::with_capacity(u.len()); for cu in u.to_ascii_uppercase() { let c = cu as char; //assert!(c ...
(bam_file: &String) -> Vec<GenomicInterval> { let bam = bam::Reader::from_path(bam_file).unwrap(); let header_view = bam.header(); let target_names_dec: Vec<&[u8]> = header_view.target_names(); let mut intervals: Vec<GenomicInterval> = vec![]; for (tid, t_name_dec) in target_names_dec.iter().enumer...
get_whole_genome_intervals
identifier_name
main.rs
.push(name_string); } target_names } pub fn u8_to_string(u: &[u8]) -> String { String::from_utf8(u.to_vec()).unwrap() } pub fn dna_vec(u: &[u8]) -> (Vec<char>) { let mut v: Vec<char> = Vec::with_capacity(u.len()); for cu in u.to_ascii_uppercase() { let c = cu as char; //assert!(c ...
.takes_value(true)) .arg(Arg::with_name("Chrom") .short("C") .long("chrom") .value_name("string") .help("Chromosome to limit analysis to.") .display_order(30) .takes_value(true)) .arg(Arg::with_name("Min coverage") .short
{ let input_args = App::new("Map Counter") .version("0.1") .author("Peter Edge <edge.peterj@gmail.com>") .about("Given a bam, count the number of positions exceeding a given min coverage and \"well-mapped\" fraction.") .arg(Arg::with_name("Input BAM") .short("b") .long("b...
identifier_body
main.rs
_names.push(name_string); } target_names } pub fn u8_to_string(u: &[u8]) -> String { String::from_utf8(u.to_vec()).unwrap() } pub fn dna_vec(u: &[u8]) -> (Vec<char>) { let mut v: Vec<char> = Vec::with_capacity(u.len()); for cu in u.to_ascii_uppercase() { let c = cu as char; //asse...
} intervals } // given a bam file name and a possible genomic interval, // if the interval exists then just return a vector holding that lone interval // otherwise, if the interval is None, // return a vector holding GenomicIntervals representing the whole genome. pub fn get_interval_lst(bam_file: &String, in...
end_pos: header_view.target_len(tid as u32).unwrap()-1 });
random_line_split
configureDCR.py
p.name] if len(ifxs2s) == 0: ifxsSetting2 = None else: ifxsSetting2 = ifxs2s[0].port if ifxsSetting2 == ifxsSetting1:
# are we done yet? if feed2path is not None: break # return feed1path, feed2path return IFPaths([feed1path, feed2path]) def setFreqWithVelocity(config, paths): "TBF: explain this" vlow = config['vlow'] vhigh = config['vhigh'] vdef = config['vdef'] # for no...
feed2path = ifPath break
conditional_block
configureDCR.py
p.name] if len(ifxs2s) == 0: ifxsSetting2 = None else: ifxsSetting2 = ifxs2s[0].port if ifxsSetting2 == ifxsSetting1: feed2path = ifPath break # are we done yet? if feed2path is not None: br...
vhigh = config['vhigh'] vdef = config['vdef'] # for no doppler affect, I think we do this: config['freq'] = config['restfreq'] config['dfreq'] = 0 user_freqs = [config["freq"]] user_dfreqs = [config["dfreq"]] freqs = user_freqs dfreqs = user_dfreqs vd = Vdef() minMaxFreqs...
vlow = config['vlow']
random_line_split
configureDCR.py
p.name] if len(ifxs2s) == 0: ifxsSetting2 = None else: ifxsSetting2 = ifxs2s[0].port if ifxsSetting2 == ifxsSetting1: feed2path = ifPath break # are we done yet? if feed2path is not None: br...
(bp1, rxNode): "Return bandpasses representing filters in receiver" bps = [] bp = copy(bp1) for fName, fLow, fHigh in rxNode.ifInfo.filters: bp = copy(bp) bp.filter(fLow, fHigh) bp.changes = "Filter %s (%f, %f)" % (fName, fLow, fHigh) bps.append(bp) return bps def ge...
getFilterBandpasses
identifier_name
configureDCR.py
.append((paramName, filterSetting)) # start calculating band pass info for path in ifPaths.paths: frontendNode = path.path[0] frontendNode.ifInfo = IFInfo() if filterSetting is not None: frontendNode.ifInfo.filters = [(filterSetting, filterLo, filterHi)] else: ...
"Mimics Configure('Continuum with RcvrArray18_26')" # configure from DB config = { 'receiver' : 'RcvrArray18_26', # changes from other 'Continuum with *' scripts 'beam' : '4,6', 'obstype' : 'Continuum', 'backend' : 'DCR', # 'DCR_AF' used by config tool to enforce Analog F...
identifier_body
datautils.py
# class names are subdirectory names in Preproc/ directory def get_class_names(path="Preproc/Train/", sort=True): if (sort): class_names = sorted(list(listdir_nohidden(path, subdirs_only=True))) # sorted alphabetically for consistency with "ls" command else: class_names = listdir_nohidden(p...
random_line_split
datautils.py
melgram, out_format='npz'): channels = melgram.shape[3] melgram = melgram.astype(np.float16) if (('jpeg' == out_format) or ('png' == out_format)) and (channels <=4): melgram = np.squeeze(melgram) # squeeze gets rid of dimensions of batch_size 1 #melgram = np.moveaxis(melgram, 1, 3).squeeze...
class_names = get_class_names(path=path) print("class_names = ",class_names) nb_classes = len(class_names) total_files = get_total_files(class_names, path=path) total_load = int(total_files * load_frac) if max_per_class > 0: total_load = min( total_load, max_per_class * nb_classes) if...
identifier_body
datautils.py
= len(files) sum_total += n_files return sum_total def
(float_img): #out_img = 255*(float_img - np.min(float_img))/np.ptp(float_img).astype(np.uint8) out_img = img_as_ubyte( (float_img-np.min(float_img))/np.ptp(float_img) ) return out_img def save_melgram(outfile, melgram, out_format='npz'): channels = melgram.shape[3] melgram = melgram.astype(np.float...
scale_to_uint8
identifier_name
datautils.py
_total += n_files return sum_total def scale_to_uint8(float_img): #out_img = 255*(float_img - np.min(float_img))/np.ptp(float_img).astype(np.uint8) out_img = img_as_ubyte( (float_img-np.min(float_img))/np.ptp(float_img) ) return out_img def save_melgram(outfile, melgram, out_format='npz'): channel...
total_load = nearest_multiple( total_load, batch_size)
conditional_block
lib.rs
Mut}; } } cfg_if::cfg_if! { if #[cfg(feature = "device")] { mod slave_req_handler; mod slave_proxy; pub use self::slave_req_handler::{ Protocol, SlaveReqHandler, SlaveReqHelper, VhostUserSlaveReqHandler, VhostUserSlaveReqHandlerMut, }; pub use self...
{ /// client exited properly. #[error("client exited properly")] ClientExit, /// client disconnected. /// If connection is closed properly, use `ClientExit` instead. #[error("client closed the connection")] Disconnect, /// Virtio/protocol features mismatch. #[error("virtio features ...
Error
identifier_name
lib.rs
Mut}; } } cfg_if::cfg_if! { if #[cfg(feature = "device")] { mod slave_req_handler; mod slave_proxy; pub use self::slave_req_handler::{ Protocol, SlaveReqHandler, SlaveReqHelper, VhostUserSlaveReqHandler, VhostUserSlaveReqHandlerMut, }; pub use self...
libc::EACCES => Error::SocketConnect(IOError::from_raw_os_error(libc::EACCES)), // Catch all other errors e => Error::SocketError(IOError::from_raw_os_error(e)), } } } /// Result of vhost-user operations pub type Result<T> = std::result::Result<T, Error>; /// Result of...
{ match err.errno() { // Retry: // * EAGAIN, EWOULDBLOCK: The socket is marked nonblocking and the requested operation // would block. // * EINTR: A signal occurred before any data was transmitted // * ENOBUFS: The output queue for a network inte...
identifier_body
lib.rs
)) } #[cfg(all(test, feature = "device"))] mod dummy_slave; #[cfg(all(test, feature = "vmm", feature = "device"))] mod tests { use std::sync::Arc; use std::sync::Barrier; use std::sync::Mutex; use std::thread; use base::AsRawDescriptor; use tempfile::tempfile; use super::*; use crate...
{ panic!("invalid error code conversion!"); }
conditional_block
lib.rs
//! virtqueues sharing with a user space process on the same host. It uses communication over a //! Unix domain socket to share file descriptors in the ancillary data of the message. //! The protocol defines 2 sides of the communication, master and slave. Master is the application //! that shares its virtqueues. Slave ...
//! vhost implementation in the Linux kernel. It implements the control plane needed to establish
random_line_split
file.go
.ProcessorEvent) f.logs = make(map[string]os.FileInfo) if _, err := os.Stat(f.c.Storage); os.IsNotExist(err) { if err = os.MkdirAll(f.c.Storage, 0755); err != nil { return nil, err } } if err = f.nextFile(); err != nil { return nil, err } if err = f.watch(); err != nil { return } if err = f.loadFil...
if evt.Op&fsnotify.Remove == fsnotify.Remove { f.eLock.Lock() delete(f.logs, evt.Name) f.eLock.Unlock() log.Info("remove file: %s", evt.Name) } } } // setIndex setIndex func (f *FileCache) setIndex(idx *Index) (err error) { w, err := os.OpenFile(f.c.Index, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666) ...
{ if !strings.HasSuffix(evt.Name, f.c.Suffix) { log.Warn("create invalid file: %s", evt.Name) continue } fi, err := os.Stat(evt.Name) if err != nil { log.Error("os.Stat(%s) error(%v)", evt.Name, err) continue } f.eLock.Lock() f.logs[evt.Name] = fi f.eLock.Unlock() log.Info("cr...
conditional_block
file.go
err = os.MkdirAll(f.c.Storage, 0755); err != nil { return nil, err } } if err = f.nextFile(); err != nil { return nil, err } if err = f.watch(); err != nil { return } if err = f.loadFiles(); err != nil { return } go f.watchproc() go f.writeProcess() go f.readProcess() return f, nil } func (f *...
{ w, err := os.OpenFile(f.c.Index, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666) if err != nil { log.Error("os.OpenFile(%s) error(%v)", f.c.Index, err) return } defer w.Close() b, err := json.Marshal(idx) if err != nil { log.Error("json.Marshal(%v)", idx) return } if _, err = w.Write(b); err != nil { log....
identifier_body
file.go
cur.Close() } name := f.nextFileName() f, err := os.OpenFile(name, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0666) if err != nil { log.Error("os.OpenFile(%s) error(%v)", name, err) continue } cur = f wr.Reset(f) total = 0 continue } } } // index index func (f *FileCache) index() (...
nextFileName
identifier_name
file.go
event.ProcessorEvent) f.logs = make(map[string]os.FileInfo) if _, err := os.Stat(f.c.Storage); os.IsNotExist(err) { if err = os.MkdirAll(f.c.Storage, 0755); err != nil { return nil, err } } if err = f.nextFile(); err != nil { return nil, err } if err = f.watch(); err != nil { return } if err = f.lo...
f.eLock.Unlock() log.Info("remove file: %s", evt.Name) } } } // setIndex setIndex func (f *FileCache) setIndex(idx *Index) (err error) { w, err := os.OpenFile(f.c.Index, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666) if err != nil { log.Error("os.OpenFile(%s) error(%v)", f.c.Index, err) return } defer w.Cl...
} if evt.Op&fsnotify.Remove == fsnotify.Remove { f.eLock.Lock() delete(f.logs, evt.Name)
random_line_split
main.rs
process::{exit, Command}; use tempdir::TempDir; use cretonne::settings::Configurable; macro_rules! vprintln { ($x: expr, $($tts:tt)*) => { if $x { println!($($tts)*); } } } macro_rules! vprint { ($x: expr, $($tts:tt)*) => { if $x { print!($($tts)*); ...
(args: &Args, path: PathBuf, name: &str, isa: &TargetIsa) -> Result<(), String> { let mut terminal = term::stdout().unwrap(); terminal.fg(term::color::YELLOW).unwrap(); vprint!(args.flag_verbose, "Handling: "); terminal.reset().unwrap(); vprintln!(args.flag_verbose, "\"{}\"", name); terminal.fg(...
handle_module
identifier_name
main.rs
[b'\0', b'a', b's', b'm']) { let tmp_dir = TempDir::new("cretonne-wasm").unwrap(); let file_path = tmp_dir.path().join("module.wasm"); File::create(file_path.clone()).unwrap(); Command::new("wat2wasm") .arg(path.clone()) .arg("-o") .arg(file_path.to_st...
{ let msg = err.to_string(); let str1 = match err.location { AnyEntity::Inst(inst) => { format!( "{}\n{}: {}\n\n", msg, inst, func.dfg.display_inst(inst, isa) ) } _ => String::from(format!("{}\n", msg...
identifier_body
main.rs
use cretonne::ir; use cretonne::ir::entities::AnyEntity; use cretonne::isa::TargetIsa; use cretonne::verifier; use cretonne::settings; use std::fs::File; use std::error::Error; use std::io; use std::io::stdout; use std::io::prelude::*; use docopt::Docopt; use std::path::Path; use std::process::{exit, Command}; use temp...
use cretonne::flowgraph::ControlFlowGraph; use cretonne::dominator_tree::DominatorTree; use cretonne::Context; use cretonne::result::CtonError;
random_line_split
nodeserver.go
req.GetVolumeContext()["csi.storage.k8s.io/ephemeral"] == "" && ns.ephemeral // Kubernetes 1.15 doesn't have csi.storage.k8s.io/ephemeral if req.GetVolumeCapability().GetBlock() != nil && req.GetVolumeCapability().GetMount() != nil { return nil, status.Error(codes.InvalidArgument, "cannot have both block and m...
random_line_split
nodeserver.go
StorageCapacity, mountAccess, ephemeralVolume) if err != nil && !os.IsExist(err) { glog.Error("ephemeral mode failed to create volume: ", err) return nil, status.Error(codes.Internal, err.Error()) } glog.V(4).Infof("ephemeral mode: created volume: %s", vol.VolPath) } vol, err := getVolumeByID(req.GetVolu...
{ // Check arguments if len(req.GetVolumeId()) == 0 { return nil, status.Error(codes.InvalidArgument, "Volume ID missing in request") } if len(req.GetStagingTargetPath()) == 0 { return nil, status.Error(codes.InvalidArgument, "Target path missin gin request") } return &csi.NodeUnstageVolumeResponse{}, nil }
identifier_body
nodeserver.go
nil, status.Error(codes.InvalidArgument, "Target path missing in request") } targetPath := req.GetTargetPath() ephemeralVolume := req.GetVolumeContext()["csi.storage.k8s.io/ephemeral"] == "true" || req.GetVolumeContext()["csi.storage.k8s.io/ephemeral"] == "" && ns.ephemeral // Kubernetes 1.15 doesn't have csi.st...
(ctx context.Context, req *csi.NodeStageVolumeRequest) (*csi.NodeStageVolumeResponse, error) { // Check arguments if len(req.GetVolumeId()) == 0 { return nil, status.Error(codes.InvalidArgument, "Volume ID missing in request") } if len(req.GetStagingTargetPath
NodeStageVolume
identifier_name
nodeserver.go
nil, status.Error(codes.InvalidArgument, "Target path missing in request") } targetPath := req.GetTargetPath() ephemeralVolume := req.GetVolumeContext()["csi.storage.k8s.io/ephemeral"] == "true" || req.GetVolumeContext()["csi.storage.k8s.io/ephemeral"] == "" && ns.ephemeral // Kubernetes 1.15 doesn't have csi.st...
if req.GetVolumeCapability().GetBlock() != nil { if vol.VolAccessType != blockAccess { return nil, status.Error(codes.InvalidArgument, "cannot publish a non-block volume as block volume") } volPathHandler := volumepathhandler.VolumePathHandler{} // Get loop device from the volume path loopDevice, err ...
{ return nil, status.Error(codes.NotFound, err.Error()) }
conditional_block
lib.rs
`] trait. During the //! dispatching process (in [`Display::dispatch_clients()`]), all requests sent by clients are read from //! their respective process and delivered to your processing logic, by invoking methods on the various //! [`Dispatch`] implementations of your `State` struct. In this paradigm, your `State` ne...
/// wayland-scanner. fn write_event( &self, dh: &DisplayHandle, req: Self::Event, ) -> Result<Message<ObjectId, std::os::unix::io::RawFd>, InvalidId>; /// Creates a weak handle to this object /// /// This weak handle will not keep the user-data associated with the object...
) -> Result<(Self, Self::Request), DispatchError>; /// Serialize an event for this object /// /// **Note:** This method is mostly meant as an implementation detail to be used by code generated by
random_line_split
lib.rs
you using [`DisplayHandle::create_global()`], and require your `State` to //! implement the [`GlobalDispatch`] trait for the interface associated with that global. //! //! ## Logging //! //! This crate can generate some runtime error message (notably when a protocol error occurs). By default //! those messages are pri...
{ write!(f, "Bad message for object {interface}@{sender_id} on opcode {opcode}",) }
conditional_block
lib.rs
trait. During the //! dispatching process (in [`Display::dispatch_clients()`]), all requests sent by clients are read from //! their respective process and delivered to your processing logic, by invoking methods on the various //! [`Dispatch`] implementations of your `State` struct. In this paradigm, your `State` need...
(&self) -> bool { if let Some(handle) = self.handle().upgrade() { handle.object_info(self.id()).is_ok() } else { false } } /// Access the user-data associated with this object fn data<U: 'static>(&self) -> Option<&U>; /// Access the raw data associated w...
is_alive
identifier_name
player_vlc.rs
{}", url); let mut resp = self .0 .get(url.as_ref()) .basic_auth("", Some(VLC_HTTP_PASSWORD)) .send()?; if !resp.status().is_success() { return Err(VlcError::BadResponse(format_err!( "Bad HTTP status {} : {}", ...
is_ok
identifier_name
player_vlc.rs
::BadResponse(format_err!( "Bad HTTP status {} : {}", resp.status(), resp.text().unwrap_or_else(|_| "N/A".to_string()) ))); } Ok(resp.text()?) } } pub struct VlcPlayer<C: HttpClient = ReqwestClient> { vlc_config: VlcConfig, confi...
{ match self.send_status_cmd("", &[]) { Ok(_) => true, Err(e) => { debug!("Got error response while checking health of VLC: {}", e); false } } }
identifier_body
player_vlc.rs
(VlcError::NotStarted) } /// Convert `audio_volume` set in config into the value /// range used in VLC player fn audio_volume(&self) -> std::result::Result<u32, VlcError> { Ok((VLC_VOLUME_MAX as f32 * self.config()?.audio_volume).round() as u32) } fn http_port(&self) -> u32 { s...
random_line_split
player_vlc.rs
VlcConfig) -> Self { Self::new_with_client( config, ReqwestClient( reqwest::Client::builder() .timeout(Some(Duration::from_secs(VLC_REQUEST_TIMEOUT))) .build() .expect("reqwest client"), ), )...
{ // Rust's Command doesn't support other than SIGKILL in portable interface unsafe { libc::kill(proc.id() as i32, libc::SIGTERM); } match proc.wait() { Ok(status) => debug!("VLC process exit with {}", status.code().unwrap_or(-1)), ...
conditional_block
render.ts
Layout) { // Run through our data, calculate normals and such. const t = vec3.create(); const posData = new Float32Array(chunk.indexData.length * 3); const nrmData = new Float32Array(chunk.indexData.length * 3); for (let i = 0; i < chunk.indexData.length; i += 3) { ...
{ const renderInstManager = this.renderHelper.renderInstManager; const mainColorDesc = makeBackbufferDescSimple(GfxrAttachmentSlot.Color0, viewerInput, standardFullClearRenderPassDescriptor); const mainDepthDesc = makeBackbufferDescSimple(GfxrAttachmentSlot.DepthStencil, viewerInput, standardFu...
identifier_body
render.ts
'../Camera.js'; import { GfxrAttachmentSlot } from '../gfx/render/GfxRenderGraph.js'; class IVProgram extends DeviceProgram { public static a_Position = 0; public static a_Normal = 1; public static ub_SceneParams = 0; public static ub_ObjectParams = 1; public override both = ` precision mediump ...
const d = templateRenderInst.mapUniformBufferF32(IVProgram.ub_ObjectParams); offs += fillColor(d, offs, this.iv.color); for (let i = 0; i < this.chunks.length; i++) this.chunks[i].prepareToRender(renderInstManager); renderInstManager.popTemplateRenderInst(); } publ...
const templateRenderInst = renderInstManager.pushTemplateRenderInst(); let offs = templateRenderInst.allocateUniformBuffer(IVProgram.ub_ObjectParams, 4);
random_line_split
render.ts
'../Camera.js'; import { GfxrAttachmentSlot } from '../gfx/render/GfxRenderGraph.js'; class IVProgram extends DeviceProgram { public static a_Position = 0; public static a_Normal = 1; public static ub_SceneParams = 0; public static ub_ObjectParams = 1; public override both = ` precision mediump ...
(renderInstManager: GfxRenderInstManager): void { if (!this.visible) return; const templateRenderInst = renderInstManager.pushTemplateRenderInst(); let offs = templateRenderInst.allocateUniformBuffer(IVProgram.ub_ObjectParams, 4); const d = templateRenderInst.mapUniformBuff...
prepareToRender
identifier_name
pdf.js
ff8746', fontSize: 24, offset: [-15, 0] }, data: [{ value: value, name: name, areaStyle: { normal: { color: 'rgba( 255, 100, 15, 0.5 )' } }, itemStyle: { normal: { color:...
lue2.length) { if (op.value1[ps.v1_i] == op.value2[ps.v2_i]) { ps.v1_new_value += op.value1[ps.v1_i].replace(/</g, "<").replace(">", ">"); ps.v2_new_value += op.value2[ps.v2_i].replace(/</g, "<").replace(">", ">"); ps.v1_i += 1; ps.v2_i += 1; if (ps.v1_i >= op.value1.length...
identifier_body
pdf.js
的颜色 color: '#fff' } }, axisLine: { show: false }, splitLine: { show: true, lineStyle: { width: 1, // 设置网格的颜色 color: '#878787' } }, indicator: indicator }, series:...
op.value2.length) { if (op.value1[ps.v1_i] == op.value2[ps.v2_i]) { ps.v1_new_value += op.value1[ps.v1_i].replace(/</g, "<").replace(">", ">"); ps.v2_new_value += op.value2[ps.v2_i].replace(/</g, "<").replace(">", ">"); ps.v1_i += 1; ps.v2_i += 1; if (ps.v1_i >= op.value1.l...
<
identifier_name
pdf.js
color: '#fff' } }, axisLine: { show: false }, splitLine: { show: true, lineStyle: { width: 1, // 设置网格的颜色 color: '#878787' } }, indicator: indicator }, series: [{...
length && ps.v2_i < op.value2.length) { if (op.value1[ps.v1_i] == op.value2[ps.v2_i]) { ps.v1_new_value += op.value1[ps.v1_i].replace(/</g, "<").replace(">", ">"); ps.v2_new_value += op.value2[ps.v2_i].replace(/</g, "<").replace(">", ">"); ps.v1_i += 1; ps.v2_i += 1; if (ps...
{ op.eq_index = 5; } if (!op.value1 || !op.value2) { return op; } var ps = { v1_i: 0, v1_new_value: "", v2_i: 0, v2_new_value: "" }; while (ps.v1_i < op.value1.
conditional_block
pdf.js
的颜色 color: '#fff' } }, axisLine: { show: false }, splitLine: { show: true, lineStyle: { width: 1, // 设置网格的颜色 color: '#878787' } }, indicator: indicator }, series:...
} }, indicator: indicator }, series: [{ name: name, type: 'radar', symbolSize: 6, label: { show: true, position: 'top', color: 'rgb(51,51,51)', fontSize: 18, offset: [0, 0] }, data: [{...
color: 'rgb(102, 102, 102)',
random_line_split
EMPIRIC_analysis_EXP.py
(dat, dataset): """This function filters low-qual and other controls data from the original expanded version of the EMPIRIC dataset.""" # dat = dat[dat['organism'].isin(dataset)] no_mmei_index = dat['mmei']=='no' nonstop_index = dat['mutstop']=='no' zerofit_index = dat['fitness'].abs()>1e-4 ...
filterDataset
identifier_name
EMPIRIC_analysis_EXP.py
This function filters low-qual and other controls data from the original expanded version of the EMPIRIC dataset.""" # dat = dat[dat['organism'].isin(dataset)] no_mmei_index = dat['mmei']=='no' nonstop_index = dat['mutstop']=='no' zerofit_index = dat['fitness'].abs()>1e-4 mutwt_index = dat['...
#main function for running PCA, calls on subfunctions def runPCA(dat): """ run PCA, notes: matrix has to be pandas df, and can contain NAs, they are ommited during covariation calculation and NAs are filled with 0.0 during the projection onto eigenvectors. """ #####################################...
"""Takes raw EMPIRIC data (unrolled and filtered), and features of positions in library: Returns a merged table, where each library position is characterized by features and 20-EMPIRIC fitness readings. BEWARE: Unique labels are 'organism-pos' and their order as in features table, which is cruicial for comp...
identifier_body
EMPIRIC_analysis_EXP.py
"""Takes raw EMPIRIC data (unrolled and filtered), and features of positions in library: Returns a merged table, where each library position is characterized by features and 20-EMPIRIC fitness readings. BEWARE: Unique labels are 'organism-pos' and their order as in features table, which is cruicial for ...
print pc,'%.1f%%'%var_dict[pc]
conditional_block
EMPIRIC_analysis_EXP.py
import collections # EMPIRIC_raw_data_fname = "db-fitness.csv" # # most important reference file with all the libraries information ... # EMPIRIC_features_fname = "features-original.csv" # 20 amino acids ... aacids = sorted(list(SeqUtils.IUPAC.protein.letters)) #filter dataset def filterDataset(dat, dataset): ...
random_line_split
ExportGltf.ts
Globals.binBytesWritten, byteLength: indices.byteLength, }); GltfGlobals.binBytesWritten += indices.byteLength; fs.writeSync(GltfGlobals.binFile, indices); } function addMeshPointsAndNormals(points: Float64Array, normals: Float32Array) { // GLTF is RHS with Y-up, iModel.js is RHS with Z-up const...
TranslationRotationScale
identifier_name