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
index.js
//index.js const AV = require('../../libs/av-weapp-min.js') var app = getApp() Page({ data: { motto: 'Hello World', userInfo: {} }, //事件处理函数 bindViewTap: function() { wx.navigateTo({ url: '../logs/logs' }) }, onLoad: function() { console.log('onLoad') this.saveUser() }, saveUser() { var that =...
}) } })
url: '/pages/plan/index'
random_line_split
index.js
//index.js const AV = require('../../libs/av-weapp-min.js') var app = getApp() Page({ data: { motto: 'Hello World', userInfo: {} }, //事件处理函数 bindViewTap: function() { wx.navigateTo({ url: '../logs/logs' }) }, onLoad: function() { console.log('onLoad') this.saveUser() }, saveUser() { var that
}); }) }, createPlan() { wx.navigateTo({ url: '/pages/plan/index' }) } })
= this //调用应用实例的方法获取全局数据 app.getUserInfo(function(userInfo) { //update data that.setData({ userInfo: userInfo }) wx.setStorage({ key: "userInfo", data: userInfo }) let nickName = that.data.userInfo.nickName let avatarUrl = that.data.userInfo.avatarUrl let gender = that.data.user...
identifier_body
ldd.rs
extern crate glob; extern crate clap; extern crate elfkit; use std::fs::{File}; use elfkit::Elf; use std::path::Path; use std::collections::HashSet; use std::io::{self}; use std::io::BufReader; use std::io::BufRead; use glob::glob; struct Ldd { sysroot: String, lpaths: Vec<String>, visited: Hash...
} if a.chars().last().unwrap() != '/' { a.push('/'); } if b.chars().nth(0).unwrap() == '/' { return a + &b[1..]; } return a + b; } impl Ldd { fn recurse(&mut self, path: &str) { let mut f = File::open(path).unwrap(); let mut elf = Elf::from_reader(&mut f).un...
if a.len() < 1 { return a;
random_line_split
ldd.rs
extern crate glob; extern crate clap; extern crate elfkit; use std::fs::{File}; use elfkit::Elf; use std::path::Path; use std::collections::HashSet; use std::io::{self}; use std::io::BufReader; use std::io::BufRead; use glob::glob; struct Ldd { sysroot: String, lpaths: Vec<String>, visited: Hash...
} } } } } for dep in &mut deps { let mut found = false; for lpath in self.lpaths.iter() { let joined = join_paths(&lpath, &dep); let joined = Path::new(&joined); ...
{ let mut f = File::open(path).unwrap(); let mut elf = Elf::from_reader(&mut f).unwrap(); let mut deps = Vec::new(); for shndx in 0..elf.sections.len() { if elf.sections[shndx].header.shtype == elfkit::types::SectionType::DYNAMIC { elf.load(shndx, &mut f).unw...
identifier_body
ldd.rs
extern crate glob; extern crate clap; extern crate elfkit; use std::fs::{File}; use elfkit::Elf; use std::path::Path; use std::collections::HashSet; use std::io::{self}; use std::io::BufReader; use std::io::BufRead; use glob::glob; struct Ldd { sysroot: String, lpaths: Vec<String>, visited: Hash...
(&mut self, path: &str) { let mut f = File::open(path).unwrap(); let mut elf = Elf::from_reader(&mut f).unwrap(); let mut deps = Vec::new(); for shndx in 0..elf.sections.len() { if elf.sections[shndx].header.shtype == elfkit::types::SectionType::DYNAMIC { elf...
recurse
identifier_name
gtk_wrapper.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Created on Thu Mar 24 16:25:41 2016 @author: pavel """ from gi.repository import Gtk import parameter_types as ptypes from logger import Logger logger = Logger.get_logger() # import gobject gobject.threads_init() #decorator is used to update gtk objects from ano...
class GTK_ParamSlider(GTK_ParamWrapper): from math import log10 NUM_STEPS = 100 ORIENTATION = Gtk.Orientation.HORIZONTAL def _set_gui_obj(self): #(initial value, min value, max value, # step increment - press cursor keys to see!, # page increment - c...
new_val = model[active][0] param.set_val(new_val) logger.to_log(new_val, combobox)
conditional_block
gtk_wrapper.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Created on Thu Mar 24 16:25:41 2016 @author: pavel """ from gi.repository import Gtk import parameter_types as ptypes from logger import Logger logger = Logger.get_logger() # import gobject gobject.threads_init() #decorator is used to update gtk objects from ano...
(self, parameter): self.parameter = parameter self.container = Gtk.Box(spacing=2) self.container.set_homogeneous(False) self._set_name(parameter.get_name()) self.param_gui_obj = None self._set_gui_obj() self._append_gui_ob...
__init__
identifier_name
gtk_wrapper.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Created on Thu Mar 24 16:25:41 2016 @author: pavel """ from gi.repository import Gtk import parameter_types as ptypes from logger import Logger logger = Logger.get_logger() # import gobject gobject.threads_init() #decorator is used to update gtk objects from ano...
class GTK_ParamSlider(GTK_ParamWrapper): from math import log10 NUM_STEPS = 100 ORIENTATION = Gtk.Orientation.HORIZONTAL def _set_gui_obj(self): #(initial value, min value, max value, # step increment - press cursor keys to see!, # page increment - click around...
param.set_val(new_val) logger.to_log(new_val, combobox)
random_line_split
gtk_wrapper.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Created on Thu Mar 24 16:25:41 2016 @author: pavel """ from gi.repository import Gtk import parameter_types as ptypes from logger import Logger logger = Logger.get_logger() # import gobject gobject.threads_init() #decorator is used to update gtk objects from ano...
@staticmethod def get_wrapper(obj): wrapper = TYPE_MATCHES.get(type(obj), GTK_ReadOnlyWrapper) return wrapper(obj) class GTK_ReadOnlyWrapper(GTK_Wrapper): def __init__(self, obj): self.label = Gtk.Label() self.label.set_text(repr(obj)) def...
raise NotImplementedError()
identifier_body
client.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import random sys.path.append('.') from twisted.internet import reactor from twisted.python import log from . import driver from . import multiplexer from . import record_layer from . import updater from . import dsl from . import conf EVENT_LOOP_FREQUENCY_S ...
def terminate(self, stream_id): del self.streams_[stream_id] # call this function if you want reload formats from disk # at the next possible time def reload_driver(self): self.reload_ = True def check_for_update(self): # uncomment the following line to check for updates ...
stream = multiplexer.MarionetteStream( self.multiplexer_incoming_, self.multiplexer_outgoing_, self.stream_counter_, srv_queue) stream.host = self self.streams_[self.stream_counter_] = stream self.stream_counter_ = random.randint(1,2**32-1) ...
identifier_body
client.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import random sys.path.append('.') from twisted.internet import reactor from twisted.python import log from . import driver from . import multiplexer from . import record_layer from . import updater from . import dsl from . import conf EVENT_LOOP_FREQUENCY_S ...
self.reload_ = False # first update must be reactor.callLater(AUTOUPDATE_DELAY, self.check_for_update) def set_driver(self, format_name, format_version=None): self.format_name_ = format_name if format_version == None: self.format_version_ = dsl.get_latest_versio...
self.streams_ = {} self.stream_counter_ = random.randint(1,2**32-1) self.set_driver(format_name, format_version)
random_line_split
client.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import random sys.path.append('.') from twisted.internet import reactor from twisted.python import log from . import driver from . import multiplexer from . import record_layer from . import updater from . import dsl from . import conf EVENT_LOOP_FREQUENCY_S ...
def start_new_stream(self, srv_queue=None): stream = multiplexer.MarionetteStream( self.multiplexer_incoming_, self.multiplexer_outgoing_, self.stream_counter_, srv_queue) stream.host = self self.streams_[self.stream_counter_] = stream ...
stream_id = cell_obj.get_stream_id() try: self.streams_[stream_id].srv_queue.put(payload) except: log.msg("Client.process_cell: Caught KeyError exception for stream_id :%d" % (stream_id)) return
conditional_block
client.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import random sys.path.append('.') from twisted.internet import reactor from twisted.python import log from . import driver from . import multiplexer from . import record_layer from . import updater from . import dsl from . import conf EVENT_LOOP_FREQUENCY_S ...
(self, callback): # could be replaced with code that updates from a different # source (e.g., local computations) update_server = conf.get("general.update_server") updater = updater.FormatUpdater(update_server, use_marionette=True, callback=callback) return updater.do_update() ...
do_update
identifier_name
conv.py
"""convert between game types""" import argparse import itertools import json import sys from gameanalysis import gambit from gameanalysis import gamereader from gameanalysis import matgame from gameanalysis import paygame from gameanalysis import rsgame
['empty'], 'Strip payoff data', """Strip all payoff data from a game and return only its base structure---role and strategy names and player counts.""", lambda game, out: json.dump( rsgame.empty_copy(game).to_json(), out)), 'game': ( [], 'Sparse payoff format', ""...
_TYPES = { 'emptygame': (
random_line_split
conv.py
"""convert between game types""" import argparse import itertools import json import sys from gameanalysis import gambit from gameanalysis import gamereader from gameanalysis import matgame from gameanalysis import paygame from gameanalysis import rsgame _TYPES = { 'emptygame': ( ['empty'], 'Strip payoff...
"""Entry point for conversion""" game = gamereader.load(args.input) lookup = {} for key, (aliases, _, _, func) in _TYPES.items(): for alias in itertools.chain([key], aliases): lookup[alias] = func lookup[args.type](game, args.output) args.output.write('\n')
identifier_body
conv.py
"""convert between game types""" import argparse import itertools import json import sys from gameanalysis import gambit from gameanalysis import gamereader from gameanalysis import matgame from gameanalysis import paygame from gameanalysis import rsgame _TYPES = { 'emptygame': ( ['empty'], 'Strip payoff...
(args): """Entry point for conversion""" game = gamereader.load(args.input) lookup = {} for key, (aliases, _, _, func) in _TYPES.items(): for alias in itertools.chain([key], aliases): lookup[alias] = func lookup[args.type](game, args.output) args.output.write('\n')
main
identifier_name
conv.py
"""convert between game types""" import argparse import itertools import json import sys from gameanalysis import gambit from gameanalysis import gamereader from gameanalysis import matgame from gameanalysis import paygame from gameanalysis import rsgame _TYPES = { 'emptygame': ( ['empty'], 'Strip payoff...
lookup[args.type](game, args.output) args.output.write('\n')
for alias in itertools.chain([key], aliases): lookup[alias] = func
conditional_block
SugangSnuLecture.ts
export default interface SugangSnuLecture { // 교과구분 classification: string; // 개설대학 college: string; // 개설학과 department: string; // 이수과정 academic_course: string; // 학년 academic_year: string; // 교과목 번호 course_number: string; // 강좌 번호 lecture_number: string; // ...
// 개설 상태 lecture_status: string; }
random_line_split
jk_utils.py
# -*- coding=utf-8 -*- import requests import os import json import sys import time reload(sys) sys.setdefaultencoding('utf8') download_base_url = 'http://www.jikexueyuan.com/course/video_download' cookie_map = 'gr_user_id=eb91fa90-1980-4500-a114-6fea026da447; _uab_collina=148758210602708013401536; connect.sid=s%3AsR...
else: print u'%s 请求失败,状态%d' % (download_url, response.status_code) return 500 except Exception, e: print u'%s 请求失败,\n异常信息:%s' % (download_url, e) return 500 def create_dir(path): if not os.path.exists(path): try: os.makedirs(path) ex...
print u'下载:%s %d秒' % (file_path, int(time.time() - begin_time)) return 200 except Exception: print u'下载:%s 失败' % file_path return 500
random_line_split
jk_utils.py
# -*- coding=utf-8 -*- import requests import os import json import sys import time reload(sys) sys.setdefaultencoding('utf8') download_base_url = 'http://www.jikexueyuan.com/course/video_download' cookie_map = 'gr_user_id=eb91fa90-1980-4500-a114-6fea026da447; _uab_collina=148758210602708013401536; connect.sid=s%3AsR...
def del_dir(path): assert os.path.exists(path) and os.path.isdir(path) for root, dirs, files in os.walk(path, topdown=False): for name in files: os.remove(os.path.join(root, name)) for name in dirs: os.rmdir(os.path.join(root, name)) os.rmdir(path) def create_fil...
/')[0:-1])
identifier_name
jk_utils.py
# -*- coding=utf-8 -*- import requests import os import json import sys import time reload(sys) sys.setdefaultencoding('utf8') download_base_url = 'http://www.jikexueyuan.com/course/video_download' cookie_map = 'gr_user_id=eb91fa90-1980-4500-a114-6fea026da447; _uab_collina=148758210602708013401536; connect.sid=s%3AsR...
= parent_dir(name) if parent_path and not os.path.exists(parent_path): create_dir(parent_path) with open(name, mode)as f: f.write(data) except Exception, e: print u'%s 创建失败\n异常:%s' % (name, e)
os.rmdir(os.path.join(root, name)) os.rmdir(path) def create_file(name, mode='r', data=""): try: parent_path
conditional_block
jk_utils.py
# -*- coding=utf-8 -*- import requests import os import json import sys import time reload(sys) sys.setdefaultencoding('utf8') download_base_url = 'http://www.jikexueyuan.com/course/video_download' cookie_map = 'gr_user_id=eb91fa90-1980-4500-a114-6fea026da447; _uab_collina=148758210602708013401536; connect.sid=s%3AsR...
split('/')[0:-1]) def del_dir(path): assert os.path.exists(path) and os.path.isdir(path) for root, dirs, files in os.walk(path, topdown=False): for name in files: os.remove(os.path.join(root, name)) for name in dirs: os.rmdir(os.path.join(root, name)) os.rmdir(path)...
edirs(path) except Exception, e: print u'文件夹%s 创建失败;\n %s' % (path, e) else: print u'文件夹%s 已经存在' % path def parent_dir(path): if path[-1] == '/': path = path[0:-1] return '/'.join(path.
identifier_body
single-nodes-validator.ts
import { CEGModel } from '../../model/CEGModel';
import { Type } from '../../util/type'; import { ElementValidatorBase } from '../element-validator-base'; import { ValidationMessage } from '../validation-message'; import { ValidationResult } from '../validation-result'; import { Validator } from '../validator-decorator'; @Validator(CEGModel) export class SingleNodes...
import { CEGNode } from '../../model/CEGNode'; import { IContainer } from '../../model/IContainer';
random_line_split
single-nodes-validator.ts
import { CEGModel } from '../../model/CEGModel'; import { CEGNode } from '../../model/CEGNode'; import { IContainer } from '../../model/IContainer'; import { Type } from '../../util/type'; import { ElementValidatorBase } from '../element-validator-base'; import { ValidationMessage } from '../validation-message'; import...
let node: CEGNode = element as CEGNode; let hasIncomingConnections: boolean = node.incomingConnections && node.incomingConnections.length > 0; let hasOutgoingConnections: boolean = node.outgoingConnections && node.outgoingConnections.length > 0; return !hasIncomingConnec...
{ return false; }
conditional_block
single-nodes-validator.ts
import { CEGModel } from '../../model/CEGModel'; import { CEGNode } from '../../model/CEGNode'; import { IContainer } from '../../model/IContainer'; import { Type } from '../../util/type'; import { ElementValidatorBase } from '../element-validator-base'; import { ValidationMessage } from '../validation-message'; import...
(element: CEGModel, contents: IContainer[]): ValidationResult { let invalidNodes: IContainer[] = contents.filter((element: IContainer) => { if (!Type.is(element, CEGNode)) { return false; } let node: CEGNode = element as CEGNode; let hasIncomingCon...
validate
identifier_name
single-nodes-validator.ts
import { CEGModel } from '../../model/CEGModel'; import { CEGNode } from '../../model/CEGNode'; import { IContainer } from '../../model/IContainer'; import { Type } from '../../util/type'; import { ElementValidatorBase } from '../element-validator-base'; import { ValidationMessage } from '../validation-message'; import...
}
{ let invalidNodes: IContainer[] = contents.filter((element: IContainer) => { if (!Type.is(element, CEGNode)) { return false; } let node: CEGNode = element as CEGNode; let hasIncomingConnections: boolean = node.incomingConnections && node.incomingC...
identifier_body
index.d.ts
/* * @license Apache-2.0 * * Copyright (c) 2019 The Stdlib 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 ap...
* // returns NaN * * @example * var v = mode( 2.0, NaN ); * // returns NaN * * @example * var v = mode( NaN, 2.0 ); * // returns NaN */ declare function mode( alpha: number, beta: number ): number; // EXPORTS // export = mode;
* var v = mode( 1.0, -0.1 ); * // returns NaN * * @example * var v = mode( -0.1, 1.0 );
random_line_split
PageStoreSpec.js
describe('paging', function(){ var welcomeHolder = app.PageStore.welcome; var roomsHolder = app.PageStore.rooms; beforeEach(function(){ app.PageStore.welcome = welcomeHolder; app.PageStore.rooms = roomsHolder; }); it('should have a welcome route that invokes a callback', function(){ var counter...
dest: 'welcome' }); expect(counter).to.equal(1); }); it('should have a rooms route that passes the roomId to a callback', function(){ var id; app.PageStore.rooms = function(roomId){id = roomId;}; app.PageActions.navigate({ dest: 'rooms', props: '0' }); expect(id).to.eq...
app.PageStore.welcome = function(){counter++;}; app.PageActions.navigate({
random_line_split
manifest.py
value in item_classes.items(): self[key] = TypeData(manifest, value) self.initialized = True self.json_obj = None # type: None def __setitem__(self, key, value): # type: (Text, TypeData) -> None if self.initialized: raise AttributeError dict.__setit...
data[new_type][rel_path_parts] = manifest_items data[new_type].hashes[rel_path_parts] = file_hash # Make sure to terminate the Pool, to avoid hangs on Python 3. # https://docs.python.org/3/library/multiprocessing.html#multiprocessing.pool.Pool if pool is not None: ...
results = map(compute_manifest_items, to_update) for result in results: rel_path_parts, new_type, manifest_items, file_hash = result
random_line_split
manifest.py
value in item_classes.items(): self[key] = TypeData(manifest, value) self.initialized = True self.json_obj = None # type: None def __setitem__(self, key, value): # type: (Text, TypeData) -> None if self.initialized: raise AttributeError dict.__setit...
for test_type, type_paths in obj["items"].items(): if test_type not in item_classes: raise ManifestError if types and test_type not in types: continue
raise ManifestError
conditional_block
manifest.py
value in item_classes.items(): self[key] = TypeData(manifest, value) self.initialized = True self.json_obj = None # type: None def __setitem__(self, key, value): # type: (Text, TypeData) -> None if self.initialized: raise AttributeError dict.__setit...
(object): def __init__(self, tests_root, url_base="/"): # type: (Text, Text) -> None assert url_base is not None self._data = ManifestData(self) # type: ManifestData self.tests_root = tests_root # type: Text self.url_base = url_base # type: Text def __iter__(self): ...
Manifest
identifier_name
manifest.py
value in item_classes.items(): self[key] = TypeData(manifest, value) self.initialized = True self.json_obj = None # type: None def __setitem__(self, key, value): # type: (Text, TypeData) -> None if self.initialized: raise AttributeError dict.__setit...
def itertypes(self, *types): # type: (*Text) -> Iterator[Tuple[Text, Text, Set[ManifestItem]]] for item_type in (types or sorted(self._data.keys())): for path in self._data[item_type]: rel_path = os.sep.join(path) tests = self._data[item_type][path] ...
return self.itertypes()
identifier_body
mem.rs
"linux")] extern { fn mallinfo() -> struct_mallinfo; } #[cfg(target_os = "linux")] #[repr(C)] pub struct struct_mallinfo { arena: c_int, ordblks: c_int, smblks: c_int, hblks: c_int, hblkhd: c_int, usmblks: c_int, fsmblks: ...
{ vec![] }
identifier_body
mem.rs
ProfilerMsg::RegisterReporter(name, reporter) => { // Panic if it has already been registered. let name_clone = name.clone(); match self.reporters.insert(name, reporter) { None => true, Some(_) => panic!(format!("Registe...
} fn handle_msg(&mut self, msg: ProfilerMsg) -> bool { match msg {
random_line_split
mem.rs
system-heap-unclassified" values. let mut forest = ReportsForest::new(); let mut jemalloc_heap_reported_size = 0; let mut system_heap_reported_size = 0; let mut jemalloc_heap_allocated_size: Option<usize> = None; let mut system_heap_allocated_size: Option<usize> = None; ...
(&mut self) { // Fill in sizes of interior nodes, and recursively sort the sub-trees. for (_, tree) in &mut self.trees { tree.compute_interior_node_sizes_and_sort(); } // Put the trees into a sorted vector. Primary sort: degenerate trees (those containing a // single...
print
identifier_name
attr.rs
.meta().name_str_pair() } } impl AttrMetaMethods for MetaItem { fn name(&self) -> @str { match self.node { MetaWord(n) => n, MetaNameValue(n, _) => n, MetaList(n, _) => n } } fn value_str(&self) -> Option<@str> { match self.node { Met...
(&self) -> Attribute { if self.node.is_sugared_doc { let comment = self.value_str().unwrap(); let meta = mk_name_value_item_str(@"doc", strip_doc_comment_decoration(comment).to_managed()); mk_attr(meta) } else { ...
desugar_doc
identifier_name
attr.rs
self.meta().name_str_pair() } } impl AttrMetaMethods for MetaItem { fn name(&self) -> @str { match self.node { MetaWord(n) => n, MetaNameValue(n, _) => n, MetaList(n, _) => n } } fn value_str(&self) -> Option<@str> { match self.node { ...
}, _ => None } } fn meta_item_list<'a>(&'a self) -> Option<&'a [@MetaItem]> { match self.node { MetaList(_, ref l) => Some(l.as_slice()), _ => None } } fn name_str_pair(&self) -> Option<(@str, @str)> { self.value_str().map...
}
random_line_split
attr.rs
.meta().name_str_pair() } } impl AttrMetaMethods for MetaItem { fn name(&self) -> @str { match self.node { MetaWord(n) => n, MetaNameValue(n, _) => n, MetaList(n, _) => n } } fn value_str(&self) -> Option<@str> { match self.node { Met...
pub fn mk_word_item(name: @str) -> @MetaItem { @dummy_spanned(MetaWord(name)) } pub fn mk_attr(item: @MetaItem) -> Attribute { dummy_spanned(Attribute_ { style: ast::AttrInner, value: item, is_sugared_doc: false, }) } pub fn mk_sugared_doc_attr(text: @str, lo: BytePos, hi: BytePo...
{ @dummy_spanned(MetaList(name, items)) }
identifier_body
resources.js
featureOutsideAOIMessage: "Feature cannot be added outside study area", // Error message when feature edits are performed outside the study area noEditingPermissionsMessage: "You do not have permission to perform this action.", //Message when user do not have editing permissions base...
infoBtnToolTip: "Map information" // Command button to view the 'Map information' }, issueWall: { noResultsFound: "No features found", // Shown in the issue wall when no issues are present in layer noResultsFoundInCurrentBuffer: "No features found near you", // Shown ...
random_line_split
meme_processory.py
#!/usr/bin/env python """ Process meme.txt files to generate conservation plots
import seaborn as sns import numpy as np import matplotlib.pyplot as plt from scipy.stats.stats import pearsonr from Bio import motifs def plot_meme_against_phylo(meme_record, phylo): sns.set(style="darkgrid") def position_wise_profile(counts_dict, length): profile = map(dict, zip(*[[(k, v) for v in value] f...
""" import argparse import csv import sys
random_line_split
meme_processory.py
#!/usr/bin/env python """ Process meme.txt files to generate conservation plots """ import argparse import csv import sys import seaborn as sns import numpy as np import matplotlib.pyplot as plt from scipy.stats.stats import pearsonr from Bio import motifs def plot_meme_against_phylo(meme_record, phylo): sns.set(s...
main(sys.argv[1:])
conditional_block
meme_processory.py
#!/usr/bin/env python """ Process meme.txt files to generate conservation plots """ import argparse import csv import sys import seaborn as sns import numpy as np import matplotlib.pyplot as plt from scipy.stats.stats import pearsonr from Bio import motifs def plot_meme_against_phylo(meme_record, phylo): sns.set(s...
def main(argv): parser = argparse.ArgumentParser(description='Process meme files') parser.add_argument('-i', '--meme', metavar='<meme_out>', help='Meme input file', required=True) parser.add_argument('-m', '--motif', metavar='<motif_no>', help='Motif number', required=True, type=int) parser.add_argum...
sorted_profile = [] for p in profile: sorted_profile.append(sorted(p.items(), key=lambda x:x[1])) for i,p in enumerate(sorted_profile): sorted_profile[i] = p[-max_count:] return sorted_profile
identifier_body
meme_processory.py
#!/usr/bin/env python """ Process meme.txt files to generate conservation plots """ import argparse import csv import sys import seaborn as sns import numpy as np import matplotlib.pyplot as plt from scipy.stats.stats import pearsonr from Bio import motifs def plot_meme_against_phylo(meme_record, phylo): sns.set(s...
(profile, max_count=2): sorted_profile = [] for p in profile: sorted_profile.append(sorted(p.items(), key=lambda x:x[1])) for i,p in enumerate(sorted_profile): sorted_profile[i] = p[-max_count:] return sorted_profile def main(argv): parser = argparse.ArgumentParser(description='Pro...
find_max_occurence
identifier_name
tests.rs
#![deny(warnings)] #![allow(unstable)] extern crate cargo; extern crate flate2; extern crate git2; extern crate hamcrest; extern crate serialize; extern crate tar; extern crate term; extern crate url; #[macro_use] extern crate log; mod support; macro_rules! test { ($name:ident $expr:expr) => ( #[test] ...
mod test_cargo_compile_path_deps; mod test_cargo_compile_plugins; mod test_cargo_cross_compile; mod test_cargo_doc; mod test_cargo_features; mod test_cargo_fetch; mod test_cargo_freshness; mod test_cargo_generate_lockfile; mod test_cargo_new; mod test_cargo_package; mod test_cargo_profiles; mod test_cargo_publish; mod ...
mod test_cargo_compile_git_deps; mod test_cargo_compile_old_custom_build;
random_line_split
de.js
// moment.js locale configuration // locale : german (de) // author : lluchs : https://github.com/lluchs // author: Menelion Elensúle: https://github.com/Oire (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { modu...
number, withoutSuffix, key, isFuture) { var format = { 'm': ['eine Minute', 'einer Minute'], 'h': ['eine Stunde', 'einer Stunde'], 'd': ['ein Tag', 'einem Tag'], 'dd': [number + ' Tage', number + ' Tagen'], 'M': ['ein Monat', 'einem Monat'], 'MM': [number + ' Monate', number + ' Monaten'], 'y': [...
rocessRelativeTime(
identifier_name
de.js
// moment.js locale configuration // locale : german (de) // author : lluchs : https://github.com/lluchs // author: Menelion Elensúle: https://github.com/Oire (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { modu...
return moment.defineLocale('de', { months : 'Januar_Februar_März_April_Mai_Juni_Juli_August_September_Oktober_November_Dezember'.split('_'), monthsShort : 'Jan._Febr._Mrz._Apr._Mai_Jun._Jul._Aug._Sept._Okt._Nov._Dez.'.split('_'), weekdays : 'Sonntag_Montag_Dienstag_Mittwoch_Donnerstag_Freitag_Samstag'.split('_'...
var format = { 'm': ['eine Minute', 'einer Minute'], 'h': ['eine Stunde', 'einer Stunde'], 'd': ['ein Tag', 'einem Tag'], 'dd': [number + ' Tage', number + ' Tagen'], 'M': ['ein Monat', 'einem Monat'], 'MM': [number + ' Monate', number + ' Monaten'], 'y': ['ein Jahr', 'einem Jahr'], 'yy': [nu...
identifier_body
de.js
// moment.js locale configuration // locale : german (de) // author : lluchs : https://github.com/lluchs // author: Menelion Elensúle: https://github.com/Oire (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { modu...
'MM': [number + ' Monate', number + ' Monaten'], 'y': ['ein Jahr', 'einem Jahr'], 'yy': [number + ' Jahre', number + ' Jahren'] }; return withoutSuffix ? format[key][0] : format[key][1]; } return moment.defineLocale('de', { months : 'Januar_Februar_März_April_Mai_Juni_Juli_August_September_Oktober_Nov...
'M': ['ein Monat', 'einem Monat'],
random_line_split
field_checkbox.js
/** * Redux Checkbox * Dependencies : jquery * Feature added by : Dovy Paukstys * Date : 17 June 2014 */ /*global redux_change, wp, redux*/ (function( $ ) { "use strict"; redux.field_objects = redux.field_objects || {}; redux.field_objects.checkbox = redux.field_objects.chec...
$(this).parent().find('.checkbox-check').val(val); redux_change( $( this ) ); } ); } ); }; })( jQuery );
{ val = $(this).parent().find('.checkbox-check' ).attr('data-val'); }
conditional_block
field_checkbox.js
/** * Redux Checkbox * Dependencies : jquery * Feature added by : Dovy Paukstys * Date : 17 June 2014 */ /*global redux_change, wp, redux*/ (function( $ ) { "use strict"; redux.field_objects = redux.field_objects || {}; redux.field_objects.checkbox = redux.field_objects.chec...
var parent = el; if ( !el.hasClass( 'redux-field-container' ) ) { parent = el.parents( '.redux-field-container:first' ); } if ( parent.hasClass( 'redux-field-init' ) ) { parent.removeClass( 'redux-field-init' ); ...
random_line_split
partition_health.py
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
super(PartitionHealth, self).__init__(aggregated_health_state=aggregated_health_state, health_events=health_events, unhealthy_evaluations=unhealthy_evaluations, health_statistics=health_statistics) self.partition_id = partition_id self.replica_health_states = replica_health_states
identifier_body
partition_health.py
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
:type health_statistics: :class:`HealthStatistics <azure.servicefabric.models.HealthStatistics>` :param partition_id: :type partition_id: str :param replica_health_states: The list of replica health states associated with the partition. :type replica_health_states: list of :class:`ReplicaH...
:type unhealthy_evaluations: list of :class:`HealthEvaluationWrapper <azure.servicefabric.models.HealthEvaluationWrapper>` :param health_statistics:
random_line_split
partition_health.py
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
(EntityHealth): """Information about the health of a Service Fabric partition. :param aggregated_health_state: Possible values include: 'Invalid', 'Ok', 'Warning', 'Error', 'Unknown' :type aggregated_health_state: str or :class:`enum <azure.servicefabric.models.enum>` :param health_events: Th...
PartitionHealth
identifier_name
qt.py
#!/usr/bin/env python # # Electrum - lightweight Bitcoin client # Copyright (C) 2014 Thomas Voegtlin # # Permission is hereby granted, free of charge, to any person # obtaining a copy of this software and associated documentation files # (the "Software"), to deal in the Software without restriction, # including without...
message = bitcoin.encrypt_message(tx.raw, K) try: server.put(_hash, message) except Exception as e: traceback.print_exc(file=sys.stdout) window.show_message("Failed to send transaction to cosigning pool.") return ...
continue
conditional_block
qt.py
#!/usr/bin/env python # # Electrum - lightweight Bitcoin client # Copyright (C) 2014 Thomas Voegtlin # # Permission is hereby granted, free of charge, to any person # obtaining a copy of this software and associated documentation files # (the "Software"), to deal in the Software without restriction, # including without...
def clear(self, keyhash): server.delete(keyhash) self.received.remove(keyhash) def run(self): while self.running: if not self.keyhashes: time.sleep(2) continue for keyhash in self.keyhashes: if keyhash in self.rec...
self.keyhashes = keyhashes
identifier_body
qt.py
#!/usr/bin/env python # # Electrum - lightweight Bitcoin client # Copyright (C) 2014 Thomas Voegtlin # # Permission is hereby granted, free of charge, to any person # obtaining a copy of this software and associated documentation files # (the "Software"), to deal in the Software without restriction, # including without...
(self, tx): for window, xpub, K, _hash in self.cosigner_list: if not self.cosigner_can_sign(tx, xpub): continue message = bitcoin.encrypt_message(tx.raw, K) try: server.put(_hash, message) except Exception as e: trac...
do_send
identifier_name
qt.py
#!/usr/bin/env python # # Electrum - lightweight Bitcoin client # Copyright (C) 2014 Thomas Voegtlin # # Permission is hereby granted, free of charge, to any person # obtaining a copy of this software and associated documentation files # (the "Software"), to deal in the Software without restriction, # including without...
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS # BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN # ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALIN...
random_line_split
app.js
var express = require('express'); var path = require('path'); var favicon = require('serve-favicon'); var logger = require('morgan'); var Session = require('express-session'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); // create session middleware var session = Session({ ...
res.send({ status: status, message: err.message, stack: err.stack, }); }); } // production error handler // no stacktraces leaked to user app.use(function (err, req, res, next) { console.log('caused production error handler'); res.status(err.status || 500...
var status = err.status || 500; res.status(status);
random_line_split
app.js
var express = require('express'); var path = require('path'); var favicon = require('serve-favicon'); var logger = require('morgan'); var Session = require('express-session'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); // create session middleware var session = Session({ ...
}, dashboard_routes); // routes for RESTful APIs app.use('/test', auth.forAllUsers, test_routes); app.use('/authentications', auth.forAllUsers, authentications_routes); app.use('/users', auth.forAllUsers, users_routes); app.use('/regions', auth.forAllUsers, regions_routes); app.use('/information', auth.forAllUsers, i...
{ res.redirect('/login'); console.log('redirect'); }
conditional_block
ICapabilitiesNotification.d.ts
/** --| ADAPTIVE RUNTIME PLATFORM |---------------------------------------------------------------------------------------- (C) Copyright 2013-2015 Carlos Lozano Diez t/a Adaptive.me <http://adaptive.me>. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance wi...
{ value: string; constructor(value: string); toString(): string; /** @property {Adaptive.ICapabilitiesNotification} [Alarm='Alarm'] */ static Alarm: ICapabilitiesNotification; /** @property {Adaptive.ICapabilitiesNotification} [LocalNotifica...
ICapabilitiesNotification
identifier_name
ICapabilitiesNotification.d.ts
/** --| ADAPTIVE RUNTIME PLATFORM |---------------------------------------------------------------------------------------- (C) Copyright 2013-2015 Carlos Lozano Diez t/a Adaptive.me <http://adaptive.me>. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance wi...
*/ static Alarm: ICapabilitiesNotification; /** @property {Adaptive.ICapabilitiesNotification} [LocalNotification='LocalNotification'] */ static LocalNotification: ICapabilitiesNotification; /** @property {Adaptive.ICapabilitiesNotification} [RemoteN...
constructor(value: string); toString(): string; /** @property {Adaptive.ICapabilitiesNotification} [Alarm='Alarm']
random_line_split
indexentries.py
# -*- coding: utf-8 -*- """ sphinx.environment.managers.indexentries ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Index entries manager for sphinx.environment. :copyright: Copyright 2007-2016 by the Sphinx team, see AUTHORS. :license: BSD, see LICENSE for details. """ import re import bisect import un...
for fn, entries in iteritems(self.data): # new entry types must be listed in directives/other.py! for type, value, tid, main, index_key in entries: try: if type == 'single': try: entry, subentry = s...
try: uri = builder.get_relative_uri('genindex', fn) + '#' + tid except NoUri: pass else: # maintain links in sorted/deterministic order bisect.insort(entry[0], (main, uri))
conditional_block
indexentries.py
# -*- coding: utf-8 -*- """ sphinx.environment.managers.indexentries ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Index entries manager for sphinx.environment. :copyright: Copyright 2007-2016 by the Sphinx team, see AUTHORS. :license: BSD, see LICENSE for details. """ import re import bisect import un...
(self, env): super(IndexEntries, self).__init__(env) self.data = env.indexentries def clear_doc(self, docname): self.data.pop(docname, None) def merge_other(self, docnames, other): for docname in docnames: self.data[docname] = other.indexentries[docname] def pr...
__init__
identifier_name
indexentries.py
# -*- coding: utf-8 -*- """ sphinx.environment.managers.indexentries ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Index entries manager for sphinx.environment. :copyright: Copyright 2007-2016 by the Sphinx team, see AUTHORS. :license: BSD, see LICENSE for details. """ import re import bisect import un...
else: # maintain links in sorted/deterministic order bisect.insort(entry[0], (main, uri)) for fn, entries in iteritems(self.data): # new entry types must be listed in directives/other.py! for type, value, tid, main, index_key in en...
"""Create the real index from the collected index entries.""" from sphinx.environment import NoUri new = {} def add_entry(word, subword, main, link=True, dic=new, key=None): # Force the word to be unicode if it's a ASCII bytestring. # This will solve problems with unico...
identifier_body
indexentries.py
# -*- coding: utf-8 -*- """ sphinx.environment.managers.indexentries ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Index entries manager for sphinx.environment. :copyright: Copyright 2007-2016 by the Sphinx team, see AUTHORS. :license: BSD, see LICENSE for details. """ import re import bisect import un...
def add_entry(word, subword, main, link=True, dic=new, key=None): # Force the word to be unicode if it's a ASCII bytestring. # This will solve problems with unicode normalization later. # For instance the RFC role will add bytestrings at the moment word = text_ty...
random_line_split
core_parallel_multifile_actions_1.py
#!/usr/bin/python # Copyright 2007 Rene Rivera.
# Copyright 2011 Steven Watanabe # Distributed under the Boost Software License, Version 1.0. # (See accompanying file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) # Added to guard against a bug causing targets to be used before they # themselves have finished building. This used to happen for targets bu...
random_line_split
ram_file_system_test.py
# Copyright 2020 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
(self): class MyModule(module.Module): @def_function.function(input_signature=[]) def foo(self): return constant_op.constant([1]) saved_model.save(MyModule(), 'ram://my_module') loaded = saved_model.load('ram://my_module') self.assertAllEqual(loaded.foo(), [1]) if __name__ == '_...
test_savedmodel
identifier_name
ram_file_system_test.py
# Copyright 2020 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
def test_savedmodel(self): class MyModule(module.Module): @def_function.function(input_signature=[]) def foo(self): return constant_op.constant([1]) saved_model.save(MyModule(), 'ram://my_module') loaded = saved_model.load('ram://my_module') self.assertAllEqual(loaded.foo(), [1...
estimator.train(input_fn=input_fn, steps=10) estimator.train(input_fn=input_fn, steps=10) estimator.train(input_fn=input_fn, steps=10) estimator.train(input_fn=input_fn, steps=10)
random_line_split
ram_file_system_test.py
# Copyright 2020 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
def input_fn(): batch_size = 128 return (constant_op.constant(np.random.randn(batch_size, 100), dtype=dtypes.float32), constant_op.constant(np.random.randn(batch_size, 1), dtype=dtypes.float32)) config = RunConfig...
del params x = core_layers.dense(features, 100) x = core_layers.dense(x, 100) x = core_layers.dense(x, 100) x = core_layers.dense(x, 100) y = core_layers.dense(x, 1) loss = losses.mean_squared_error(labels, y) opt = adam.AdamOptimizer(learning_rate=0.1) train_op = opt.min...
identifier_body
ram_file_system_test.py
# Copyright 2020 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
matches = ['%d.txt' % i for i in range(10)] self.assertEqual(gfile.ListDirectory('ram://a/b/'), matches) def test_glob(self): for i in range(10): with gfile.GFile('ram://a/b/%d.txt' % i, 'w') as f: f.write('') with gfile.GFile('ram://c/b/%d.txt' % i, 'w') as f: f.write('') ...
with gfile.GFile('ram://a/b/%d.txt' % i, 'w') as f: f.write('') with gfile.GFile('ram://c/b/%d.txt' % i, 'w') as f: f.write('')
conditional_block
JPC.py
digest() self.db_host = config['db_host'] self.db_name = config['db_name'] self.db_username = config['db_username'] self.db_password = config['db_password'] return # # チェック # def execute(self): import codecs import commands import ...
if 'id' not in self.packet :
random_line_split
JPC.py
, output=filepath_out) ) # コードを削除 try: os.remove(filepath_in) except Exception: pass # コンパイル結果を送信 try: self.ws.send(json.dumps({'compile': compile_result})) except Exception: pass # コンパイルできているか if not...
t),
conditional_block
JPC.py
filepath_config): import hashlib # 設定ファイルをロード fp = open(filepath_config, 'r') config = json.load(fp) fp.close() # 設定をクラス変数に格納 self.host = config['host'] self.port = config['port'] self.langlist = json.load(open(config['langfile'],...
__(self,
identifier_name
JPC.py
'][lang] # 必要なデータを生成 filepath_in = self.randstr(8) + extension filepath_out = self.randstr(8) username = self.randstr(16) # /tmpに移動 os.chdir('/tmp/') # ユーザーを作成する try: os.system("useradd -M {0}".format(username)) pwnam = pwd.getpwnam...
ue # # payloadが有効かを調べる # def check_payload(self): # 最低限の情報が記載されているか if 'lang' not in self.packet : return False if 'code' not in self.packet : return False if 'id' not in self.packet : return False if 'iv' not in self.packet : return False if ...
identifier_body
User.data.test.js
const expect = require('chai').expect; const User = require('../index'); const mongoose = require('mongoose'); const userData = { minimal : require('../data/sample.minimal.json'), full : require('../data/sample.full.json') }; describe('User instance data', function() { describe('should fail if ', () =>...
}); });
}); });
random_line_split
User.data.test.js
const expect = require('chai').expect; const User = require('../index'); const mongoose = require('mongoose'); const userData = { minimal : require('../data/sample.minimal.json'), full : require('../data/sample.full.json') }; describe('User instance data', function() { describe('should fail if ', () =>...
}); describe('should be valid if', () => { it('the minimun data is provided', (done) => { const user = new User(userData.minimal); user.validate((err) => { expect(err).to.be.not.ok; done(); }); }); it('every data type is right', (done) => { userData.full.update...
{ return (done) => { const user = new User(value); user.validate((err) => { expect(err.errors[field]).to.exist; done(); }); }; }
identifier_body
User.data.test.js
const expect = require('chai').expect; const User = require('../index'); const mongoose = require('mongoose'); const userData = { minimal : require('../data/sample.minimal.json'), full : require('../data/sample.full.json') }; describe('User instance data', function() { describe('should fail if ', () =>...
(field, value){ return (done) => { const user = new User(value); user.validate((err) => { expect(err.errors[field]).to.exist; done(); }); }; } }); describe('should be valid if', () => { it('the minimun data is provided', (done) => { const user =...
testErrorIfFieldIsMissing
identifier_name
moves-based-on-type-block-bad.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // 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 ...
fn main() { let s = S { x: ~Bar(~42) }; loop { f(&s, |hellothere| { match hellothere.x { //~ ERROR cannot move out ~Foo(_) => {} ~Bar(x) => println!("{}", x.to_str()), //~ NOTE attempting to move value to here ~Baz => {} } ...
{ g(s) }
identifier_body
moves-based-on-type-block-bad.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // 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 ...
() { let s = S { x: ~Bar(~42) }; loop { f(&s, |hellothere| { match hellothere.x { //~ ERROR cannot move out ~Foo(_) => {} ~Bar(x) => println!("{}", x.to_str()), //~ NOTE attempting to move value to here ~Baz => {} } }) }...
main
identifier_name
moves-based-on-type-block-bad.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // 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 ...
fn main() { let s = S { x: ~Bar(~42) }; loop { f(&s, |hellothere| { match hellothere.x { //~ ERROR cannot move out ~Foo(_) => {} ~Bar(x) => println!("{}", x.to_str()), //~ NOTE attempting to move value to here ~Baz => {} } ...
g(s) }
random_line_split
lib.rs
use std::collections::HashMap; #[derive(Default)] pub struct School(HashMap<u8, Vec<String>>); impl School { pub fn new() -> School { School(HashMap::new()) } /// Vector of all distinct grades in ascending order pub fn grades(&self) -> Vec<u8>
/// Vector of all names or None if no names are found pub fn grade(&self, grade: u8) -> Option<&Vec<String>> { self.0.get(&grade) } /// Add name and grade combination to School pub fn add(&mut self, grade: u8, name: &str) { let val = self.0.entry(grade).or_insert_with(Vec::new); ...
{ // map to convert & to value let mut ret: Vec<u8> = self.0.keys().cloned().collect(); // must be in order ret.sort(); ret }
identifier_body
lib.rs
use std::collections::HashMap; #[derive(Default)] pub struct School(HashMap<u8, Vec<String>>); impl School { pub fn
() -> School { School(HashMap::new()) } /// Vector of all distinct grades in ascending order pub fn grades(&self) -> Vec<u8> { // map to convert & to value let mut ret: Vec<u8> = self.0.keys().cloned().collect(); // must be in order ret.sort(); ret } ...
new
identifier_name
lib.rs
use std::collections::HashMap; #[derive(Default)] pub struct School(HashMap<u8, Vec<String>>); impl School { pub fn new() -> School { School(HashMap::new()) } /// Vector of all distinct grades in ascending order pub fn grades(&self) -> Vec<u8> { // map to convert & to value le...
ret } /// Vector of all names or None if no names are found pub fn grade(&self, grade: u8) -> Option<&Vec<String>> { self.0.get(&grade) } /// Add name and grade combination to School pub fn add(&mut self, grade: u8, name: &str) { let val = self.0.entry(grade).or_insert_...
random_line_split
krumo.js
/** * JavaScript routines for Krumo * * @version $Id: krumo.js,v 1.1.2.2 2008/06/03 20:36:03 weitzman Exp $ * @link http://sourceforge.net/projects/krumo */ ///////////////////////////////////////////////////////////////////////////// /** * Krumo JS Class */ function krumo() { } // -- -- -- -- -- -- -- -- -- -- -- ...
* Hover over an HTML element * * @param HtmlElement el * @return void */ krumo.over = function(el) { krumo.reclass(el, 'krumo-hover'); } // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- /** * Hover out an HTML element * * @param HtmlElement el * @return void */ krumo.out = function(...
// -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- /**
random_line_split
krumo.js
/** * JavaScript routines for Krumo * * @version $Id: krumo.js,v 1.1.2.2 2008/06/03 20:36:03 weitzman Exp $ * @link http://sourceforge.net/projects/krumo */ ///////////////////////////////////////////////////////////////////////////// /** * Krumo JS Class */ function
() { } // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- /** * Add a CSS class to an HTML element * * @param HtmlElement el * @param string className * @return void */ krumo.reclass = function(el, className) { if (el.className.indexOf(className) < 0) { el.className += (' ' + classNa...
krumo
identifier_name
krumo.js
/** * JavaScript routines for Krumo * * @version $Id: krumo.js,v 1.1.2.2 2008/06/03 20:36:03 weitzman Exp $ * @link http://sourceforge.net/projects/krumo */ ///////////////////////////////////////////////////////////////////////////// /** * Krumo JS Class */ function krumo() { } // -- -- -- -- -- -- -- -- -- -- -- ...
} // toggle class // if (ul[0].parentNode.style.display == 'block') { krumo.reclass(el, 'krumo-opened'); } else { krumo.unclass(el, 'krumo-opened'); } } // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- /** * Hover over an HTML element * * @param HtmlElement el * @return ...
{ ul[i].parentNode.style.display = (ul[i].parentNode.style.display == 'none') ? 'block' : 'none'; }
conditional_block
krumo.js
/** * JavaScript routines for Krumo * * @version $Id: krumo.js,v 1.1.2.2 2008/06/03 20:36:03 weitzman Exp $ * @link http://sourceforge.net/projects/krumo */ ///////////////////////////////////////////////////////////////////////////// /** * Krumo JS Class */ function krumo()
// -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- /** * Add a CSS class to an HTML element * * @param HtmlElement el * @param string className * @return void */ krumo.reclass = function(el, className) { if (el.className.indexOf(className) < 0) { el.className += (' ' + className); ...
{ }
identifier_body
lib.rs
2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! An implementation of re-entrant mutexes. //! //! Re-entrant mutexes are like mutexes, but where it is expected //! that a single thread may own a lock more than once. //! It provides the same int...
#[allow(unsafe_code)] pub fn lock<'a>(&'a self) -> LockResult<()> { let (guard, result) = match self.mutex.lock() { Ok(guard) => (guard, Ok(())), Err(err) => (err.into_inner(), Err(PoisonError::new(()))), }; unsafe { self.set_guard_and_owner(guard); } res...
{ let guard_ptr = &mut *self.guard.get(); let old_owner = self.owner(); self.owner.store(None, Ordering::Relaxed); // Make sure we release the lock before checking the assertions. // We protect logging by a re-entrant lock, so we don't want // to do any incidental logging...
identifier_body
lib.rs
2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! An implementation of re-entrant mutexes. //! //! Re-entrant mutexes are like mutexes, but where it is expected //! that a single thread may own a lock more than once. //! It provides the same int...
Ok(self.mk_guard()) } pub fn try_lock(&self) -> TryLockResult<ReentrantMutexGuard<T>> { trace!("{:?} Try locking.", ThreadId::current()); if self.mutex.owner() != Some(ThreadId::current()) { trace!("{:?} Becoming owner?", ThreadId::current()); if let Err(err) = ...
{ trace!("{:?} Becoming owner.", ThreadId::current()); if let Err(_) = self.mutex.lock() { trace!("{:?} Poison!", ThreadId::current()); return Err(PoisonError::new(self.mk_guard())); } trace!("{:?} Became owner.", ThreadId::current()); ...
conditional_block
lib.rs
2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! An implementation of re-entrant mutexes. //! //! Re-entrant mutexes are like mutexes, but where it is expected //! that a single thread may own a lock more than once. //! It provides the same int...
(&self, value: Option<ThreadId>, ordering: Ordering) -> Option<ThreadId> { let number = value.map(|id| id.0.get()).unwrap_or(0); let number = self.0.swap(number, ordering); NonZeroUsize::new(number).map(ThreadId) } } /// A type for hand-over-hand mutexes. /// /// These support `lock` and `u...
swap
identifier_name
lib.rs
2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! An implementation of re-entrant mutexes. //! //! Re-entrant mutexes are like mutexes, but where it is expected //! that a single thread may own a lock more than once. //! It provides the same int...
unsafe { self.set_guard_and_owner(guard); } result } #[allow(unsafe_code)] pub fn try_lock(&self) -> TryLockResult<()> { let (guard, result) = match self.mutex.try_lock() { Ok(guard) => (guard, Ok(())), Err(TryLockError::WouldBlock) => return Err(TryLockError:...
Err(err) => (err.into_inner(), Err(PoisonError::new(()))), };
random_line_split
nest.js
// Nest: A location (node) connected to other Nests via Webs (edges) in the game that Spiders can converge on, regardless of owner. // DO NOT MODIFY THIS FILE // Never try to directly create an instance of this class, or modify its member variables. // Instead, you should only be reading its variables and calling its ...
set x(value) { client.gameManager.setMemberValue(this, 'x', value); } /** * The Y coordinate of the Nest. Used for distance calculations. * * @type {number} */ get y() { return client.gameManager.getMemberValue(this, 'y'); } set y(value) { client.gameManager.setMemberValue(this,...
{ return client.gameManager.getMemberValue(this, 'x'); }
identifier_body
nest.js
// Nest: A location (node) connected to other Nests via Webs (edges) in the game that Spiders can converge on, regardless of owner. // DO NOT MODIFY THIS FILE // Never try to directly create an instance of this class, or modify its member variables. // Instead, you should only be reading its variables and calling its ...
/** * Initializes a Nest with basic logic as provided by the Creer code generator. * * Never use this directly. It is for internal Joueur use. */ constructor(...args) { super(...args); // The following values should get overridden when delta states are merged, but we set them here as a refere...
*/ class Nest extends GameObject {
random_line_split
nest.js
// Nest: A location (node) connected to other Nests via Webs (edges) in the game that Spiders can converge on, regardless of owner. // DO NOT MODIFY THIS FILE // Never try to directly create an instance of this class, or modify its member variables. // Instead, you should only be reading its variables and calling its ...
(value) { client.gameManager.setMemberValue(this, 'spiders', value); } /** * Webs that connect to this Nest. * * @type {Array.<Spiders.Web>} */ get webs() { return client.gameManager.getMemberValue(this, 'webs'); } set webs(value) { client.gameManager.setMemberValue(this, 'webs', va...
spiders
identifier_name
split_file.py
#!/usr/bin/env python """ split_file.py [-o <dir>] <path> Take the file at <path> and write it to multiple files, switching to a new file every time an annotation of the form "// BEGIN file1.swift" is encountered. If <dir> is specified, place the files in <dir>; otherwise, put them in the current directory. """ impo...
elif fp_out: fp_out.write(line) fp_in.close() if fp_out: fp_out.close()
if fp_out: fp_out.close() fp_out = open(os.path.join(dest_dir, m.group(1)), 'w')
conditional_block
split_file.py
#!/usr/bin/env python """ split_file.py [-o <dir>] <path> Take the file at <path> and write it to multiple files, switching to a new file every time an annotation of the form "// BEGIN file1.swift" is encountered. If <dir> is specified, place the files in <dir>; otherwise, put them in the current directory. """ impo...
for line in fp_in: m = re.match(r'^//\s*BEGIN\s+([^\s]+)\s*$', line) if m: if fp_out: fp_out.close() fp_out = open(os.path.join(dest_dir, m.group(1)), 'w') elif fp_out: fp_out.write(line) fp_in.close() if fp_out: fp_out.close()
if len(args) != 1: usage() fp_in = open(args[0], 'r')
random_line_split
split_file.py
#!/usr/bin/env python """ split_file.py [-o <dir>] <path> Take the file at <path> and write it to multiple files, switching to a new file every time an annotation of the form "// BEGIN file1.swift" is encountered. If <dir> is specified, place the files in <dir>; otherwise, put them in the current directory. """ impo...
(): sys.stderr.write(__doc__.strip() + "\n") sys.exit(1) fp_out = None dest_dir = '.' try: opts, args = getopt.getopt(sys.argv[1:], 'o:h') for (opt, arg) in opts: if opt == '-o': dest_dir = arg elif opt == '-h': usage() except getopt.GetoptError: usage() if...
usage
identifier_name
split_file.py
#!/usr/bin/env python """ split_file.py [-o <dir>] <path> Take the file at <path> and write it to multiple files, switching to a new file every time an annotation of the form "// BEGIN file1.swift" is encountered. If <dir> is specified, place the files in <dir>; otherwise, put them in the current directory. """ impo...
fp_out = None dest_dir = '.' try: opts, args = getopt.getopt(sys.argv[1:], 'o:h') for (opt, arg) in opts: if opt == '-o': dest_dir = arg elif opt == '-h': usage() except getopt.GetoptError: usage() if len(args) != 1: usage() fp_in = open(args[0], 'r') for lin...
sys.stderr.write(__doc__.strip() + "\n") sys.exit(1)
identifier_body
city.rs
extern crate rustc_serialize; use rustc_serialize::json::{Json, ToJson}; use std::fmt; use std::collections::BTreeMap; #[derive(Clone, RustcEncodable, RustcDecodable)] pub struct City{ pub name: String, pub coordinates: (f64, f64), } impl PartialEq for City { fn eq(&self, other: &City) -> bool { self.coordinate...
(&self) -> Json { let mut d = BTreeMap::new(); d.insert("name".to_string(), self.name.to_json()); d.insert("coordinates".to_string(), self.coordinates.to_json()); Json::Object(d) } }
to_json
identifier_name
city.rs
extern crate rustc_serialize; use rustc_serialize::json::{Json, ToJson}; use std::fmt; use std::collections::BTreeMap; #[derive(Clone, RustcEncodable, RustcDecodable)] pub struct City{ pub name: String, pub coordinates: (f64, f64), } impl PartialEq for City { fn eq(&self, other: &City) -> bool { self.coordinate...
} impl ToJson for City { fn to_json(&self) -> Json { let mut d = BTreeMap::new(); d.insert("name".to_string(), self.name.to_json()); d.insert("coordinates".to_string(), self.coordinates.to_json()); Json::Object(d) } }
}
random_line_split
city.rs
extern crate rustc_serialize; use rustc_serialize::json::{Json, ToJson}; use std::fmt; use std::collections::BTreeMap; #[derive(Clone, RustcEncodable, RustcDecodable)] pub struct City{ pub name: String, pub coordinates: (f64, f64), } impl PartialEq for City { fn eq(&self, other: &City) -> bool { self.coordinate...
} impl fmt::Display for City { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { write!(f, "Name:{},X:{},Y:{}", self.name, self.coordinates.0, self.coordinates.1) } } impl ToJson for City { fn to_json(&self) -> Json { let mut d = BTreeMap::new(); d.insert("name".to_string(), ...
{ self.coordinates.0 != other.coordinates.0 || self.coordinates.1 != other.coordinates.1 }
identifier_body