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
flocking-node.js
= require("fs"), url = require("url"), fluid = fluid || require("infusion"), flock = fluid.registerNamespace("flock"), Speaker = require("speaker"), Readable = require("stream").Readable, midi = require("midi"); (function () { "use strict"; /*******************************************...
outputStream.push(out); }; fluid.demands("flock.audioStrategy.platform", "flock.platform.nodejs", { funcName: "flock.audioStrategy.nodejs" }); /**************************** * Web MIDI Pseudo-Polyfill * ****************************/ fluid.registerNamespace("flock.midi...
{ for (var i = 0, offset = 0; i < krPeriods; i++, offset += m.bytesPerBlock) { evaluator.clearBuses(); evaluator.gen(); // Interleave each output channel. for (var chan = 0; chan < chans; chan++) { var bus = evaluator.buses...
conditional_block
flocking-node.js
fs = require("fs"), url = require("url"), fluid = fluid || require("infusion"), flock = fluid.registerNamespace("flock"), Speaker = require("speaker"), Readable = require("stream").Readable, midi = require("midi"); (function () { "use strict"; /****************************************...
funcName: "flock.audioStrategy.nodejs.writeSamples", args: ["{arguments}.0", "{that}"] }, startReadingAudioInput: { funcName: "flock.fail", args: "Audio input is not currently supported on Node.js" }, stopR...
args: ["{that}.outputStream", "{that}.speaker"] }, // TODO: De-thatify. writeSamples: {
random_line_split
app.py
levelname:<8} {message}", style='{', filename='logs.log', filemode='a' ) f = open("logs.log", "w+") logging.info('Main application has been initialized!') """ Check if environment variables are set """ if os.environ.get("MONGO_URI") and os.environ.get("SECRET_KEY"): MONGO_URI = os.environ.get("MONGO_U...
DATABASE = "TheInterviewMasterDeck" date_today = datetime.datetime.now() conn = mongo_connect(MONGO_URI) mongo_database = conn[DATABASE] logging.info('MongoDB Server version: %s', conn.server_info()["version"]) mongo_collection = mongo_database["questions"] index_name = 'question_1' if index_name not in mongo_collectio...
1. Will connect to MongoDB using the environmental variable 2. Will create a search index if not yet created 3. Will detect if database has been setup """
random_line_split
app.py
:<8} {message}", style='{', filename='logs.log', filemode='a' ) f = open("logs.log", "w+") logging.info('Main application has been initialized!') """ Check if environment variables are set """ if os.environ.get("MONGO_URI") and os.environ.get("SECRET_KEY"): MONGO_URI = os.environ.get("MONGO_URI") ...
@ app.route("/admin_card_delete/<card_id>", methods=["GET", "POST"]) def admin_card_delete(card_id): """ Questions Card Update Form :type card_id: :param card_id: """ if request.method == "GET": if session.get('logged_in') is True: mongo_collection = mongo_database["quest...
return admin()
conditional_block
app.py
levelname:<8} {message}", style='{', filename='logs.log', filemode='a' ) f = open("logs.log", "w+") logging.info('Main application has been initialized!') """ Check if environment variables are set """ if os.environ.get("MONGO_URI") and os.environ.get("SECRET_KEY"): MONGO_URI = os.environ.get("MONGO_U...
request.form.get("id")) logging.info('Questions Card %s has been updated.' % request.form.get("id")) return redirect(url_for("admin_cards")) else: return admin() @ app.route("/admin_card_delete/<card_id>", methods=["GET", "POST"])...
""" Questions Card Update Execution: 1. Will check if logged in and method is POST 2. Will attempt to update the Question Card accordingly :type card_id: :param card_id: """ if request.method == "POST": if session.get('logged_in') is True: mongo_collectio...
identifier_body
app.py
:<8} {message}", style='{', filename='logs.log', filemode='a' ) f = open("logs.log", "w+") logging.info('Main application has been initialized!') """ Check if environment variables are set """ if os.environ.get("MONGO_URI") and os.environ.get("SECRET_KEY"): MONGO_URI = os.environ.get("MONGO_URI") ...
(): """ End User Index Page """ mongo_collection = mongo_database["settings"] doc_instructions = mongo_collection.find_one({"id": "instructions"}) instructions = markdown.markdown(doc_instructions['text']) return render_template("index.html", instructions=instructions) @ app.route("/start"...
index
identifier_name
main.rs
stack: vec![], output: "".to_string(), } } } enum Msg { Input(String), Interval(String), Toggle, Step, Reset, Tick, } fn update(context: &mut Context<Msg>, model: &mut Model, msg: Msg) { match msg { Msg::Input(input) => { // model.befunge.source = string_to_array(input.as_str...
running: false, mode: Mode::End,
random_line_split
main.rs
) -> Array2d<char> { source.split("\n").map( |v| v.chars().collect() ).collect() } fn cyclic_index<T>(a: &Vec<T>, i: i64) -> Option<i64> { let l = a.len() as i64; if l == 0 { None } else { Some(i % l) } } fn cyclic_index2d<T>(a: &Array2d<T>, cursor: (i64, i64)) -> Option<(i64, i64)> { let (x, y) = curso...
fix_char_width
identifier_name
main.rs
struct Model { input: String, interval: String, time: u64, befunge: Befunge, } struct Befunge { source: Array2d<char>, cursor: (i64, i64), direction: Direction, running: bool, mode: Mode, stack: Stack, output: String } type Stack = Vec<i64>; #[derive(Debug)] enum Mode { StringMode, End, None }...
{ let model = init_model(); program(model, update, view); }
identifier_body
section.rs
use crate::val_helpr::ValidationResult; use crate::{compose::text, elems::BlockElement}; /// # Section Block /// /// _[slack api docs 🔗]_ /// /// Available in surfaces: /// - [modals 🔗] /// - [messages 🔗] /// - [home tabs 🔗] /// /// A `section` is one of the most flexible blocks available - /// it can be used a...
Validate::validate(self) } } /// Section block builder pub mod build { use std::marker::PhantomData; use super::*; use crate::build::*; /// Compile-time markers for builder methods #[allow(non_camel_case_types)] pub mod method { /// SectionBuilder.text #[derive(Clone, Copy, Debug)] pub ...
#[cfg(feature = "validation")] #[cfg_attr(docsrs, doc(cfg(feature = "validation")))] pub fn validate(&self) -> ValidationResult {
random_line_split
section.rs
fn builder() -> build::SectionBuilderInit<'a> { build::SectionBuilderInit::new() } /// Validate that this Section block agrees with Slack's model requirements /// /// # Errors /// - If `fields` contains more than 10 fields /// - If one of `fields` longer than 2000 chars /// - If `text` longer than 3...
lds",
identifier_name
section.rs
crate::val_helpr::ValidationResult; use crate::{compose::text, elems::BlockElement}; /// # Section Block /// /// _[slack api docs 🔗]_ /// /// Available in surfaces: /// - [modals 🔗] /// - [messages 🔗] /// - [home tabs 🔗] /// /// A `section` is one of the most flexible blocks available - /// it can be used as a...
ique identifier for a block. /// /// You can use this `block_id` when you receive an interaction payload /// to [identify the source of the action 🔗]. /// /// If not specified, a `block_id` will be generated. /// /// Maximum length for this field is 25
/// A string acting as a un
identifier_body
Release.py
#definitionsperson """ # Map BibTeX to CFF fields name_fields = { "last": "family-names", "bibtex_first": "given-names", "prelast": "name-particle", "lineage": "name-suffix", } result = { cff_field: " ".join(person.get_part(bibtex_field)) for bibtex_fi...
"sep": 9, "oct": 10, "nov": 11, "dec": 12, }[bib_value[:3].lower()] return bib_value cff_reference = { "type": _cff_transform(cff_field="type", bib_value=bib_entry.type), "authors": [ ...
if cff_field == "type": if bib_value == "inproceedings": return "article" elif bib_value == "incollection": return "article" elif cff_field == "publisher": return {"name": bib_value} elif cff_field == "month": try: ...
identifier_body
Release.py
\[{}\]\(.*\)".format(DOI_PATTERN), r"DOI: [{}]({})".format(doi, doi_url), content, flags=re.MULTILINE, ) assert ( num_subs > 0 ), "Could not find DOI (matching '{}') with link in file '{}'.".format( DOI_PATTERN, readme_file ) ...
help=( "Dry mode, only check that all files are consistent. Nothing is" " edited or uploaded to Zenodo. Used in CI tests to make sure"
random_line_split
Release.py
#definitionsperson """ # Map BibTeX to CFF fields name_fields = { "last": "family-names", "bibtex_first": "given-names", "prelast": "name-particle", "lineage": "name-suffix", } result = { cff_field: " ".join(person.get_part(bibtex_field)) for bibtex_fi...
( metadata: dict, version_name: str, metadata_file: str, citation_file: str, bib_file: str, references_file: str, readme_file: str, zenodo: Zenodo, github: Github, update_only: bool, check_only: bool, ): # Validate new version name match_version_name = re.match(VERSIO...
prepare
identifier_name
Release.py
#definitionsperson """ # Map BibTeX to CFF fields name_fields = { "last": "family-names", "bibtex_first": "given-names", "prelast": "name-particle", "lineage": "name-suffix", } result = { cff_field: " ".join(person.get_part(bibtex_field)) for bibtex_fi...
if "Affiliations" in author and len(author["Affiliations"]) > 0: citation_author["affiliation"] = " and ".join( author["Affiliations"] ) citation_authors.append(citation_author) # References in CITATION.cff format citation_references =...
citation_author["orcid"] = ( "https://orcid.org/" + author["Orcid"] )
conditional_block
match.go
(1) < 1 { // match.slotxxxResult = goodHands[rand.Intn(len(goodHands))] // } // match.playerResult.SlotxxxResult = match.slotxxxResult match.playerResult.MapPaylineIndexToWonMoney, match.playerResult.MapPaylineIndexToIsWin, match.playerResult.MatchWonType = CalcWonMoneys( match.slotxxxResult, match.payLineInde...
break } else { go func(match *SlotxxxMatch, action *Action) {
random_line_split
match.go
"sumWonMoney": result1p.SumWonMoney, "sumLostMoney": result1p.SumLostMoney, "mapPaylineIndexToWonMoney": result1p.MapPaylineIndexToWonMoney, "mapPaylineIndexToIsWin": result1p.MapPaylineIndexToIsWin, "matchWonType": result1p.MatchWonType, "changedMoney": ...
E[3] { jackpotObj = match.game.jackpot10000 } else { } if jackpotObj != nil { temp := match.moneyPerLine * int64(len(match.payLineIndexs)) temp = int64(0.025 * float64(temp)) // repay to users 95% jackpotObj.AddMoney(temp) if match.playerResult.MatchWonType == MATCH_WON_TYPE_JACKPOT { amount := int64...
se if match.moneyPerLine == MONEYS_PER_LIN
conditional_block
match.go
"}, []string{"Ac"}}, // [][]string{[]string{"8d"}, []string{"7d"}, []string{"9d"}}, // [][]string{[]string{"4h"}, []string{"6h"}, []string{"5h"}}, // [][]string{[]string{"3s"}, []string{"As"}, []string{"2s"}}, // [][]string{[]string{"8s"}, []string{"8c"}, []string{"8d"}}, // [][]string{[]string{"6s"}, []strin...
() string { return match.game.Cu
identifier_body
match.go
"sumWonMoney": result1p.SumWonMoney, "sumLostMoney": result1p.SumLostMoney, "mapPaylineIndexToWonMoney": result1p.MapPaylineIndexToWonMoney, "mapPaylineIndexToIsWin": result1p.MapPaylineIndexToIsWin, "matchWonType": result1p.MatchWonType, "changedMoney": ...
r := recover(); r != nil { bytes := debug.Stack() fmt.Println("ERROR ERROR ERROR: ", r, string(bytes)) } }() defer func() { match.game.mutex.Lock() delete(match.game.mapPlayerIdToMatch, match.player.Id()) match.game.mutex.Unlock() }() // _______________________________________________________________...
if
identifier_name
upgrading.go
func (this *UpgradingController) Get() { //导出 isExport, _ := this.GetInt("isExport", 0) if isExport == 1 { this.Export() return } beego.Informational("query upgrading") gId, _ := this.GetInt64("gameId", 0) account := strings.TrimSpace(this.GetString("account")) totalamount1 := strings.TrimSpace(this.GetSt...
{ this.EnableXSRF = false }
identifier_body
upgrading.go
.Retjson(this.Ctx, &msg, &code) gId, _ := this.GetInt64("gameId", 0) o := orm.NewOrm() //删除所有,再插入 upgradingdel := Upgrading{GameId: gId} _, err0 := o.Delete(&upgradingdel, "GameId") if err0 != nil { beego.Error("删除之前的所有记录失败", err0) msg = "删除之前的所有记录失败" return } models := make([]Upgrading, 0) //idsDel := m...
}
random_line_split
upgrading.go
json(this.Ctx, &msg, &code) gId, _ := this.GetInt64("gameId", 0) o := orm.NewOrm() //删除所有,再插入 upgradingdel := Upgrading{GameId: gId} _, err0 := o.Delete(&upgradingdel, "GameId") if err0 != nil { beego.Error("删除之前的所有记录失败", err0) msg = "删除之前的所有记录失败" return } models := make([]Upgrading, 0) //idsDel := make(...
identifier_name
upgrading.go
} gameid, err := strconv.ParseInt(strings.TrimSpace(row[0]), 10, 64) if err != nil { msg = fmt.Sprintf("%s第%d行有效投注必须为数字<br>", msg, i+1) continue } account := strings.TrimSpace(row[1]) if account == "" { msg = fmt.Sprintf("%s第%d行会员账号不能为空<br>", msg, i+1) } total, err := strconv.ParseInt(strings.T...
break } } } } code = 1 o.Commit() msg = fmt.Sprintf("已成功更新%d个会员的月俸禄", sum) } func (this *UpgradingController) CreateTotal() { var code int var msg string defer sysmanage.Retjson(this.Ctx, &msg, &code) gId, _ := this.GetInt64("gameId", 0) o := orm.NewOrm() //删除所有,再插入 upgradingdel := Upgrading{...
unt, "更新月俸禄失败", err) o.Rollback() msg = "更新月俸禄失败" return } sum += 1
conditional_block
legacy_message.go
then this might be a proto3 empty message // from before the size cache was added. If there are any fields, check to // see that at least one of them looks like something we generated. if t.Elem().Kind() == reflect.Struct { if nfield := t.Elem().NumField(); nfield > 0 { hasProtoField := false for i := 0; i ...
fd.L1.Message = LegacyLoadMessageDesc(t) default: if t.Kind() == reflect.Map {
random_line_split
legacy_message.go
.ProtoMessage); ok { panic(fmt.Sprintf("%v already implements proto.Message", t)) } mdV1, ok := mv.(messageV1) if !ok { return aberrantLoadMessageDesc(t, name) } // If this is a dynamic message type where there isn't a 1-1 mapping between // Go and protobuf types, calling the Descriptor method on the zero va...
} } // Obtain a list of the extension ranges. if fn, ok := t.MethodByName("ExtensionRangeArray"); ok { vs := fn.Func.Call([]reflect.Value{reflect.Zero(fn.Type.In(0))})[0] for i := 0; i < vs.Len(); i++ { v := vs.Index(i) md.L2.ExtensionRanges.List = append(md.L2.ExtensionRanges.List, [2]protoreflect.Fie...
{ if vs, ok := v.Interface().([]interface{}); ok { for _, v := range vs { oneofWrappers = append(oneofWrappers, reflect.TypeOf(v)) } } }
conditional_block
legacy_message.go
))}) { if vs, ok := v.Interface().([]interface{}); ok { for _, v := range vs { oneofWrappers = append(oneofWrappers, reflect.TypeOf(v)) } } } } } // Obtain a list of the extension ranges. if fn, ok := t.MethodByName("ExtensionRangeArray"); ok { vs := fn.Func.Call([]reflect.Value{refle...
{ // Check whether this supports the legacy merger. dstv := in.Destination.(unwrapper).protoUnwrap() merger, ok := dstv.(legacyMerger) if ok { merger.Merge(Export{}.ProtoMessageV1Of(in.Source)) return protoiface.MergeOutput{Flags: protoiface.MergeComplete} } // If legacy merger is unavailable, implement merg...
identifier_body
legacy_message.go
XX_MessageName()) } }() if name.IsValid() { return name } if t.Kind() == reflect.Ptr { t = t.Elem() } return AberrantDeriveFullName(t) } func aberrantAppendField(md *filedesc.Message, goType reflect.Type, tag, tagKey, tagVal string) { t := goType isOptional := t.Kind() == reflect.Ptr && t.Elem().Kind() !...
Clear
identifier_name
install.rs
&saved)?; } // return a generic error so our exit status is right bail!("install failed"); } // Because grub picks /boot by label and the OS picks /boot, we can end up racing/flapping // between picking a /boot partition on startup. So check amount of filesystems labeled 'boot' ...
write_firstboot_kargs
identifier_name
install.rs
_path_buf(); config_dest.push("ignition.firstboot"); // if the file doesn't already exist, fail, since our assumptions // are wrong let mut config_out = OpenOptions::new() .append(true) .open(&config_dest) .with_context(|| format!("opening first-boot file {}", config_dest.display...
{ use PartitionFilter::*; let g = |v| Label(glob::Pattern::new(v).unwrap()); let i = |v| Some(NonZeroU32::new(v).unwrap()); assert_eq!( parse_partition_filters(&["foo", "z*b?", ""], &["1", "7-7", "2-4", "-3", "4-"]) .unwrap(), vec![ ...
identifier_body
install.rs
.collect::<Vec<&str>>(), &config .save_partindex .iter() .map(|s| s.as_str()) .collect::<Vec<&str>>(), )?; // compute sector size // Uninitialized ECKD DASD's blocksize is 512, but after formatting // it changes to the recommended 4096...
.map(|s| s.as_str())
random_line_split
lib.rs
_use] extern crate lazy_static; extern crate num_cpus; #[macro_use] extern crate state_machine_future; extern crate tokio_core; extern crate tokio_timer; extern crate void; #[macro_use] pub mod js_native; mod error; mod future_ext; pub mod gc_roots; pub(crate) mod js_global; pub mod promise_future_glue; pub(crate) mo...
} StarlingMessage::NewTask(task, join_handle) => { self.tasks.insert(task.id(), task); self.threads.insert(join_handle.thread().id(), join_handle); } } } Ok(()) } } /// Messages that threads can s...
{ // TODO: notification of shutdown and joining other threads and things. return Err(error); }
conditional_block
lib.rs
path/to/main.js") /// // Finish configuring the `Options` builder and run the event /// // loop! /// .run()?; /// # Ok(()) /// # } /// ``` #[derive(Clone, Debug)] pub struct Options { main: path::PathBuf, sync_io_pool_threads: usize, cpu_pool_threads: usize, channel_buffer_size: usize, } co...
{ assert_send::<StarlingMessage>(); }
identifier_body
lib.rs
_use] extern crate lazy_static; extern crate num_cpus; #[macro_use] extern crate state_machine_future; extern crate tokio_core; extern crate tokio_timer; extern crate void; #[macro_use] pub mod js_native; mod error; mod future_ext; pub mod gc_roots; pub(crate) mod js_global; pub mod promise_future_glue; pub(crate) mo...
cpu_pool: CpuPool::new(cpu_pool_threads), sender, }; Ok(Starling { handle, receiver, tasks, threads, }) } /// Run the main Starling event loop with the specified options. pub fn run(mut self) -> Result<()> { ...
options: Arc::new(opts), sync_io_pool: CpuPool::new(sync_io_pool_threads),
random_line_split
lib.rs
_use] extern crate lazy_static; extern crate num_cpus; #[macro_use] extern crate state_machine_future; extern crate tokio_core; extern crate tokio_timer; extern crate void; #[macro_use] pub mod js_native; mod error; mod future_ext; pub mod gc_roots; pub(crate) mod js_global; pub mod promise_future_glue; pub(crate) mo...
<T>(&self) -> usize { let size_of_t = cmp::max(1, mem::size_of::<T>()); let capacity = self.channel_buffer_size / size_of_t; cmp::max(1, capacity) } } /// The Starling supervisory thread. /// /// The supervisory thread doesn't do much other than supervise other threads: the IO /// event loo...
buffer_capacity_for
identifier_name
random_state.rs
fn with_fixed_keys() -> RandomState { let [k0, k1, k2, k3] = get_fixed_seeds()[0]; RandomState { k0, k1, k2, k3 } } /// Build a `RandomState` from a single key. The provided key does not need to be of high quality, /// but all `RandomState`s created from the same key will produce identical...
let a = RandomState::generate_with(1, 2, 3, 4); let b = RandomState::generate_with(1, 2, 3, 4); assert_ne!(a.build_hasher().finish(), b.build_hasher().finish()); }
random_line_split
random_state.rs
the same key will produce identical hashers. /// (In contrast to `generate_with` above) /// /// This allows for explicitly setting the seed to be used. /// /// Note: This method does not require the provided seed to be strong. #[inline] pub fn with_seed(key: usize) -> RandomState { ...
test_not_pi_const
identifier_name
random_state.rs
u64, k1: u64, k2: u64, k3: u64) -> RandomState { let src = get_src(); let fixed = get_fixed_seeds(); RandomState::from_keys(&fixed[0], &[k0, k1, k2, k3], src.gen_hasher_seed()) } fn from_keys(a: &[u64; 4], b: &[u64; 4], c: usize) -> RandomState { let &[k0, k1, k2, k3] = a; ...
{ RandomState::hash_one(self, x) }
identifier_body
Pretty.ts
.sessionId, PASS); this._log.push('✓ ' + test.id); } } @eventHandler() tunnelDownloadProgress(message: TunnelMessage) { const progress = message.progress; this.tunnelState = 'Downloading ' + (progress.received / progress.total * 100).toFixed(2) + '%'; } @eventHandler() tunnelStatus(message: TunnelMessa...
random_line_split
Pretty.ts
._header = ''; this._reports = {}; this._log = []; this.tunnelState = ''; this._renderTimeout = undefined; this._total = new Report(); } @eventHandler() runStart() { this._header = this.executor.config.name; this._charm = this._charm || this._newCharm(); const resize = () => { this.dimensions.wi...
andler() suiteEnd(suite: Suite) { if (suite.error) { this._record(suite.sessionId, FAIL); const message = '! ' + suite.id; this._log.push(message + '\n' + this.formatter.format(suite.error)); } } @eventHandler() testEnd(test: Test) { if (test.skipped) { this._record(test.sessionId, SKIP); thi...
mTests = suite.numTests; this._total.numTotal += numTests; if (suite.sessionId) { this._getReporter(suite).numTotal += numTests; } } } @eventH
conditional_block
Pretty.ts
._header = ''; this._reports = {}; this._log = []; this.tunnelState = ''; this._renderTimeout = undefined; this._total = new Report(); } @eventHandler() runStart() { this._header = this.executor.config.name; this._charm = this._charm || this._newCharm(); const resize = () => { this.dimensions.wi...
) { if (!suite.hasParent) { const numTests = suite.numTests; this._total.numTotal += numTests; if (suite.sessionId) { this._getReporter(suite).numTotal += numTests; } } } @eventHandler() suiteEnd(suite: Suite) { if (suite.error) { this._record(suite.sessionId, FAIL); const message = '!...
ite: Suite
identifier_name
docker.go
err := tlsconfig.Client(options) if err != nil { panic(err) } httpClient := &http.Client{ Transport: &http.Transport{ Proxy: http.ProxyFromEnvironment, DialContext: (&net.Dialer{ Timeout: 30 * time.Second, KeepAlive: 30 * time.Second, }).DialContext, // ForceAttemptHT...
envVar = append(envVar, util.ActionEnvVariableSkip+"="+strconv.Itoa(common.Flags.Skipping.SkippingLevel())) envVar = append(envVar, util.ActionEnvVariableKey+"="+a.String()) envVar = append(envVar, "http_proxy="+common.Flags.Proxy.HTTP) envVar = append(envVar, "https_proxy="+common.Flags.Proxy.HTTPS) envVar = appe...
envVar = append(envVar, util.StarterVerbosityVariableKey+"="+strconv.Itoa(common.Flags.Logging.VerbosityLevel()))
random_line_split
docker.go
} } // ContainerRunningByImageName returns true if a container, built // on the given image, is running func ContainerRunningByImageName(name string) (string, bool, error) { containers, err := getContainers() if err != nil { return "", false, nil } for _, c := range containers { if c.Image == name || c.Image+...
getImages
identifier_name
docker.go
Var, util.StarterEnvVariableKey+"="+url) envVar = append(envVar, util.StarterEnvNameVariableKey+"="+common.Flags.Descriptor.File) envVar = append(envVar, util.StarterEnvLoginVariableKey+"="+common.Flags.Descriptor.Login) envVar = append(envVar, util.StarterEnvPasswordVariableKey+"="+common.Flags.Descriptor.Password)...
{ return nil, e }
conditional_block
docker.go
err := tlsconfig.Client(options) if err != nil { panic(err) } httpClient := &http.Client{ Transport: &http.Transport{ Proxy: http.ProxyFromEnvironment, DialContext: (&net.Dialer{ Timeout: 30 * time.Second, KeepAlive: 30 * time.Second, }).DialContext, // ForceAttemptHT...
//containerRunningById returns true if a container with the given id is running func containerRunningById(id string) (bool, error) { containers, err := getContainers() if err != nil { return false, err } for _, c := range containers { if c.ID == id { return true, nil } } return false, nil } //stopCont...
{ containers, err := getContainers() if err != nil { return "", false, nil } for _, c := range containers { if c.Image == name || c.Image+":latest" == name { return c.ID, true, nil } } return "", false, nil }
identifier_body
quiz.js
// set answers into the quiz var quizItems = modal.find("ol.quiz > li"); for( prop in data) { if( prop.startsWith("answer")) { var n = prop.replace("answer",""); // get the answer number log("answer number:", n, "quizItems", quizItems); //var li = $(quizItems[n]);...
setClass(li, "answer", id); // will remove old classes li.data("type","input"); //setClass(li, "answer", q); // will remove old classes li.find("input,select,textarea").each(function(inpNum, inp) { $(inp).attr("name", "answer" + q); }); }); if( data )...
var li = $(n); var id = li.attr("id");
random_line_split
quiz.js
// set answers into the quiz var quizItems = modal.find("ol.quiz > li"); for( prop in data) { if( prop.startsWith("answer")) { var n = prop.replace("answer",""); // get the answer number log("answer number:", n, "quizItems", quizItems); //var li = $(quizItems[n]);...
function ensureOneEmptyRadio(ol) { // remove any li's containing empty labels, then add one empty one removeEmptyRadios(ol); addRadioToMulti(ol); } function addRadioToMulti(ol) { var
{ ol.find("li").each(function(i, n) { var li = $(n); var txt = li.find("label").text().trim() if( txt == "" || txt.startsWith("[")) { li.remove(); } }); }
identifier_body
quiz.js
// set answers into the quiz var quizItems = modal.find("ol.quiz > li"); for( prop in data) { if( prop.startsWith("answer")) { var n = prop.replace("answer",""); // get the answer number log("answer number:", n, "quizItems", quizItems); //var li = $(quizItems[n]);...
(form, data) { log("prepareQuizForSave: build data object for quiz"); var quiz = form.find("#quizQuestions"); // Set names onto all inputs. Just number them answer0, answer1, etc. And add a class to the li with the name of the input, to use in front end validation var questions = quiz.find("ol.quiz > li...
prepareQuizForSave
identifier_name
quiz.js
radios.filter("[value=" + val + "]"); log("radio val", val, radio); radio.attr("checked", "true"); // set radio buttons log("restored radio", radio); } } } modal.find("input[type=radio]").closest("ol").each(function(i,n...
{ $.each(classes.split(" "), function(i, n) { if( n.startsWith(prefix)) { el.removeClass(n); } }); }
conditional_block
PaymentChannelsClient.js
(address) { const { provider } = Engine.context.NetworkController.state; this.selectedAddress = address; this.state = { ready: false, provider, hubUrl: null, tokenAddress: null, contractAddress: null, hubWalletAddress: null, ethprovider: null, tokenContract: null, connext: null, chan...
constructor
identifier_name
PaymentChannelsClient.js
break; default: throw new Error(`Unrecognized network: ${type}`); } const { KeyringController, TransactionController } = Engine.context; const opts = { hubUrl, externalWallet: { external: true, address: this.selectedAddress, getAddress: () => Promise.resolve(this.selectedAddress), s...
const currentBalance = (newState && newState.persistent.channel && newState.persistent.channel.balanceTokenUser) || '0'; if (toBN(prevBalance).lt(toBN(currentBalance))) { this.checkPaymentHistory(); } }; handleInternalTransactions = txHash => { const { withdrawalPendingValue } = this.state; const net...
} checkForBalanceChange = async newState => { // Check for balance changes const prevBalance = (this.state && this.state.channelState && this.state.channelState.balanceTokenUser) || '0';
random_line_split
PaymentChannelsClient.js
runtime: null, exchangeRate: 0, sendAmount: '', sendRecipient: '', depositAmount: '', status: { txHash: '', type: '', reset: false }, depositPending: false, withdrawalPending: false, withdrawalPendingValue: undefined, blocked: false, transactions: [], swapPending: fals...
{ const { provider } = Engine.context.NetworkController.state; this.selectedAddress = address; this.state = { ready: false, provider, hubUrl: null, tokenAddress: null, contractAddress: null, hubWalletAddress: null, ethprovider: null, tokenContract: null, connext: null, channelManager...
identifier_body
PaymentChannelsClient.js
async () => { TransactionController.hub.removeAllListeners( `${signedTx.transactionMeta.id}:confirmed` ); setTimeout(() => { TransactionsNotificationManager.showInstantPaymentNotification('pending_deposit'); }, 1000); resolve({ hash, wait: () ...
{ amount = maxAmount; }
conditional_block
test_utils.py
= 'localhost' os.environ['HTTP_HOST'] = 'localhost' os.environ['SERVER_PORT'] = '8080' os.environ['USER_EMAIL'] = '' os.environ['USER_ID'] = '' os.environ['USER_IS_ADMIN'] = '0' os.environ['DEFAULT_VERSION_HOSTNAME'] = '%s:%s' % ( os.environ['HTTP_HOST'], os.environ['SERVER_PORT']) cl...
if task.url == '/_ah/queue/deferred': deferred.run(task.payload) else: # All other tasks are expected to be mapreduce ones. headers = { key: str(val) for key, val in task.headers.iteritems() } ...
conditional_block
test_utils.py
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Common utilities for test classes.""" import contextlib import os import re import unittest import webtest from core.domain import config...
(self): return os.environ['USER_ID'] def get_user_id_from_email(self, email): return current_user_services.get_user_id_from_email(email) def save_new_default_exploration(self, exploration_id, owner_id, title='A title'): """Saves a new default exploration written by owner_id...
get_current_logged_in_user_id
identifier_name
test_utils.py
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Common utilities for test classes.""" import contextlib import os import re import unittest import webtest from core.domain import config...
json_response.content_type, 'application/javascript') self.assertTrue(json_response.body.startswith(feconf.XSSI_PREFIX)) return json.loads(json_response.body[len(feconf.XSSI_PREFIX):]) def get_json(self, url): """Get a JSON response, transformed to a Python object.""" j...
self.assertEqual(json_response.status_int, 200) self.assertEqual(
random_line_split
test_utils.py
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Common utilities for test classes.""" import contextlib import os import re import unittest import webtest from core.domain import config...
def setUp(self): empty_environ() from google.appengine.datastore import datastore_stub_util from google.appengine.ext import testbed self.testbed = testbed.Testbed() self.testbed.activate() # Configure datastore policy to emulate instantaneously and globally ...
from google.appengine.ext import ndb ndb.delete_multi(ndb.Query().iter(keys_only=True))
identifier_body
visualizations.go
izationWithDashboards { // This function is used, when log.Logger.Debug("rendering data to user") response := []common.VisualizationWithDashboards{} for visualizationPtr, dashboards := range *data { renderedVisualization := VisualizationDashboardToResponse( &visualizationPtr, dashboards) response = append(r...
// Delete dashboards, that were not uploaded to grafana deleteDashboardsDB = append(deleteDashboardsDB, dashboardsDB[len(uploadedGrafanaSlugs):]...) if len(updateDashboardsDB) > 0 { dashboardsToReturn := []*models.Dashboard{} dashboardsToReturn = append(dashboardsToReturn, updateDashboardsDB...) ...
{ grafanaDeletionErr := clients.Grafana.DeleteDashboard(slugToDelete, organizationID) // if already created dashboard was failed to delete - // corresponding db entry has to be updated with grafanaSlug // to guarantee consistency if grafanaDeletionErr != nil { log.Logger.Errorf("Error during pe...
conditional_block
visualizations.go
{ log.Logger.Debug("Querying data to user according to name and tags") data, err := clients.DatabaseManager.QueryVisualizationsDashboards( "", name, organizationID, tags) if err != nil { log.Logger.Errorf("Error getting data from db: '%s'", err) return nil, err } return GroupedVisualizationDashboardToResp...
VisualizationDelete
identifier_name
visualizations.go
izationWithDashboards { // This function is used, when log.Logger.Debug("rendering data to user") response := []common.VisualizationWithDashboards{} for visualizationPtr, dashboards := range *data { renderedVisualization := VisualizationDashboardToResponse( &visualizationPtr, dashboards) response = append(r...
if err != nil { // something is wrong with rendering of user provided template return nil, common.NewUserDataError(err.Error()) } renderedTemplates = append(renderedTemplates, templateBuffer.String()) } return renderedTemplates, nil } // VisualizationsPost handler creates new visualizations func (h *V1V...
{ // this function takes Visualization data and returns rendered templates log.Logger.Debug("Rendering golang templates") renderedTemplates := []string{} for index := range templates { // validate that golang template is valid // "missingkey=error" would return error, if user did not provide // all parameters...
identifier_body
visualizations.go
missingkey=error").Parse(templates[index]) if err != nil { // something is wrong with structure of user provided template return nil, common.NewUserDataError( fmt.Sprintf("ErrorMsg: '%s', TemplateIndex: '%d'", err.Error(), index)) } // render golang template with user provided arguments to buffer ...
for index, dashboardDB := range dashboardsDB {
random_line_split
consumers.go
ColonOrDeclare() Token { t := Token{ Type: Colon, Value: string(Colon), Column: l.Column, Line: l.Line, } l.move() // check if it is a `:=` if next, _ := l.peek(); next == '=' { t.Type = Declare t.Value = `:=` l.move() } return t } // recognizeOperator consumes an operator token func (l *L...
return l.getUnknownToken(string(op)) } // consume equals sign t.Value = string(op) + "=" l.move() return t } if !isBoolOperator(next) { switch op { case '+': t.Type = Plus // check if increment and consume if next == '+' { t.Type = Increment t.Value = "++" l.move() } cas...
{ switch op { case '+': t.Type = PlusEq case '-': t.Type = MinusEq case '/': t.Type = DivEq case '*': t.Type = TimesEq case '%': t.Type = ModEq case '&': t.Type = BitAndEq case '|': t.Type = BitOrEq case '^': t.Type = BitXorEq default: l.retract()
conditional_block
consumers.go
OrDeclare() Token { t := Token{ Type: Colon, Value: string(Colon), Column: l.Column, Line: l.Line, } l.move() // check if it is a `:=` if next, _ := l.peek(); next == '=' { t.Type = Declare t.Value = `:=` l.move() } return t } // recognizeOperator consumes an operator token func (l *Lexer)...
() Token { c := l.getCurr() if isArithmeticOperator(c) || isBitOperator(c) || c == '!' { t := l.consumeArithmeticOrBitOperator() if t.Type == Unknown && isBoolOperator(c) { return l.consumableBoolOperator() } return t } // attempt to consume shift operator if beginsBitShift(c) { if t := l.consumeBit...
recognizeOperator
identifier_name
consumers.go
arithmetic, bit or boolean then it is comparison return l.consumeComparisonOperator() } // consumebitShiftOperator consumes a bit shifting operator func (l *Lexer) consumeBitShiftOperator() Token { c := l.getCurr() t := Token{ Column: l.Column, Line: l.Line, } switch c { case '<': t.Type = BitLeftShift...
func (l *Lexer) consumeString() Token { nextState := &nextStringState
random_line_split
consumers.go
ColonOrDeclare() Token { t := Token{ Type: Colon, Value: string(Colon), Column: l.Column, Line: l.Line, } l.move() // check if it is a `:=` if next, _ := l.peek(); next == '=' { t.Type = Declare t.Value = `:=` l.move() } return t } // recognizeOperator consumes an operator token func (l *L...
switch char { case '<': if hasEquals { t.Type = LessThanOrEqual t.Value = "<=" } else { t.Type = LessThan t.Value = "<" } case '>': if hasEquals { t.Type = GreaterThanOrEqual t.Value = ">=" } else { t.Type = GreaterThan t.Value = ">" } case '=': if hasEquals { t.Type = Equal...
{ t := Token{ Column: l.Column, Line: l.Line, } char := l.getCurr() hasEquals := false if l.position+1 < len(l.input) { // copy next rune cpy := l.input[l.position+1] // move cursor to accommodate '=' if cpy == '=' { hasEquals = true l.move() } }
identifier_body
lib.rs
b fn flush(&mut self) -> Result<(), Error> { if self.bit_count > 0 { self.buffer <<= 8 - self.bit_count; let mut buffer = 0; for i in 0..8 { buffer <<= 1; buffer |= (self.buffer >> i) & 1; } self.output_vector.push(buff...
*/ pu
identifier_name
lib.rs
を保持する ymd: 年, 月, 日のデータを保持する */ struct Header{ buffer: Vec<u8>, before_size: u32, after_size: u32, filename: String, crc32: u32, hms: u16, ymd: u16, } impl Header { pub fn new(before_size: u32, after_size: u32, filename: impl Into<String>, crc32: u32, hms: u16, ymd: u16) -> Se...
<u8>{ self.push_pk0506(); self.push16(0x0000); self.push16(0x0000); self.push16(0x0001); self.push16(0x0001); self.push32(header_size); self.push32(header_start); self.push16(0x00); self.buffer } /* cloneの実装を行なっている */ pub fn ...
identifier_body
lib.rs
pub fn seek_byte(&mut self) -> u8{ self.buffer[self.buf_count] } /* bit_countを進める。bufferの最後まできていた場合には load_next_byteで次のブロックを読み込む。 */ pub fn next_byte(&mut self) { if self.buf_count + 1 < self.buf_size { self.buf_count += 1; } else { let _ =...
*/
random_line_split
font.go
octets_to_u16(font.cmap, offset), offset+2 offset = offset + 2 // uint16, (2 * segCount) - searchRange. // range_shift, offset := octets_to_u16(font.cmap, offset), offset+2 offset = offset + 2 // log.Printf("seg_count %v", seg_count) f.cmap_entry_array = make([]cmap_entry_t, seg_count) // uint16 * seg_...
{ msg := fmt.Sprintf("INVALID: bad maxp length %v", len(font.maxp)) return errors.New(msg) }
conditional_block
font.go
3 { valid = true break } // Microsoft UCS-2 Encoding or Microsoft UCS-4 Encoding. if pid_psid == 0x00030001 || pid_psid == 0x0003000a { valid = true // Don't break. So that unicode encoding can override ms encoding. } // TODO(coding): support whole list about pid and psid. // https://developer...
{ if len(font.kern) <= 0 { if font.kern_num != 0 { return errors.New("INVALID: kern length.") } else { return nil } } index := 0 // uint16, The version number of the kerning table (0x00010000 for the // current version). // // Upto now, only support the older version. Windows only support the older...
identifier_body
font.go
begin := int(octets_to_u32(ttf_bytes, table_offset+8)) length := int(octets_to_u32(ttf_bytes, table_offset+12)) switch title { case "cmap": new_font.cmap, err = read_table(ttf_bytes, begin, length) case "head": new_font.head, err = read_table(ttf_bytes, begin, length) case "kern": new_font.kern,...
new_font := new(Font) for i := 0; i < table_num; i++ { table_offset := 16*i + 12 title := string(ttf_bytes[table_offset : table_offset+4])
random_line_split
font.go
, err = read_table(ttf_bytes, begin, length) case "prep": new_font.prep, err = read_table(ttf_bytes, begin, length) case "hhea": new_font.hhea, err = read_table(ttf_bytes, begin, length) } if err != nil { return } } if err = new_font.parse_head(); err != nil { return } if err = new_font.p...
() error { if len(f.cmap) < 4 { log.Print("Font cmap too short.") } index := 2 subtable_num, index := int(octets_to_u16(f.cmap, index)), index+2 if len(f.cmap) < subtable_num*8+4 { log.Print("Font cmap too short.") } valid := false offset := 0 for i := 0; i < subtable_num; i++ { // platform id is plat...
parse_cmap
identifier_name
main.rs
()?; let mut linkages = HashMap::new(); let results = app.get_docs().process(&self.spec)?; // note: avoid name clash with db table let mut first = true; for doc in results { if first { first = false; } else { tcprintln!(app.ps, ("...
_n => { tcprintln!(app.ps, [hl: "Paths::"]); for p in path_reprs { tcprintln!(app.ps, (" {}", p)); } } } tcprintln!(app.ps, [hl: "Open-URL:"], (" {}", doc.open_url())); ...
} match path_reprs.len() { 0 => tcprintln!(app.ps, [hl: "Path:"], (" [none??]")), 1 => tcprintln!(app.ps, [hl: "Path:"], (" {}", path_reprs[0])),
random_line_split
main.rs
()?; let mut linkages = HashMap::new(); let results = app.get_docs().process(&self.spec)?; // note: avoid name clash with db table let mut first = true; for doc in results { if first { first = false; } else { tcprintln!(app.ps, ("...
(self, app: &mut
cli
identifier_name
finality.rs
blank finality checker under the given validator set. pub fn blank(signers: Vec<PublicKey>) -> Self { RollingFinality { headers: VecDeque::new(), signers: SimpleList::new(signers), sign_count: HashMap::new(), last_pushed: None, } } pub fn add_signer(&mut self, signer: PublicKey) { self.s...
/// Push a hash onto the rolling finality checker (implying `subchain_head` == head.parent) /// /// Fails if `signer` isn't a member of the active validator set. /// Returns a list of all newly finalized headers. // TODO: optimize with smallvec. pub fn push_hash(&mut self, head: H256, signers:...
{ self.headers.pop_back() }
identifier_body
finality.rs
ers set. pub fn build_ancestry_subchain<I>(&mut self, iterable: I) -> Result<(), UnknownValidator> where I: IntoIterator<Item=(H256, Vec<u64>)> { self.clear(); for (hash, signers) in iterable { self.check_signers(&signers)?; if self.last_pushed.is_none() { self.last_pushed = Some(hash.c...
rejects_unknown_signers
identifier_name
finality.rs
RollingFinality { headers: VecDeque::new(), signers: SimpleList::new(signers), sign_count: HashMap::new(), last_pushed: None, } } pub fn add_signer(&mut self, signer: PublicKey) { self.signers.add(signer) } pub fn remove_signer(&mut self, signer: &u64) { self.signers.remov...
/// Create a blank finality checker under the given validator set. pub fn blank(signers: Vec<PublicKey>) -> Self {
random_line_split
finality.rs
blank finality checker under the given validator set. pub fn blank(signers: Vec<PublicKey>) -> Self { RollingFinality { headers: VecDeque::new(), signers: SimpleList::new(signers), sign_count: HashMap::new(), last_pushed: None, } } pub fn add_signer(&mut self, signer: PublicKey) { self.s...
for signer in signers.iter() { *self.sign_count.entry(signer.clone()).or_insert(0) += 1; } } self.headers.push_front((hash, signers)); } trace!(target: "finality", "Rolling finality state: {:?}", self.headers); Ok(()) } /// Clear the finality status, but keeps the validator set. pub fn ...
{ trace!(target: "finality", "Encountered already finalized block {:?}", hash.clone()); break }
conditional_block
installerTools.js
the given // searchKey. Start in the directory given in path and // search each sub directory. // All matches are added to the array listPaths. var listFiles = fs.readdirSync(path); for (var indx =0; indx < listFiles.length; indx++) { var fileName = listFiles[indx]; ...
else { console.log('installLabel [' + path + ']'); poContent += '\n\n' + data; } innerCallback(); }); // only one possible language match per .po file ...
fs.readFile(path, 'utf8', function(err, data) { if (err) { console.error(err); }
random_line_split
installerTools.js
the given // searchKey. Start in the directory given in path and // search each sub directory. // All matches are added to the array listPaths. var listFiles = fs.readdirSync(path); for (var indx =0; indx < listFiles.length; indx++) { var fileName = listFiles[indx]; ...
// no language matches for this .po file innerCallback(); return; }, callback); } //// Ian's label import algorithm var importPoContent = function(callback) { var allcontentssplit = poContent.split(/\r?\n\s*\r?\n/); ...
{ // Only read .po files that follow the right naming convention if (path.indexOf('labels_' + langList[i] + '.po') !== -1) { fs.readFile(path, 'utf8', function(err, data) { if (err) { console.error(err); ...
conditional_block
main.js
(e){ e = e || window.event; return e.target || e.srcElement; // Accommodate all browsers } /****************************** OBJECTS-ORIENTED VARIABLES ******************************/ /***** Navigation Object Literal *****/ var nav = { // Show active nav item link, using green bar, // on main navig...
targetChoice
identifier_name
main.js
", profile:"john-2134", join:"May 28, 2013", email:"johnny90064@example.com", recentActivity:"posted Facebook's Changes for 2016.", recentTime:"3 hours ago", activity: "posted" }, { id:9009, first: "Crystal", last:"Meyers", profile:"crystal-9009", join:"Aug 23, 2016", email:"crystal1989@example.com", recentA...
{ $emailNotification.switchButton({ checked: true }); }
conditional_block
main.js
// Get enclosing element on an event (e.g. "click") function targetChoice(e){ e = e || window.event; return e.target || e.srcElement; // Accommodate all browsers } /****************************** OBJECTS-ORIENTED VARIABLES ******************************/ /***** Navigation Object Literal *****/ var ...
{ var regex = /(<([^]+)>\n)/ig; var cleanIt = message.replace(regex, ""); var results = cleanIt.trim(); return results; }
identifier_body
main.js
lineTraffic.trafficWeek(); break; case "months": lineTraffic.trafficMonth(); break; } } }; /***** Daily Traffic Bar Chart Object Literal *****/ var barDailyTraffic = { // Daily Traffic data barDay: function() { var days = { labels: ["Sun", "Mon", "Tues", "Wed", "Thur", "Fr...
sel.appendChild(li); } // Hide list if no Choices
random_line_split
docker.go
.ParseNormalizedNamed(dockerRef) if err != nil { return nil, fmt.Errorf("Argument 1 (ref): can't parse %q: %v", dockerRef, err) } if command == "" { return nil, fmt.Errorf("Argument 2 (command) can't be empty") } if deps == nil || deps.Len() == 0 { return nil, fmt.Errorf("Argument 3 (deps) can't be empty")...
{ result = append(result, model.Mount{LocalPath: m.src.path, ContainerPath: m.mountPoint}) }
conditional_block
docker.go
type dockerImageBuildType int const ( UnknownBuild = iota StaticBuild FastBuild CustomBuild ) func (d *dockerImage) Type() dockerImageBuildType { if !d.staticBuildPath.Empty() { return StaticBuild } if !d.baseDockerfilePath.Empty() { return FastBuild } if d.customCommand != "" { return CustomBuild ...
{ return model.ImageID(d.ref) }
identifier_body
docker.go
Value(contextVal) if err != nil { return nil, err } var sba map[string]string if buildArgs != nil { d, ok := buildArgs.(*starlark.Dict) if !ok { return nil, fmt.Errorf("Argument 3 (build_args): expected dict, got %T", buildArgs) } sba, err = skylarkStringDictToGoMap(d) if err != nil { return nil...
var _ starlark.Value = &fastBuild{} func (b *fastBuild) String() string { return fmt.Sprintf("fast_build(%q)", b.img.ref.String()) } func (b *fastBuild) Type() string { return "fast_build" } func (b *fastBuild) Freeze() {} func (b *fastBuild) Truth() starlark.Bool {
type fastBuild struct { s *tiltfileState img *dockerImage }
random_line_split
docker.go
() (uint32, error) { return 0, fmt.Errorf("unhashable type: custom_build") } const ( addFastBuildN = "add_fast_build" ) func (b *customBuild) Attr(name string) (starlark.Value, error) { switch name { case addFastBuildN: return starlark.NewBuiltin(name, b.addFastBuild), nil default: return starlark.None, nil ...
dockerignoresForImage
identifier_name
TextRank.py
(z)) return weight def get_wordnet_pos(self, treebank_tag): if treebank_tag.startswith('N'): return wn.NOUN elif treebank_tag.startswith('J'): return wn.ADJ elif treebank_tag.startswith('R'): return wn.ADV else: r...
#tokens = nltk.word_from nltk.stem.porter import *tokenize(s.translate(self.tbl)) tokens = nltk.word_tokenize(s.translate(string.punctuation)) tags = nltk.pos_tag(tokens) print(tags) wid = 0 for ws in tags: z = ws[0].rstrip('\'\"...
for sid, s in enumerate(sentences): s = s.rstrip('\n') #print(sid, '>>', s) ids = set() s = s.lower()
random_line_split
TextRank.py
(z)) return weight def get_wordnet_pos(self, treebank_tag): if treebank_tag.startswith('N'): return wn.NOUN elif treebank_tag.startswith('J'):
elif treebank_tag.startswith('R'): return wn.ADV else: return '' def buildGraph(self, sentences): g = nx.DiGraph() wordList = defaultdict(set) for sid, s in enumerate(sentences): s = s.rstrip('\n') #print(sid, '>>', s) ...
return wn.ADJ
conditional_block
TextRank.py
(z)) return weight def get_wordnet_pos(self, treebank_tag): if treebank_tag.startswith('N'): return wn.NOUN elif treebank_tag.startswith('J'): return wn.ADJ elif treebank_tag.startswith('R'): return wn.ADV else: r...
''' def compareAbstract(self, summary_sentences, abs_sentences, n, fname): precision = 0 recall = 0 avgO = 0 i = 0 i_measure = 0 #print('Abstract of ', fname) tokens = set(nltk.word_tokenize(abs_sentences.translate(string.punctuat...
setB = set() stemmer = SnowballStemmer("english") setA = set(setA).difference(self.excludeSet) for a in setA: print(a) xss = re.split(r'-', a) if len(xss) > 1: #input() #print(xss) for xs in xss: ...
identifier_body
TextRank.py
: ssen = '' weight = 0.000 senIndex = 0 class TextRank: def __init__(self, pathList): self.engStopWords = set(stopwords.words('english')) self.excludeSet = set(string.punctuation) self.excludeSet = self.excludeSet.union(self.engStopWords) extra = set(['also', 'e.g.'...
SentenceSample
identifier_name
bos.go
lastSlice := int(math.Floor(float64(size)/partSize)), size%partSize if partNums == 0 { body, err := bce.NewBodyFromSizedReader(r, lastSlice) if err != nil { return errors.Wrapf(err, "failed to create SizedReader for %s", name) } if _, err := b.client.PutObject(b.name, name, body, nil); err != nil { ret...
{ tmpBucketName = tmpBucketName[:31] }
conditional_block
bos.go
conf.SecretKey == "" { return errors.New("insufficient BOS configuration information") } return nil } // parseConfig unmarshal a buffer into a Config with default HTTPConfig values. func parseConfig(conf []byte) (Config, error) { config := Config{} if err := yaml.Unmarshal(conf, &config); err != nil { retur...
(ctx context.Context, name string) (io.ReadCloser, error) { return b.getRange(ctx, b.name, name, 0, -1) } // GetRange returns a new range reader for the given object name and range. func (b *Bucket) GetRange(ctx context.Context, name string, off, length int64) (io.ReadCloser, error) { return b.getRange(ctx, b.name, ...
Get
identifier_name
bos.go
|| conf.SecretKey == "" { return errors.New("insufficient BOS configuration information") } return nil } // parseConfig unmarshal a buffer into a Config with default HTTPConfig values. func parseConfig(conf []byte) (Config, error) { config := Config{} if err := yaml.Unmarshal(conf, &config); err != nil { r...
_, err := b.client.GetObjectMeta(b.name, name) if err != nil { if b.IsObjNotFoundErr(err) { return false, nil } return false, errors.Wrapf(err, "getting object metadata of %s", name) } return true, nil } func (b *Bucket) Close() error { return nil } // ObjectSize returns the size of the specified object...
// Exists checks if the given object exists in the bucket. func (b *Bucket) Exists(_ context.Context, name string) (bool, error) {
random_line_split
bos.go
conf.SecretKey == "" { return errors.New("insufficient BOS configuration information") } return nil } // parseConfig unmarshal a buffer into a Config with default HTTPConfig values. func parseConfig(conf []byte) (Config, error) { config := Config{} if err := yaml.Unmarshal(conf, &config); err != nil { retur...
// Delete removes the object with the given name. func (b *Bucket) Delete(_ context.Context, name string) error { return b.client.DeleteObject(b.name, name) } // Upload the contents of the reader as an object into the bucket. func (b *Bucket) Upload(_ context.Context, name string, r io.Reader) error { size, err :=...
{ return b.name }
identifier_body
remote.py
_is_error(ex, 429): #import pdb; pdb.set_trace() raise Gmail.UserRateException(ex) elif ex_is_error(ex, 500): raise Gmail.GenericException(ex) else: raise Gmail.BatchException(ex) responses.append...
@property def scopes(self): """Scopes used for authorization.""" return [scope.rsplit('/', 1)[1] for scope in self.opts.scopes] @property def writable(self): """Whether the account was authorized as read-only or not.""" return 'gmail.modify' in self.scopes @proper...
"""How often to poll for new messages / updates.""" return self.opts.poll_interval
identifier_body
remote.py
_is_error(ex, 429): #import pdb; pdb.set_trace() raise Gmail.UserRateException(ex) elif ex_is_error(ex, 500): raise Gmail.GenericException(ex) else: raise Gmail.BatchException(ex) responses.append...
else: outq.put([ridx, responses]) break inq.task_done() print("worker %d stoping" % my_idx) def __init__(self, **kwargs): """Initialize a new object using the options passed in.""" self.opts = self.options.push(kwargs) ...
outq.put([ridx, ex]) break
random_line_split
remote.py
_is_error(ex, 429): #import pdb; pdb.set_trace() raise Gmail.UserRateException(ex) elif ex_is_error(ex, 500): raise Gmail.GenericException(ex) else: raise Gmail.BatchException(ex) responses.append...
batch.execute(http=http) return responses @staticmethod def worker(my_idx, inq, outq): """Entry point for new executor threads. Downloading (or importing) metadata is limited by the round-trip time to Gmail if we only use one thread. This wrapper function makes it possible to start m...
batch.add(cmd, callback=lambda a, b, c: handler(a, b, c, responses), request_id=gid)
conditional_block
remote.py
_is_error(ex, 429): #import pdb; pdb.set_trace() raise Gmail.UserRateException(ex) elif ex_is_error(ex, 500): raise Gmail.GenericException(ex) else: raise Gmail.BatchException(ex) responses.append...
(self, start=0): """Get a list of changes since the given start point (a history id).""" hist = self.service.users().history() try: results = hist.list(userId='me', startHistoryId=start).execute() if 'history' in results: yield results['history'] ...
get_history_since
identifier_name