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 |
|---|---|---|---|---|
backend.rs | // Copyright 2017-2019 Parity Technologies (UK) Ltd.
// This file is part of Substrate.
// Substrate is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) a... | else {
root_map = Some(map);
}
}
// root handling
if let Some(map) = root_map.take() {
root = Some(insert_into_memory_db::<H, _>(
&mut mdb,
map.clone().into_iter().chain(new_child_roots.into_iter())
)?);
}
let root = match root {
Some(root) => root,
None => insert_into_memory_db::<... | {
let ch = insert_into_memory_db::<H, _>(&mut mdb, map.clone().into_iter())?;
new_child_roots.push((storage_key.clone(), ch.as_ref().into()));
} | conditional_block |
backend.rs | // Copyright 2017-2019 Parity Technologies (UK) Ltd.
// This file is part of Substrate.
// Substrate is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) a... |
fn for_keys_with_prefix<F: FnMut(&[u8])>(&self, prefix: &[u8], f: F) {
self.inner.get(&None).map(|map| map.keys().filter(|key| key.starts_with(prefix)).map(|k| &**k).for_each(f));
}
fn for_keys_in_child_storage<F: FnMut(&[u8])>(&self, storage_key: &[u8], mut f: F) {
self.inner.get(&Some(storage_key.to_vec()))... | {
Ok(self.inner.get(&None).map(|map| map.get(key).is_some()).unwrap_or(false))
} | identifier_body |
manager.go | package xym
import (
"sync"
"github.com/lightpaw/male7/pb/shared_proto"
"sync/atomic"
"sort"
"github.com/lightpaw/male7/util/imath"
"github.com/lightpaw/male7/util/sortkeys"
atomic2 "github.com/lightpaw/male7/util/atomic"
"github.com/lightpaw/male7/service/herosnapshot/snapshotdata"
"github.com/lightpaw/male7... | := m.Get()
if r != nil {
proto.UpdateTime = timeutil.Marshal64(r.updateTime)
proto.RankHero = make([]*server_proto.XuanyuanRankHeroProto, 0, len(r.rankHeros))
for _, v := range r.rankHeros {
_, mirror := v.GetMirror()
proto.RankHero = append(proto.RankHero, &server_proto.XuanyuanRankHeroProto{
HeroId... | ) {
r | identifier_name |
manager.go | package xym
import (
"sync"
"github.com/lightpaw/male7/pb/shared_proto"
"sync/atomic"
"sort"
"github.com/lightpaw/male7/util/imath"
"github.com/lightpaw/male7/util/sortkeys"
atomic2 "github.com/lightpaw/male7/util/atomic"
"github.com/lightpaw/male7/service/herosnapshot/snapshotdata"
"github.com/lightpaw/male7... | var emptyBytes = make([]byte, 0)
func (hero *XyRankHero) clearTargetBytesCache() {
hero.targetBytesCache.Store(emptyBytes)
}
func (hero *XyRankHero) encodeTarget(getter func(int64) *snapshotdata.HeroSnapshot) *shared_proto.XuanyuanTargetProto {
proto := &shared_proto.XuanyuanTargetProto{}
heroSnapshot := getter(h... | return protoBytes
}
| random_line_split |
manager.go | package xym
import (
"sync"
"github.com/lightpaw/male7/pb/shared_proto"
"sync/atomic"
"sort"
"github.com/lightpaw/male7/util/imath"
"github.com/lightpaw/male7/util/sortkeys"
atomic2 "github.com/lightpaw/male7/util/atomic"
"github.com/lightpaw/male7/service/herosnapshot/snapshotdata"
"github.com/lightpaw/male7... | .v.Store(toSet)
}
func (r *RoRankList) update(newHeroMap map[int64]*XyHero, rankCount int, updateTime time.Time, prev *RoRank) {
// 单线程更新
//if len(newHeroMap) <= 0 && prev != nil {
// // 改个时间
// r.set(&RoRank{
// heroMap: prev.heroMap,
// rankHeros: prev.rankHeros,
// updateTime: updateTime,
// })
// r... | rn rank.(*RoRank)
}
return nil
}
func (r *RoRankList) set(toSet *RoRank) {
r | identifier_body |
manager.go | package xym
import (
"sync"
"github.com/lightpaw/male7/pb/shared_proto"
"sync/atomic"
"sort"
"github.com/lightpaw/male7/util/imath"
"github.com/lightpaw/male7/util/sortkeys"
atomic2 "github.com/lightpaw/male7/util/atomic"
"github.com/lightpaw/male7/service/herosnapshot/snapshotdata"
"github.com/lightpaw/male7... | ange m.challengerMap {
proto.Challenger = append(proto.Challenger, &server_proto.XuanyuanRankHeroProto{
HeroId: v.heroId,
Score: v.score,
Win: v.win,
Lose: v.lose,
Mirror: v.combatMirror,
})
}
}
func (m *XuanyuanManager) Unmarshal(proto *server_proto.XuanyuanModuleProto) {
if proto == nil {
... | dateTime)
proto.RankHero = make([]*server_proto.XuanyuanRankHeroProto, 0, len(r.rankHeros))
for _, v := range r.rankHeros {
_, mirror := v.GetMirror()
proto.RankHero = append(proto.RankHero, &server_proto.XuanyuanRankHeroProto{
HeroId: v.heroId,
Score: v.score.Load(),
RankScore: v.rankScor... | conditional_block |
webpack.ts | /* eslint-disable no-underscore-dangle */
/* eslint-disable @typescript-eslint/no-var-requires */
import * as path from 'path';
import * as url from 'url';
import * as webpack from 'webpack';
import type { BroilerConfig } from './config';
import { executeSync } from './exec';
// Webpack plugins
const ExtractCssChunks =... | {
return new BundleAnalyzerPlugin({
// Can be `server`, `static` or `disabled`.
// In `server` mode analyzer will start HTTP server to show bundle report.
// In `static` mode single HTML file with bundle report will be generated.
// In `disabled` mode you can use this plugin to just ... | identifier_body | |
webpack.ts | /* eslint-disable no-underscore-dangle */
/* eslint-disable @typescript-eslint/no-var-requires */
import * as path from 'path';
import * as url from 'url';
import * as webpack from 'webpack';
import type { BroilerConfig } from './config';
import { executeSync } from './exec';
// Webpack plugins
const ExtractCssChunks =... |
// Enable sourcemaps for debugging webpack's output.
devtool: 'source-map',
// Plugins
plugins,
};
}
function getCommonPlugins(options: {
frontend: boolean;
devServer: boolean;
assetsFilePrefix: string;
tsConfigPath: string;
sourceDirPath: string;
compilerO... | // Look from this library's node modules!
modules: [ownModulesDirPath, modulesDirPath],
}, | random_line_split |
webpack.ts | /* eslint-disable no-underscore-dangle */
/* eslint-disable @typescript-eslint/no-var-requires */
import * as path from 'path';
import * as url from 'url';
import * as webpack from 'webpack';
import type { BroilerConfig } from './config';
import { executeSync } from './exec';
// Webpack plugins
const ExtractCssChunks =... | (options: {
assetsFilePrefix: string;
debug: boolean;
devServer: boolean;
tsConfigPath: string;
emitFile: boolean;
compilerOptions?: unknown;
}): webpack.RuleSetRule[] {
const { tsConfigPath, compilerOptions, debug, devServer, assetsFilePrefix, emitFile } = options;
return [
// P... | getCommonRules | identifier_name |
webpack.ts | /* eslint-disable no-underscore-dangle */
/* eslint-disable @typescript-eslint/no-var-requires */
import * as path from 'path';
import * as url from 'url';
import * as webpack from 'webpack';
import type { BroilerConfig } from './config';
import { executeSync } from './exec';
// Webpack plugins
const ExtractCssChunks =... | else {
// API not available. Let the bundle to compile without it, but
// raise error if attempting to `require`
externals.push('_service');
}
// If a database defined, compile it as well
if (databaseFile) {
// eslint-disable-next-line no-underscore-dangle
aliases._d... | {
// eslint-disable-next-line no-underscore-dangle
aliases._service = path.resolve(projectRootPath, sourceDir, serverFile);
} | conditional_block |
calibration.py | ### Calibration과 이미지 Merge에 사용되는 모듈 ###
import numpy as np
from PIL import Image
# from skimage import color, viewer, img_as_float, img_as_ubyte, img_as_uint, data
# from skimage.filters import gaussian
# from skimage.color import rgb2gray
# import matplotlib.image as mpimg
import matplotlib.pylab as plt
import ... |
print('Centroid : ', cX, cY)
# ref_square에 구하기 'ㄱ'부분 길이 구하기
ref_square_w = point2_distance(y_min_blob[0:2], x_max_blob[0:2]) # 'ㄱ'의 'ㅡ'부분
ref_square_h = point2_distance(y_max_blob[0:2], x_max_blob[0:2]) # 'ㄱ'의 '|'부분
print('ref_square_w : ', ref_square_w)
print('ref_square_h : ', r... |
cv2.circle(img_temp, (cX, cY), 15, (100, 100, 100), -1)
cv2.circle(img_copy, (cX, cY), 15, (100, 100, 100), -1)
| random_line_split |
calibration.py | ### Calibration과 이미지 Merge에 사용되는 모듈 ###
import numpy as np
from PIL import Image
# from skimage import color, viewer, img_as_float, img_as_ubyte, img_as_uint, data
# from skimage.filters import gaussian
# from skimage.color import rgb2gray
# import matplotlib.image as mpimg
import matplotlib.pylab as plt
import ... | plt.subplot(121), plt.imshow(img, cmap='gray'), plt.title('origin_binary_img')
plt.subplot(122), plt.imshow(img_copy, cmap='gray'), plt.title('Blob info')
plt.show();
return blob_info
# for quad camera
# 무게중심(CX,CY) 찾기, 및 BLOB 사각형의 'ㄱ'부분 길이 구하기 (ref_square_w, ref_square_h),
def find_centroid_for_q... | d) # 추출결과의 중심, 추출결과의 diameter (blob의 직경x)
cv2.circle(img_copy, (x,y), 1, (155, 155, 155), 10)
cv2.circle(img_copy, (x,y), int(k.size/2), (155, 155, 155), 10)
blob_info.append([x,y,k.size]) # x,y, diameter 정보
blob_info = np.array(blob_info) # argmin, argmx 를 위해 numpy 사용
... | conditional_block |
calibration.py | ### Calibration과 이미지 Merge에 사용되는 모듈 ###
import numpy as np
from PIL import Image
# from skimage import color, viewer, img_as_float, img_as_ubyte, img_as_uint, data
# from skimage.filters import gaussian
# from skimage.color import rgb2gray
# import matplotlib.image as mpimg
import matplotlib.pylab as plt
import ... | am(img, blob_info) :
img_h, img_w = np.shape(img)
img_copy = np.copy(img) # 무게중심 표시를 위한 img
img_temp = np.zeros((img_h, img_w), dtype=np.uint8) # 25개의 blob중 가장자리 blob 으로 무게중심 찾기 위한 사각형
x_min_blob = blob_info[np.argmin(blob_info[::, 0])] # 모든 x에서 가장 작은 blob
x_max_blob = blob_info[np.argmax(blob... | ob_info = [] # 추출한 blob 정보
# blob detection
params = cv2.SimpleBlobDetector_Params()
params.blobColor = 255 # 밝은 얼룩 추출
# params.minThreshold = 240
# params.maxThreshold = 255
params.filterByArea = True
params.minArea = 10*10;
params.maxArea = 200*200
params.filterByCirculari... | identifier_body |
calibration.py | ### Calibration과 이미지 Merge에 사용되는 모듈 ###
import numpy as np
from PIL import Image
# from skimage import color, viewer, img_as_float, img_as_ubyte, img_as_uint, data
# from skimage.filters import gaussian
# from skimage.color import rgb2gray
# import matplotlib.image as mpimg
import matplotlib.pylab as plt
import ... | 122), plt.imshow(dst, cmap='gray'), plt.title('After_affine')
plt.show();
print('img. max : ', np.max(np.unique(img)), 'img. min : ', np.min(np.unique(img)))
print('affine img. max : ', np.max(np.unique(dst)), 'affine img. min : ', np.min(np.unique(dst)))
return dst
# centroid를 중심으로 돌린 이미지... | t.subplot( | identifier_name |
ml_cms_heights.py | import cPickle
import os
import pandas as pd
import pdb
import numpy as np
import logging
import sys
import calendar
import matplotlib.pyplot as plt
from math import ceil
from sklearn.feature_selection import SelectKBest, f_classif, f_regression
from sklearn.grid_search import GridSearchCV, RandomizedSearchCV
from skl... |
else:
return predicted, {'RMSE': np.nan, 'MAE': np.nan, r'$r^{2}$': np.nan, 'Bias': np.nan,
'Nash-Sutcliff': np.nan}
def do_ml_model():
obj = MLCms(config_file='config_CMS.txt')
obj.train_ml_model()
if __name__ == '__main__':
do_ml_model()
| expected, predicted = compute_stats.remove_nans(expected, predicted)
cm = confusion_matrix(expected, predicted, labels=self.dict_cc.keys()).T
# Compute and plot class probabilities
proba_cc = self.model.predict_proba(data)
df_proba = pd.DataFrame(proba_cc... | conditional_block |
ml_cms_heights.py | import cPickle
import os
import pandas as pd
import pdb
import numpy as np
import logging
import sys
import calendar
import matplotlib.pyplot as plt
from math import ceil
from sklearn.feature_selection import SelectKBest, f_classif, f_regression
from sklearn.grid_search import GridSearchCV, RandomizedSearchCV
from skl... |
def do_forecasting(self, df_forecast, mon_names, available_target=False, name_target='yield'):
"""
1. Does classification/regression based on already built model.
2. Plots confusion matrix for classification tasks, scatter plot for regression
3. Plots accuracy statistics for classi... | """
:return:
"""
logger.info('#########################################################################')
logger.info('train_ml_model')
logger.info('#########################################################################')
#############################################... | identifier_body |
ml_cms_heights.py | import cPickle
import os
import pandas as pd
import pdb
import numpy as np
import logging
import sys
import calendar
import matplotlib.pyplot as plt
from math import ceil
from sklearn.feature_selection import SelectKBest, f_classif, f_regression
from sklearn.grid_search import GridSearchCV, RandomizedSearchCV
from skl... | (self):
"""
:return:
"""
logger.info('#########################################################################')
logger.info('train_ml_model')
logger.info('#########################################################################')
#############################... | train_ml_model | identifier_name |
ml_cms_heights.py | import cPickle
import os
import pandas as pd
import pdb
import numpy as np
import logging
import sys
import calendar
import matplotlib.pyplot as plt
from math import ceil
from sklearn.feature_selection import SelectKBest, f_classif, f_regression
from sklearn.grid_search import GridSearchCV, RandomizedSearchCV
from skl... |
class MLCms:
"""
"""
def __init__(self, config_file=''):
# Parse config file
self.parser = SafeConfigParser()
self.parser.read(config_file)
# machine learning specific variables
self.classify = constants.DO_CLASSIFICATION # Regress or classify?
self.vars_... | # create_forecast_df
# do_forecasting | random_line_split |
aws.go | // Copyright © 2018 NAME HERE <EMAIL ADDRESS>
//
// 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 ... |
ec2IP := node[0]
fmt.Println(node)
DomainName := strings.TrimSpace(string(loadBalancerName))
loadBalancerDomainName := "apiserver_loadbalancer_domain_name: " + DomainName
fmt.Fprintf(g, "#Set cloud provider to AWS\n")
fmt.Fprintf(g, "cloud_provider: 'aws'\n")
fmt.Fprintf(g, "#Load... |
fmt.Println(err)
os.Exit(1)
}
| conditional_block |
aws.go | // Copyright © 2018 NAME HERE <EMAIL ADDRESS>
//
// 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 ... | awsBastionSize := viper.GetString("aws.aws_bastion_size")
awsKubeMasterNum := viper.GetString("aws.aws_kube_master_num")
awsKubeMasterSize := viper.GetString("aws.aws_kube_master_size")
awsEtcdNum := viper.GetString("aws.aws_etcd_num")
awsEtcdSize := viper.GetString("aws.aws_etcd_size")
awsKubeWorkerN... | awsCidrSubnetsPrivate := viper.GetString("aws.aws_cidr_subnets_private")
awsCidrSubnetsPublic := viper.GetString("aws.aws_cidr_subnets_public") | random_line_split |
aws.go | // Copyright © 2018 NAME HERE <EMAIL ADDRESS>
//
// 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 ... |
clusterCmd.AddCommand(awsCmd)
// Here you will define your flags and configuration settings.
// Cobra supports Persistent Flags which will work for this command
// and all subcommands, e.g.:
// awsCmd.PersistentFlags().String("foo", "", "A help for foo")
// Cobra supports local flags which will only run when t... | identifier_body | |
aws.go | // Copyright © 2018 NAME HERE <EMAIL ADDRESS>
//
// 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 ... | ) {
clusterCmd.AddCommand(awsCmd)
// Here you will define your flags and configuration settings.
// Cobra supports Persistent Flags which will work for this command
// and all subcommands, e.g.:
// awsCmd.PersistentFlags().String("foo", "", "A help for foo")
// Cobra supports local flags which will only run whe... | nit( | identifier_name |
raft.go | package raft
//
// this is an outline of the API that raft must expose to
// the service (or tester). see comments below for
// each of these functions for more details.
//
// rf = Make(...)
// create a new Raft server.
// rf.Start(command interface{}) (index, Term, isleader)
// start agreement on a new log entry
... |
}
func (rf *Raft) broadcastAppendEntries() {
//fmt.Printf("[::broadcastAppendEntries][Candidate = %v]", rf.me)
rf.mtx.Lock()
defer rf.mtx.Unlock()
N := rf.commitIndex
last := rf.log[len(rf.log)-1].LogIndex
// step1: iterate all commitLog
for i := rf.commitIndex + 1; i <= last; i++ {
num := 1
for j := r... | {
if i != rf.me && rf.state == STATE_CANDIDATE {
go func(i int) {
var reply RequestVoteReply
rf.sendRequestVote(i, args, &reply)
}(i)
}
} | conditional_block |
raft.go | package raft
//
// this is an outline of the API that raft must expose to
// the service (or tester). see comments below for
// each of these functions for more details.
//
// rf = Make(...)
// create a new Raft server.
// rf.Start(command interface{}) (index, Term, isleader)
// start agreement on a new log entry
... |
func (rf *Raft) working() {
for {
switch rf.state {
case STATE_LEADER:
rf.broadcastAppendEntries()
time.Sleep(SEND_ENTRY_INTERVAL)
case STATE_FOLLOWER:
select {
case <-rf.chanHeartBeat: // RequestAppendEntries
case <-rf.chanVoteOther: // RequestVote
case <-time.After(time.Duration(rand.Int63(... | {
// Your code here, if desired.
} | identifier_body |
raft.go | package raft
//
// this is an outline of the API that raft must expose to
// the service (or tester). see comments below for
// each of these functions for more details.
//
// rf = Make(...)
// create a new Raft server.
// rf.Start(command interface{}) (index, Term, isleader)
// start agreement on a new log entry
... | if (rf.voteFor == -1 || rf.voteFor == args.CandidateId) && isNewer {
rf.chanVoteOther <- 1
rf.state = STATE_FOLLOWER
reply.VoteGranted = true
rf.voteFor = args.CandidateId
}
}
func (rf *Raft) RequestAppendEntries(args RequestAppendEntriesArgs, reply *RequestAppendEntriesReply) {
// Your code here.
// Q: sh... | random_line_split | |
raft.go | package raft
//
// this is an outline of the API that raft must expose to
// the service (or tester). see comments below for
// each of these functions for more details.
//
// rf = Make(...)
// create a new Raft server.
// rf.Start(command interface{}) (index, Term, isleader)
// start agreement on a new log entry
... | () {
//fmt.Printf("[::broadcastAppendEntries][Candidate = %v]", rf.me)
rf.mtx.Lock()
defer rf.mtx.Unlock()
N := rf.commitIndex
last := rf.log[len(rf.log)-1].LogIndex
// step1: iterate all commitLog
for i := rf.commitIndex + 1; i <= last; i++ {
num := 1
for j := range rf.peers {
if j != rf.me && rf.matc... | broadcastAppendEntries | identifier_name |
mod.rs | // High-level Internal Representation of GObject artifacts
//
// Here we provide a view of the world in terms of what GObject knows:
// classes, interfaces, signals, etc.
//
// We construct this view of the world from the raw Abstract Syntax
// Tree (AST) from the previous stage.
use std::collections::HashMap;
use pr... |
fn extract_inputs(&mut self, punc: &'ast Punctuated<syn::FnArg, Token!(,)>) -> Result<Vec<FnArg<'ast>>> {
punc.iter().map(|arg| {
match *arg {
syn::FnArg::Captured(syn::ArgCaptured { ref pat, ref ty, .. }) => {
let (name, mutbl) = match *pat {
... | {
match *output {
ReturnType::Type(_, ref boxt) => self.extract_ty(boxt),
ReturnType::Default => Ok(Ty::Unit),
}
} | identifier_body |
mod.rs | // High-level Internal Representation of GObject artifacts
//
// Here we provide a view of the world in terms of what GObject knows:
// classes, interfaces, signals, etc.
//
// We construct this view of the world from the raw Abstract Syntax
// Tree (AST) from the previous stage.
use std::collections::HashMap;
use pr... | }
}
}
Ok(())
}
pub fn iter<'a>(&'a self) -> impl Iterator<Item = &'a Class> + 'a {
self.items.values()
}
}
impl<'ast> Class<'ast> {
fn translate_slot(&mut self, item: &'ast ast::ImplItem) -> Result<Slot<'ast>> {
assert_eq!(item.attrs.len(), ... | random_line_split | |
mod.rs | // High-level Internal Representation of GObject artifacts
//
// Here we provide a view of the world in terms of what GObject knows:
// classes, interfaces, signals, etc.
//
// We construct this view of the world from the raw Abstract Syntax
// Tree (AST) from the previous stage.
use std::collections::HashMap;
use pr... | (&self) -> usize {
self.items.len()
}
pub fn get(&self, name: &str) -> &Class {
self.items.iter().find(|c| c.1.name == name).unwrap().1
}
fn add(&mut self, ast_class: &'ast ast::Class) -> Result<()>
{
let prev = self.items.insert(ast_class.name, Class {
name: as... | len | identifier_name |
events.py | import abc
import hashlib
import time
from functools import reduce
from logging import getLevelName
import attr
import numpy as np
import pathlib2
import six
from PIL import Image
from six.moves.urllib.parse import urlparse, urlunparse
from ...backend_api.services import events
from ...config import deferred_config
f... | LoggerRoot.get_base_logger().info(
"inf value encountered. Reporting it as '{}'. Use clearml.Logger.set_reporting_inf_value to assign another value".format(
cls.default_inf_value
)
)
cls._report_inf_warning_i... | random_line_split | |
events.py | import abc
import hashlib
import time
from functools import reduce
from logging import getLevelName
import attr
import numpy as np
import pathlib2
import six
from PIL import Image
from six.moves.urllib.parse import urlparse, urlunparse
from ...backend_api.services import events
from ...config import deferred_config
f... | (self, metric, variant, image_data, local_image_path=None, iter=0, upload_uri=None,
file_history_size=None, delete_after_upload=False, **kwargs):
# param override_filename: override uploaded file name (notice extension will be added from local path
# param override_filename_ext: overrid... | __init__ | identifier_name |
events.py | import abc
import hashlib
import time
from functools import reduce
from logging import getLevelName
import attr
import numpy as np
import pathlib2
import six
from PIL import Image
from six.moves.urllib.parse import urlparse, urlunparse
from ...backend_api.services import events
from ...config import deferred_config
f... |
def _get_base_dict(self):
""" Get a dict with the base attributes """
res = dict(
task=self._task,
timestamp=self._timestamp,
metric=self._metric,
variant=self._variant
)
if self._iter is not None:
res.update(iter=self._it... | """ Update event properties """
if task:
self._task = task
if iter_offset is not None and self._iter is not None:
self._iter += iter_offset | identifier_body |
events.py | import abc
import hashlib
import time
from functools import reduce
from logging import getLevelName
import attr
import numpy as np
import pathlib2
import six
from PIL import Image
from six.moves.urllib.parse import urlparse, urlunparse
from ...backend_api.services import events
from ...config import deferred_config
f... |
return val
class ScalarEvent(MetricsEventAdapter):
""" Scalar event adapter """
def __init__(self, metric, variant, value, iter, **kwargs):
self._value = self._convert_np_nan_inf(value)
super(ScalarEvent, self).__init__(metric=metric, variant=variant, iter=iter, **kwargs)
def ge... | cls._report_inf_warning_iteration += 1
if cls._report_inf_warning_iteration >= cls.report_inf_warning_period:
LoggerRoot.get_base_logger().info(
"inf value encountered. Reporting it as '{}'. Use clearml.Logger.set_reporting_inf_value to assign another value".format(
... | conditional_block |
merkle.rs | // LNP/BP client-side-validation foundation libraries implementing LNPBP
// specifications & standards (LNPBP-4, 7, 8, 9, 42, 81)
//
// Written in 2019-2021 by
// Dr. Maxim Orlovsky <orlovsky@pandoracore.com>
//
// To the extent possible under law, the author(s) have dedicated all
// copyright and related and neigh... |
}
/// The source data for the [LNPBP-81] merklization process.
///
/// [LNPBP-81]: https://github.com/LNP-BP/LNPBPs/blob/master/lnpbp-0081.md
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Default)]
pub struct MerkleSource<T>(
/// Array of the data which will be merklized
pub Vec<T>,
);
impl<L,... | {
let div = len / 2 + len % 2;
let (node1, height1) = merklize_inner(
engine_proto,
// Normally we should use `iter.by_ref().take(div)`, but currently
// rust compilers is unable to parse recursion with generic types
iter.by_ref().take(div).collect::<Vec<... | conditional_block |
merkle.rs | // LNP/BP client-side-validation foundation libraries implementing LNPBP
// specifications & standards (LNPBP-4, 7, 8, 9, 42, 81)
//
// Written in 2019-2021 by
// Dr. Maxim Orlovsky <orlovsky@pandoracore.com>
//
// To the extent possible under law, the author(s) have dedicated all
// copyright and related and neigh... |
}
impl<L> FromIterator<L> for MerkleSource<L>
where
L: CommitEncode,
{
fn from_iter<T: IntoIterator<Item = L>>(iter: T) -> Self {
iter.into_iter().collect::<Vec<_>>().into()
}
}
impl<L> CommitEncode for MerkleSource<L>
where
L: ConsensusMerkleCommit,
{
fn commit_encode<E: io::Write>(&self... | { Self(collection.into_iter().collect()) } | identifier_body |
merkle.rs | // LNP/BP client-side-validation foundation libraries implementing LNPBP
// specifications & standards (LNPBP-4, 7, 8, 9, 42, 81)
//
// Written in 2019-2021 by
// Dr. Maxim Orlovsky <orlovsky@pandoracore.com>
//
// To the extent possible under law, the author(s) have dedicated all
// copyright and related and neigh... | let iter = if extend {
iter.chain(vec![empty_node]).collect::<Vec<_>>().into_iter()
} else {
iter.collect::<Vec<_>>().into_iter()
};
let (node2, height2) = merklize_inner(
engine_proto,
iter,
depth + 1,
(div % 2 + l... | depth + 1,
false,
Some(empty_node),
);
| random_line_split |
merkle.rs | // LNP/BP client-side-validation foundation libraries implementing LNPBP
// specifications & standards (LNPBP-4, 7, 8, 9, 42, 81)
//
// Written in 2019-2021 by
// Dr. Maxim Orlovsky <orlovsky@pandoracore.com>
//
// To the extent possible under law, the author(s) have dedicated all
// copyright and related and neigh... | <E: io::Write>(&self, e: E) -> usize {
let leafs = self.0.iter().map(L::consensus_commit);
merklize(L::MERKLE_NODE_PREFIX, leafs).0.commit_encode(e)
}
}
impl<L> ConsensusCommit for MerkleSource<L>
where
L: ConsensusMerkleCommit + CommitEncode,
{
type Commitment = MerkleNode;
#[inline]
... | commit_encode | identifier_name |
mysql_table_scanner.go | package mysqlbatch
import (
"context"
"database/sql"
"fmt"
"reflect"
"strconv"
"sync"
"time"
"github.com/juju/errors"
"github.com/pingcap/parser"
log "github.com/sirupsen/logrus"
"github.com/moiot/gravity/pkg/core"
"github.com/moiot/gravity/pkg/metrics"
"github.com/moiot/gravity/pkg/mysql"
"github.com/... | (table *schema_store.Table) error {
row := tableScanner.db.QueryRow(fmt.Sprintf("SHOW CREATE TABLE `%s`.`%s`", table.Schema, table.Name))
var t, create string
err := row.Scan(&t, &create)
if err != nil {
return errors.Trace(err)
}
msg := NewCreateTableMsg(tableScanner.parser, table, create)
if err := tableSc... | initTableDDL | identifier_name |
mysql_table_scanner.go | package mysqlbatch
import (
"context"
"database/sql"
"fmt"
"reflect"
"strconv"
"sync"
"time"
"github.com/juju/errors"
"github.com/pingcap/parser"
log "github.com/sirupsen/logrus"
"github.com/moiot/gravity/pkg/core"
"github.com/moiot/gravity/pkg/metrics"
"github.com/moiot/gravity/pkg/mysql"
"github.com/... |
func GetScanIdx(columnTypes []*sql.ColumnType, scanColumn string) (int, error) {
for i := range columnTypes {
if columnTypes[i].Name() == scanColumn {
return i, nil
}
}
return 0, errors.Errorf("cannot find scan index")
}
func newBatchDataPtrs(columnTypes []*sql.ColumnType, batch int) [][]interface{} {
ret... | {
statement := fmt.Sprintf("SELECT * FROM `%s`.`%s` LIMIT 1", schema, table)
rows, err := db.Query(statement)
if err != nil {
return nil, errors.Trace(err)
}
defer rows.Close()
return rows.ColumnTypes()
} | identifier_body |
mysql_table_scanner.go | package mysqlbatch
import (
"context"
"database/sql"
"fmt"
"reflect"
"strconv"
"sync"
"time" | log "github.com/sirupsen/logrus"
"github.com/moiot/gravity/pkg/core"
"github.com/moiot/gravity/pkg/metrics"
"github.com/moiot/gravity/pkg/mysql"
"github.com/moiot/gravity/pkg/position_store"
"github.com/moiot/gravity/pkg/schema_store"
"github.com/moiot/gravity/pkg/utils"
)
var ErrTableEmpty = errors.New("table... |
"github.com/juju/errors"
"github.com/pingcap/parser" | random_line_split |
mysql_table_scanner.go | package mysqlbatch
import (
"context"
"database/sql"
"fmt"
"reflect"
"strconv"
"sync"
"time"
"github.com/juju/errors"
"github.com/pingcap/parser"
log "github.com/sirupsen/logrus"
"github.com/moiot/gravity/pkg/core"
"github.com/moiot/gravity/pkg/metrics"
"github.com/moiot/gravity/pkg/mysql"
"github.com/... |
}
}
func (tableScanner *TableScanner) AfterMsgCommit(msg *core.Msg) error {
p, ok := msg.InputContext.(position_store.MySQLTablePosition)
if !ok {
return errors.Errorf("type invalid")
}
tableScanner.positionStore.PutCurrent(*msg.InputStreamKey, p)
return nil
}
func (tableScanner *TableScanner) initTableDDL... | {
log.Fatalf("[tableScanner] failed to emit: %v", errors.ErrorStack(err))
} | conditional_block |
index.ts | import {
ATOM,
IAtom,
IComposedAtom,
IConfig,
ICssPropToToken,
IScreens,
ISheet,
IThemeAtom,
ITokensDefinition,
TCss,
} from "./types";
import {
createSheets,
cssPropToToken,
getVendorPrefixAndProps,
hashString,
specificityProps,
} from "./utils";
export * from "./types";
export * from ".... | else if (canCallSpecificityProps && prop in specificityProps) {
createCssAtoms(
specificityProps[prop](config)(props[prop]) as any,
cb,
screen,
pseudo,
false,
false
);
} else {
cb(
createAtom(
prop,
... | {
createCssAtoms(
utils[prop](config)(props[prop]) as any,
cb,
screen,
pseudo,
false
);
} | conditional_block |
index.ts | import {
ATOM,
IAtom,
IComposedAtom,
IConfig,
ICssPropToToken,
IScreens,
ISheet,
IThemeAtom,
ITokensDefinition,
TCss,
} from "./types";
import {
createSheets,
cssPropToToken,
getVendorPrefixAndProps,
hashString,
specificityProps,
} from "./utils";
export * from "./types";
export * from ".... | this._className = className;
// @ts-ignore
this.toString = toStringCachedAtom;
return className;
};
const createToString = (
sheets: { [screen: string]: ISheet },
screens: IScreens = {},
cssClassnameProvider: (atom: IAtom, seq: number | null) => [string, string?], // [className, pseudo]
preInjectedRule... | const className = this.atoms.map((atom) => atom.toString()).join(" ");
// cache the className on this instance
// @ts-ignore | random_line_split |
telegraf.go | /*
* Copyright 2020 Rackspace US, Inc.
*
* 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 agr... |
func (tr *TelegrafRunner) handleTelegrafConfigurationOp(op *telemetry_edge.ConfigurationOp) bool {
switch op.GetType() {
case telemetry_edge.ConfigurationOp_CREATE, telemetry_edge.ConfigurationOp_MODIFY:
var finalConfig []byte
var err error
finalConfig, err = ConvertJsonToTelegrafToml(op.GetContent(), op.Extr... | {
var configs []byte
configs = append(configs, tr.tomlMainConfig...)
// telegraf can only handle one 'inputs' header per file so add exactly one here
configs = append(configs, []byte("[inputs]")...)
for _, v := range tr.tomlConfigs {
// remove the other redundant '[inputs]' headers here
if bytes.Equal([]byte("... | identifier_body |
telegraf.go | /*
* Copyright 2020 Rackspace US, Inc.
*
* 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 agr... |
// wait just a bit between each try
time.Sleep(telegrafTestMonitorRetryDelay)
}
log.
WithError(err).
WithField("correlationId", correlationId).
WithField("content", content).
WithField("out", string(cmdOut)).
Debug("ran telegraf with test config")
if err != nil {
if exitErr, ok := err.(*exec.ExitEr... | {
break
} | conditional_block |
telegraf.go | /*
* Copyright 2020 Rackspace US, Inc.
*
* 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 agr... | () {
tr.commandHandler.Stop(tr.running)
tr.running = nil
}
func (tr *TelegrafRunner) createMainConfig() ([]byte, error) {
data := &telegrafMainConfigData{
IngestAddress: tr.ingestAddress,
DefaultMonitoringInterval: viper.GetDuration(config.AgentsDefaultMonitoringInterval),
MaxFlushInterval: ... | Stop | identifier_name |
telegraf.go | /*
* Copyright 2020 Rackspace US, Inc.
*
* 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 agr... |
type TelegrafRunner struct {
ingestAddress string
basePath string
running *AgentRunningContext
commandHandler CommandHandler
configServerMux *http.ServeMux
configServerURL string
configServerToken string
configServerHandler http.HandlerFunc
tomlMainConfig []byt... | MaxFlushInterval time.Duration
} | random_line_split |
main_test.go | package main
import (
"bufio"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"log"
"os"
"strings"
"testing"
"github.com/CMSgov/bcda-app/bcda/client"
"github.com/CMSgov/bcda-app/bcda/database"
"github.com/CMSgov/bcda-app/bcda/models"
"github.com/CMSgov/bcda-app/bcda/testUtils"
que "github.com/bgentry/que-go"... | (t *testing.T) {
origFailPct := os.Getenv("EXPORT_FAIL_PCT")
defer os.Setenv("EXPORT_FAIL_PCT", origFailPct)
os.Setenv("EXPORT_FAIL_PCT", "60")
assert.Equal(t, 60.0, getFailureThreshold())
os.Setenv("EXPORT_FAIL_PCT", "-1")
assert.Equal(t, 0.0, getFailureThreshold())
os.Setenv("EXPORT_FAIL_PCT", "500")
asser... | TestGetFailureThreshold | identifier_name |
main_test.go | package main
import (
"bufio"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"log"
"os"
"strings"
"testing"
"github.com/CMSgov/bcda-app/bcda/client"
"github.com/CMSgov/bcda-app/bcda/database"
"github.com/CMSgov/bcda-app/bcda/models"
"github.com/CMSgov/bcda-app/bcda/testUtils"
que "github.com/bgentry/que-go"... | assert.Equal(t, ooResp+"\n", string(fData))
os.Remove(filePath)
}
func (bbc *MockBlueButtonClient) GetExplanationOfBenefitData(patientID string, jobID string) (string, error) {
args := bbc.Called(patientID)
return args.String(0), args.Error(1)
}
// Returns copy of a static json file (From Blue Button Sandbox ori... | }
ooResp := `{"resourceType":"OperationOutcome","issue":[{"severity":"Error"}]}`
| random_line_split |
main_test.go | package main
import (
"bufio"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"log"
"os"
"strings"
"testing"
"github.com/CMSgov/bcda-app/bcda/client"
"github.com/CMSgov/bcda-app/bcda/database"
"github.com/CMSgov/bcda-app/bcda/models"
"github.com/CMSgov/bcda-app/bcda/testUtils"
que "github.com/bgentry/que-go"... |
scanner := bufio.NewScanner(file)
// 33 entries in test EOB data returned by bbc.getData, times two beneficiaries
for i := 0; i < 66; i++ {
assert.True(t, scanner.Scan())
var jsonOBJ map[string]interface{}
err := json.Unmarshal(scanner.Bytes(), &jsonOBJ)
assert.Nil(t, err)
assert.NotNil(t, jsonO... | {
log.Fatal(err)
} | conditional_block |
main_test.go | package main
import (
"bufio"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"log"
"os"
"strings"
"testing"
"github.com/CMSgov/bcda-app/bcda/client"
"github.com/CMSgov/bcda-app/bcda/database"
"github.com/CMSgov/bcda-app/bcda/models"
"github.com/CMSgov/bcda-app/bcda/testUtils"
que "github.com/bgentry/que-go"... |
func (s *MainTestSuite) TestProcessJobEOB() {
db := database.GetGORMDbConnection()
defer database.Close(db)
j := models.Job{
ACOID: uuid.Parse("DBBD1CE1-AE24-435C-807D-ED45953077D3"),
UserID: uuid.Parse("82503A18-BF3B-436D-BA7B-BAE09B7FFD2F"),
RequestURL: "/api/v1/Patient/$export",
Status: "P... | {
fData, err := ioutil.ReadFile("../shared_files/synthetic_beneficiary_data/" + endpoint)
if err != nil {
return "", err
}
cleanData := strings.Replace(string(fData), "20000000000001", patientID, -1)
return cleanData, err
} | identifier_body |
api_op_ChangeCidrCollection.go | // Code generated by smithy-go-codegen DO NOT EDIT.
package route53
import (
"context"
"errors"
"fmt"
"github.com/aws/aws-sdk-go-v2/aws"
awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware"
"github.com/aws/aws-sdk-go-v2/aws/signer/v4"
internalauth "github.com/aws/aws-sdk-go-v2/internal/auth"
"github.co... |
if err = addendpointDisableHTTPSMiddleware(stack, options); err != nil {
return err
}
return nil
}
func newServiceMetadataMiddleware_opChangeCidrCollection(region string) *awsmiddleware.RegisterServiceMetadata {
return &awsmiddleware.RegisterServiceMetadata{
Region: region,
ServiceID: ServiceID,
... | {
return err
} | conditional_block |
api_op_ChangeCidrCollection.go | // Code generated by smithy-go-codegen DO NOT EDIT.
package route53
import (
"context"
"errors"
"fmt"
"github.com/aws/aws-sdk-go-v2/aws"
awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware"
"github.com/aws/aws-sdk-go-v2/aws/signer/v4"
internalauth "github.com/aws/aws-sdk-go-v2/internal/auth"
"github.co... | (stack *middleware.Stack, options Options) error {
return stack.Serialize.Insert(&opChangeCidrCollectionResolveEndpointMiddleware{
EndpointResolver: options.EndpointResolverV2,
BuiltInResolver: &builtInResolver{
Region: options.Region,
UseDualStack: options.EndpointOptions.UseDualStackEndpoint,
UseF... | addChangeCidrCollectionResolveEndpointMiddleware | identifier_name |
api_op_ChangeCidrCollection.go | // Code generated by smithy-go-codegen DO NOT EDIT.
package route53
import (
"context"
"errors"
"fmt"
"github.com/aws/aws-sdk-go-v2/aws"
awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware"
"github.com/aws/aws-sdk-go-v2/aws/signer/v4"
internalauth "github.com/aws/aws-sdk-go-v2/internal/auth"
"github.co... | }
if err = addOpChangeCidrCollectionValidationMiddleware(stack); err != nil {
return err
}
if err = stack.Initialize.Add(newServiceMetadataMiddleware_opChangeCidrCollection(options.Region), middleware.Before); err != nil {
return err
}
if err = awsmiddleware.AddRecursionDetection(stack); err != nil {
return... | if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil {
return err
}
if err = addChangeCidrCollectionResolveEndpointMiddleware(stack, options); err != nil {
return err | random_line_split |
api_op_ChangeCidrCollection.go | // Code generated by smithy-go-codegen DO NOT EDIT.
package route53
import (
"context"
"errors"
"fmt"
"github.com/aws/aws-sdk-go-v2/aws"
awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware"
"github.com/aws/aws-sdk-go-v2/aws/signer/v4"
internalauth "github.com/aws/aws-sdk-go-v2/internal/auth"
"github.co... |
func addChangeCidrCollectionResolveEndpointMiddleware(stack *middleware.Stack, options Options) error {
return stack.Serialize.Insert(&opChangeCidrCollectionResolveEndpointMiddleware{
EndpointResolver: options.EndpointResolverV2,
BuiltInResolver: &builtInResolver{
Region: options.Region,
UseDualStack... | {
if awsmiddleware.GetRequiresLegacyEndpoints(ctx) {
return next.HandleSerialize(ctx, in)
}
req, ok := in.Request.(*smithyhttp.Request)
if !ok {
return out, metadata, fmt.Errorf("unknown transport type %T", in.Request)
}
if m.EndpointResolver == nil {
return out, metadata, fmt.Errorf("expected endpoint re... | identifier_body |
mod.rs | // This file is part of Substrate.
// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Softwa... | prometheus_future::with_poll_durations(poll_duration, poll_start, task);
// The logic of `AssertUnwindSafe` here is ok considering that we throw
// away the `Future` after it has panicked.
panic::AssertUnwindSafe(inner).catch_unwind()
};
futures::pin_mut!(task);
match select(on_exit, t... | let poll_duration =
metrics.poll_duration.with_label_values(&[name, group, task_type_label]);
let poll_start =
metrics.poll_start.with_label_values(&[name, group, task_type_label]);
let inner = | random_line_split |
mod.rs | // This file is part of Substrate.
// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Softwa... | ,
TaskType::Blocking => {
let handle = self.tokio_handle.clone();
self.tokio_handle.spawn_blocking(move || {
handle.block_on(future);
});
},
}
}
}
impl sp_core::traits::SpawnNamed for SpawnTaskHandle {
fn spawn_blocking(
&self,
name: &'static str,
group: Option<&'static str>,
future:... | {
self.tokio_handle.spawn(future);
} | conditional_block |
mod.rs | // This file is part of Substrate.
// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Softwa... | {
essential_failed_tx: TracingUnboundedSender<()>,
inner: SpawnTaskHandle,
}
impl SpawnEssentialTaskHandle {
/// Creates a new `SpawnEssentialTaskHandle`.
pub fn new(
essential_failed_tx: TracingUnboundedSender<()>,
spawn_task_handle: SpawnTaskHandle,
) -> SpawnEssentialTaskHandle {
SpawnEssentialTaskHandl... | SpawnEssentialTaskHandle | identifier_name |
adapters.py | # Copyright 2014 Mirantis, Inc.
#
# 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 ... | (self):
return u'{0}-{1}'.format(self.plugin.name, self.plugin.version)
@property
def slaves_scripts_path(self):
return settings.PLUGINS_SLAVES_SCRIPTS_PATH.format(
plugin_name=self.path_name)
@property
def deployment_tasks(self):
deployment_tasks = []
for t... | full_name | identifier_name |
adapters.py | # Copyright 2014 Mirantis, Inc.
#
# 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 ... | class PluginAdapterV4(PluginAdapterV3):
"""Plugin wrapper class for package version 4.0.0"""
components = 'components.yaml'
def sync_metadata_to_db(self):
super(PluginAdapterV4, self).sync_metadata_to_db()
db_config_metadata_mapping = {
'components_metadata': self.components
... | data_to_update[attribute] = attribute_data
Plugin.update(self.plugin, data_to_update)
| random_line_split |
adapters.py | # Copyright 2014 Mirantis, Inc.
#
# 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 ... |
else:
logger.warning("Config {0} is not readable.".format(config))
def _load_tasks(self, config):
data = self._load_config(config)
for item in data:
# backward compatibility for plugins added in version 6.0,
# and it is expected that task with role: [con... | with open(config, "r") as conf:
try:
return yaml.safe_load(conf.read())
except yaml.YAMLError as exc:
logger.warning(exc)
raise errors.ParseError(
'Problem with loading YAML file {0}'.format(config)) | conditional_block |
adapters.py | # Copyright 2014 Mirantis, Inc.
#
# 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 ... |
class PluginAdapterV4(PluginAdapterV3):
"""Plugin wrapper class for package version 4.0.0"""
components = 'components.yaml'
def sync_metadata_to_db(self):
super(PluginAdapterV4, self).sync_metadata_to_db()
db_config_metadata_mapping = {
'components_metadata': self.component... | """Plugin wrapper class for package version 3.0.0"""
node_roles_config_name = 'node_roles.yaml'
volumes_config_name = 'volumes.yaml'
deployment_tasks_config_name = 'deployment_tasks.yaml'
network_roles_config_name = 'network_roles.yaml'
def sync_metadata_to_db(self):
"""Sync metadata from ... | identifier_body |
food.py | '''
Raj Palleti
Last revision: 8/16/19
This class instantiates foodProcessor to get each person's foods, allergens,
and nutrients from the user's text, which is recognized using the Google Voice Kit.
It then uses foodLog to log each person's dietary info into their own sheet in a Google Spreadsheet.
'''
# Set the '... | (text):
'''
This method splits the text into substrings, where each begins with a name
and continues until reaching the next name. It will return the list of substrings
and a list that contains the name in each substring.
'''
# Set your own path for the classification model and Stanford tagg... | get_substrings | identifier_name |
food.py | '''
Raj Palleti
Last revision: 8/16/19
This class instantiates foodProcessor to get each person's foods, allergens,
and nutrients from the user's text, which is recognized using the Google Voice Kit.
It then uses foodLog to log each person's dietary info into their own sheet in a Google Spreadsheet.
'''
# Set the '... |
index = index + len(word)
if index < len(text) and text[index] == ' ':
index = index + 1
newText += ' '
return newText
def get_substrings(text):
'''
This method splits the text into substrings, where each begins with a name
and continues until reaching the ... | if "female" in det.get_gender(word):
lastFemaleName = word
elif "male" in det.get_gender(word):
lastMaleName = word | conditional_block |
food.py | '''
Raj Palleti
Last revision: 8/16/19
This class instantiates foodProcessor to get each person's foods, allergens,
and nutrients from the user's text, which is recognized using the Google Voice Kit.
It then uses foodLog to log each person's dietary info into their own sheet in a Google Spreadsheet.
'''
# Set the '... | for nutrient in diet[name]['nutrients']:
ip.append(diet[name]['nutrients'][nutrient][i])
payload = {"values": [ip]}
flog.write_to_sheet(credentials, '1GxFpWhwISzni7DWviFzH500k9eFONpSGQ8uJ0-kBKY4', name, payload)
# Construct a new row cont... | else:
ip.append(diet[name]['allergens'][i])
| random_line_split |
food.py | '''
Raj Palleti
Last revision: 8/16/19
This class instantiates foodProcessor to get each person's foods, allergens,
and nutrients from the user's text, which is recognized using the Google Voice Kit.
It then uses foodLog to log each person's dietary info into their own sheet in a Google Spreadsheet.
'''
# Set the '... |
def log_diet(diet, rawText):
'''
This method uses the diet dictionary to log the dietary information for each person in the corresponding sheet.
It will also update everyone's summary log sheet.
'''
# Instantiate foodLog
flog = foodLog.foodLog()
cupertino = timezone('US/Pacific')
now... | '''
This method concatenates the list of allergens in each food to a string.
'''
if len(allergens) == 1:
return allergens[0]
algs = ''
for i in range(len(allergens)):
for j in range(len(allergens[i])):
if j == len(allergens[i]) - 1:
algs += allergens[i]... | identifier_body |
parser.go | // Package parser implements a parser for HCL (HashiCorp Configuration
// Language)
package parser
import (
"bytes"
"errors"
"fmt"
"strings"
"github.com/hashicorp/hcl/hcl/ast"
"github.com/hashicorp/hcl/hcl/scanner"
"github.com/hashicorp/hcl/hcl/token"
)
type Parser struct {
sc *scanner.Scanner
// Last read... |
// we don't return a nil node, because might want to use already
// collected items.
if err != nil {
return node, err
}
node.Add(n)
// object lists can be optionally comma-delimited e.g. when a list of maps
// is being expressed, so a comma is allowed here - it's simply consumed
tok := p.scan()
... | {
break // we are finished
} | conditional_block |
parser.go | // Package parser implements a parser for HCL (HashiCorp Configuration
// Language)
package parser
import (
"bytes"
"errors"
"fmt"
"strings"
"github.com/hashicorp/hcl/hcl/ast"
"github.com/hashicorp/hcl/hcl/scanner"
"github.com/hashicorp/hcl/hcl/token"
)
type Parser struct {
sc *scanner.Scanner
// Last read... | (p *Parser, msg string) *Parser {
p.printTrace(msg, "(")
p.indent++
return p
}
// Usage pattern: defer un(trace(p, "..."))
func un(p *Parser) {
p.indent--
p.printTrace(")")
}
| trace | identifier_name |
parser.go | // Package parser implements a parser for HCL (HashiCorp Configuration
// Language)
package parser
import (
"bytes"
"errors"
"fmt"
"strings"
"github.com/hashicorp/hcl/hcl/ast"
"github.com/hashicorp/hcl/hcl/scanner"
"github.com/hashicorp/hcl/hcl/token"
)
type Parser struct {
sc *scanner.Scanner
// Last read... | node := &ast.ObjectList{}
for {
if obj {
tok := p.scan()
p.unscan()
if tok.Type == token.RBRACE {
break
}
}
n, err := p.objectItem()
if err == errEofToken {
break // we are finished
}
// we don't return a nil node, because might want to use already
// collected items.
if err != n... | // The parameter" obj" tells this whether to we are within an object (braces:
// '{', '}') or just at the top level. If we're within an object, we end
// at an RBRACE.
func (p *Parser) objectList(obj bool) (*ast.ObjectList, error) {
defer un(trace(p, "ParseObjectList")) | random_line_split |
parser.go | // Package parser implements a parser for HCL (HashiCorp Configuration
// Language)
package parser
import (
"bytes"
"errors"
"fmt"
"strings"
"github.com/hashicorp/hcl/hcl/ast"
"github.com/hashicorp/hcl/hcl/scanner"
"github.com/hashicorp/hcl/hcl/token"
)
type Parser struct {
sc *scanner.Scanner
// Last read... |
func trace(p *Parser, msg string) *Parser {
p.printTrace(msg, "(")
p.indent++
return p
}
// Usage pattern: defer un(trace(p, "..."))
func un(p *Parser) {
p.indent--
p.printTrace(")")
}
| {
if !p.enableTrace {
return
}
const dots = ". . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . "
const n = len(dots)
fmt.Printf("%5d:%3d: ", p.tok.Pos.Line, p.tok.Pos.Column)
i := 2 * p.indent
for i > n {
fmt.Print(dots)
i -= n
}
// i <= n
fmt.Print(dots[0:i])
fmt.Println(a...)
} | identifier_body |
dom-movement.ts | /**
* This is required to work around a problem when extending built-in classes
* like ``Error``. Some of the constructors for these classes return a value
* from the constructor, which is then picked up by the constructors generated
* by TypeScript (same with ES6 code transpiled through Babel), and this messes
* ... | while (current !== null);
}
}
| {
yield current;
current = this.previous(current);
} | conditional_block |
dom-movement.ts | /**
* This is required to work around a problem when extending built-in classes
* like ``Error``. Some of the constructors for these classes return a value
* from the constructor, which is then picked up by the constructors generated
* by TypeScript (same with ES6 code transpiled through Babel), and this messes
* ... | (node: Node, offset: number, child: Node): 1 | 0 | -1 {
const pointed = node.childNodes[offset];
if (pointed === undefined) {
// Undefined means we are after all other elements. (A negative offset,
// before all nodes, is not possible here.)
return 1;
}
// We return -1 when pointed === child becaus... | pointedCompare | identifier_name |
dom-movement.ts | /**
* This is required to work around a problem when extending built-in classes
* like ``Error``. Some of the constructors for these classes return a value
* from the constructor, which is then picked up by the constructors generated
* by TypeScript (same with ES6 code transpiled through Babel), and this messes
* ... |
}
type NodeTest = (node: Node) => boolean;
// tslint:disable-next-line:no-any
function indexOf(arrayLike: any, el: any): number {
return Array.prototype.indexOf.call(arrayLike, el);
}
/**
* A space delimits a part of a DOM tree in which one can obtain locations.
*/
export class DOMSpace implements Iterable<DOML... | {
if (this.equals(other)) {
return 0;
}
const { node, offset } = this;
const { node: otherNode, offset: otherOffset } = other;
if (node === otherNode) {
// The case where offset === otherOffset cannot happen here because it is
// covered above.
return offset - otherOffset <... | identifier_body |
dom-movement.ts | /**
* This is required to work around a problem when extending built-in classes
* like ``Error``. Some of the constructors for these classes return a value
* from the constructor, which is then picked up by the constructors generated
* by TypeScript (same with ES6 code transpiled through Babel), and this messes
* ... | return this.offset === this.normalizedOffset;
}
/**
* Convert a location with an offset which is out of bounds, to a location
* with an offset within bounds.
*
* An offset less than 0 will be normalized to 0. An offset pointing beyond
* the end of the node's data will be normalized to point at t... |
/**
* ``true`` if the location is already normalized. ``false`` if not.
*/
get isNormalized(): boolean { | random_line_split |
routing.py | """Routing configuration, broken out separately for ease of consultation
without going through the whole app config everything.
Some useful helpers are at the bottom. Be familiar with them!
"""
import re
import floof.model as model
from floof.resource import contextualize
from pyramid.exceptions import NotFound
from... |
def filter_sqlalchemy_query(self, query, request):
"""Takes a query, filters it as demanded by the matchdict, and returns
a new one.
"""
query = query.filter(self.sqla_column == request.matchdict[self.key])
if self.parent_router:
query = query.join(self.sqla_re... | """Constructs a chain of url prefixes going up to the root."""
if self.parent_router:
ret = self.parent_router.full_url_prefix
else:
ret = ''
ret += self.url_prefix
return ret | identifier_body |
routing.py | """Routing configuration, broken out separately for ease of consultation
without going through the whole app config everything.
Some useful helpers are at the bottom. Be familiar with them!
"""
import re
import floof.model as model
from floof.resource import contextualize
from pyramid.exceptions import NotFound
from... |
self.key = match.group(1)
### Dealing with chaining
def chain(self, url_prefix, sqla_column, rel):
"""Create a new sugar router with this one as the parent."""
return self.__class__(
self.config, url_prefix, sqla_column,
parent_router=self, rel=rel)
@prop... | raise ValueError("Can't find a route kwarg in {0!r}".format(url_prefix)) | conditional_block |
routing.py | """Routing configuration, broken out separately for ease of consultation
without going through the whole app config everything.
Some useful helpers are at the bottom. Be familiar with them!
"""
import re
import floof.model as model
from floof.resource import contextualize
from pyramid.exceptions import NotFound
from... | (title):
"""Given a title that will be used as flavor text in a URL, returns a
string that will look less like garbage in an address bar.
"""
# RFC 3986 section 2.3 says: letters, numbers, and -_.~ are unreserved
return re.sub('[^-_.~a-zA-Z0-9]', '-', title)
def filestore_pregenerator(request, elem... | _make_url_friendly | identifier_name |
routing.py | """Routing configuration, broken out separately for ease of consultation
without going through the whole app config everything.
Some useful helpers are at the bottom. Be familiar with them!
"""
import re
import floof.model as model
from floof.resource import contextualize
from pyramid.exceptions import NotFound
from... | """Takes a query, filters it as demanded by the matchdict, and returns
a new one.
"""
query = query.filter(self.sqla_column == request.matchdict[self.key])
if self.parent_router:
query = query.join(self.sqla_rel)
query = self.parent_router.filter_sqlalche... |
def filter_sqlalchemy_query(self, query, request): | random_line_split |
mod.rs | // Copyright © 2020 Brian Merchant.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except accordi... | pub const_retractive: f64,
/// Stiffness of cytoplasm.
pub stiffness_cyto: f64,
/// Rate of Rho GTPase GDI unbinding and subsequent membrane attachment.
pub k_mem_on_vertex: f64,
/// Rate of Rho GTPase membrane disassociation.
pub k_mem_off: f64,
/// Diffusion rate of Rho GTPase on membr... | /// Stiffness of edge.
pub stiffness_edge: f64,
/// Rac1 mediated protrusive force constant.
pub const_protrusive: f64,
/// RhoA mediated protrusive force constant. | random_line_split |
mod.rs | // Copyright © 2020 Brian Merchant.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except accordi... | {
/// Viscosity value used to calculate change in position of a
/// vertex due to calculated forces on it.
pub vertex_eta: f64,
pub interactions: InteractionParams,
}
impl RawWorldParameters {
pub fn refine(&self, bq: &CharacteristicQuantities) -> WorldParameters {
WorldParameters {
... | orldParameters | identifier_name |
plugins.go | // Copyright 2015 Light Code Labs, LLC
//
// 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 agre... |
// caddyfile loaders in registration order
for _, loader := range caddyfileLoaders {
p["caddyfile_loaders"] = append(p["caddyfile_loaders"], loader.name)
}
if defaultCaddyfileLoader.name != "" {
p["caddyfile_loaders"] = append(p["caddyfile_loaders"], defaultCaddyfileLoader.name)
}
// List the event hook pl... | {
p["server_types"] = append(p["server_types"], name)
} | conditional_block |
plugins.go | // Copyright 2015 Light Code Labs, LLC
//
// 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 agre... | (serverType, afterDir string, callback ParsingCallback) {
if _, ok := parsingCallbacks[serverType]; !ok {
parsingCallbacks[serverType] = make(map[string][]ParsingCallback)
}
parsingCallbacks[serverType][afterDir] = append(parsingCallbacks[serverType][afterDir], callback)
}
// SetupFunc is used to set up a plugin,... | RegisterParsingCallback | identifier_name |
plugins.go | // Copyright 2015 Light Code Labs, LLC
//
// 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 agre... |
// restoreEventHooks restores eventHooks with a provided *sync.Map
func restoreEventHooks(m *sync.Map) {
// Purge old event hooks
purgeEventHooks()
// Restore event hooks
m.Range(func(k, v interface{}) bool {
eventHooks.Store(k, v)
return true
})
}
// ParsingCallback is a function that is called after
// a... | {
eventHooks.Range(func(k, _ interface{}) bool {
eventHooks.Delete(k)
return true
})
} | identifier_body |
plugins.go | // Copyright 2015 Light Code Labs, LLC
//
// 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 agre... | // limitations under the License.
package caddy
import (
"fmt"
"log"
"net"
"sort"
"sync"
"github.com/coredns/caddy/caddyfile"
)
// These are all the registered plugins.
var (
// serverTypes is a map of registered server types.
serverTypes = make(map[string]ServerType)
// plugins is a map of server type to... | // See the License for the specific language governing permissions and | random_line_split |
2#allAnglesLengths.py | #!/usr/bin/env python
#all_angle_lengths.py
""" Calculates all angles, lengths and representative angles and lengths.
For a given triple of amino acids, this calculates all the angles , lengths
and representative angle and length. The angles are the angles formed by the
median of corresponding vertex an... |
def indexFind(index_of_2,i1,j1,k1):
if index_of_2==i1:
indexOf0=j1
indexOf1=k1
elif index_of_2==j1:
indexOf0=i1
indexOf1=k1
elif index_of_2==k1:
indexOf0=i1
indexOf1=j1
return indexOf0, indexOf1
def processFiles(fileName):
"""Calculates all angles, al... | """Calculate Distance between two points in 3D space."""
x1=xCord[indexLabel1]
x2=xCord[indexLabel2]
y1=yCord[indexLabel1]
y2=yCord[indexLabel2]
z1=zCord[indexLabel1]
z2=zCord[indexLabel2]
distance=(((x1-x2)**2+(y2-y1)**2+(z2-z1)**2)**0.5)
return distance | identifier_body |
2#allAnglesLengths.py | #!/usr/bin/env python
#all_angle_lengths.py
""" Calculates all angles, lengths and representative angles and lengths.
For a given triple of amino acids, this calculates all the angles , lengths
and representative angle and length. The angles are the angles formed by the
median of corresponding vertex an... | Theta2=180*(math.acos((s1**2-s2**2-s3**2)/(2*s2*s3)))/3.14
#if Theta2 > 90:
# Theta2 = abs(180-Theta2)
if Theta2<=90:
all_angleList[round(Theta2,round_off_to)] +=1
else:
all_angleList[round(abs(1... | random_line_split | |
2#allAnglesLengths.py | #!/usr/bin/env python
#all_angle_lengths.py
""" Calculates all angles, lengths and representative angles and lengths.
For a given triple of amino acids, this calculates all the angles , lengths
and representative angle and length. The angles are the angles formed by the
median of corresponding vertex an... | (indexLabel1,indexLabel2):
"""Calculate Distance between two points in 3D space."""
x1=xCord[indexLabel1]
x2=xCord[indexLabel2]
y1=yCord[indexLabel1]
y2=yCord[indexLabel2]
z1=zCord[indexLabel1]
z2=zCord[indexLabel2]
distance=(((x1-x2)**2+(y2-y1)**2+(z2-z1)**2)**0.5)
return distance
d... | calcDist | identifier_name |
2#allAnglesLengths.py | #!/usr/bin/env python
#all_angle_lengths.py
""" Calculates all angles, lengths and representative angles and lengths.
For a given triple of amino acids, this calculates all the angles , lengths
and representative angle and length. The angles are the angles formed by the
median of corresponding vertex an... |
elif(sortedLabel[0]==sortedLabel[1])and(sortedLabel[1]!=sortedLabel[2]):
indexOf2=keepLabelIndex[sortedLabel[2]]
indices=indexFind(indexOf2,i,j,k)
a=indexOf2
b=indices[0]
c=indices[1]
... | for index_ in range(0,3):
sortedIndex[index_]=keepLabelIndex[sortedLabel[index_]]
indexOf0=sortedIndex[0]
indexOf1=sortedIndex[1]
indexOf2=sortedIndex[2] | conditional_block |
kmz.go | // cutkmz subcommands
//
// Other than root.go, each of these go files is a cutkmz subcommand implementation
//
// - kmz - produces a KMZ with input JPG chopped into 1024x1024 tiles
// - bigkmz - produces a KMZ containing input JPG as is for higher resolution uses such as Google Earth
package cmd
import (
"ar... |
// finishTileBox completes the tile.box by setting its east and south
// boundaries relative to its current north and west values using the
// tile pixel size reltative to the full map size.
func finishTileBox(tile, fullMap *mapTile) {
nsDeltaDeg, ewDeltaDeg := delta(tile.width, tile.height, fullMap.box, fullMap.wid... | {
t, err := template.New("kmlftr").Parse(kmlFtr)
if err != nil {
return err
}
return t.Execute(w, nil)
} | identifier_body |
kmz.go | // cutkmz subcommands
//
// Other than root.go, each of these go files is a cutkmz subcommand implementation
//
// - kmz - produces a KMZ with input JPG chopped into 1024x1024 tiles
// - bigkmz - produces a KMZ containing input JPG as is for higher resolution uses such as Google Earth
package cmd
import (
"ar... | (outFile, inFile string, maxPixArea int) error {
// param order super sensitive
cmd := exec.Command("convert", "-resize", "@"+fmt.Sprintf("%v", maxPixArea), inFile, "-strip", "-interlace", "none", outFile)
glog.Infof("About to run: %#v\n", cmd.Args)
_, err := cmd.Output()
if err != nil {
return err
}
return ni... | resizeFixToJpg | identifier_name |
kmz.go | // cutkmz subcommands
//
// Other than root.go, each of these go files is a cutkmz subcommand implementation
//
// - kmz - produces a KMZ with input JPG chopped into 1024x1024 tiles
// - bigkmz - produces a KMZ containing input JPG as is for higher resolution uses such as Google Earth
package cmd
import (
"ar... | if err := process(viper.GetViper(), args); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
fmt.Fprintf(os.Stderr, "see 'cutkmz kmz -h' for help\n")
os.Exit(1)
}
},
}
func init() {
RootCmd.AddCommand(kmzCmd)
kmzCmd.Flags().StringP("image", "i", "", "image file named with its bounding box in dec... |
`,
Run: func(cmd *cobra.Command, args []string) { | random_line_split |
kmz.go | // cutkmz subcommands
//
// Other than root.go, each of these go files is a cutkmz subcommand implementation
//
// - kmz - produces a KMZ with input JPG chopped into 1024x1024 tiles
// - bigkmz - produces a KMZ containing input JPG as is for higher resolution uses such as Google Earth
package cmd
import (
"ar... |
return e - w
}
// normEasting returns the given longitude in dec degress normalized to be within [-180,180]
func normEasting(deg float64) float64 {
// go's Mod fcn preserves sign on first param
if deg < -180 {
return math.Mod(deg+180, 360) + 180
}
if deg > 180 {
return math.Mod(deg-180, 360) - 180
}
return... | {
return 360 + e - w
} | conditional_block |
redis.go | // Copyright 2020 gorse Project Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed ... | (ctx context.Context, sortedSets ...SortedSet) error {
p := r.client.Pipeline()
for _, sorted := range sortedSets {
if len(sorted.scores) > 0 {
members := make([]redis.Z, 0, len(sorted.scores))
for _, score := range sorted.scores {
members = append(members, redis.Z{Member: score.Id, Score: score.Score})
... | AddSorted | identifier_name |
redis.go | // Copyright 2020 gorse Project Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed ... |
// AddSorted add scores to sorted set.
func (r *Redis) AddSorted(ctx context.Context, sortedSets ...SortedSet) error {
p := r.client.Pipeline()
for _, sorted := range sortedSets {
if len(sorted.scores) > 0 {
members := make([]redis.Z, 0, len(sorted.scores))
for _, score := range sorted.scores {
members =... | strconv.FormatFloat(end, 'g', -1, 64)).
Err()
} | random_line_split |
redis.go | // Copyright 2020 gorse Project Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed ... |
return &ReturnValue{err: err}
}
return &ReturnValue{value: val}
}
// Delete object from Redis.
func (r *Redis) Delete(ctx context.Context, key string) error {
return r.client.Del(ctx, r.Key(key)).Err()
}
// GetSet returns members of a set from Redis.
func (r *Redis) GetSet(ctx context.Context, key string) ([]st... | {
return &ReturnValue{err: errors.Annotate(ErrObjectNotExist, key)}
} | conditional_block |
redis.go | // Copyright 2020 gorse Project Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed ... |
// Init nothing.
func (r *Redis) Init() error {
return nil
}
func (r *Redis) Scan(work func(string) error) error {
ctx := context.Background()
if clusterClient, isCluster := r.client.(*redis.ClusterClient); isCluster {
return clusterClient.ForEachMaster(ctx, func(ctx context.Context, client *redis.Client) error... | {
return r.client.Ping(context.Background()).Err()
} | identifier_body |
input.go | package tui
import (
"context"
"fmt"
"sync"
"time"
"unicode/utf8"
"golang.org/x/crypto/ssh/terminal"
)
const (
// Basic keycodes, map directly to their ANSI numbering
// order strictly matters
Null rune = iota // ctrl-space
CtrlA
CtrlB
CtrlC
CtrlD // aka EOF
CtrlE
CtrlF
CtrlG
CtrlH // \b backsp But... | (fd int, nonblock bool) (int, bool) {
b := make([]byte, 1)
err := setNonBlock(fd, nonblock)
if err != nil {
return 0, false
}
if n, err := sysRead(fd, b); err != nil || n < 1 {
return 0, false
}
return int(b[0]), true
}
//@todo: more shift/ctrl/alt of extended keys like Home, F#, PgUp
//http://www.manmrk.ne... | getchar | identifier_name |
input.go | package tui
import (
"context"
"fmt"
"sync"
"time"
"unicode/utf8"
"golang.org/x/crypto/ssh/terminal"
)
const (
// Basic keycodes, map directly to their ANSI numbering
// order strictly matters
Null rune = iota // ctrl-space
CtrlA
CtrlB
CtrlC
CtrlD // aka EOF
CtrlE
CtrlF
CtrlG
CtrlH // \b backsp But... |
ib := inputBuf{b: make([]byte, 0, 9)}
go func() {
for {
select {
case <-ctx.Done():
return
case ev := <-ib.readEvent(fd):
ch <- ev
}
}
}()
return ch, restore, nil
}
type inputBuf struct {
b []byte
mu sync.Mutex
}
func (ib *inputBuf) readEvent(fd int) <-chan Event {
ch := make(chan Ev... | {
return nil, restore, err
} | conditional_block |
input.go | package tui
import (
"context"
"fmt"
"sync"
"time"
"unicode/utf8"
"golang.org/x/crypto/ssh/terminal"
)
const (
// Basic keycodes, map directly to their ANSI numbering
// order strictly matters
Null rune = iota // ctrl-space
CtrlA
CtrlB
CtrlC
CtrlD // aka EOF
CtrlE
CtrlF
CtrlG
CtrlH // \b backsp But... |
/*
* Gets first byte, blocking to do so.
* Tries to get any extra bytes within a 100ms timespan
* like esc key sequences (arrows, etc)
*
*/
func fillBuf(fd int, buf []byte) []byte {
const pollInt = 5 //ms
const span = 100 //ms -- reflected via retries*pollInt
c, ok := getchar(fd, false)
if !ok {
return b... | {
ch := make(chan Event)
go func() {
ib.mu.Lock()
defer func() {
ib.mu.Unlock()
}()
for ; len(ib.b) == 0; ib.b = fillBuf(fd, ib.b) {
}
if len(ib.b) == 0 {
close(ch)
return
}
sz := 1
defer func() {
ib.b = ib.b[sz:]
}()
switch ib.b[0] {
case byte(CtrlC), byte(CtrlG), byte(CtrlQ)... | identifier_body |
input.go | package tui
import (
"context"
"fmt"
"sync"
"time"
"unicode/utf8"
"golang.org/x/crypto/ssh/terminal"
)
const (
// Basic keycodes, map directly to their ANSI numbering
// order strictly matters
Null rune = iota // ctrl-space
CtrlA
CtrlB
CtrlC
CtrlD // aka EOF
CtrlE
CtrlF
CtrlG
CtrlH // \b backsp But... |
type EvType uint8
const (
EventInvalid EvType = iota
KeySpecial
KeyPrint
Mouse
)
/*
How to determine mouse action:
Mousedown: Type=Mouse && Btn != 3 && !Motion
Mouseup: Type=Mouse && Btn == 3 && !Motion
Mousedrag: Type=Mouse && Btn != 3 && Motion
Mousemove: Type=Mouse && Btn == 3 && Motion
ScrollUp: Type... | CtrlAltz
) | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.