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
backend.rs
fn consolidate(&mut self, other: Self); } impl Consolidate for () { fn consolidate(&mut self, _: Self) { () } } impl Consolidate for Vec<(Option<Vec<u8>>, Vec<u8>, Option<Vec<u8>>)> { fn consolidate(&mut self, mut other: Self) { self.append(&mut other); } } impl<H: Hasher, KF: trie::KeyFunction<H>> Consolid...
{ 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
fn exists_child_storage(&self, storage_key: &[u8], key: &[u8]) -> Result<bool, Self::Error> { Ok(self.child_storage(storage_key, key)?.is_some()) } /// Retrieve all entries keys of child storage and call `f` for each of those keys. fn for_keys_in_child_storage<F: FnMut(&[u8])>(&self, storage_key: &[u8], f: F); ...
{ Ok(self.inner.get(&None).map(|map| map.get(key).is_some()).unwrap_or(false)) }
identifier_body
manager.go
:= 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
i, v := range proto.RankHero { rank := i + 1 newHero := newRankHero(v.HeroId, u64.FromInt64(int64(v.Score)), u64.FromInt64(int64(v.RankScore)), v.Win, v.Lose, rank, v.Mirror) newRo.heroMap[newHero.heroId] = newHero newRo.rankHeros = append(newRo.rankHeros, newHero) } m.rrl.set(newRo) m.Lock() def...
return protoBytes }
random_line_split
manager.go
Hero, &server_proto.XuanyuanRankHeroProto{ HeroId: v.heroId, Score: v.score.Load(), RankScore: v.rankScore, Win: v.win.Load(), Lose: v.lose.Load(), Mirror: mirror, }) } } m.RLock() defer m.RUnlock() for _, v := range m.challengerMap { proto.Challenger = append(pr...
.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
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
` binding library. */ new webpack.IgnorePlugin({ resourceRegExp: /^\.\/native$/, contextRegExp: /node_modules\/pg\/lib$/, }), ]; if (!devServer) { // Generate some stats for the bundles plugins.push(getBundleAnalyzerPlugin(analyze, path.resolve(st...
{ 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
string` appName: title, // TODO: Your application's description. `string` appDescription: null, // TODO: Your (or your developer's) name. `string` developerName: null, // TODO: Your (or your developer...
// Look from this library's node modules! modules: [ownModulesDirPath, modulesDirPath], },
random_line_split
webpack.ts
Windows 8 tile icons. `boolean` or `{ background }` windows: !devServer && !debug, // Create Yandex browser icon. `boolean` or `{ background }` yandex: false, }, }, }), ); } return { ...
getCommonRules
identifier_name
webpack.ts
Server) { plugins.push( // Generate some stats for the bundles getBundleAnalyzerPlugin(analyze, path.resolve(stageDirPath, `report-frontend.html`)), ); } // Define the entry for the app const entries: Record<string, string[]> = { app: [require.resolve(devServe...
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
1])] # 모든 x에서 가장 작은 blob y_max_blob = blob_info[np.argmax(blob_info[::, 1])] # int로 변경 x_min_blob = x_min_blob.astype(np.int) x_max_blob = x_max_blob.astype(np.int) y_min_blob = y_min_blob.astype(np.int) y_max_blob = y_max_blob.astype(np.int) print('x_min_blob : ', x_min_blob[0:2])...
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
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
params.filterByConvexity = False params.filterByInertia = True params.minInertiaRatio = 0.7; # 타원~원 = 0~1 # 줄 = 0 detector = cv2.SimpleBlobDetector_create(params) keypoints = detector.detect(img_copy) print('Detecting한 Blob개수 : ', len(keypoints)) # Blob labeling 수행 im_with_key...
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
# find 5 ymin 5 ymax blob sorted_y_blob = blob_info[blob_info[::, 1].argsort()] # y기준 sort y_min_5_blob = sorted_y_blob[:5] # 모든 y에서 가장 작은 5개 blob 후보군 y_max_5_blob = sorted_y_blob[-5:] # 모든 y에서 가장 큰 5개 blob 후보군 x_max_blob_of_y_min = y_min_5_blob[np.argmax(y_min_5_blob[::, 0])] # (1) x_min...
t.subplot(
identifier_name
ml_cms_heights.py
idx, len(lat_lons) # vals_pi.append(rgeo.get_value_at_point('C:\\Users\\ritvik\\Documents\\PhD\\Projects\\CMS\\Input\\Soils\\PI.tif', # lon, lat, replace_ras=False)) # vals_di.append(rgeo.get_value_at_point('C:\\Users\\ritvik\\Documents\\PhD\\P...
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
countries x crops # train_ml_model # create_train_df # compute_ml_vars # ; create ml model # loop_forecasting # create_forecast_df # do_forecasting class MLCms: """ """ def __init__(self, config_file=''): # Parse config file self.parser...
# clf.fit(data, target) # # predict_val = clf.predict(after.as_matrix(columns=cols[1:])) # results = compute_stats.ols(predict_val.tolist(), after_target.tolist()) # print results.rsquared # import matplotlib.pyplot as plt # plt.scatter(after_target, predict_val) ...
""" :return: """ logger.info('#########################################################################') logger.info('train_ml_model') logger.info('#########################################################################') #############################################...
identifier_body
ml_cms_heights.py
x crops # train_ml_model # create_train_df # compute_ml_vars # ; create ml model # loop_forecasting # create_forecast_df # do_forecasting class MLCms: """ """ def __init__(self, config_file=''): # Parse config file self.parser = SafeCon...
(self): """ :return: """ logger.info('#########################################################################') logger.info('train_ml_model') logger.info('#########################################################################') #############################...
train_ml_model
identifier_name
ml_cms_heights.py
countries x crops # train_ml_model # create_train_df # compute_ml_vars # ; create ml model # loop_forecasting
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
_vars", 0755) exec.Command("cp", "-rfp", "./kubespray/inventory/sample/", "./kubespray/inventory/awscluster/").Run() exec.Command("cp", "./kubespray/inventory/hosts", "./kubespray/inventory/awscluster/hosts").Run() //Enable load balancer api access and copy the kubeconfig file locally loadBalancerName...
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
/group_vars", 0755) exec.Command("cp", "-rfp", "./kubespray/inventory/sample/", "./kubespray/inventory/awscluster/").Run() exec.Command("cp", "./kubespray/inventory/hosts", "./kubespray/inventory/awscluster/hosts").Run() //Enable load balancer api access and copy the kubeconfig file locally loadBalanc...
awsBastionSize := viper.GetString("aws.aws_bastion_size") awsKubeMasterNum := viper.GetString("aws.aws_kube_master
awsCidrSubnetsPrivate := viper.GetString("aws.aws_cidr_subnets_private") awsCidrSubnetsPublic := viper.GetString("aws.aws_cidr_subnets_public")
random_line_split
aws.go
_ACCESS_KEY = %s\n", awsSecretKey) fmt.Fprintf(file, "AWS_SSH_KEY_NAME = %s\n", awsAccessSSHKey) fmt.Fprintf(file, "AWS_DEFAULT_REGION = %s\n", awsDefaultRegion) } terrSet := exec.Command("terraform", "destroy", "-var-file=credentials.tfvars", "-force") terrSet.Dir = "./kubespray/contrib/terraform/aws/...
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
credentials.tfvars"); err == nil { fmt.Println("Credentials file already exists, creation skipped") } else { fmt.Println("Please enter your AWS access key ID") var awsAccessKeyID string fmt.Scanln(&awsAccessKeyID) fmt.Println("Please enter your AWS SECRET ACCESS KEY") var awsSecretKey strin...
nit(
identifier_name
raft.go
storage, // where it can later be retrieved after a crash and restart. // see paper's Figure 2 for a description of what should be persistent. // func (rf *Raft) persist() { // Your code here. // Example: // w := new(bytes.Buffer) // e := gob.NewEncoder(w) // e.Encode(rf.xxx) // e.Encode(rf.yyy) // data := w.By...
{ 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
(args RequestAppendEntriesArgs, reply *RequestAppendEntriesReply) { // Your code here. // Q: should candidate append entries? //fmt.Println("[::RequestAppendEntries]", args) rf.mtx.Lock() defer rf.mtx.Unlock() defer rf.persist() // case 1: check term reply.Success = false if args.Term < rf.currentTerm { re...
{ // Your code here, if desired. }
identifier_body
raft.go
, rf.state == STATE_LEADER } // // save Raft's persistent state to stable storage, // where it can later be retrieved after a crash and restart. // see paper's Figure 2 for a description of what should be persistent. // func (rf *Raft) persist() { // Your code here. // Example: // w := new(bytes.Buffer) // e := go...
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
crash and restart. // see paper's Figure 2 for a description of what should be persistent. // func (rf *Raft) persist() { // Your code here. // Example: // w := new(bytes.Buffer) // e := gob.NewEncoder(w) // e.Encode(rf.xxx) // e.Encode(rf.yyy) // data := w.Bytes() // rf.persister.SaveRaftState(data) w := new...
broadcastAppendEntries
identifier_name
mod.rs
pub struct VirtualMethod<'ast> { pub sig: FnSig<'ast>, pub body: Option<&'ast Block>, } pub struct FnSig<'ast> { pub name: Ident, pub inputs: Vec<FnArg<'ast>>, pub output: Ty<'ast>, } pub enum FnArg<'ast> { SelfRef(Token!(&), Token!(self)), Arg { mutbl: Option<Token![mut]>, ...
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
pub struct VirtualMethod<'ast> { pub sig: FnSig<'ast>, pub body: Option<&'ast Block>, } pub struct FnSig<'ast> { pub name: Ident, pub inputs: Vec<FnArg<'ast>>, pub output: Ty<'ast>, } pub enum FnArg<'ast> { SelfRef(Token!(&), Token!(self)), Arg { mutbl: Option<Token![mut]>, ...
} } } 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
pub struct VirtualMethod<'ast> { pub sig: FnSig<'ast>, pub body: Option<&'ast Block>, } pub struct FnSig<'ast> { pub name: Ident, pub inputs: Vec<FnArg<'ast>>, pub output: Ty<'ast>, } pub enum FnArg<'ast> { SelfRef(Token!(&), Token!(self)), Arg { mutbl: Option<Token![mut]>, ...
(&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
model_event # Try creating an event just to trigger validation _ = self.get_api_event() self.upload_exception = None @abc.abstractmethod def get_api_event(self): """ Get an API event instance """ pass def get_file_entry(self): """ Get information for a fil...
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
model_event # Try creating an event just to trigger validation _ = self.get_api_event() self.upload_exception = None @abc.abstractmethod def get_api_event(self): """ Get an API event instance """ pass def get_file_entry(self): """ Get information for a fil...
(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
model_event # Try creating an event just to trigger validation _ = self.get_api_event() self.upload_exception = None @abc.abstractmethod def get_api_event(self): """ Get an API event instance """ pass def get_file_entry(self): """ Get information for a fil...
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
model_event # Try creating an event just to trigger validation _ = self.get_api_event() self.upload_exception = None @abc.abstractmethod def get_api_event(self): """ Get an API event instance """ pass def get_file_entry(self): """ Get information for a fil...
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
I: IntoIterator<Item = MerkleNode>, <I as IntoIterator>::IntoIter: ExactSizeIterator<Item = MerkleNode>, { let mut tag_engine = sha256::Hash::engine(); tag_engine.input(prefix.as_bytes()); tag_engine.input(":merkle:".as_bytes()); let iter = data.into_iter(); let width = iter.len(); // Tag...
engine_proto, iter, depth + 1, (div % 2 + len % 2) / 2 == 1, Some(empty_node), ); assert_eq!( height1, height2, "merklization algorithm failure: height of subtrees is not equal \ (width = {}, de...
{ 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
I: IntoIterator<Item = MerkleNode>, <I as IntoIterator>::IntoIter: ExactSizeIterator<Item = MerkleNode>, { let mut tag_engine = sha256::Hash::engine(); tag_engine.input(prefix.as_bytes()); tag_engine.input(":merkle:".as_bytes()); let iter = data.into_iter(); let width = iter.len(); // Tag...
} 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
I: IntoIterator<Item = MerkleNode>, <I as IntoIterator>::IntoIter: ExactSizeIterator<Item = MerkleNode>, { let mut tag_engine = sha256::Hash::engine(); tag_engine.input(prefix.as_bytes()); tag_engine.input(":merkle:".as_bytes()); let iter = data.into_iter(); let width = iter.len(); // Tag...
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
I: IntoIterator<Item = MerkleNode>, <I as IntoIterator>::IntoIter: ExactSizeIterator<Item = MerkleNode>, { let mut tag_engine = sha256::Hash::engine(); tag_engine.input(prefix.as_bytes()); tag_engine.input(":merkle:".as_bytes()); let iter = data.into_iter(); let width = iter.len(); // Tag...
<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
tableName string, maxFullDumpRowsCount int) (string, error) { pks, err := utils.GetPrimaryKeys(sourceDB, dbName, tableName) if err != nil { return "", errors.Trace(err) } if len(pks) == 1 { return pks[0], nil } uniqueIndexes, err := utils.GetUniqueIndexesWithoutPks(sourceDB, dbName, tableName) if err != n...
initTableDDL
identifier_name
mysql_table_scanner.go
tableName) } func FindMaxMinValueFromDB(db *sql.DB, dbName string, tableName string, scanColumn string) (interface{}, interface{}) { var max interface{} var min interface{} maxStatement := fmt.Sprintf("SELECT MAX(`%s`) FROM `%s`.`%s`", scanColumn, dbName, tableName) log.Infof("[FindMaxMinValueFromDB] statement: ...
{ 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
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
} func (tableScanner *TableScanner) Wait() { tableScanner.wg.Wait() } // DetectScanColumn find a column that we used to scan the table // SHOW INDEX FROM .. // Pick primary key, if there is only one primary key // If pk not found try using unique index // fail func DetectScanColumn(sourceDB *sql.DB, dbName string, t...
{ log.Fatalf("[tableScanner] failed to emit: %v", errors.ErrorStack(err)) }
conditional_block
index.ts
this._className = className[0]; // 3. switch from this `toString` to a much simpler one this.toString = toStringCachedAtom; return className[0]; }; }; const createServerToString = ( sheets: { [screen: string]: ISheet }, screens: IScreens = {}, cssClassnameProvider: (atom: IAtom, seq: number | nu...
else if (canCallSpecificityProps && prop in specificityProps) { createCssAtoms( specificityProps[prop](config)(props[prop]) as any, cb, screen,
{ createCssAtoms( utils[prop](config)(props[prop]) as any, cb, screen, pseudo, false ); }
conditional_block
index.ts
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
2s" omit_hostname = true [[outputs.socket_writer]] address = "tcp://{{.IngestAddress}}" data_format = "json" json_timestamp_units = "1ms" [[inputs.internal]] collect_memstats = false `)) var ( telegrafStartupDuration = 10 * time.Second ) const ( telegrafMaxTestMonitorRetries = 3 telegrafTestMonitorRetryD...
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
func (tr *TelegrafRunner) Load(agentBasePath string) error { tr.ingestAddress = config.GetListenerAddress(config.TelegrafJsonListener) tr.basePath = agentBasePath tr.configServerToken = uuid.NewV4().String() tr.configServerHandler = func(w http.ResponseWriter, r *http.Request) { if r.Header.Get("authorization") !...
{ break }
conditional_block
telegraf.go
2s" omit_hostname = true [[outputs.socket_writer]] address = "tcp://{{.IngestAddress}}" data_format = "json" json_timestamp_units = "1ms" [[inputs.internal]] collect_memstats = false `)) var ( telegrafStartupDuration = 10 * time.Second ) const ( telegrafMaxTestMonitorRetries = 3 telegrafTestMonitorRetryD...
() { 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
2s" omit_hostname = true [[outputs.socket_writer]] address = "tcp://{{.IngestAddress}}" data_format = "json" json_timestamp_units = "1ms" [[inputs.internal]] collect_memstats = false `)) var ( telegrafStartupDuration = 10 * time.Second ) const ( telegrafMaxTestMonitorRetries = 3 telegrafTestMonitorRetryD...
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
07" beneficiaryIDs := []string{"10000", "11000"} jobID := "1" staging := fmt.Sprintf("%s/%s", os.Getenv("FHIR_STAGING_DIR"), jobID) // clean out the data dir before beginning this test os.RemoveAll(staging) testUtils.CreateStaging(jobID) for i := 0; i < len(beneficiaryIDs); i++ { bbc.On("GetExplanationOfBene...
(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
TestGetFailureThreshold
identifier_name
main_test.go
if err != nil { log.Fatal(err) } 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...
} ooResp := `{"resourceType":"OperationOutcome","issue":[{"severity":"Error"}]}`
random_line_split
main_test.go
7" beneficiaryIDs := []string{"10000", "11000"} jobID := "1" staging := fmt.Sprintf("%s/%s", os.Getenv("FHIR_STAGING_DIR"), jobID) // clean out the data dir before beginning this test os.RemoveAll(staging) testUtils.CreateStaging(jobID) for i := 0; i < len(beneficiaryIDs); i++ { bbc.On("GetExplanationOfBenef...
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
ToFile(nil, "9c05c1f8-349d-400f-9b69-7963f2262b08", []string{"20000", "21000"}, "1", "ExplanationOfBenefit") assert.NotNil(t, err) } func TestWriteEOBDataToFileInvalidACO(t *testing.T) { bbc := MockBlueButtonClient{} acoID := "9c05c1f8-349d-400f-9b69-7963f2262zzz" beneficiaryIDs := []string{"10000", "11000"} _, ...
{ 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
mithy-go/transport/http" ) // Creates, changes, or deletes CIDR blocks within a collection. Contains // authoritative IP information mapping blocks to one or multiple locations. A // change request can update multiple locations in a collection at a time, which is // helpful if you want to move one or more CIDR blocks ...
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
params = &ChangeCidrCollectionInput{} } result, metadata, err := c.invokeOperation(ctx, "ChangeCidrCollection", params, optFns, c.addOperationChangeCidrCollectionMiddlewares) if err != nil { return nil, err } out := result.(*ChangeCidrCollectionOutput) out.ResultMetadata = metadata return out, nil } type C...
addChangeCidrCollectionResolveEndpointMiddleware
identifier_name
api_op_ChangeCidrCollection.go
/smithy-go/transport/http" ) // Creates, changes, or deletes CIDR blocks within a collection. Contains // authoritative IP information mapping blocks to one or multiple locations. A // change request can update multiple locations in a collection at a time, which is // helpful if you want to move one or more CIDR block...
} 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
mithy-go/transport/http" ) // Creates, changes, or deletes CIDR blocks within a collection. Contains // authoritative IP information mapping blocks to one or multiple locations. A // change request can update multiple locations in a collection at a time, which is // helpful if you want to move one or more CIDR blocks ...
if err != nil { return out, metadata, fmt.Errorf("failed to resolve service endpoint, %w", err) } req.URL = &resolvedEndpoint.URI for k := range resolvedEndpoint.Headers { req.Header.Set( k, resolvedEndpoint.Headers.Get(k), ) } authSchemes, err := internalauth.GetAuthenticationSchemes(&resolvedEndp...
{ 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
to do for example /// `spawn(format!("{:?}", some_public_key))`. pub fn spawn( &self, name: &'static str, group: impl Into<GroupName>, task: impl Future<Output = ()> + Send + 'static, ) { self.spawn_inner(name, group, task, TaskType::Async) } /// Spawns the blocking task with the given name. See also `...
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
to do for example /// `spawn(format!("{:?}", some_public_key))`. pub fn spawn( &self, name: &'static str, group: impl Into<GroupName>, task: impl Future<Output = ()> + Send + 'static, ) { self.spawn_inner(name, group, task, TaskType::Async) } /// Spawns the blocking task with the given name. See also `...
, 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
to do for example /// `spawn(format!("{:?}", some_public_key))`. pub fn spawn( &self, name: &'static str, group: impl Into<GroupName>, task: impl Future<Output = ()> + Send + 'static, ) { self.spawn_inner(name, group, task, TaskType::Async) } /// Spawns the blocking task with the given name. See also `...
{ 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
# # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under...
(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
0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # unde...
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
# # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under...
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
0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # unde...
self._update_plugin(db_config_metadata_mapping) def _update_plugin(self, mapping): data_to_update = {} for attribute, config in six.iteritems(mapping): config_file_path = os.path.join(self.plugin_path, config) attribute_data = self._load_config(config_file_path) ...
"""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
, which will be used to replace the pronouns "He" and "She". lastMaleName = '' lastFemaleName = '' index = 0 newText = '' for i in range(wordCount): word = classified_text[i][0] partOfSpeech = classified_text[i][1] if word == 'He' or word == 'he': if lastMaleN...
(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
, which will be used to replace the pronouns "He" and "She". lastMaleName = '' lastFemaleName = '' index = 0 newText = '' for i in range(wordCount): word = classified_text[i][0] partOfSpeech = classified_text[i][1] if word == 'He' or word == 'he': if lastMaleN...
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
, which will be used to replace the pronouns "He" and "She". lastMaleName = '' lastFemaleName = '' index = 0 newText = '' for i in range(wordCount): word = classified_text[i][0] partOfSpeech = classified_text[i][1] if word == 'He' or word == 'he': if lastMaleN...
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
, which will be used to replace the pronouns "He" and "She". lastMaleName = '' lastFemaleName = '' index = 0 newText = '' for i in range(wordCount): word = classified_text[i][0] partOfSpeech = classified_text[i][1] if word == 'He' or word == 'he': if lastMaleN...
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
break } } n, err := p.objectItem() if err == errEofToken
// 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
.Errorf("nested object expected: LBRACE got: %s", p.tok.Type), } } if keyCount == 0 { return nil, &PosError{ Pos: p.tok.Pos, Err: errors.New("no object keys found!"), } } return keys, nil case token.LBRACE: var err error // If we have no keys, then it is a syntax error. i.e....
trace
identifier_name
parser.go
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
: fmt.Errorf("nested object expected: LBRACE got: %s", p.tok.Type), } } if keyCount == 0 { return nil, &PosError{ Pos: p.tok.Pos, Err: errors.New("no object keys found!"), } } return keys, nil case token.LBRACE: var err error // If we have no keys, then it is a syntax error....
{ 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
* @throws {CannotEscapeIrrelevantNode} If the container is irrelevant. * * @throw {ReversedRangeError} If ``max`` is less than ``min``. */ constructor(readonly min: DOMLoc, readonly max: DOMLoc, readonly relevanceTest: NodeTest = () => true) { if (!(this.isRelevant(min.node) ...
{ yield current; current = this.previous(current); }
conditional_block
dom-movement.ts
(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
_POSITION_FOLLOWING) !== 0 ? -1 : // child follows pointed 1; // child is before pointed } /** * Models a DOM location. A DOM location is a pair of node and offset. * * In theory it would be possible to support nodes of any type, but this library * currently only supports only ``Element``, ``Document``, ``...
if ((result & Node.DOCUMENT_POSITION_FOLLOWING) !== 0) { // otherNode follows node. return (result & Node.DOCUMENT_POSITION_CONTAINED_BY) !== 0 ? // otherNode is contained by node but we still need to figure out the // relative positions of the node pointed by [node, offset] and ...
{ 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
_POSITION_FOLLOWING) !== 0 ? -1 : // child follows pointed 1; // child is before pointed } /** * Models a DOM location. A DOM location is a pair of node and offset. * * In theory it would be possible to support nodes of any type, but this library * currently only supports only ``Element``, ``Document``, ``...
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
/profile') # Regular user control panel r('controls.index', '/account/controls') r('controls.auth', '/account/controls/authentication') r('controls.persona', '/account/controls/persona') r('controls.persona.add', '/account/controls/persona/add') r('controls.persona.remove', '/account/controls/p...
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
/profile') # Regular user control panel r('controls.index', '/account/controls') r('controls.auth', '/account/controls/authentication') r('controls.persona', '/account/controls/persona') r('controls.persona.add', '/account/controls/persona/add') r('controls.persona.remove', '/account/controls/p...
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
work', **kw) # Albums # XXX well this is getting complicated! needs to check user, needs to check id, needs to generate correctly, needs a title like art has user_router = SugarRouter(config, '/users/{user}', model.User.name) album_router = user_router.chain('/albums/{album}', model.Album.id, rel=mode...
_make_url_friendly
identifier_name
routing.py
account/profile') # Regular user control panel r('controls.index', '/account/controls') r('controls.auth', '/account/controls/authentication') r('controls.persona', '/account/controls/persona') r('controls.persona.add', '/account/controls/persona/add') r('controls.persona.remove', '/account/con...
"""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
.shape .iter() .map(|p| V2d { x: bq.normalize(&p[0]), y: bq.normalize(&p[1]), }) .collect::<Vec<V2d>>(); let bbox = BBox::from_points(&shape); BdryParams { shape, bbox, skip_b...
/// 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
line-of-sight blockage should be /// penalized. pub los_penalty: f64, /// Distance from point of emission at which COA signal reaches half /// its maximum value. pub halfmax_dist: Length, /// Magnitude of COA. It will be divided by `NVERTS` so that it scales based /// on the number of verti...
{ /// 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
"] { str += " " + name + "\n" } if len(pl["event_hooks"]) > 0 { str += "\nEvent hook plugins:\n" for _, name := range pl["event_hooks"] { str += " hook." + name + "\n" } } if len(pl["clustering"]) > 0 { str += "\nClustering plugins:\n" for _, name := range pl["clustering"] { str += " " + name...
// 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
"\n" } if len(pl["event_hooks"]) > 0 { str += "\nEvent hook plugins:\n" for _, name := range pl["event_hooks"] { str += " hook." + name + "\n" } } if len(pl["clustering"]) > 0 { str += "\nClustering plugins:\n" for _, name := range pl["clustering"] { str += " " + name + "\n" } } str += "\n...
RegisterParsingCallback
identifier_name
plugins.go
"] { str += " " + name + "\n" } if len(pl["event_hooks"]) > 0 { str += "\nEvent hook plugins:\n" for _, name := range pl["event_hooks"] { str += " hook." + name + "\n" } } if len(pl["clustering"]) > 0 { str += "\nClustering plugins:\n" for _, name := range pl["clustering"] { str += " " + name...
// 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
// 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
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
=i1 indexOf1=j1 return indexOf0, indexOf1 def processFiles(fileName): """Calculates all angles, all lengths, representative angle and maxDist after performing rule-based labelling. Arguments: fileName: The protein file in PDB/ENT format. Returns: all_angleList: A Counter having...
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
(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
1 indexOf1=j1 return indexOf0, indexOf1 def processFiles(fileName): """Calculates all angles, all lengths, representative angle and maxDist after performing rule-based labelling. Arguments: fileName: The protein file in PDB/ENT format. Returns: all_angleList: A Counter having a...
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
the given file name. The Float slice is in order: northLat, // southLat, eastLong, westLong in decimal degrees func getBox(image string) (base string, box []float64, err error) { c := strings.Split(image, "_") if len(c) != 5 { err = fmt.Errorf("File name must include bounding box name_N_S_E_W.jpg in decimal degre...
{ t, err := template.New("kmlftr").Parse(kmlFtr) if err != nil { return err } return t.Execute(w, nil) }
identifier_body
kmz.go
two ints separated by space, but got: %v", b) } width, err = strconv.Atoi(string(wh[0])) if err != nil { return } height, err = strconv.Atoi(string(wh[1])) if err != nil { return } return } // process the name-geo-anchored files args into KMZs. Uses // "max_tiles" and and "drawing_order" from viper if pre...
resizeFixToJpg
identifier_name
kmz.go
Short: "Creates .kmz from a JPG with map tiles small enough for a Garmin GPS", Long: `Creates .kmz map tiles for a Garmin from a larger geo-poisitioned map image. Tested on a 62s & 64s Crunches and converts a raster image (.jpg,.gif,.tiff etc) to match what Garmin devices can handle wrt resolution and max tile-size....
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
, height int, err error) { if _, err := os.Stat(imageFilename); os.IsNotExist(err) { return 0, 0, err } cmd := exec.Command(identifyProg, "-format", "%w %h", imageFilename) glog.Infof("About to run: %#v\n", cmd.Args) var b []byte b, err = cmd.Output() if err != nil { return 0, 0, err } wh := bytes.Split(b,...
{ return 360 + e - w }
conditional_block
redis.go
, errors.Errorf("invalid option value %q", kv[1])) } handlers := map[string]optionHandler{ "max_retries": {int: &options.MaxRetries}, "min_retry_backoff": {duration: &options.MinRetryBackoff}, "max_retry_backoff": {duration: &options.MaxRetryBackoff}, "dial_timeout": {duration: &options.DialTi...
AddSorted
identifier_name
redis.go
url.QueryUnescape(kv[1]) if err != nil { return errors.Wrap(err, errors.Errorf("invalid option value %q", kv[1])) } handlers := map[string]optionHandler{ "max_retries": {int: &options.MaxRetries}, "min_retry_backoff": {duration: &options.MinRetryBackoff}, "max_retry_backoff": {duration: &options.M...
strconv.FormatFloat(end, 'g', -1, 64)). Err() }
random_line_split
redis.go
Unescape(username) if err != nil { return nil, errors.Wrap(err, fmt.Errorf("invalid username")) } // Validate and process the password. if strings.Contains(password, ":") { return nil, fmt.Errorf("unescaped colon in password") } if strings.Contains(password, "/") { return nil, fmt.Errorf("unescape...
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
Unescape(username) if err != nil { return nil, errors.Wrap(err, fmt.Errorf("invalid username")) } // Validate and process the password. if strings.Contains(password, ":") { return nil, fmt.Errorf("unescaped colon in password") } if strings.Contains(password, "/") { return nil, fmt.Errorf("unescape...
// 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
AltX AltY AltZ AltOpenBracket AltFwdSlash AltCloseBracket AltCaret AltUnderscore AltGrave Alta Altb Altc Altd Alte Altf Altg Alth Alti Altj Altk Altl Altm Altn Alto Altp Altq Altr Alts Altt Altu Altv Altw Altx Alty Altz AltOpenCurly AltPipe AltCloseCurly AltTilde AltBS //End pr...
(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
AltX AltY AltZ AltOpenBracket AltFwdSlash AltCloseBracket AltCaret AltUnderscore AltGrave Alta Altb Altc Altd Alte Altf Altg Alth Alti Altj Altk Altl Altm Altn Alto Altp Altq Altr Alts Altt Altu Altv Altw Altx Alty Altz AltOpenCurly AltPipe AltCloseCurly AltTilde AltBS //End pr...
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
W AltX AltY AltZ AltOpenBracket AltFwdSlash AltCloseBracket AltCaret AltUnderscore AltGrave Alta Altb Altc Altd Alte Altf Altg Alth Alti Altj Altk Altl Altm Altn Alto Altp Altq Altr Alts Altt Altu Altv Altw Altx Alty Altz AltOpenCurly AltPipe AltCloseCurly AltTilde AltBS //End p...
}() switch ib.b[0] { case byte(CtrlC), byte(CtrlG), byte(CtrlQ): ch <- Event{KeySpecial, rune(ib.b[0]), nil} return case 127: ch <- Event{KeySpecial, BSpace, nil} return case 0: ch <- Event{KeySpecial, Null, nil} // Ctrl-space? return case byte(ESC): ch <- ib.escSequence(&sz) return...
{ 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:]
identifier_body
input.go
W AltX AltY AltZ AltOpenBracket AltFwdSlash AltCloseBracket AltCaret AltUnderscore AltGrave Alta Altb Altc Altd Alte Altf Altg Alth Alti Altj Altk Altl Altm Altn Alto Altp Altq Altr Alts Altt Altu Altv Altw Altx Alty Altz AltOpenCurly AltPipe AltCloseCurly AltTilde AltBS //End p...
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