file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
_typecheck.py | # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
def _replace_forward_references(t, context):
"""Replace forward references in the given type."""
if isinstance(t, str):
return context[t]
elif isinstance(t, Type):
return type(t)(*[_replace_forward_references(t, context) for t in t._types]) # pylint: disable=protected-access
else:
return t
def... | """A typed dict.
A correct type has the correct parametric types for keys and values.
"""
def __instancecheck__(self, instance):
return (isinstance(instance, dict)
and super(Dict, self).__instancecheck__(instance)) | identifier_body |
_typecheck.py | # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | """
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:
# Th... | random_line_split | |
_typecheck.py | # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
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 | # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | (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 | package main
import (
"fmt"
"io/ioutil"
"math"
"math/rand"
"runtime"
"sort"
"time"
"github.com/go-gl/gl/v4.1-core/gl"
"github.com/go-gl/glfw/v3.2/glfw"
"github.com/go-gl/mathgl/mgl32"
"github.com/meshiest/dungeon-game/platform"
"github.com/meshiest/go-dungeon/dungeon"
)
func FloorTile(xInt int, zInt int... | (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 | package main
import (
"fmt"
"io/ioutil"
"math"
"math/rand"
"runtime"
"sort"
"time"
"github.com/go-gl/gl/v4.1-core/gl"
"github.com/go-gl/glfw/v3.2/glfw"
"github.com/go-gl/mathgl/mgl32"
"github.com/meshiest/dungeon-game/platform"
"github.com/meshiest/go-dungeon/dungeon"
)
func FloorTile(xInt int, zInt int... |
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.Yaw -= mouseSe... | {
fmt.Println("FPS is ", fps)
lastFPS = time
fps = 0
} | conditional_block |
game.go | package main
import (
"fmt"
"io/ioutil"
"math"
"math/rand"
"runtime"
"sort"
"time"
"github.com/go-gl/gl/v4.1-core/gl"
"github.com/go-gl/glfw/v3.2/glfw"
"github.com/go-gl/mathgl/mgl32"
"github.com/meshiest/dungeon-game/platform"
"github.com/meshiest/go-dungeon/dungeon"
)
func FloorTile(xInt int, zInt int... |
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 | package main
import (
"fmt"
"io/ioutil"
"math"
"math/rand"
"runtime"
"sort"
"time"
"github.com/go-gl/gl/v4.1-core/gl"
"github.com/go-gl/glfw/v3.2/glfw"
"github.com/go-gl/mathgl/mgl32"
"github.com/meshiest/dungeon-game/platform"
"github.com/meshiest/go-dungeon/dungeon"
)
func FloorTile(xInt int, zInt int... | direction.X()*cos - sin*direction.Y(),
direction.X()*sin + cos*direction.Y(),
}
player.X += float64(rotated.X()) * player.Speed * delta * boost
player.Y += float64(rotated.Y()) * player.Speed * delta * boost
}
player.CollideWithDungeon(dungeon)
camera = mgl32.LookAt(
float32(player.X), float... | sin := float32(math.Sin(player.Yaw - math.Pi/2))
rotated := mgl32.Vec2{ | random_line_split |
service_map.py | # -*- cpy-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 ma... |
@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 | # -*- cpy-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 ma... | (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 | # -*- cpy-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 ma... |
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 | # -*- cpy-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 ma... | 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 | /*Name: Irfan shah */
/* CHAPTER# 38-44 */
/* 1. Write a custom function power ( a, b ), to calculate the value of
/* a raised to b.*/
function raisedValue(){
var a =prompt("enter first value");
var b = prompt("enter se... | 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 | /*Name: Irfan shah */
/* CHAPTER# 38-44 */
/* 1. Write a custom function power ( a, b ), to calculate the value of
/* a raised to b.*/
function raisedValue(){
var a =prompt("enter first value");
var b = prompt("enter second value");
consol... | 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 | /*Name: Irfan shah */
/* CHAPTER# 38-44 */
/* 1. Write a custom function power ( a, b ), to calculate the value of
/* a raised to b.*/
function raisedValue(){
var a =prompt("enter first value");
var b = prompt("enter se... |
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 | /*Name: Irfan shah */
/* CHAPTER# 38-44 */
/* 1. Write a custom function power ( a, b ), to calculate the value of
/* a raised to b.*/
function raisedValue(){
var a =prompt("enter first value");
var b = prompt("enter se... |
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 | //! <img src="https://raw.githubusercontent.com/maciejhirsz/logos/master/logos.svg?sanitize=true" alt="Logos logo" width="250" align="right">
//!
//! # Logos
//!
//! _Create ridiculously fast Lexers._
//!
//! **Logos** has two goals:
//!
//! + To make it easy to create a Lexer, so you can focus on more complex problems... |
#[cfg(doctest)]
mod test_readme {
macro_rules! external_doc_test {
($x:expr) => {
#[doc = $x]
extern "C" {}
};
}
external_doc_test!(include_str!("../../README.md"));
}
| {
Skip
} | identifier_body |
lib.rs | //! <img src="https://raw.githubusercontent.com/maciejhirsz/logos/master/logos.svg?sanitize=true" alt="Logos logo" width="250" align="right">
//!
//! # Logos
//!
//! _Create ridiculously fast Lexers._
//!
//! **Logos** has two goals:
//!
//! + To make it easy to create a Lexer, so you can focus on more complex problems... | <T, E> {
/// Emit a token with a given value `T`. Use `()` for unit variants without fields.
Emit(T),
/// Skip current match, analog to [`Skip`](./struct.Skip.html).
Skip,
/// Emit a `<Token as Logos>::ERROR` token.
Error(E),
}
/// Predefined callback that will inform the `Lexer` to skip a defi... | FilterResult | identifier_name |
lib.rs | //! <img src="https://raw.githubusercontent.com/maciejhirsz/logos/master/logos.svg?sanitize=true" alt="Logos logo" width="250" align="right">
//!
//! # Logos
//!
//! _Create ridiculously fast Lexers._
//!
//! **Logos** has two goals:
//!
//! + To make it easy to create a Lexer, so you can focus on more complex problems... | }
/// Type that can be returned from a callback, either producing a field
/// for a token, skipping it, or emitting an error.
///
/// # Example
///
/// ```rust
/// use logos::{Logos, FilterResult};
///
/// #[derive(Debug, PartialEq, Clone, Default)]
/// enum LexingError {
/// NumberParseError,
/// NumberIsTen,... | random_line_split | |
environment.py | from multiprocessing import Process, Pipe
import numpy as np
import cv2
from collections import deque
import gym
from gym import spaces
from copy import copy
cv2.ocl.setUseOpenCL(False)
def worker(remote, parent_remote, env_fn):
parent_remote.close()
env = env_fn()
while True:
cmd, data = remote.... |
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 | from multiprocessing import Process, Pipe
import numpy as np
import cv2
from collections import deque
import gym
from gym import spaces
from copy import copy
| 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 | from multiprocessing import Process, Pipe
import numpy as np
import cv2
from collections import deque
import gym
from gym import spaces
from copy import copy
cv2.ocl.setUseOpenCL(False)
def worker(remote, parent_remote, env_fn):
parent_remote.close()
env = env_fn()
while True:
cmd, data = remote.... |
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 | from multiprocessing import Process, Pipe
import numpy as np
import cv2
from collections import deque
import gym
from gym import spaces
from copy import copy
cv2.ocl.setUseOpenCL(False)
def worker(remote, parent_remote, env_fn):
parent_remote.close()
env = env_fn()
while True:
cmd, data = remote.... | (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 | import { Api } from "../tl";
import { Message } from "../tl/custom/message";
import type { DateLike, EntityLike, FileLike, MarkupLike, MessageIDLike, MessageLike } from "../define";
import { RequestIter } from "../requestIter";
import { TotalList } from "../Helpers";
import type { TelegramClient } from "../";
interface... | 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 | import { Api } from "../tl";
import { Message } from "../tl/custom/message";
import type { DateLike, EntityLike, FileLike, MarkupLike, MessageIDLike, MessageLike } from "../define";
import { RequestIter } from "../requestIter";
import { TotalList } from "../Helpers";
import type { TelegramClient } from "../";
interface... | 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 | // Copyright 2016-2023, Pulumi Corporation.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or... |
func ignoredTokens(info *b.ProviderInfo) map[string]bool {
ignored := map[string]bool{}
if info == nil {
return ignored
}
for _, tk := range info.IgnoreMappings {
ignored[tk] = true
}
return ignored
}
func mapProviderItems(info *b.ProviderInfo, each func(string, shim.Resource) bool) {
ignored := ignoredTo... | {
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 | // Copyright 2016-2023, Pulumi Corporation.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or... |
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 | // Copyright 2016-2023, Pulumi Corporation.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or... | (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 | // Copyright 2016-2023, Pulumi Corporation.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or... | //
// 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 | package engine
import (
"context"
"fmt"
"math/rand"
"sort"
"strings"
"time"
"github.com/didi/nightingale/v5/src/server/writer"
"github.com/prometheus/common/model"
"github.com/toolkits/pkg/logger"
"github.com/toolkits/pkg/net/httplib"
"github.com/toolkits/pkg/str"
"github.com/didi/nightingale/v5/src/mode... | 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 | package engine
import (
"context"
"fmt"
"math/rand"
"sort"
"strings"
"time"
"github.com/didi/nightingale/v5/src/server/writer"
"github.com/prometheus/common/model"
"github.com/toolkits/pkg/logger"
"github.com/toolkits/pkg/net/httplib"
"github.com/toolkits/pkg/str"
"github.com/didi/nightingale/v5/src/mode... | :%d promql:%s, error:%v", r.RuleID(), promql, err)
return
}
if len(warnings) > 0 {
logger.Errorf("recording_rule_eval:%d promql:%s, warnings:%v", r.RuleID(), promql, warnings)
return
}
ts := conv.ConvertToTimeSeries(value, r.rule)
if len(ts) != 0 {
for _, v := range ts {
writer.Writers.PushSample(r.rul... | nd(), promql, time.Now())
if err != nil {
logger.Errorf("recording_rule_eval | identifier_body |
worker.go | package engine
import (
"context"
"fmt"
"math/rand"
"sort"
"strings"
"time"
"github.com/didi/nightingale/v5/src/server/writer"
"github.com/prometheus/common/model"
"github.com/toolkits/pkg/logger"
"github.com/toolkits/pkg/net/httplib"
"github.com/toolkits/pkg/str"
"github.com/didi/nightingale/v5/src/mode... | {
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 | package engine
import (
"context"
"fmt"
"math/rand"
"sort"
"strings"
"time"
"github.com/didi/nightingale/v5/src/server/writer"
"github.com/prometheus/common/model"
"github.com/toolkits/pkg/logger"
"github.com/toolkits/pkg/net/httplib"
"github.com/toolkits/pkg/str"
"github.com/didi/nightingale/v5/src/mode... | numLabels := len(m)
labelStrings := make([]string, 0, numLabels)
for label, value := range m {
labelStrings = append(labelStrings, fmt.Sprintf("%s=%s", label, value))
}
if numLabels > 1 {
sort.Strings(labelStrings)
}
return labelStrings
}
func (r RuleEval) handleNewEvent(event *models.AlertCurEvent) {
i... |
func labelMapToArr(m map[string]string) []string { | random_line_split |
event_test.go | // Copyright 2016 The go-ethereum Authors
// This file is part of the go-ethereum library.
//
// The go-ethereum library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License... | 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 | // Copyright 2016 The go-ethereum Authors
// This file is part of the go-ethereum library.
//
// The go-ethereum library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License... |
return b.Bytes()
}
// TestEventUnpackIndexed verifies that indexed field will be skipped by event decoder.
func TestEventUnpackIndexed(t *testing.T) {
definition := `[{"name": "test", "type": "event", "inputs": [{"indexed": true, "name":"value1", "type":"uint8"},{"indexed": false, "name":"value2", "type":"uint8"}]}... | {
val, _ := intType.pack(reflect.ValueOf(tc.want.Value2))
b.Write(val)
} | conditional_block |
event_test.go | // Copyright 2016 The go-ethereum Authors
// This file is part of the go-ethereum library.
//
// The go-ethereum library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License... |
func unpackTestEventData(dest interface{}, hexData string, jsonEvent []byte, assert *assert.Assertions) error {
data, err := hex.DecodeString(hexData)
assert.NoError(err, "Hex data should be a correct hex-string")
var e Event
assert.NoError(json.Unmarshal(jsonEvent, &e), "Should be able to unmarshal event ABI")
... | {
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 | // Copyright 2016 The go-ethereum Authors
// This file is part of the go-ethereum library.
//
// The go-ethereum library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License... | (intType, arrayType Type) []byte {
var b bytes.Buffer
if tc.want.Value1 != nil {
val, _ := intType.pack(reflect.ValueOf(tc.want.Value1))
b.Write(val)
}
if !reflect.DeepEqual(tc.want.Values, [2]*big.Int{nil, nil}) {
val, _ := arrayType.pack(reflect.ValueOf(tc.want.Values))
b.Write(val)
}
if tc.want.Value2... | encoded | identifier_name |
PolicyEditForm.js | /**
* Created by lzb on 2020-04-23.
*/
import React, { forwardRef, useImperativeHandle } from 'react';
import {
Button,
ConfigProvider,
DatePicker,
Form,
Icon,
Input, InputNumber,
message,
Modal,
Radio,
Switch
} from "antd";
import {
POLICY_LEVEL,
RULE_REBATE_LADDER,
WHITE_LIST_ACCOUNTS_LIMI... | 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 | /**
* Created by lzb on 2020-04-23.
*/
import React, { forwardRef, useImperativeHandle } from 'react';
import {
Button,
ConfigProvider,
DatePicker,
Form,
Icon,
Input, InputNumber,
message,
Modal,
Radio,
Switch
} from "antd";
import {
POLICY_LEVEL,
RULE_REBATE_LADDER,
WHITE_LIST_ACCOUNTS_LIMI... |
// 处理 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 | /**
* Created by lzb on 2020-04-23.
*/
import React, { forwardRef, useImperativeHandle } from 'react';
import {
Button,
ConfigProvider,
DatePicker,
Form,
Icon,
Input, InputNumber,
message,
Modal,
Radio,
Switch
} from "antd";
import {
POLICY_LEVEL,
RULE_REBATE_LADDER,
WHITE_LIST_ACCOUNTS_LIMI... | irm({
title: "特殊账号或白名单中设置了该平台的账号,若删除该平台,账号将一起删除,是否确认此操作?",
onOk: () => {
// 删除平台
confirm()
// 删除账号
const {
specialAccountRules,
whiteList
} = props.form.getFieldsValue([ 'specialAccountRules', 'whiteList.accountList' ])
let r1 = specialAc... | Modal.conf | identifier_name |
PolicyEditForm.js | /**
* Created by lzb on 2020-04-23.
*/
import React, { forwardRef, useImperativeHandle } from 'react';
import {
Button,
ConfigProvider,
DatePicker,
Form,
Icon,
Input, InputNumber,
message,
Modal,
Radio,
Switch
} from "antd";
import {
POLICY_LEVEL,
RULE_REBATE_LADDER,
WHITE_LIST_ACCOUNTS_LIMI... | <Button icon="plus" type="primary">添加白名单账号</Button>
</AccountListEdit>
)}
</FormItem>
<Settlement form={props.form} data={data} />
<FormItem label='保底政策' {...formItemLayout}>
{
getFieldDecorator('isGuaranteed', {
initialValu... | > | random_line_split |
grid.rs | // Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License in the LICENSE-APACHE file or at:
// https://www.apache.org/licenses/LICENSE-2.0
//! A grid widget
use kas::layout::{DynGridStorage, GridCh... | <'a, W: Widget> {
list: &'a [(GridChildInfo, W)],
}
impl<'a, W: Widget> Iterator for ListIter<'a, W> {
type Item = &'a (GridChildInfo, W);
fn next(&mut self) -> Option<Self::Item> {
if let Some((first, rest)) = self.list.split_first() {
self.list = rest;
Some(first)
}... | ListIter | identifier_name |
grid.rs | // Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License in the LICENSE-APACHE file or at:
// https://www.apache.org/licenses/LICENSE-2.0
//! A grid widget
use kas::layout::{DynGridStorage, GridCh... | else {
None
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
let len = self.len();
(len, Some(len))
}
}
impl<'a, W: Widget> ExactSizeIterator for ListIterMut<'a, W> {
fn len(&self) -> usize {
self.list.len()
}
}
| {
self.list = rest;
Some(first)
} | conditional_block |
grid.rs | // Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License in the LICENSE-APACHE file or at:
// https://www.apache.org/licenses/LICENSE-2.0
//! A grid widget
use kas::layout::{DynGridStorage, GridCh... | 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 | // Based originally on jquery.pjax.js
// copyright chris wanstrath
// https://github.com/defunkt/jquery-pjax
import {Mediator} from 'scaleapp';
import $ from 'jquery';
let defaults = $.extend(true, {}, $.ajaxSettings, {
timeout: 120000,
push: true,
replace: false,
type: "GET",
dataType: "html",
... | 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 | // Based originally on jquery.pjax.js
// copyright chris wanstrath
// https://github.com/defunkt/jquery-pjax
import {Mediator} from 'scaleapp';
import $ from 'jquery';
let defaults = $.extend(true, {}, $.ajaxSettings, {
timeout: 120000,
push: true,
replace: false,
type: "GET",
dataType: "html",
... | // 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 | // Based originally on jquery.pjax.js
// copyright chris wanstrath
// https://github.com/defunkt/jquery-pjax
import {Mediator} from 'scaleapp';
import $ from 'jquery';
let defaults = $.extend(true, {}, $.ajaxSettings, {
timeout: 120000,
push: true,
replace: false,
type: "GET",
dataType: "html",
... | _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._stripPjaxParam(xhr.getResponseHeader("X-PJAX-URL") || this._requestUrl);
... | return $(this.parseHTML(html));
}
| identifier_body |
hypermodel.js | // Based originally on jquery.pjax.js
// copyright chris wanstrath
// https://github.com/defunkt/jquery-pjax
import {Mediator} from 'scaleapp';
import $ from 'jquery';
let defaults = $.extend(true, {}, $.ajaxSettings, {
timeout: 120000,
push: true,
replace: false,
type: "GET",
dataType: "html",
... | 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 | package gosmonaut
import (
"errors"
"fmt"
"io"
"runtime"
"sync"
"time"
)
/* Gosmonaut */
type osmPair struct {
i OSMEntity
e error
}
// Config defines the configuration for Gosmonaut.
type Config struct {
// DebugMode prints duration and memory info and runs the garbage collector
// after every processing... |
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 | package gosmonaut
import (
"errors"
"fmt"
"io"
"runtime"
"sync"
"time"
)
/* Gosmonaut */
type osmPair struct {
i OSMEntity
e error
}
// Config defines the configuration for Gosmonaut.
type Config struct {
// DebugMode prints duration and memory info and runs the garbage collector
// after every processing... |
func (g *Gosmonaut) uncacheNodes(refs []int64) ([]Node, error) {
nodes := make([]Node, len(refs))
for i, id := range refs {
if n, err := g.uncacheNode(id); err == nil {
nodes[i] = n
} else {
return nil, err
}
}
return nodes, nil
}
/* Debug Mode */
func (g *Gosmonaut) printWarning(warning string) {
... | {
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 | package gosmonaut
import (
"errors"
"fmt"
"io"
"runtime"
"sync"
"time"
)
/* Gosmonaut */
type osmPair struct {
i OSMEntity
e error
}
// Config defines the configuration for Gosmonaut.
type Config struct {
// DebugMode prints duration and memory info and runs the garbage collector
// after every processing... | 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 | package gosmonaut
import (
"errors"
"fmt"
"io"
"runtime"
"sync"
"time"
)
/* Gosmonaut */
type osmPair struct {
i OSMEntity
e error
}
// Config defines the configuration for Gosmonaut.
type Config struct {
// DebugMode prints duration and memory info and runs the garbage collector
// after every processing... | (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 | /*
NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN
MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
mMMMMMMMMMNNNmmNNNMMNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
mmNMMNMMMMNNNN... |
return false;
})
.catch(() => undefined);
if (device) {
const ckeckVersion = await isBeta(page);
if (ckeckVersion === false) {
await page.evaluate(async () => {
await window.Store.Login.triggerCriticalSyncLogout();
});
... | {
return true;
} | conditional_block |
initializer.ts | /*
NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN
MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
mMMMMMMMMMNNNmmNNNMMNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
mmNMMNMMMMNNNN... | {
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 | /*
NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN
MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
mMMMMMMMMMNNNmmNNNMMNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
mmNMMNMMMMNNNN... | (
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 | /*
NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN | mMMMMMMMMMNNNmmNNNMMNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
mmNMMNMMMMNNNNNmmmddhdddNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
mddNMMNy:/odNmmddmmNNmdhhddmNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
NmmdNMNd:--+dNmmd... | MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM | random_line_split |
main.rs | extern crate clap;
extern crate rust_htslib;
extern crate bio;
use clap::{Arg, App};
use rust_htslib::bam;
use rust_htslib::prelude::*;
use bio::io::fasta;
#[derive(Clone)]
pub struct GenomicInterval {
pub tid: u32,
pub chrom: String,
// chromosome name
pub start_pos: u32,
// start of interval
... | (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 | extern crate clap;
extern crate rust_htslib;
extern crate bio;
use clap::{Arg, App};
use rust_htslib::bam;
use rust_htslib::prelude::*;
use bio::io::fasta;
#[derive(Clone)]
pub struct GenomicInterval {
pub tid: u32,
pub chrom: String,
// chromosome name
pub start_pos: u32,
// start of interval
... | {
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 | extern crate clap;
extern crate rust_htslib;
extern crate bio;
use clap::{Arg, App};
use rust_htslib::bam;
use rust_htslib::prelude::*;
use bio::io::fasta;
#[derive(Clone)]
pub struct GenomicInterval {
pub tid: u32,
pub chrom: String,
// chromosome name
pub start_pos: u32,
// start of interval
... | }
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 | from copy import copy
# from ifpaths import *
# from paths import getIFPaths
from StaticDefs import IF3, IFfilters, BEAM_TO_FEED_DES, FILTERS, RCVR_IF_NOMINAL, RCVR_SIDEBAND, vframe
from StaticDefs import RCVR_FREQS, DEF_ON_SYSTEMS, DEF_OFF_SYSTEMS
from StaticDefs import QD_AND_ACTIVE_SURFACE_ON_RCVRS, PFRCVRS, PF2RCV... |
# 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 | from copy import copy
# from ifpaths import *
# from paths import getIFPaths
from StaticDefs import IF3, IFfilters, BEAM_TO_FEED_DES, FILTERS, RCVR_IF_NOMINAL, RCVR_SIDEBAND, vframe
from StaticDefs import RCVR_FREQS, DEF_ON_SYSTEMS, DEF_OFF_SYSTEMS
from StaticDefs import QD_AND_ACTIVE_SURFACE_ON_RCVRS, PFRCVRS, PF2RCV... | 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 | from copy import copy
# from ifpaths import *
# from paths import getIFPaths
from StaticDefs import IF3, IFfilters, BEAM_TO_FEED_DES, FILTERS, RCVR_IF_NOMINAL, RCVR_SIDEBAND, vframe
from StaticDefs import RCVR_FREQS, DEF_ON_SYSTEMS, DEF_OFF_SYSTEMS
from StaticDefs import QD_AND_ACTIVE_SURFACE_ON_RCVRS, PFRCVRS, PF2RCV... | (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 | from copy import copy
# from ifpaths import *
# from paths import getIFPaths
from StaticDefs import IF3, IFfilters, BEAM_TO_FEED_DES, FILTERS, RCVR_IF_NOMINAL, RCVR_SIDEBAND, vframe
from StaticDefs import RCVR_FREQS, DEF_ON_SYSTEMS, DEF_OFF_SYSTEMS
from StaticDefs import QD_AND_ACTIVE_SURFACE_ON_RCVRS, PFRCVRS, PF2RCV... |
def test9():
# Argus
# from production config_status:
# RcvrArray75_115:J10->IFRouter:J12->SWITCH2->IFXS9:thru->IFRouter:J66->OpticalDriver2:J1->OpticalDriver2:J4->DCR:A_2
# RcvrArray75_115:J11->IFRouter:J20->SWITCH3->IFXS10:thru->IFRouter:J67->OpticalDriver3:J1->OpticalDriver3:J4->DCR:A_3
pass... | "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 | '''
datautils.py: Just some routines that we use for moving data around
'''
from __future__ import print_function
import numpy as np
import librosa
import os
from os.path import isfile, splitext
from imageio import imread, imwrite
import glob
from skimage import img_as_ubyte
from random import shuffle
def listdir_no... |
# 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 |
'''
datautils.py: Just some routines that we use for moving data around
'''
from __future__ import print_function
import numpy as np
import librosa
import os
from os.path import isfile, splitext
from imageio import imread, imwrite
import glob
from skimage import img_as_ubyte
from random import shuffle
def listdir_n... | 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 |
'''
datautils.py: Just some routines that we use for moving data around
'''
from __future__ import print_function
import numpy as np
import librosa
import os
from os.path import isfile, splitext
from imageio import imread, imwrite
import glob
from skimage import img_as_ubyte
from random import shuffle
def listdir_n... | (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 |
'''
datautils.py: Just some routines that we use for moving data around
'''
from __future__ import print_function
import numpy as np
import librosa
import os
from os.path import isfile, splitext
from imageio import imread, imwrite
import glob
from skimage import img_as_ubyte
from random import shuffle
def listdir_n... |
print(" total files = ",total_files,", going to load total_load = ",total_load)
print("total files = ",total_files,", going to load total_load = ",total_load)
# pre-allocate memory for speed (old method used np.concatenate, slow)
mel_dims = get_sample_dimensions(class_names,path=path) # get d... | total_load = nearest_multiple( total_load, batch_size) | conditional_block |
lib.rs | // Copyright (C) 2019 Alibaba Cloud. All rights reserved.
// SPDX-License-Identifier: Apache-2.0 or BSD-3-Clause
//! Virtio Vhost Backend Drivers
//!
//! Virtio devices use virtqueues to transport data efficiently. The first generation of virtqueue
//! is a set of three different single-producer, single-consumer ring ... | {
/// 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 | // Copyright (C) 2019 Alibaba Cloud. All rights reserved.
// SPDX-License-Identifier: Apache-2.0 or BSD-3-Clause
//! Virtio Vhost Backend Drivers
//!
//! Virtio devices use virtqueues to transport data efficiently. The first generation of virtqueue
//! is a set of three different single-producer, single-consumer ring ... |
}
/// Result of vhost-user operations
pub type Result<T> = std::result::Result<T, Error>;
/// Result of request handler.
pub type HandlerResult<T> = std::result::Result<T, IOError>;
/// Utility function to take the first element from option of a vector of files.
/// Returns `None` if the vector contains no file or ... | {
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 | // Copyright (C) 2019 Alibaba Cloud. All rights reserved.
// SPDX-License-Identifier: Apache-2.0 or BSD-3-Clause
//! Virtio Vhost Backend Drivers
//!
//! Virtio devices use virtqueues to transport data efficiently. The first generation of virtqueue
//! is a set of three different single-producer, single-consumer ring ... |
}
}
| {
panic!("invalid error code conversion!");
} | conditional_block |
lib.rs | // Copyright (C) 2019 Alibaba Cloud. All rights reserved.
// SPDX-License-Identifier: Apache-2.0 or BSD-3-Clause
//! Virtio Vhost Backend Drivers
//!
//! Virtio devices use virtqueues to transport data efficiently. The first generation of virtqueue
//! is a set of three different single-producer, single-consumer ring ... | //! 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 | package file
import (
"os"
"bufio"
"time"
"io/ioutil"
"math/rand"
"path"
"strconv"
"sync"
"fmt"
"errors"
"encoding/binary"
"encoding/json"
"sort"
"bytes"
"io"
"strings"
"go-common/app/service/ops/log-agent/event"
"go-common/library/log"
"go-common/app/service/ops/log-agent/pkg/flowmonitor"
"github... |
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 | package file
import (
"os"
"bufio"
"time"
"io/ioutil"
"math/rand"
"path"
"strconv"
"sync"
"fmt"
"errors"
"encoding/binary"
"encoding/json"
"sort"
"bytes"
"io"
"strings"
"go-common/app/service/ops/log-agent/event"
"go-common/library/log"
"go-common/app/service/ops/log-agent/pkg/flowmonitor"
"github... |
// tailLog check the log format and get log from reader
func (f *FileCache) tailLog(rr *bufio.Reader) (b []byte, err error) {
var (
t []byte
)
// peek magic
for {
if b, err = rr.Peek(_logMagicSize); err != nil {
return
}
if bytes.Equal(b, logMagic) {
break
}
rr.Discard(1)
}
// peek length
if ... | {
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 | package file
import (
"os"
"bufio"
"time"
"io/ioutil"
"math/rand"
"path"
"strconv"
"sync"
"fmt"
"errors"
"encoding/binary"
"encoding/json"
"sort"
"bytes"
"io"
"strings"
"go-common/app/service/ops/log-agent/event"
"go-common/library/log"
"go-common/app/service/ops/log-agent/pkg/flowmonitor"
"github... | () string {
return path.Join(f.c.Storage, strconv.FormatInt(time.Now().Unix(), 10)+f.c.Suffix)
}
// nextFile set first log filename.
// sorted by name.
func (f *FileCache) nextFile() (err error) {
f.next <- f.nextFileName()
return
}
| nextFileName | identifier_name |
file.go | package file
import (
"os"
"bufio"
"time"
"io/ioutil"
"math/rand"
"path"
"strconv"
"sync"
"fmt"
"errors"
"encoding/binary"
"encoding/json"
"sort"
"bytes"
"io"
"strings"
"go-common/app/service/ops/log-agent/event"
"go-common/library/log"
"go-common/app/service/ops/log-agent/pkg/flowmonitor"
"github... | 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 | //! CLI tool to use the functions provided by the [wasmstandalone](../wasmstandalone/index.html)
//! crate.
//!
//! Reads Wasm binary files (one Wasm module per file), translates the functions' code to Cretonne
//! IL. Can also executes the `start` function of the module by laying out the memories, globals
//! and tabl... | (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 | //! CLI tool to use the functions provided by the [wasmstandalone](../wasmstandalone/index.html)
//! crate.
//!
//! Reads Wasm binary files (one Wasm module per file), translates the functions' code to Cretonne
//! IL. Can also executes the `start` function of the module by laying out the memories, globals
//! and tabl... | {
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 | //! CLI tool to use the functions provided by the [wasmstandalone](../wasmstandalone/index.html)
//! crate.
//!
//! Reads Wasm binary files (one Wasm module per file), translates the functions' code to Cretonne
//! IL. Can also executes the `start` function of the module by laying out the memories, globals
//! and tabl... | 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 | package hostpath
import (
"os"
"fmt"
"strings"
"github.com/golang/glog"
"golang.org/x/net/context"
"github.com/container-storage-interface/spec/lib/go/csi"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"k8s.io/kubernetes/pkg/util/mount"
"k8s.io/kubernetes/pkg/volume/util/volumepathhandler"... | return &csi.NodeStageVolumeResponse{}, nil
}
// NodeUnstageVolume is the reverse of NodeStageVolume. Called by Controller Orchestrator to unmount the
// volume from the staging path.
func (ns *nodeServer) NodeUnstageVolume(ctx context.Context, req *csi.NodeUnstageVolumeRequest) (*csi.NodeUnstageVolumeResponse, error)... | random_line_split | |
nodeserver.go | package hostpath
import (
"os"
"fmt"
"strings"
"github.com/golang/glog"
"golang.org/x/net/context"
"github.com/container-storage-interface/spec/lib/go/csi"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"k8s.io/kubernetes/pkg/util/mount"
"k8s.io/kubernetes/pkg/volume/util/volumepathhandler"... |
// NodeGetInfo returns the supported capabilities of the node server. This should
// eventually return the droplet ID if possible. This is sused so the Controller
// Orchestrator knows where to place the workload. The result of this function will
// be used by the Controller Orchestrator in the ControllerPublishVol... | {
// 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 | package hostpath
import (
"os"
"fmt"
"strings"
"github.com/golang/glog"
"golang.org/x/net/context"
"github.com/container-storage-interface/spec/lib/go/csi"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"k8s.io/kubernetes/pkg/util/mount"
"k8s.io/kubernetes/pkg/volume/util/volumepathhandler"... | (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()) == 0 {
return nil, status.Error(codes.InvalidArg... | NodeStageVolume | identifier_name |
nodeserver.go | package hostpath
import (
"os"
"fmt"
"strings"
"github.com/golang/glog"
"golang.org/x/net/context"
"github.com/container-storage-interface/spec/lib/go/csi"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"k8s.io/kubernetes/pkg/util/mount"
"k8s.io/kubernetes/pkg/volume/util/volumepathhandler"... |
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 | //! Interface for interacting with the Wayland protocol, server-side.
//!
//! ## General concepts
//!
//! This crate is structured around four main objects: the [`Display`] and [`DisplayHandle`] structs,
//! resources (objects implementing the [`Resource`] trait), and the [`Dispatch`] trait.
//!
//! The [`Display`] is ... | /// 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 | //! Interface for interacting with the Wayland protocol, server-side.
//!
//! ## General concepts
//!
//! This crate is structured around four main objects: the [`Display`] and [`DisplayHandle`] structs,
//! resources (objects implementing the [`Resource`] trait), and the [`Dispatch`] trait.
//!
//! The [`Display`] is ... |
}
}
}
/// A weak handle to a Wayland object
///
/// This handle does not keep the underlying user data alive, and can be converted back to a full resource
/// using [`Weak::upgrade()`].
#[derive(Debug, Clone)]
pub struct Weak<I> {
handle: WeakHandle,
id: ObjectId,
_iface: std::marker::PhantomD... | {
write!(f, "Bad message for object {interface}@{sender_id} on opcode {opcode}",)
} | conditional_block |
lib.rs | //! Interface for interacting with the Wayland protocol, server-side.
//!
//! ## General concepts
//!
//! This crate is structured around four main objects: the [`Display`] and [`DisplayHandle`] structs,
//! resources (objects implementing the [`Resource`] trait), and the [`Dispatch`] trait.
//!
//! The [`Display`] is ... | (&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 | use crate::player::{Player, Result, SlideshowConfig};
use elementtree::Element;
use failure::{format_err, Fail};
use libc;
use log::{debug, info, warn};
use reqwest;
use std::path::PathBuf;
use std::process::Child;
use std::process::Command;
use std::time::Duration;
use std::time::Instant;
use url::Url;
const VLC_VOLU... | (&self) -> bool {
match self.send_status_cmd("", &[]) {
Ok(_) => true,
Err(e) => {
debug!("Got error response while checking health of VLC: {}", e);
false
}
}
}
}
impl<C: HttpClient> Drop for VlcPlayer<C> {
fn drop(&mut self) {... | is_ok | identifier_name |
player_vlc.rs | use crate::player::{Player, Result, SlideshowConfig};
use elementtree::Element;
use failure::{format_err, Fail};
use libc;
use log::{debug, info, warn};
use reqwest;
use std::path::PathBuf;
use std::process::Child;
use std::process::Command;
use std::time::Duration;
use std::time::Instant;
use url::Url;
const VLC_VOLU... |
}
impl<C: HttpClient> Drop for VlcPlayer<C> {
fn drop(&mut self) {
if let Some(mut proc) = self.process.take() {
// Rust's Command doesn't support other than SIGKILL in portable interface
unsafe {
libc::kill(proc.id() as i32, libc::SIGTERM);
}
... | {
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 | use crate::player::{Player, Result, SlideshowConfig};
use elementtree::Element;
use failure::{format_err, Fail};
use libc;
use log::{debug, info, warn};
use reqwest;
use std::path::PathBuf;
use std::process::Child;
use std::process::Command;
use std::time::Duration;
use std::time::Instant;
use url::Url;
const VLC_VOLU... | fn dummy_bin_player<
C: Fn(&str, &HashMap<&str, &str>) -> std::result::Result<String, VlcError>,
>(
client: C,
) -> (tempfile::NamedTempFile, VlcPlayer<C>) {
let mut dummy_bin = tempfile::NamedTempFile::new().unwrap();
let file = dummy_bin.as_file_mut();
writeln!(file... | random_line_split | |
player_vlc.rs | use crate::player::{Player, Result, SlideshowConfig};
use elementtree::Element;
use failure::{format_err, Fail};
use libc;
use log::{debug, info, warn};
use reqwest;
use std::path::PathBuf;
use std::process::Child;
use std::process::Command;
use std::time::Duration;
use std::time::Instant;
use url::Url;
const VLC_VOLU... |
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::cell::{Cell, RefCell};
use std::collections::HashMap;
use std::fs;
use std::io::Write;
use std::os::unix::fs::PermissionsExt;
use tempfile;
impl<F: Fn(&str, &HashMap<&str, &str>) -> std::result::Result<String, VlcError>> HttpClie... | {
// 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 |
import { vec3 } from 'gl-matrix';
import { DeviceProgram } from '../Program.js';
import * as Viewer from '../viewer.js';
import * as UI from '../ui.js';
import * as IV from './iv.js';
import { GfxDevice, GfxBufferUsage, GfxBuffer, GfxFormat, GfxInputLayout, GfxProgram, GfxBindingLayoutDescriptor, GfxVertexBufferFreq... |
public destroy(device: GfxDevice): void {
device.destroyProgram(this.program);
this.ivRenderers.forEach((r) => r.destroy(device));
this.renderHelper.destroy();
}
public createPanels(): UI.Panel[] {
const layersPanel = new UI.LayerPanel();
layersPanel.setLayers(this... | {
const renderInstManager = this.renderHelper.renderInstManager;
const mainColorDesc = makeBackbufferDescSimple(GfxrAttachmentSlot.Color0, viewerInput, standardFullClearRenderPassDescriptor);
const mainDepthDesc = makeBackbufferDescSimple(GfxrAttachmentSlot.DepthStencil, viewerInput, standardFu... | identifier_body |
render.ts | import { vec3 } from 'gl-matrix';
import { DeviceProgram } from '../Program.js';
import * as Viewer from '../viewer.js';
import * as UI from '../ui.js';
import * as IV from './iv.js';
import { GfxDevice, GfxBufferUsage, GfxBuffer, GfxFormat, GfxInputLayout, GfxProgram, GfxBindingLayoutDescriptor, GfxVertexBufferFrequ... | 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 |
import { vec3 } from 'gl-matrix';
import { DeviceProgram } from '../Program.js';
import * as Viewer from '../viewer.js';
import * as UI from '../ui.js';
import * as IV from './iv.js';
import { GfxDevice, GfxBufferUsage, GfxBuffer, GfxFormat, GfxInputLayout, GfxProgram, GfxBindingLayoutDescriptor, GfxVertexBufferFreq... | (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 | define(function (require, exports, module) {
var echarts = require('echarts');
var template = require('art-template');
/**
* 将阿拉拍数字转化为汉字(1-10)
* @param number
*/
template.defaults.imports.toChineseCharacter = function (number) {
var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var characters = ['... | var fullScore = 5;
var count = 0;
var result = '<div class="score-star"></div>';
var $result = $(result);
if (typeof score !== 'number') {
console.error('分数必须是数字')
} else {
var intScore = parseInt(score);
//是否有半分
var halfFlag = score > intScore;
for (var i = 0; i < ... | 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 | define(function (require, exports, module) {
var echarts = require('echarts');
var template = require('art-template');
/**
* 将阿拉拍数字转化为汉字(1-10)
* @param number
*/
template.defaults.imports.toChineseCharacter = function (number) {
var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var characters = ['... | 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 | define(function (require, exports, module) {
var echarts = require('echarts');
var template = require('art-template');
/**
* 将阿拉拍数字转化为汉字(1-10)
* @param number
*/
template.defaults.imports.toChineseCharacter = function (number) {
var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var characters = ['... | 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 | define(function (require, exports, module) {
var echarts = require('echarts');
var template = require('art-template');
/**
* 将阿拉拍数字转化为汉字(1-10)
* @param number
*/
template.defaults.imports.toChineseCharacter = function (number) {
var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var characters = ['... | }
},
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 |
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
from scipy import stats as st
import matplotlib.mlab as mlab
from Bio import SeqUtils
from Bio.SeqUtils import ProtParamData
import math
from mpl_toolkits.axes_grid1 import make_axes_locatable
import matplotlib as mpl
import collections
# EMPIRI... | (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 |
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
from scipy import stats as st
import matplotlib.mlab as mlab
from Bio import SeqUtils
from Bio.SeqUtils import ProtParamData
import math
from mpl_toolkits.axes_grid1 import make_axes_locatable
import matplotlib as mpl
import collections
# EMPIRI... |
#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 |
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
from scipy import stats as st
import matplotlib.mlab as mlab
from Bio import SeqUtils
from Bio.SeqUtils import ProtParamData
import math
from mpl_toolkits.axes_grid1 import make_axes_locatable
import matplotlib as mpl
import collections
# EMPIRI... |
#
# now merge components to lib_dat as well ...
# merge PC table to lib_dat as well ...
merged_dat = merged_dat.merge( pd.DataFrame(PC_dict,index=merged_dat['organism-pos']), left_on='organism-pos', right_index=True )
# add more columns to the merged_dat ...
# get average fitness per position, ... | print pc,'%.1f%%'%var_dict[pc] | conditional_block |
EMPIRIC_analysis_EXP.py | import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
from scipy import stats as st
import matplotlib.mlab as mlab
from Bio import SeqUtils
from Bio.SeqUtils import ProtParamData
import math
from mpl_toolkits.axes_grid1 import make_axes_locatable
import matplotlib as mpl | 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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.