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
tgsrv.go
tgbotapi.Chat json.Unmarshal(b, &chat) if chat != nil { subs := usersub("", chat.ID, true) cmds := subs2cmds(subs) var txt = strings.Replace(params.SubsHelp, "channelname", chanName, -1) + "\n\nList of urls of @" + chanName + ":\n\n" for _, v := range cmds { ...
json.Unmarshal(body, &channels) for _, channel := range channels { cmds["channel_!_delete_!_"+channel.UserName] = "delete @" + channel.UserName cmds["channel_!_list_!_"+channel.UserName] = "list of urls of @" + channel.UserName } msg := tgbotapi.NewMessage(update.Message.Chat.ID, "Instruction...
random_line_split
tgsrv.go
s...) return buttonsRow } func userNew(user *tgbotapi.User) bool { urlUsr := params.Users + strconv.Itoa(user.ID) log.Println("userNew", urlUsr) b, _ := json.Marshal(user) httputils.HttpPut(params.UserName+user.UserName, nil, b) res := httputils.HttpPut(urlUsr, nil, b) //telefeedbot if user.ID > 0 { pubSubT...
ext string
identifier_name
cfg.rs
} bail!("Did not find valid configuration!"); } #[allow(dead_code)] pub fn dummy_host_str() -> &'static str { include_str!("dummy_host.yml") } #[allow(dead_code)] pub fn dummy_host() -> Host { Host::from_yaml( "dummy_host".to_string(), &YamlLoader::load_from_str(dummy_host_str()).unwra...
bail! {"Prefix needs to be between 8 and 128 characters."};
random_line_split
cfg.rs
8, /// Compute hash on remote side after upload to verify. pub verify_via_hash: bool, } /// Authentication configuration #[derive(Debug, Clone)] pub struct Auth { /// Try to use auth information for the given host from openssh settings pub from_openssh: bool, /// Perform interactive authenticatio...
} impl Config { pub fn load<T: AsRef<str> + Display>(dir: T) -> Result<Option<Config>> { let config_dir = match expanduser(dir.as_ref()) { Ok(p) => p, Err(e) => { bail!("Error when expanding path to config file: {}", e); } }; let global =...
{ Config { auth: Auth::default(), default_host: None, expire: None, hosts: HashMap::new(), prefix_length: 32, verify_via_hash: true, } }
identifier_body
cfg.rs
8, /// Compute hash on remote side after upload to verify. pub verify_via_hash: bool, } /// Authentication configuration #[derive(Debug, Clone)] pub struct Auth { /// Try to use auth information for the given host from openssh settings pub from_openssh: bool, /// Perform interactive authenticatio...
(alias: String, input: &Yaml) -> Result<Host> { Self::from_yaml_with_config(alias, input, &Config::default()) } fn from_yaml_with_config(alias: String, input: &Yaml, config: &Config) -> Result<Host> { log::trace!("Reading host: {}", alias); if let Yaml::Hash(dict) = input { ...
from_yaml
identifier_name
error.rs
2n_status_code::SUCCESS { Ok(self) } else { Err(Error::capture()) } } } impl Fallible for isize { type Output = usize; fn into_result(self) -> Result<Self::Output, Error> { // Negative values can't be converted to a real size // and instead indicate ...
match self.0 { Context::InvalidInput | Context::MissingWaker => ErrorType::UsageError, Context::Application(_) => ErrorType::Application, Context::Code(code, _) => unsafe { ErrorType::from(s2n_error_get_type(code)) }, } } pub fn source(&self) -> ErrorSource {...
pub fn kind(&self) -> ErrorType {
random_line_split
error.rs
} enum Context { InvalidInput, MissingWaker, Code(s2n_status_code::Type, Errno), Application(Box<dyn std::error::Error + Send + Sync + 'static>), } pub struct Error(Context); pub trait Fallible { type Output; fn into_result(self) -> Result<Self::Output, Error>; } impl Fallible for s2n_stat...
{ match input as s2n_error_type::Type { s2n_error_type::OK => ErrorType::NoError, s2n_error_type::IO => ErrorType::IOError, s2n_error_type::CLOSED => ErrorType::ConnectionClosed, s2n_error_type::BLOCKED => ErrorType::Blocked, s2n_error_type::ALERT => E...
identifier_body
error.rs
2n_status_code::SUCCESS { Ok(self) } else { Err(Error::capture()) } } } impl Fallible for isize { type Output = usize; fn into_result(self) -> Result<Self::Output, Error> { // Negative values can't be converted to a real size // and instead indicate ...
(&self) -> bool { matches!(self.kind(), ErrorType::Blocked) } } #[cfg(feature = "quic")] impl Error { /// s2n-tls does not send specific errors. /// /// However, we can attempt to map local errors into the alerts /// that we would have sent if we sent alerts. /// /// This API is cur...
is_retryable
identifier_name
_utils.py
class Subscriptable(Generic[U, V]): """ Decorator to make a subscriptable instance from a __getitem__ function Usage: @Subscriptable def my_subscriptable(key): return key assert my_subscriptable[8] == 8 """ __slots__ = ("_func",) def __init__(self, func: Ca...
""" Mixin class to make a class non-heritable and non-instanciable """ __slots__ = ("__weakref__",) def __init__(self): raise TypeError("Cannot instanciate virtual class") def __init_subclass__(cls, *args, **kwargs): if Virtual not in cls.__bases__: raise TypeError("Ca...
identifier_body
_utils.py
indentation of the first non-empty line is removed from all lines if possible. This allows better indentation when used as a decorator. Unused empty lines means initial enpty lines for ``pre``, and final empty lines for ``post``. Arguments: docstring: replaces the docstring of the object ...
: """ Descriptor for class properties """ __slots__ = ("fget", "fset") def __init__( self, fget: Union[classmethod, staticmethod], fset: Union[classmethod, staticmethod] = None, ): self.fget = fget self.fset = fset def __get__(self, obj: U, cls: Typ...
ClassPropertyDescriptor
identifier_name
_utils.py
indentation of the first non-empty line is removed from all lines if possible. This allows better indentation when used as a decorator. Unused empty lines means initial enpty lines for ``pre``, and final empty lines for ``post``. Arguments: docstring: replaces the docstring of the object ...
) def _sig_to_def(sig: inspect.Signature) -> str: return str(sig).split("->", 1)[0].strip()[1:-1] def _sig_to_call(sig: inspect.Signature) -> str: l = [] for p in sig.parameters.values(): if p.kind is inspect.Parameter.KEYWORD_ONLY: l.append(f"{p.name}={p.name}") else: ...
random_line_split
_utils.py
_)(value) @property def __isabstractmethod__(self): return any( getattr(f, "__isabstractmethod__", False) for f in (self.fget, self.fset) ) def setter(self, func): if not isinstance(func, (classmethod, staticmethod)): func = classmethod(func) self.fs...
try: index = next(i for i, l in enumerate(doc) if l.strip()) doc = doc[index:] except StopIteration: doc = []
conditional_block
monotone_stack.go
/) - [2104. 子数组范围和](https://leetcode.cn/problems/sum-of-subarray-ranges/) - [2281. 巫师的总力量和](https://leetcode.cn/problems/sum-of-total-strength-of-wizards/) - [2818. 操作使得分最大](https://leetcode.cn/problems/apply-operations-to-maximize-score/) 模板题 https://www.luogu.com.cn/problem/P5788 https://www.luogu.com.cn/problem/P28...
} for i, v := range a { sz := right[i] - left[i] - 1 if v > ans
for i := range right { right[i] = n } st := []int{-1} for i, v := range a { for len(st) > 1 && a[st[len(st)-1]] >= v { // 这里是 right 小于等于 right[st[len(st)-1]] = i st = st[:len(st)-1] } left[i] = st[len(st)-1] st = append(st, i) } } // EXTRA: 求所有长为 i 的子区间的最小值的最大值 // https://codeforces....
identifier_body
monotone_stack.go
/) - [2104. 子数组范围和](https://leetcode.cn/problems/sum-of-subarray-ranges/) - [2281. 巫师的总力量和](https://leetcode.cn/problems/sum-of-total-strength-of-wizards/) - [2818. 操作使得分最大](https://leetcode.cn/problems/apply-operations-to-maximize-score/) 模板题 https://www.luogu.com.cn/problem/P5788 https://www.luogu.com.cn/problem/P28...
} { // TIPS: 如果有一侧定义成小于等于,还可以一次遍历求出 left 和 right left := make([]int, n) right := make([]int, n) for i := range right { right[i] = n } st := []int{-1} for i, v := range a { for len(st) > 1 && a[st[len(st)-1]] >= v { // 这里是 right 小于等于 right[st[len(st)-1]] = i st = st[:len(st)-1] } lef...
tot := (i - left[i]) * (right[i] - i) _ = tot //tot := (sum[r] + mod - sum[l]) % mod
random_line_split
monotone_stack.go
} } // EXTRA: 求所有长为 i 的子区间的最小值的最大值 // https://codeforces.com/problemset/problem/547/B LC1950 https://leetcode-cn.com/problems/maximum-of-minimum-values-in-all-subarrays/ { ans := make([]int, n+1) for i := range ans { ans[i] = -2e9 } for i, v := range a { sz := right[i] - left[i] - 1 if v > ans[s...
identifier_name
monotone_stack.go
int, n) for i := range right { right[i] = n } st := []int{-1} for i, v := range a { for len(st) > 1 && a[st[len(st)-1]] >= v { // 这里是 right 小于等于 right[st[len(st)-1]] = i st = st[:len(st)-1] } left[i] = st[len(st)-1] st = append(st, i) } } // EXTRA: 求所有长为 i 的子区间的最小值的最大值 // https://co...
, int) { n := len(a) sum := make([]int, n+1) st := []int{0} for j, v := range a { j++ sum[j] = sum[j-1] + v if sum[j] < sum[st[len(st)-1]] { st = append(st, j)
conditional_block
constants.rs
= -76; // end-of-error-codes pub const UNQLITE_CONFIG_JX9_ERR_LOG: c_int = 1; pub const UNQLITE_CONFIG_MAX_PAGE_CACHE: c_int = 2; pub const UNQLITE_CONFIG_ERR_LOG: c_int = 3; pub const UNQLITE_CONFIG_KV_ENGINE: c_int = 4; pub const UNQLITE_CONFIG_DISABLE_AUTO_COMMIT: c_int = 5; pub const UNQLITE_CONFIG_GET_KV_NAME: c...
random_line_split
segment.pb.go
// road classes are based on OpenStreetMap usage of the "highway" tag. // each value of the enumeration corresponds to one value of the tag, // except for ClassServiceOther, which is used for service and other roads. type Segment_RoadClass int32 const ( Segment_ClassMotorway Segment_RoadClass = 0 Segment_ClassT...
// This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.GoGoProtoPackageIsVersion2 // please upgrade the proto pack...
random_line_split
segment.pb.go
) String() string { return proto.EnumName(Segment_FormOfWay_name, int32(x)) } func (x *Segment_FormOfWay) UnmarshalJSON(data []byte) error { value, err := proto.UnmarshalJSONEnum(Segment_FormOfWay_value, data, "Segment_FormOfWay") if err != nil { return err } *x = Segment_FormOfWay(value) return nil } func (Seg...
func (*Segment) Descriptor() ([]byte, []int) { return fileDescriptorSegment, []int{0} } func (m *Segment) GetLrps() []*Segment_LocationReference { if m != nil { return m.Lrps } return nil } type Segment_LatLng struct { // lat & lng in EPSG:4326 multiplied by 10^7 and rounded to the nearest // integer. this gi...
{}
identifier_body
segment.pb.go
) String() string { return proto.EnumName(Segment_FormOfWay_name, int32(x)) } func (x *Segment_FormOfWay) UnmarshalJSON(data []byte) error { value, err := proto.UnmarshalJSONEnum(Segment_FormOfWay_value, data, "Segment_FormOfWay") if err != nil { return err } *x = Segment_FormOfWay(value) return nil } func (Seg...
() ([]byte, []int) { return fileDescriptorSegment, []int{0} } func (m *Segment) GetLrps() []*Segment_LocationReference { if m != nil { return m.Lrps } return nil } type Segment_LatLng struct { // lat & lng in EPSG:4326 multiplied by 10^7 and rounded to the nearest // integer. this gives a precision of about 1....
Descriptor
identifier_name
segment.pb.go
) String() string { return proto.EnumName(Segment_FormOfWay_name, int32(x)) } func (x *Segment_FormOfWay) UnmarshalJSON(data []byte) error { value, err := proto.UnmarshalJSONEnum(Segment_FormOfWay_value, data, "Segment_FormOfWay") if err != nil { return err } *x = Segment_FormOfWay(value) return nil } func (Seg...
return nil } type Segment_LatLng struct { // lat & lng in EPSG:4326 multiplied by 10^7 and rounded to the nearest // integer. this gives a precision of about 1.1cm (7/16ths of an inch) // worst case at the equator. Lat *int32 `protobuf:"fixed32,1,opt,name=lat" json:"lat,omitempty"` Lng ...
{ return m.Lrps }
conditional_block
table-form.component.ts
Length); c.revStr = `${c.tipInfo} ${this._calTotalFiled[c.field]} ${c.tipInfoType}`; } } // tab头点击 tabClick(data: any): void { // 不要用 this.tabResultFun.emit(data); setTimeout( () => { if (this.updateHeader) { if (!this._columns) { this.getUserColumns...
conditional_block
table-form.component.ts
Input() paginationRef: TemplateRef<any>; @Input() tdTemplate:TemplateRef<any>; @Input() set pageSizeOptions(val: number[]) { // 页码自定义 this._pageSizeOptions = val; } get pageSizeOptions() { return this._pageSizeOptions; } @Input() colSet = true; // 列表设置是否显示 @Input() isResetFilter: boolean; // 是否对...
refreshStatus(); } @Input() popData: any; @Input() popTableData: any = []; @Input() searchParamFiled: any; // pop弹框调接口要传的参数名 @Input() searchParamFiledNot: any; // pop弹框调接口要传的参数名不必传 {eName:ttrue},格式 @Input() tableTitle: string|TemplateRef<void>; // 表格标题 @Input() tableFooter: string|TemplateRef<void>; // 表格...
{ //用于初始化表格中存在已选数据,选中条数的变化,想触发必须更改成不同值 this.
identifier_body
table-form.component.ts
]) ]) ]*/ }) export class TableFormComponent implements OnInit,OnDestroy { // tempfindSet: any = { "parameter": "companyName", "parameterSend": "companyId", "name": "发票抬头", "formId": "company_pop" }; // 数据弹框传入参数配置格式 @ViewChild('nzTable') nzTableComponent: NzTableComponent; private gloPageSub: Subscri...
style({opacity:0,height:0,transform:'translate(30px,0)'}), animate('0.3s ease-in',style({opacity:1,height:'auto',transform:'translate(0,0)',background:'#fffeee'})) ]), transition(':leave',[ animate('0.3s ease-out',style({opacity:0,height:0,transform:'translate(30px,0)'}))
random_line_split
table-form.component.ts
Input() paginationRef: TemplateRef<any>; @Input() tdTemplate:TemplateRef<any>; @Input() set pageSizeOptions(val: number[]) { // 页码自定义 this._pageSizeOptions = val; } get pageSizeOptions() { return this._pageSizeOptions; } @Input() colSet = true; // 列表设置是否显示 @Input() isResetFilter: boolean; // 是否对...
} @Input() popData: any; @Input() popTableData: any = []; @Input() searchParamFiled: any; // pop弹框调接口要传的参数名 @Input() searchParamFiledNot: any; // pop弹框调接口要传的参数名不必传 {eName:ttrue},格式 @Input() tableTitle: string|TemplateRef<void>; // 表格标题 @Input() tableFooter: string|TemplateRef<void>; // 表格尾部 @Input() se...
Status();
identifier_name
itemUpdates.ts
.ts data, etc. * * To limit the hack, this should only be accessed from the proxy back-end, not * from the Electron front-end. */ let localItems = _.clone(items); export const localItemsById = _.zipObject( items.map((i) => i.id), localItems, ); interface PrizeItem { type_name: schemas.ItemTypeName; name: s...
(item: PrizeItem) { if (item.type_name === 'BEAST') { checkKnownEnlir(item, enlir.magicites); } else if (item.type_name === 'EQUIPMENT') { checkKnownEnlir(item, enlir.relics, enlir.heroArtifacts); } else if (item.type_name === 'ABILITY') { checkKnownEnlir(item, enlir.abilities); } else if ( item...
checkItem
identifier_name
itemUpdates.ts
data, etc. * * To limit the hack, this should only be accessed from the proxy back-end, not * from the Electron front-end. */ let localItems = _.clone(items); export const localItemsById = _.zipObject( items.map((i) => i.id), localItems, ); interface PrizeItem { type_name: schemas.ItemTypeName; name: stri...
function checkKnownDressRecord(item: PrizeItem) { if (dressRecordsById[item.id] == null) { const match = item.image_path.match(/(\d+)\/\d+\/\d+\.png/); const buddyId = match ? +match[1] : 0; showLocalDressRecord({ dress_record_id: item.id, name: item.name, buddy_id: buddyId }); } } function checkKnow...
{ if (_.every(enlirData, (i) => i[item.id] == null)) { showUnknownItem(item); } }
identifier_body
itemUpdates.ts
.info( 'New (previously unknown) item:\n' + `{\n name: "${item.name}",\n type: ItemType.${type},\n id: ${item.id}\n},`, ); } function showLocalDressRecord({ dress_record_id, name, buddy_id, }: { dress_record_id: number; name: string; buddy_id: number; }) { logger.info( 'New (previously...
showUpdateCommands(checkedLegendMateria, 'legendMateria', callback); } function getGachaShowEquipment(data: gachaSchemas.GachaShow, currentTime: number) { const equipmentList: equipmentSchemas.Equipment[] = [];
random_line_split
goog-varint.ts
) { this.assertBounds(); return [lowBits, highBits]; } } let middleByte = this.buf[this.pos++]; // last four bits of the first 32 bit number lowBits |= (middleByte & 0x0F) << 28; // 3 upper bits are part of the next 32 bit number highBits = (middleByte & 0x70) ...
{ if (value >= 0) { // write value as varint 32 while (value > 0x7f) { bytes.push((value & 0x7f) | 0x80); value = value >>> 7; } bytes.push(value); } else { for (let i = 0; i < 9; i++) { bytes.push(value & 127 | 128); value ...
identifier_body
goog-varint.ts
. // // Code generated by the Protocol Buffer compiler is owned by the owner // of the input file used when generating it. This code is not // standalone and requires a support library to be linked with it. This // support library is itself covered by the above license. /** * Read a 64 bit varint as two JS numbers...
// constants for binary math const TWO_PWR_32_DBL = (1 << 16) * (1 << 16); /** * Parse decimal string of 64 bit integer value as two JS numbers. * * Returns tuple: * [0]: minus sign? * [1]: low bits * [2]: high bits * * Copyright 2008 Google Inc. */ export function int64fromString(dec: string): [boolean, num...
bytes.push((hi >>> 31) & 0x01); }
random_line_split
goog-varint.ts
. // // Code generated by the Protocol Buffer compiler is owned by the owner // of the input file used when generating it. This code is not // standalone and requires a support library to be linked with it. This // support library is itself covered by the above license. /** * Read a 64 bit varint as two JS numbers...
(lo: number, hi: number, bytes: number[]): void { for (let i = 0; i < 28; i = i + 7) { const shift = lo >>> i; const hasNext = !((shift >>> 7) == 0 && hi == 0); const byte = (hasNext ? shift | 0x80 : shift) & 0xFF; bytes.push(byte); if (!hasNext) { return; ...
varint64write
identifier_name
goog-varint.ts
// // Code generated by the Protocol Buffer compiler is owned by the owner // of the input file used when generating it. This code is not // standalone and requires a support library to be linked with it. This // support library is itself covered by the above license. /** * Read a 64 bit varint as two JS numbers. ...
} bytes.push((hi >>> 31) & 0x01); } // constants for binary math const TWO_PWR_32_DBL = (1 << 16) * (1 << 16); /** * Parse decimal string of 64 bit integer value as two JS numbers. * * Returns tuple: * [0]: minus sign? * [1]: low bits * [2]: high bits * * Copyright 2008 Google Inc. */ export funct...
{ return; }
conditional_block
daemon.go
func (c *Command) canAccess(r *http.Request, user *userState) accessResult { if c.AdminOnly && (c.UserOK || c.GuestOK || c.UntrustedOK) { logger.Panicf("internal error: command cannot have AdminOnly together with any *OK flag") } if user != nil && !c.AdminOnly { // Authenticated users do anything not requiring ...
else { logger.Noticef("%s %s %s %s %d", r.RemoteAddr, r.Method, r.URL, t, ww.s) } } }) } // Init sets up the Daemon's internal workings. // Don't call more than once. func (d *Daemon) Init() error { listenerMap := make(map[string]net.Listener) if listener, err := getListener(d.normalSocketPath, listenerM...
{ logger.Debugf("%s %s %s %s %d", r.RemoteAddr, r.Method, r.URL, t, ww.s) logger.Noticef("%s %s %s %d", r.Method, r.URL, t, ww.s) }
conditional_block
daemon.go
OK { return accessOK } return accessUnauthorized } // the !AdminOnly check is redundant, but belt-and-suspenders if r.Method == "GET" && !c.AdminOnly { // Guest and user access restricted to GET requests if c.GuestOK { return accessOK } if isUser && c.UserOK { return accessOK } } // Remai...
{ // die when asked to restart (systemd should get us back up!) etc switch t { case state.RestartDaemon: case state.RestartSystem: // try to schedule a fallback slow reboot already here // in case we get stuck shutting down if err := reboot(rebootWaitTimeout); err != nil { logger.Noticef("%s", err) } ...
identifier_body
daemon.go
r) t := time.Now().Sub(t0) if !strings.Contains(r.URL.String(), "/v1/changes/") { if strings.HasSuffix(r.RemoteAddr, ";") { logger.Debugf("%s %s %s %s %d", r.RemoteAddr, r.Method, r.URL, t, ww.s) logger.Noticef("%s %s %s %d", r.Method, r.URL, t, ww.s) } else { logger.Noticef("%s %s %s %s %d", r.R...
random_line_split
daemon.go
func (c *Command) canAccess(r *http.Request, user *userState) accessResult { if c.AdminOnly && (c.UserOK || c.GuestOK || c.UntrustedOK) { logger.Panicf("internal error: command cannot have AdminOnly together with any *OK flag") } if user != nil && !c.AdminOnly { // Authenticated users do anything not requiring ...
(err error) { d.degradedErr = err } func (d *Daemon) addRoutes() { d.router = mux.NewRouter() for _, c := range api { c.d = d if c.PathPrefix == "" { d.router.Handle(c.Path, c).Name(c.Path) } else { d.router.PathPrefix(c.PathPrefix).Handler(c).Name(c.PathPrefix) } } // also maybe add a /favicon.ic...
SetDegradedMode
identifier_name
base.py
=subprocess.PIPE) output, errors = p.communicate() if errors: # Not currently logged in p = subprocess.Popen(["azure", "login"], stderr=subprocess.PIPE) output, errors = p.communicate() if errors: return "Failed to login: " + errors.decode("utf-8") return "Logged in to A...
(self, cmd): """ Execute a command on the client in a bash shell. """ self.log.debug("Executing command in shell: " + str(cmd)) dcos_config = os.path.expanduser('~/.dcos/dcos.toml') os.environ['PATH'] = ':'.join([os.getenv('PATH'), '/src/bin']) os.environ['DCOS_CONFIG'] = dcos_config os.makedir...
shell_execute
identifier_name
base.py
stderr=subprocess.PIPE) output, errors = p.communicate() if errors: # Not currently logged in p = subprocess.Popen(["azure", "login"], stderr=subprocess.PIPE) output, errors = p.communicate() if errors: return "Failed to login: " + errors.decode("utf-8") return "Logged ...
elif name == "publickey": self.log.debug("Checking if public SSH key exists: " + public_filepath) if not os.path.isfile(public_filepath): self._generateSSHKey(private_filepath, public_filepath) with open(public_filepath, 'r') as sshfile: value = sshfile.read().replac...
self.log.debug("Checking if private SSH key exists: " + private_filepath) if not os.path.isfile(private_filepath): self.log.debug("Key does not exist") self._generateSSHKey(private_filepath, public_filepath) with open(private_filepath, 'r') as sshfile: self.log.debug("Key ...
conditional_block
base.py
stderr=subprocess.PIPE) output, errors = p.communicate() if errors: # Not currently logged in p = subprocess.Popen(["azure", "login"], stderr=subprocess.PIPE) output, errors = p.communicate() if errors: return "Failed to login: " + errors.decode("utf-8") return "Logged ...
def shell_execute(self, cmd): """ Execute a command on the client in a bash shell. """ self.log.debug("Executing command in shell: " + str(cmd)) dcos_config = os.path.expanduser('~/.dcos/dcos.toml') os.environ['PATH'] = ':'.join([os.getenv('PATH'), '/src/bin']) os.environ['DCOS_CONFIG'] = dcos_co...
random_line_split
base.py
=subprocess.PIPE) output, errors = p.communicate() if errors: # Not currently logged in p = subprocess.Popen(["azure", "login"], stderr=subprocess.PIPE) output, errors = p.communicate() if errors: return "Failed to login: " + errors.decode("utf-8") return "Logged in to A...
def run(self): raise NotImplementedError("You must implement the run() method in your commands") def help(self): raise NotImplementedError("You must implement the help method. In most cases you will simply do 'print(__doc__)'") def getAgentIPs(self): # return a list of Agent IPs in this cluster ...
self.log.debug("Creating Resource Group") command = "azure group create " + self.config.get('Group', 'name') + " " + self.config.get('Group', 'region') os.system(command)
identifier_body
fetch.rs
#[derive(Debug)] struct State { offset: u64, eof: u32, last_line: Vec<u8>, last_request: Instant, } #[derive(Debug)] struct Cursor { url: Arc<Url>, state: Option<State>, } struct Requests { cursors: VecDeque<Arc<Mutex<Cursor>>>, timeout: Timeout, } #[derive(Debug)] pub struct Request ...
#[cfg(feature="tls_rustls")] use webpki_roots;
random_line_split
fetch.rs
Cursor>>, range: Option<(u64, u64, u64)>, } pub fn group_addrs(vec: Vec<(Address, Vec<Arc<Url>>)>) -> HashMap<SocketAddr, Vec<Arc<Url>>> { let mut urls_by_ip = HashMap::new(); for (addr, urls) in vec { for sa in addr.addresses_at(0) { let set = urls_by_ip.entry(sa) ....
"/etc/ssl/certs/ca-certificates.crt", e); } } cfg.root_store.add_server_trust_anchors( &webpki_roots::TLS_SERVER_ROOTS); cfg }); let cfg = Config::new().done(); return Box::new( join_all(urls_by_host.into_iter().map(move |(host, lis...
{ use std::io::BufReader; use std::fs::File; if urls_by_host.len() == 0 { return Box::new(ok(())); } let resolver = resolver.clone(); let tls = Arc::new({ let mut cfg = ClientConfig::new(); let read_root = File::open("/etc/ssl/certs/ca-certificates.crt") .map...
identifier_body
fetch.rs
Cursor>>, range: Option<(u64, u64, u64)>, } pub fn group_addrs(vec: Vec<(Address, Vec<Arc<Url>>)>) -> HashMap<SocketAddr, Vec<Arc<Url>>> { let mut urls_by_ip = HashMap::new(); for (addr, urls) in vec { for sa in addr.addresses_at(0) { let set = urls_by_ip.entry(sa) ....
(resolver: &Router, urls_by_host: HashMap<String, Vec<Arc<Url>>>) -> Box<Future<Item=(), Error=()>> { let resolver = resolver.clone(); let cfg = Config::new() .keep_alive_timeout(Duration::new(25, 0)) .done(); return Box::new( join_all(urls_by_host.into_iter().map(move |(host, li...
http
identifier_name
dyn_cor_rel.py
, by, rg): s_c = s[..., np.newaxis] l_by_rg = np.array([[1, 1, 1], [1/3, 1/3, -2/3], [1, -1, 0]] ) l_by_rg = (l_by_rg/((l_by_rg**2).sum(1, keepdims=True)**0.5)) rgb = l_by_rg[0]*lum + l_by_rg[1]*by + l_by_rg[2]*rg s_c = s_c*rgb[np.newaxis,np.ne...
u1, u2 = ranks.index.values[ind] inds.append([u1,u2]) plt.scatter(df['dyn'][u1,u2], df['cor'][u1,u2]**2, s=10, c='r');plt.semilogx(); #%% j=0 plt.figure(figsize=(3,8)) for ind in inds: u1, u2 = ind u1r = (da_sig.isel(unit=u1, sf=sf_ind).squeeze()**2).sum('phase')**0.5 u2r = (da_sig.isel(unit=...
random_line_split
dyn_cor_rel.py
, by, rg): s_c = s[..., np.newaxis] l_by_rg = np.array([[1, 1, 1], [1/3, 1/3, -2/3], [1, -1, 0]] ) l_by_rg = (l_by_rg/((l_by_rg**2).sum(1, keepdims=True)**0.5)) rgb = l_by_rg[0]*lum + l_by_rg[1]*by + l_by_rg[2]*rg s_c = s_c*rgb[np.newaxis,np.ne...
if by2 is None: by2 = by if rg2 is None: rg2 = rg s1 = sine_chrom(nx, ny, x_0, y_0, sf, ori, phase, lum, by, rg, bg=0) s2 = sine_chrom(nx, ny, x_0, y_0, sf2, ori+rel_ori, phase2, lum2, by2, rg2) s = s1+s2 if make_window: w = window(radius, x_0, y_0,...
lum2 = lum
conditional_block
dyn_cor_rel.py
(radius, x_0, y_0, nx, ny): x_coords = np.arange(0, nx, dtype=np.float128) - x_0 y_coords = np.arange(0, ny, dtype=np.float128) - y_0 xx, yy = np.meshgrid(x_coords, y_coords) d = (xx**2 + yy**2)**0.5 w = np.zeros((int(nx), int(ny))) w[d<=radius] = 1 return w def cos_window(radius, x_0, y_0,...
window
identifier_name
dyn_cor_rel.py
def window(radius, x_0, y_0, nx, ny): x_coords = np.arange(0, nx, dtype=np.float128) - x_0 y_coords = np.arange(0, ny, dtype=np.float128) - y_0 xx, yy = np.meshgrid(x_coords, y_coords) d = (xx**2 + yy**2)**0.5 w = np.zeros((int(nx), int(ny))) w[d<=radius] = 1 return w def cos_window(radiu...
x_coords = np.arange(0, nx, dtype=np.float64) - x_0 y_coords = np.arange(0, ny, dtype=np.float64) - y_0 xx, yy = np.meshgrid(x_coords, y_coords) mu_0, nu_0 = pol2cart(sf, np.deg2rad(ori + 90)) s = np.sin(2*np.pi*(mu_0*xx + nu_0*yy) + np.deg2rad(phase + 90)) s = s + bg return s
identifier_body
Run_all_models_modified.py
.linear_model import PassiveAggressiveClassifier from sklearn.naive_bayes import BernoulliNB from sklearn.naive_bayes import ComplementNB from sklearn.naive_bayes import MultinomialNB from sklearn.neighbors import KNeighborsClassifier from sklearn.neighbors import NearestCentroid from sklearn.pipeline import Pipeline f...
#============================================================================ # Benchmark classifiers #============================================================================ def benchmark(clf): print('_' * 80) print("Starting training: ") print(clf) init_time = time() clf.fit(X_train, y_t...
return s if len(s) <= 80 else s[:77] + "..."
identifier_body
Run_all_models_modified.py
.linear_model import PassiveAggressiveClassifier from sklearn.naive_bayes import BernoulliNB from sklearn.naive_bayes import ComplementNB from sklearn.naive_bayes import MultinomialNB from sklearn.neighbors import KNeighborsClassifier from sklearn.neighbors import NearestCentroid from sklearn.pipeline import Pipeline f...
if names_of_features: names_of_features = np.asarray(names_of_features) def trim(s): return s if len(s) <= 80 else s[:77] + "..." #============================================================================ # Benchmark classifiers #==========================================================================...
names_of_features = vectorizer.get_feature_names()
conditional_block
Run_all_models_modified.py
.linear_model import PassiveAggressiveClassifier from sklearn.naive_bayes import BernoulliNB from sklearn.naive_bayes import ComplementNB from sklearn.naive_bayes import MultinomialNB from sklearn.neighbors import KNeighborsClassifier from sklearn.neighbors import NearestCentroid from sklearn.pipeline import Pipeline f...
(object): def __init__(self, **kwargs): self.__dict__.update(kwargs) # output logs to stdout logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)s %(message)s') # show how to call hashing function op = OptionParser() op.add_option("--use_hashing", acti...
Bunch
identifier_name
Run_all_models_modified.py
from sklearn.feature_selection import SelectFromModel from sklearn.feature_selection import SelectKBest from sklearn.linear_model import RidgeClassifier from sklearn.linear_model import SGDClassifier from sklearn.linear_model import Perceptron from sklearn.linear_model import PassiveAggressiveClassifier from sklearn.na...
from sklearn.feature_extraction.text import HashingVectorizer
random_line_split
pod_helper.go
} } // Important considerations. // Pending Status in Pod could be for various reasons and sometimes could signal a problem // Case I: Pending because the Image pull is failing and it is backing off // This could be transient. So we can actually rely on the failure reason. // The failure transitions f...
} else {
random_line_split
pod_helper.go
().DefaultNodeSelector) if taskExecutionMetadata.IsInterruptible() { podSpec.NodeSelector = utils.UnionMaps(podSpec.NodeSelector, config.GetK8sPluginConfig().InterruptibleNodeSelector) } if podSpec.Affinity == nil { podSpec.Affinity = config.GetK8sPluginConfig().DefaultAffinity } } func ToK8sPodSpec(ctx contex...
{ return pluginsCore.PhaseInfoRetryableFailure("OOMKilled", "Pod reported success despite being OOMKilled", &info), nil }
conditional_block
pod_helper.go
K8sPluginConfig().SchedulerName } podSpec.NodeSelector = utils.UnionMaps(podSpec.NodeSelector, config.GetK8sPluginConfig().DefaultNodeSelector) if taskExecutionMetadata.IsInterruptible() { podSpec.NodeSelector = utils.UnionMaps(podSpec.NodeSelector, config.GetK8sPluginConfig().InterruptibleNodeSelector) } if pod...
(status v1.PodStatus, info pluginsCore.TaskInfo) (pluginsCore.PhaseInfo, error) { for _, status := range append( append(status.InitContainerStatuses, status.ContainerStatuses...), status.EphemeralContainerStatuses...) { if status.State.Terminated != nil && strings.Contains(status.State.Terminated.Reason, OOMKilled...
DemystifySuccess
identifier_name
pod_helper.go
func BuildPodWithSpec(podSpec *v1.PodSpec) *v1.Pod { pod := v1.Pod{ TypeMeta: v12.TypeMeta{ Kind: PodKind, APIVersion: v1.SchemeGroupVersion.String(), }, Spec: *podSpec, } return &pod } func BuildIdentityPod() *v1.Pod { return &v1.Pod{ TypeMeta: v12.TypeMeta{ Kind: PodKind, APIVers...
{ code = "UnknownError" message = "Pod failed. No message received from kubernetes." if len(status.Reason) > 0 { code = status.Reason } if len(status.Message) > 0 { message = status.Message } for _, c := range append( append(status.InitContainerStatuses, status.ContainerStatuses...), status.EphemeralCont...
identifier_body
searchByName.js
vm.search = search; vm.searchParamsObject = {}; // wenn iOs-App dann wird eine extra iOS-Css-Klasse benötigt im bar-header vm.isIosApp = (CONFIG.environment == 'app' && CONFIG.deviceOs == 'iOS') ? true : false; vm.urlPrefix = CONFIG.urlPrefix; vm.isTablet = (CONFIG.deviceType == 'tablet') ? true : ...
nction setSearchParamsObject(params) { // Suche über Was / Wen if (params.searchType == "what") { vm.searchParamsObject.was = params.selectedItem; vm.searchParamsObject.was_i = params.inputItem; vm.searchParamsObject.was_sel = (typeof params.was_sel !== 'undefined' && params.was_sel) ? params.was...
NavBarDelegate.showBar(true); // zeige Wo-Input vm.showWhereInputField = true; vm.showWhereSuggest = false; // zeige Was-Input vm.showWhatInputField = true; vm.showWhatSuggest = false; // verstecke Abbrechen Buttons vm.showWhatCancel = false; vm.showWhereCancel = false...
conditional_block
searchByName.js
.trackPageview('/namenssuche/'); // set canonical JamHelperFactory.setCanonical('https://www.jameda.de/empfehlen/', true); // reset back button cache JamHelperFactory.setIntoCache('profileBackParams', {}); }); $scope.$on('$ionicView.beforeLeave', function() { JamHelperFactory.reset...
/* */ setSearchParamsObject(params);
random_line_split
searchByName.js
vm.search = search; vm.searchParamsObject = {}; // wenn iOs-App dann wird eine extra iOS-Css-Klasse benötigt im bar-header vm.isIosApp = (CONFIG.environment == 'app' && CONFIG.deviceOs == 'iOS') ? true : false; vm.urlPrefix = CONFIG.urlPrefix; vm.isTablet = (CONFIG.deviceType == 'tablet') ? true : ...
$timeout(function () { var suggestScrollArea = $('ion-nav-view[name="menuContent"] ion-view[nav-view="active"] #suggest-scroll-area'); // Only on android tablets if (vm.isTablet && vm.deviceOs == 'Android') { var tmpHeight = $('ion-view[nav-view="active"] .jam-suggest-box-tablet').height(...
llHeight() {
identifier_name
searchByName.js
'; vm.bestMatchSuggest.was_sel = 1; if (data[0].header == 'Fachbereiche') { vm.bestMatchSuggest.was = data[0].list[0].term; vm.bestMatchSuggest.gruppe_fach_param = data[0].list[0].select; } else if (data[0].header == 'Namen') { vm.bestMatchSuggest.was = input.what; vm.bes...
('searchResultList', vm.searchParamsObject); } activate(
identifier_body
time.rs
64 / NSEC_PER_MSEC) } ///Gets a representation of this timespec as a number of seconds pub fn to_seconds(&self) -> i64 { self.to_milliseconds() / MSEC_PER_SEC } ///Clears this timespec, setting each value to zero pub fn clear(&mut self) { self.tv_sec = 0; self.t...
///The amount of time left until expiration (Need to verify) pub it_value: timeval } ///A system-wide clock that measures time from the "real world" /// ///This clock **is** affected by discontinuous jumps in system time, NTP, and user changes pub const CLOCK_REALTIME: ::clockid_t = 0; ///A clock that me...
///The period of time this timer should run for (Need to verify) pub it_interval: timeval,
random_line_split
time.rs
{ ///The number of seconds contained in this timespec pub tv_sec: ::time_t, ///The number of nanoseconds contained in this timespec pub tv_nsec: ::c_long } impl timespec { ///Creates a new timespec with both values defaulting to zero pub fn new() -> timespec { timespec { tv_sec: ...
timespec
identifier_name
format_wav_scp.py
, fs: int) -> np.array: # Conduct trim wtih vad information assert check_argument_types() assert uttid in vad_reader, uttid vad_info = vad_reader[uttid] total_length = sum(int((time[1] - time[0]) * fs) for time in vad_info) new_wav = np.zeros((total_length,), dtype=wav.dtype) start_frame =...
fark = open(Path(args.outdir) / f"data_{args.name}.ark", "wb") fscp_out = out_wavscp.open("w") writer = None else: writer = SoundScpWriter( args.outdir, out_wavscp, format=args.audio_format, multi_columns=args.multi_columns_output, ...
if args.audio_format.endswith("ark"):
random_line_split
format_wav_scp.py
, fs: int) -> np.array: # Conduct trim wtih vad information assert check_argument_types() assert uttid in vad_reader, uttid vad_info = vad_reader[uttid] total_length = sum(int((time[1] - time[0]) * fs) for time in vad_info) new_wav = np.zeros((total_length,), dtype=wav.dtype) start_frame =...
else: array = array[int(st * rate) :] yield utt, (array, rate), None, None def main(): logfmt = "%(asctime)s (%(module)s:%(lineno)d) %(levelname)s: %(message)s" logging.basicConfig(level=logging.INFO, format=logfmt) logging.info(get_commandline_args()) parser...
array = array[int(st * rate) : int(et * rate)]
conditional_block
format_wav_scp.py
def str2int_tuple(integers: str) -> Optional[Tuple[int, ...]]: """ >>> str2int_tuple('3,4,5') (3, 4, 5) """ assert check_argument_types() if integers.strip() in ("none", "None", "NONE", "null", "Null", "NULL"): return None return tuple(map(int, integers.strip().split(","))) de...
if value in ("none", "None", "NONE"): return None return humanfriendly.parse_size(value)
identifier_body
format_wav_scp.py
, fs: int) -> np.array: # Conduct trim wtih vad information assert check_argument_types() assert uttid in vad_reader, uttid vad_info = vad_reader[uttid] total_length = sum(int((time[1] - time[0]) * fs) for time in vad_info) new_wav = np.zeros((total_length,), dtype=wav.dtype) start_frame =...
(x, d=utt2ref_channels_dict) -> Tuple[int, ...]: chs_str = d[x] return tuple(map(int, chs_str.split())) else: utt2ref_channels = None if args.audio_format.endswith("ark") and args.multi_columns_output: raise RuntimeError("Multi columns wav.scp is not supported for ark t...
utt2ref_channels
identifier_name
cv4ag.py
('--lonshift',metavar='N.N', type=float,default=0, help='Longitudanal shift of training data.') cmdParser.add_argument('--latshift',metavar='N.N', type=float,default=0, help='Lateral shift of training data .') cmdParser.add_argument('--shiftformat',metavar='N', type=int,default=0, help='Format of longitud...
train.train(outputFolder=outputFolder, inputFile=inputFile, net=net, top=top, key=key, mode=mode, xpixel=xpixel, ypixel=ypixel, ignorebackground=b, batchsize=batchsize, maxiter=maxiter, datatype=datatype, stepsize=stepsize, initweights=initweights, createTest=test\ )
conditional_block
cv4ag.py
(argparse.ArgumentParser): # override error message to show usage def error(self, message): sys.stderr.write('error: %s\n' % message) self.print_help() sys.exit(2) cmdParser = myParse(\ description='Machine Learning Framework for Agricultural Data.', add_help=True) cmdParser.add_argument('module', me...
myParse
identifier_name
cv4ag.py
modules to be loaded. OPTION: \n\ all - all modules (except clear).\n\ parse - input file parser.\n\ satellite - get satellite data.\n\ overlay - overlay classification with satellite data. \n\ train - train.\n\ ml - apply machine learning algorithm.\n\ clear - clear generated data from previous r...
cmdParser.set_defaults(b=False) randomParser = cmdParser.add_mutually_exclusive_group(required=False) randomParser.add_argument('--random', dest='randomImages', action='store_true',help='Use random images within GIS boundary box.') randomParser.add_argument('--no-random', dest='randomImages', action='store_false',h...
cmdParser.set_defaults(test=False) backgroundParser = cmdParser.add_mutually_exclusive_group(required=False) backgroundParser.add_argument('--background', dest='b', action='store_false',help='Classify background for training (default)') backgroundParser.add_argument('--no-background', dest='b', action='store_true',...
random_line_split
cv4ag.py
cmdParser = myParse(\ description='Machine Learning Framework for Agricultural Data.', add_help=True) cmdParser.add_argument('module', metavar='OPTION', type=str,default=False, help='The modules to be loaded. OPTION: \n\ all - all modules (except clear).\n\ parse - input file parser.\n\ satellite ...
def error(self, message): sys.stderr.write('error: %s\n' % message) self.print_help() sys.exit(2)
identifier_body
movie_review_NaiveBayes.py
pos/', 0) #test_neg = get_files('../datasets/movie_reviews/data/subset/test/neg/', 1) print('* TEST DATA * ') print('# positives reviews: ', len(test_pos)) print('# negatives reviews', len(test_neg)) test_data = test_pos + test_neg print('# total reviews: ', len(test_data)) # Does not want a 50/50 split between traini...
already_counted.append(word) total_words # In[ ]: # Removes words that are not inluded in at least 0.15% of the reviews removed_words = 0 for j in range(len(train_set)): words = train_set[j][0] i = 0 while i < len(words): word = words[i] word_removed = False...
if word not in already_counted: neg_word_counter[word] += 1
conditional_block
movie_review_NaiveBayes.py
pos/', 0) #test_neg = get_files('../datasets/movie_reviews/data/subset/test/neg/', 1) print('* TEST DATA * ') print('# positives reviews: ', len(test_pos)) print('# negatives reviews', len(test_neg)) test_data = test_pos + test_neg print('# total reviews: ', len(test_data)) # Does not want a 50/50 split between traini...
ord): return (probability_appearing[word][0]*p_pos)/((probability_appearing[word][0]*p_pos + probability_appearing[word][1]*p_neg)) def p_is_negative_given_word(word): return (probability_appearing[word][1]*p_neg)/((probability_appearing[word][1]*p_neg + probability_appearing[word][0]*p_pos)) p_is_positive_gi...
is_positive_given_word(w
identifier_name
movie_review_NaiveBayes.py
pos/', 0) #test_neg = get_files('../datasets/movie_reviews/data/subset/test/neg/', 1) print('* TEST DATA * ') print('# positives reviews: ', len(test_pos)) print('# negatives reviews', len(test_neg)) test_data = test_pos + test_neg print('# total reviews: ', len(test_data)) # Does not want a 50/50 split between traini...
most_used_words_pos = sort_dict(pos_word_counter, 25) most_used_words_neg = sort_dict(neg_word_counter, 25) most_used_words_pos # In[ ]: # Need these 4 probabilities # 1) Probability that a word appears in positive reviews # 2) Probability that a word appears in negative reviews # 3) Overall probab...
most_common_words = sorted(dicti.items(), key = lambda kv: kv[1]) most_common_words.reverse() most_common_words = most_common_words[:end] # Lager dict på formen {word: count, ...} # Vil ha dict fremfor liste med tupler, pga. senere søk return dict(most_common_words)
identifier_body
movie_review_NaiveBayes.py
/pos/', 0) #test_neg = get_files('../datasets/movie_reviews/data/subset/test/neg/', 1) print('* TEST DATA * ') print('# positives reviews: ', len(test_pos)) print('# negatives reviews', len(test_neg)) test_data = test_pos + test_neg print('# total reviews: ', len(test_data)) # Does not want a 50/50 split between train...
word_removed = True removed_words += 1 if not word_removed: i += 1 j += 1 removed_words # In[ ]: def sort_dict(dicti, end): # Sorterer etter value i dict, gir liste med tupler most_common_words = sorted(dicti.items(), key = lambda kv: kv[1]) most_c...
random_line_split
tls-server.rs
BufReader::new(File::open(path)?)) .map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "invalid cert")) .map(|mut certs| certs.drain(..).map(Certificate).collect()) } fn load_keys(path: &Path, password: Option<&str>) -> io::Result<Vec<PrivateKey>> { let expected_tag = match &password { ...
(socket_addr: SocketAddr) -> anyhow::Result<()> { println!("Starting up server on {socket_addr}"); let listener = TcpListener::bind(socket_addr).await?; let server = Server::new(listener); let on_connected = |stream, _socket_addr| async move { let cert_path = Path::new("./pki/server.pem"); ...
server_context
identifier_name
tls-server.rs
mut BufReader::new(File::open(path)?)) .map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "invalid cert")) .map(|mut certs| certs.drain(..).map(Certificate).collect()) } fn load_keys(path: &Path, password: Option<&str>) -> io::Result<Vec<PrivateKey>> { let expected_tag = match &password { ...
Ok(values) => future::ready(Ok(Response::ReadInputRegisters(values))), Err(err) => future::ready(Err(err)), } } Request::ReadHoldingRegisters(addr, cnt) => { match register_read(&self.holding_registers.lock().unwrap(), addr,...
fn call(&self, req: Self::Request) -> Self::Future { match req { Request::ReadInputRegisters(addr, cnt) => { match register_read(&self.input_registers.lock().unwrap(), addr, cnt) {
random_line_split
tls-server.rs
BufReader::new(File::open(path)?)) .map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "invalid cert")) .map(|mut certs| certs.drain(..).map(Certificate).collect()) } fn load_keys(path: &Path, password: Option<&str>) -> io::Result<Vec<PrivateKey>> { let expected_tag = match &password { ...
Err(err) => future::ready(Err(err)), } } Request::WriteSingleRegister(addr, value) => { match register_write( &mut self.holding_registers.lock().unwrap(), addr, std::slice::from_ref(&v...
{ match req { Request::ReadInputRegisters(addr, cnt) => { match register_read(&self.input_registers.lock().unwrap(), addr, cnt) { Ok(values) => future::ready(Ok(Response::ReadInputRegisters(values))), Err(err) => future::ready(Err(err)), ...
identifier_body
program.py
.compile(r"(\w*)\s*(?:```)(\w*)?([\s\S]*)(?:```$)") @property def session(self): return self.bot.http._HTTPClient__session
async def _run_code(self, *, lang: str, code: str): res = await self.session.post( "https://emkc.org/api/v1/piston/execute", json={"language": lang, "source": code}) return await res.json() @commands.command() async def run(self, ctx: commands.Context, *, codeblock: ...
random_line_split
program.py
emkc.org/api/v1/piston/execute", json={"language": lang, "source": code}) return await res.json() @commands.command() async def run(self, ctx: commands.Context, *, codeblock: str): """ Run code and get results instantly **Note**: You must use codeblocks around the co...
ython_jp(self,
identifier_name
program.py
= re.compile("|".join(rep.keys())) converted_language = pattern.sub(lambda m: rep[re.escape(m.group(0))], result['language']) limit = 1024 - (29 + len(converted_language)) output = f"```{converted_language}\n{output[:limit]}```{(len(output) > limit) * (newline + '**Output shortened**')}" ...
identifier_body
program.py
(r"(\w*)\s*(?:```)(\w*)?([\s\S]*)(?:```$)") @property def session(self): return self.bot.http._HTTPClient__session async def _run_code(self, *, lang: str, code: str): res = await self.session.post( "https://emkc.org/api/v1/piston/execute", json={"language": lang, "s...
# This code mostly comes from the Sphinx repository. entry_regex = re.compile(r'(?x)(.+?)\s+(\S*:\S*)\s+(-?\d+)\s+(\S+)\s+(.*)') for line in stream.read_compressed_lines(): match = entry_regex.match(line.rstrip()) if not match: continue name...
raise RuntimeError('Invalid objects.inv file, not z-lib compatible.')
conditional_block
packer.rs
let (slate_bin, encrypted) = pack.to_binary(slate_version, secret, use_test_rng)?; SlatepackArmor::encode(&slate_bin, encrypted) } /// return slatepack pub fn decrypt_slatepack(data: &[u8], dec_key: &DalekSecretKey) -> Result<Self, Error> { let (slate_bytes, encrypted) = SlatepackArmor::decode(data)?; let ...
/// Get Sender info. It is needed to send the response back pub fn get_recipient(&self) -> Option<DalekPublicKey> { self.recipient.clone() } /// Convert this slate back to the resulting slate. Since the slate pack contain only the change set, /// to recover the data it is required original slate to merge with...
{ self.sender.clone() }
identifier_body
packer.rs
let (slate_bin, encrypted) = pack.to_binary(slate_version, secret, use_test_rng)?; SlatepackArmor::encode(&slate_bin, encrypted) } /// return slatepack pub fn decrypt_slatepack(data: &[u8], dec_key: &DalekSecretKey) -> Result<Self, Error> { let (slate_bytes, encrypted) = SlatepackArmor::decode(data)?; let...
(&self) -> SlatePurpose { self.content.clone() } /// Get Sender info. It is needed to send the response back pub fn get_sender(&self) -> Option<DalekPublicKey> { self.sender.clone() } /// Get Sender info. It is needed to send the response back pub fn get_recipient(&self) -> Option<DalekPublicKey> { self.r...
get_content
identifier_name
packer.rs
let (slate_bin, encrypted) = pack.to_binary(slate_version, secret, use_test_rng)?; SlatepackArmor::encode(&slate_bin, encrypted) } /// return slatepack pub fn decrypt_slatepack(data: &[u8], dec_key: &DalekSecretKey) -> Result<Self, Error> { let (slate_bytes, encrypted) = SlatepackArmor::decode(data)?; let...
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, ]; let sk = SecretKey::from_slice(&bytes_32).unwrap(); let secp = Secp25...
random_line_split
json.go
.SubmitRequirements[i], err = r.ToProto(); err != nil { return nil, err } } } if ci.Reviewers != nil { ret.Reviewers = &gerritpb.ReviewerStatusMap{} if accs, exist := ci.Reviewers["REVIEWER"]; exist { ret.Reviewers.Reviewers = make([]*gerritpb.AccountInfo, len(accs)) for i, acc := range accs { ...
() *gerritpb.ChangeMessageInfo { if cmi == nil { return nil } return &gerritpb.ChangeMessageInfo{ Id: cmi.ID, Author: cmi.Author.ToProto(), RealAuthor: cmi.RealAuthor.ToProto(), Date: timestamppb.New(cmi.Date.Time), Message: cmi.Message, Tag: cmi.Tag, } } type requirement ...
ToProto
identifier_name
json.go
Requirements[i], err = r.ToProto(); err != nil { return nil, err } } } if ci.Reviewers != nil { ret.Reviewers = &gerritpb.ReviewerStatusMap{} if accs, exist := ci.Reviewers["REVIEWER"]; exist { ret.Reviewers.Reviewers = make([]*gerritpb.AccountInfo, len(accs)) for i, acc := range accs { ret.Rev...
type requirement struct { Status string `json:"status"` FallbackText string `json:"fallback_text"` Type string `json:"type"` } func (r *requirement) ToProto() (*gerritpb.Requirement, error) { stringVal := "REQUIREMENT_STATUS_" + r.Status numVal, found := gerritpb.Requirement_Status_value[stringVal...
{ if cmi == nil { return nil } return &gerritpb.ChangeMessageInfo{ Id: cmi.ID, Author: cmi.Author.ToProto(), RealAuthor: cmi.RealAuthor.ToProto(), Date: timestamppb.New(cmi.Date.Time), Message: cmi.Message, Tag: cmi.Tag, } }
identifier_body
json.go
.SubmitRequirements[i], err = r.ToProto(); err != nil { return nil, err } } } if ci.Reviewers != nil { ret.Reviewers = &gerritpb.ReviewerStatusMap{} if accs, exist := ci.Reviewers["REVIEWER"]; exist { ret.Reviewers.Reviewers = make([]*gerritpb.AccountInfo, len(accs)) for i, acc := range accs { ...
if ri.Files != nil { ret.Files = make(map[string]*gerritpb.FileInfo, len(ri.Files)) for i, fi := range ri.Files { ret.Files[i] = fi.ToProto() } } if ri.Commit != nil { ret.Commit = ri.Commit.ToProto() } return ret } // https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#git-perso...
if v, ok := gerritpb.RevisionInfo_Kind_value[ri.Kind]; ok { ret.Kind = gerritpb.RevisionInfo_Kind(v) }
random_line_split
json.go
mergeable_into"` } func (mi *mergeableInfo) ToProto() (*gerritpb.MergeableInfo, error) { // Convert something like 'simple-two-way-in-core' to 'SIMPLE_TWO_WAY_IN_CORE'. strategyEnumName := strings.Replace(strings.ToUpper(mi.Strategy), "-", "_", -1) strategyEnumNum, found := gerritpb.MergeableStrategy_value[strategy...
{ reviewerDetails, err := x.ToProto() if err != nil { return nil, err } reviewers[i] = reviewerDetails }
conditional_block
list_conflict_files_test.go
byte("encoding/codagé"), }, Content: []byte(conflictContent1), }, { Header: &gitalypb.ConflictFileHeader{ CommitOid: ourCommitOid, OurMode: int32(0o100644), OurPath: []byte("files/ruby/feature.rb"), TheirPath: []byte("files/ruby/feature.rb"), }, Content: []byte(conflictContent2), ...
ctx := testhelper.Context(t) _, repo, _, client := SetupConflictsService(ctx, t, true, nil) testCases := []struct { desc string ourCommitOid string theirCommitOid string }{ { desc: "conflict side missing", ourCommitOid: "eb227b3e214624708c474bdab7bde7afc17cefcc", theirComm...
random_line_split
list_conflict_files_test.go
(t *testing.T) { ctx := testhelper.Context(t) _, repo, _, client := SetupConflictsService(ctx, t, false, nil) ourCommitOid := "1a35b5a77cf6af7edf6703f88e82f6aff613666f" theirCommitOid := "8309e68585b28d61eb85b7e2834849dda6bf1733" conflictContent1 := `<<<<<<< encoding/codagé Content is not important, file name i...
TestSuccessfulListConflictFilesRequest
identifier_name
list_conflict_files_test.go
repoPath, "reset", "--hard", "HEAD~") return oid.String() } func TestListConflictFilesFailedPrecondition(t *testing.T) { ctx := testhelper.Context(t) _, repo, _, client := SetupConflictsService(ctx, t, true, nil) testCases := []struct { desc string ourCommitOid string theirCommitOid string }...
r, err := c.Recv() if err == io.EOF { break } require.NoError(t, err) for _, file := range r.GetFiles() { // If there's a header this is the beginning of a new file if header := file.GetHeader(); header != nil { if currentFile != nil { files = append(files, currentFile) } currentFile...
conditional_block
list_conflict_files_test.go
b.ListConflictFilesRequest{ Repository: repo, OurCommitOid: our, TheirCommitOid: their, } c, err := client.ListConflictFiles(ctx, request) require.NoError(t, err) receivedFiles := getConflictFiles(t, c) require.Len(t, receivedFiles, 2) testhelper.ProtoEqual(t, &gitalypb.ConflictFileHeader{ CommitO...
tx := testhelper.Context(t) _, repo, _, client := SetupConflictsService(ctx, t, true, nil) ourCommitOid := "0b4bc9a49b562e85de7cc9e834518ea6828729b9" theirCommitOid := "bb5206fee213d983da88c47f9cf4cc6caf9c66dc" testCases := []struct { desc string request *gitalypb.ListConflictFilesRequest code codes....
identifier_body
reconcile.go
crdHandle, crdClient: crdClient, resourceClients: resourceClients, } } // Run starts the reconciliation loop and blocks until the context is done, or // there is an unrecoverable error. Reconciliation actions are done at the // supplied interval. func (r *Reconciler) Run(ctx context.Context, interval time....
func (subs subresources) any(predicate func(s *subresource) bool) bool { return len(subs.filter(predicate)) > 0 } func (subs subresources) all(predicate func(s *subresource) bool) bool { return len(subs.filter(predicate)) == len(subs) } func (r *Reconciler) planAction(controllerName string, subs subresources) (*a...
{ var result subresources for _, sub := range subs { if predicate(sub) { result = append(result, sub) } } return result }
identifier_body
reconcile.go
crdHandle, crdClient: crdClient, resourceClients: resourceClients, } } // Run starts the reconciliation loop and blocks until the context is done, or // there is an unrecoverable error. Reconciliation actions are done at the // supplied interval. func (r *Reconciler) Run(ctx context.Context, interval time....
(predicate func(s *subresource) bool) bool { return len(subs.filter(predicate)) == len(subs) } func (r *Reconciler) planAction(controllerName string, subs subresources) (*action, crd.CustomResource, error) { // If the controller name is empty, these are not our subresources; // do nothing. if controllerName == "" ...
all
identifier_name
reconcile.go
crdHandle, crdClient: crdClient, resourceClients: resourceClients, } } // Run starts the reconciliation loop and blocks until the context is done, or // there is an unrecoverable error. Reconciliation actions are done at the // supplied interval. func (r *Reconciler) Run(ctx context.Context, interval time....
subs, ok := result[cr.Name()] if !ok { glog.Warningf("[reconcile] no sub-resources found for cr %v", cr.Name()) } // Find non-existing subresources based on the expected subresource clients. existingSubs := map[string]struct{}{} for _, sub := range subs { existingSubs[sub.client.Plural()] = struct{...
{ glog.Warningf("[reconcile] failed to assert item %v to type CustomResource", item) continue }
conditional_block
reconcile.go
crdHandle, crdClient: crdClient, resourceClients: resourceClients, } } // Run starts the reconciliation loop and blocks until the context is done, or // there is an unrecoverable error. Reconciliation actions are done at the // supplied interval. func (r *Reconciler) Run(ctx context.Context, interval...
// To fix the problem, we could do a List from the CR client and then iterate // over those names instead of keys from the intermediate result map we built // based on the subresources. func (r *Reconciler) groupSubresourcesByCustomResource() subresourceMap { result := subresourceMap{} // Get the list of crs. crLis...
// custom resource, result will not have the controller name as one of its // keys. //
random_line_split
GPR_stan2.py
#import pandas as pd #num_groups = 1 #group_no = 0 #if len(sys.argv) > 1: # num_groups = int(sys.argv[1]) #if len(sys.argv) > 2: # group_no = int(sys.argv[2]) star = sys.argv[1] peak_no = int(sys.argv[2]) peak_no_str = "" if peak_no > 0: peak_no_str = str(peak_no) + "/" num_iters = 50 num_chains = 4...
from scipy.stats import gaussian_kde from sklearn.cluster import KMeans
random_line_split
GPR_stan2.py
for downsample_iter in np.arange(0, downsample_iters): if downsample_iters > 1: downsample_iter_str = '_' + str(downsample_iter) else: downsample_iter_str = '' if down_sample_factor >= 2: #indices = np.random.choice(len(t), len(t)/down_sample_factor, replace=False, p=None) ...
down_sample_factor = max(1, n_orig / 500) downsample_iters = down_sample_factor
conditional_block
index.js
() { return ( <div> <Head> <title>PublicTrades</title> <link rel="icon" href="/favicon.ico" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.6.0/gsap.min.js"></script> </Head> <main> <> {/* This example requires Tailwind CSS v2.0+ */} <div className=...
Home
identifier_name
index.js
<nav className="relative flex items-center justify-between sm:h-10 lg:justify-start" aria-label="Global"> <div className="flex items-center flex-grow flex-shrink-0 lg:flex-grow-0"> <div className="flex items-center justify-between w-full md:w-auto"> <a href="#"> ...
{ return ( <div> <Head> <title>PublicTrades</title> <link rel="icon" href="/favicon.ico" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.6.0/gsap.min.js"></script> </Head> <main> <> {/* This example requires Tailwind CSS v2.0+ */} <div className="re...
identifier_body
index.js
00" preserveAspectRatio="none" aria-hidden="true"> <polygon points="50,0 100,0 50,100 0,100" /> </svg> <div className="relative pt-6 px-4 sm:px-6 lg:px-8"> <nav className="relative flex items-center justify-between sm:h-10 lg:justify-start" aria-label="Global"> <div className="flex...
</a> </div> <div className="mt-3 sm:mt-0 sm:ml-3"> <a href="#" className="w-full flex items-center justify-center px-8 py-3 border border-transparent text-base font-medium rounded-md text-white bg-green-700 hover:bg-green-400 md:py-4 md:text-lg md:px-10"> ...
random_line_split