file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
39k
suffix
large_stringlengths
0
36.1k
middle
large_stringlengths
0
29.4k
fim_type
large_stringclasses
4 values
flocking-node.js
/* * Flocking Node.js Adaptor * http://github.com/colinbdclark/flocking * * Copyright 2013-2014, Colin Clark * Dual licensed under the MIT and GPL Version 2 licenses. */ /*jslint white: true, vars: true, undef: true, newcap: true, regexp: true, browser: true, forin: true, continue: true, nomen: true, bitwise: true...
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
/* * Flocking Node.js Adaptor * http://github.com/colinbdclark/flocking * * Copyright 2013-2014, Colin Clark * Dual licensed under the MIT and GPL Version 2 licenses. */ /*jslint white: true, vars: true, undef: true, newcap: true, regexp: true, browser: true, forin: true, continue: true, nomen: true, bitwise: true...
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
import os import pymongo import logging import datetime import markdown import random from pymongo import TEXT from flask import ( Flask, flash, render_template, redirect, request, session, url_for ) from bson.objectid import ObjectId from werkzeug.security import generate_password_hash, check_p...
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
import os import pymongo import logging import datetime import markdown import random from pymongo import TEXT from flask import ( Flask, flash, render_template, redirect, request, session, url_for ) from bson.objectid import ObjectId from werkzeug.security import generate_password_hash, check_p...
@ 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
import os import pymongo import logging import datetime import markdown import random from pymongo import TEXT from flask import ( Flask, flash, render_template, redirect, request, session, url_for ) from bson.objectid import ObjectId from werkzeug.security import generate_password_hash, check_p...
@ 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...
""" 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
import os import pymongo import logging import datetime import markdown import random from pymongo import TEXT from flask import ( Flask, flash, render_template, redirect, request, session, url_for ) from bson.objectid import ObjectId from werkzeug.security import generate_password_hash, check_p...
(): """ 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
#![recursion_limit="128"] #[macro_use] extern crate yew; use std::time::Duration; use std::char; use yew::html::*; use yew::services::timeout::TimeoutService; fn main() { let model = init_model(); program(model, update, view); } struct Model { input: String, interval: String, time: u64, befunge: Befunge,...
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
#![recursion_limit="128"] #[macro_use] extern crate yew; use std::time::Duration; use std::char; use yew::html::*; use yew::services::timeout::TimeoutService; fn main() { let model = init_model(); program(model, update, view); } struct Model { input: String, interval: String, time: u64, befunge: Befunge,...
(x: char) -> char { let ac = x as u32; if 33 <= ac && ac <= 126 { x } else { char::from_u32(160).unwrap_or(' ') } } fn colorize(source: &Array2d<char>, cursor: (i64, i64)) -> Html<Msg> { let (cx, cy) = cursor; html! { <div> { for source.iter().enumerate().map( |(y, row)| { ...
fix_char_width
identifier_name
main.rs
#![recursion_limit="128"] #[macro_use] extern crate yew; use std::time::Duration; use std::char; use yew::html::*; use yew::services::timeout::TimeoutService; fn main()
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
//! # 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 simple text block, //! in combination with text fields, //! or side-by-side with any o...
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
//! # 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 simple text block, //! in combination with text fields, //! or side-by-side with any o...
10, texts.as_ref()).and( texts.iter() .map(|text| { below_len( "Section.fields", 2000, text.as_ref())...
lds",
identifier_name
section.rs
//! # 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 simple text block, //! in combination with text fields, //! or side-by-side with any o...
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 255 characters. /// /// [identify...
/// A string acting as a un
identifier_body
Release.py
#!/usr/bin/env python # Distributed under the MIT License. # See LICENSE.txt for details. import datetime import difflib import logging import operator import os import pathlib import re import tempfile import textwrap import urllib from typing import List import git import pybtex.database import requests import upl...
cff_reference = { "type": _cff_transform(cff_field="type", bib_value=bib_entry.type), "authors": [ to_cff_person(person) for person in bib_entry.persons["author"] ], } # Map BibTeX to CFF fields. This is just a subset of the most relevant # fields. fields = { ...
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
#!/usr/bin/env python # Distributed under the MIT License. # See LICENSE.txt for details. import datetime import difflib import logging import operator import os import pathlib import re import tempfile import textwrap import urllib from typing import List import git import pybtex.database import requests import upl...
" changes to the repository remain compatible with this script." ), ) subparsers = parser.add_subparsers() parser_prepare = subparsers.add_parser("prepare", parents=[parent_parser]) parser_prepare.set_defaults(subprogram=prepare) parser_prepare.add_argument( "--update-onl...
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
#!/usr/bin/env python # Distributed under the MIT License. # See LICENSE.txt for details. import datetime import difflib import logging import operator import os import pathlib import re import tempfile import textwrap import urllib from typing import List import git import pybtex.database import requests import upl...
( 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
#!/usr/bin/env python # Distributed under the MIT License. # See LICENSE.txt for details. import datetime import difflib import logging import operator import os import pathlib import re import tempfile import textwrap import urllib from typing import List import git import pybtex.database import requests import upl...
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
package slotxxx import ( "encoding/json" "errors" "fmt" "math/rand" "runtime/debug" "sync" "time" //"github.com/vic/vic_go/models/currency" //"github.com/vic/vic_go/models/game" "github.com/vic/vic_go/models/player" // "github.com/vic/vic_go/utils" "github.com/vic/vic_go/models/cardgame" "github.com/vic/...
defer func() { if r := recover(); r != nil { bytes := debug.Stack() fmt.Println("ERROR ERROR ERROR: ", r, string(bytes)) } }() if action.actionName == ACTION_GET_MATCH_INFO { action.chanResponse <- &ActionResponse{err: nil} match.updateMatchStatus() } else if action.acti...
break } else { go func(match *SlotxxxMatch, action *Action) {
random_line_split
match.go
package slotxxx import ( "encoding/json" "errors" "fmt" "math/rand" "runtime/debug" "sync" "time" //"github.com/vic/vic_go/models/currency" //"github.com/vic/vic_go/models/game" "github.com/vic/vic_go/models/player" // "github.com/vic/vic_go/utils" "github.com/vic/vic_go/models/cardgame" "github.com/vic/...
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
package slotxxx import ( "encoding/json" "errors" "fmt" "math/rand" "runtime/debug" "sync" "time" //"github.com/vic/vic_go/models/currency" //"github.com/vic/vic_go/models/game" "github.com/vic/vic_go/models/player" // "github.com/vic/vic_go/utils" "github.com/vic/vic_go/models/cardgame" "github.com/vic/...
rrencyType() } // json obj represent general match info func (match *SlotxxxMatch) SerializedData() map[string]interface{} { data := match.playerResult.Serialize() data["phase"] = match.phase data["currentXxxLevel"] = match.currentXxxLevel data["currentXxxMoney"] = match.currentXxxMoney data["is1stTryFailed"] = m...
() string { return match.game.Cu
identifier_body
match.go
package slotxxx import ( "encoding/json" "errors" "fmt" "math/rand" "runtime/debug" "sync" "time" //"github.com/vic/vic_go/models/currency" //"github.com/vic/vic_go/models/game" "github.com/vic/vic_go/models/player" // "github.com/vic/vic_go/utils" "github.com/vic/vic_go/models/cardgame" "github.com/vic/...
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
package upgrading import ( "fmt" "games-web/models/common" . "games-web/models/gamedetail/upgrading" "games-web/utils" "github.com/360EntSecGroup-Skylar/excelize" "github.com/astaxie/beego" "github.com/astaxie/beego/orm" "github.com/astaxie/beego/utils/pagination" "html/template" "math" "net/url" "os" "ph...
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
package upgrading import ( "fmt" "games-web/models/common" . "games-web/models/gamedetail/upgrading" "games-web/utils" "github.com/360EntSecGroup-Skylar/excelize" "github.com/astaxie/beego" "github.com/astaxie/beego/orm" "github.com/astaxie/beego/utils/pagination" "html/template" "math" "net/url" "os" "ph...
}
random_line_split
upgrading.go
package upgrading import ( "fmt" "games-web/models/common" . "games-web/models/gamedetail/upgrading" "games-web/utils" "github.com/360EntSecGroup-Skylar/excelize" "github.com/astaxie/beego" "github.com/astaxie/beego/orm" "github.com/astaxie/beego/utils/pagination" "html/template" "math" "net/url" "os" "ph...
identifier_name
upgrading.go
package upgrading import ( "fmt" "games-web/models/common" . "games-web/models/gamedetail/upgrading" "games-web/utils" "github.com/360EntSecGroup-Skylar/excelize" "github.com/astaxie/beego" "github.com/astaxie/beego/orm" "github.com/astaxie/beego/utils/pagination" "html/template" "math" "net/url" "os" "ph...
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
// Copyright 2018 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package impl import ( "fmt" "reflect" "strings" "sync" "google.golang.org/protobuf/internal/descopts" ptag "google.golang.org/protobuf/internal/encoding...
n := len(md.L1.Messages.List) md.L1.Messages.List = append(md.L1.Messages.List, filedesc.Message{L2: new(filedesc.MessageL2)}) md2 := &md.L1.Messages.List[n] md2.L0.FullName = md.FullName().Append(protoreflect.Name(strs.MapEntryName(string(fd.Name())))) md2.L0.ParentFile = md.L0.ParentFile md2.L...
fd.L1.Message = LegacyLoadMessageDesc(t) default: if t.Kind() == reflect.Map {
random_line_split
legacy_message.go
// Copyright 2018 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package impl import ( "fmt" "reflect" "strings" "sync" "google.golang.org/protobuf/internal/descopts" ptag "google.golang.org/protobuf/internal/encoding...
} } // 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
// Copyright 2018 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package impl import ( "fmt" "reflect" "strings" "sync" "google.golang.org/protobuf/internal/descopts" ptag "google.golang.org/protobuf/internal/encoding...
// aberrantMessageType implements MessageType for all types other than pointer-to-struct. type aberrantMessageType struct { t reflect.Type } func (mt aberrantMessageType) New() protoreflect.Message { if mt.t.Kind() == reflect.Ptr { return aberrantMessage{reflect.New(mt.t.Elem())} } return aberrantMessage{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
// Copyright 2018 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package impl import ( "fmt" "reflect" "strings" "sync" "google.golang.org/protobuf/internal/descopts" ptag "google.golang.org/protobuf/internal/encoding...
(protoreflect.FieldDescriptor) { panic("invalid Message.Clear on " + string(m.Descriptor().FullName())) } func (m aberrantMessage) Get(fd protoreflect.FieldDescriptor) protoreflect.Value { if fd.Default().IsValid() { return fd.Default() } panic("invalid Message.Get on " + string(m.Descriptor().FullName())) } func...
Clear
identifier_name
install.rs
// Copyright 2019 CoreOS, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in...
(mountpoint: &Path, args: &str) -> Result<()> { eprintln!("Writing first-boot kernel arguments"); // write the arguments let mut config_dest = mountpoint.to_path_buf(); config_dest.push("ignition.firstboot"); // if the file doesn't already exist, fail, since our assumptions // are wrong let...
write_firstboot_kargs
identifier_name
install.rs
// Copyright 2019 CoreOS, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in...
#[test] fn test_update_grub_cfg() { let base_cfgs = vec![ // no existing commands "a\nb\n# CONSOLE-SETTINGS-START\n# CONSOLE-SETTINGS-END\nc\nd", // one existing command "a\nb\n# CONSOLE-SETTINGS-START\nas df\n# CONSOLE-SETTINGS-END\nc\nd", /...
{ 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
// Copyright 2019 CoreOS, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in...
.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
//! The Starling JavaScript runtime. //! // `error_chain!` can recurse deeply #![recursion_limit = "1024"] #![deny(missing_docs)] #![deny(missing_debug_implementations)] // Annoying warning emitted from the `error_chain!` macro. #![allow(unused_doc_comment)] #[macro_use] extern crate derive_error_chain; #[macro_use] ...
} 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
//! The Starling JavaScript runtime. //! // `error_chain!` can recurse deeply #![recursion_limit = "1024"] #![deny(missing_docs)] #![deny(missing_debug_implementations)] // Annoying warning emitted from the `error_chain!` macro. #![allow(unused_doc_comment)] #[macro_use] extern crate derive_error_chain; #[macro_use] ...
#[test] fn task_message_is_send() { assert_send::<TaskMessage>(); } }
{ assert_send::<StarlingMessage>(); }
identifier_body
lib.rs
//! The Starling JavaScript runtime. //! // `error_chain!` can recurse deeply #![recursion_limit = "1024"] #![deny(missing_docs)] #![deny(missing_debug_implementations)] // Annoying warning emitted from the `error_chain!` macro. #![allow(unused_doc_comment)] #[macro_use] extern crate derive_error_chain; #[macro_use] ...
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
//! The Starling JavaScript runtime. //! // `error_chain!` can recurse deeply #![recursion_limit = "1024"] #![deny(missing_docs)] #![deny(missing_debug_implementations)] // Annoying warning emitted from the `error_chain!` macro. #![allow(unused_doc_comment)] #[macro_use] extern crate derive_error_chain; #[macro_use] ...
<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
use core::hash::Hash; cfg_if::cfg_if! { if #[cfg(any( all(any(target_arch = "x86", target_arch = "x86_64"), target_feature = "aes", not(miri)), all(any(target_arch = "arm", target_arch = "aarch64"), any(target_feature = "aes", target_feature = "crypto"), not(miri), feature = "stdsimd") ))] { ...
#[cfg(all(feature = "runtime-rng", not(all(feature = "compile-time-rng", test))))] #[test] fn test_not_pi() { assert_ne!(PI, get_fixed_seeds()[0]); } #[cfg(all(feature = "compile-time-rng", any(not(feature = "runtime-rng"), test)))] #[test] fn test_not_pi_const() { assert_ne...
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
use core::hash::Hash; cfg_if::cfg_if! { if #[cfg(any( all(any(target_arch = "x86", target_arch = "x86_64"), target_feature = "aes", not(miri)), all(any(target_arch = "arm", target_arch = "aarch64"), any(target_feature = "aes", target_feature = "crypto"), not(miri), feature = "stdsimd") ))] { ...
() { assert_ne!(PI, get_fixed_seeds()[0]); } #[cfg(all(not(feature = "runtime-rng"), not(feature = "compile-time-rng")))] #[test] fn test_pi() { assert_eq!(PI, get_fixed_seeds()[0]); } #[test] fn test_with_seeds_const() { const _CONST_RANDOM_STATE: RandomState = Ran...
test_not_pi_const
identifier_name
random_state.rs
use core::hash::Hash; cfg_if::cfg_if! { if #[cfg(any( all(any(target_arch = "x86", target_arch = "x86_64"), target_feature = "aes", not(miri)), all(any(target_arch = "arm", target_arch = "aarch64"), any(target_feature = "aes", target_feature = "crypto"), not(miri), feature = "stdsimd") ))] { ...
} #[cfg(feature = "specialize")] impl BuildHasherExt for RandomState { #[inline] fn hash_as_u64<T: Hash + ?Sized>(&self, value: &T) -> u64 { let mut hasher = AHasherU64 { buffer: self.k0, pad: self.k1, }; value.hash(&mut hasher); hasher.finish() } ...
{ RandomState::hash_one(self, x) }
identifier_body
Pretty.ts
/** * Handles presentation of runner results to the user */ import Executor from '../executors/Executor'; import Suite from '../Suite'; import Test from '../Test'; import Reporter, { createEventHandler, ReporterProperties } from './Reporter'; import { CoverageMessage, DeprecationMessage } from '../executors/Executor...
firefox: 'Fx', opera: 'O', safari: 'Saf', 'internet explorer': 'IE', phantomjs: 'Phan' }; const ANSI_COLOR = { red: encode('[31m').toString('utf8'), green: encode('[32m').toString('utf8'), yellow: encode('[33m').toString('utf8'), reset: encode('[0m').toString('utf8') }; function pad(width: number): string { ...
random_line_split
Pretty.ts
/** * Handles presentation of runner results to the user */ import Executor from '../executors/Executor'; import Suite from '../Suite'; import Test from '../Test'; import Reporter, { createEventHandler, ReporterProperties } from './Reporter'; import { CoverageMessage, DeprecationMessage } from '../executors/Executor...
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
/** * Handles presentation of runner results to the user */ import Executor from '../executors/Executor'; import Suite from '../Suite'; import Test from '../Test'; import Reporter, { createEventHandler, ReporterProperties } from './Reporter'; import { CoverageMessage, DeprecationMessage } from '../executors/Executor...
) { 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
package docker import ( "bufio" "encoding/json" "fmt" "github.com/ekara-platform/engine/action" "io/ioutil" "net" "net/http" "os" "path/filepath" "strconv" "strings" "time" "golang.org/x/net/context" "docker.io/go-docker" "docker.io/go-docker/api/types" "docker.io/go-docker/api/types/container" "doc...
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
package docker import ( "bufio" "encoding/json" "fmt" "github.com/ekara-platform/engine/action" "io/ioutil" "net" "net/http" "os" "path/filepath" "strconv" "strings" "time" "golang.org/x/net/context" "docker.io/go-docker" "docker.io/go-docker/api/types" "docker.io/go-docker/api/types/container" "doc...
() ([]types.ImageSummary, error) { images, err := client.ImageList(context.Background(), types.ImageListOptions{}) if err != nil { return []types.ImageSummary{}, err } return images, nil } // ImagePull pulls the image corresponding to th given name // and wait for the download to be completed. // // The completi...
getImages
identifier_name
docker.go
package docker import ( "bufio" "encoding/json" "fmt" "github.com/ekara-platform/engine/action" "io/ioutil" "net" "net/http" "os" "path/filepath" "strconv" "strings" "time" "golang.org/x/net/context" "docker.io/go-docker" "docker.io/go-docker/api/types" "docker.io/go-docker/api/types/container" "doc...
return f, nil }
{ return nil, e }
conditional_block
docker.go
package docker import ( "bufio" "encoding/json" "fmt" "github.com/ekara-platform/engine/action" "io/ioutil" "net" "net/http" "os" "path/filepath" "strconv" "strings" "time" "golang.org/x/net/context" "docker.io/go-docker" "docker.io/go-docker/api/types" "docker.io/go-docker/api/types/container" "doc...
//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
// aaa var $content; var selectedProgram = null; var selectedCourse = null; var selectModule = null; var parentOrgHref; function loadQuizEditor(modal, data) { modal.find("#quizQuestions").html(data.body); var olQuiz = modal.find("ol.quiz"); if( olQuiz.length == 0 ) { olQuiz = $("<ol class='quiz'>...
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
// aaa var $content; var selectedProgram = null; var selectedCourse = null; var selectModule = null; var parentOrgHref; function loadQuizEditor(modal, data) { modal.find("#quizQuestions").html(data.body); var olQuiz = modal.find("ol.quiz"); if( olQuiz.length == 0 ) { olQuiz = $("<ol class='quiz'>...
function ensureOneEmptyRadio(ol) { // remove any li's containing empty labels, then add one empty one removeEmptyRadios(ol); addRadioToMulti(ol); } function addRadioToMulti(ol) { var question = ol.closest("li").attr("class"); log("addRadioToMulti", ol, question); var answerId = Math.floor(...
{ 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
// aaa var $content; var selectedProgram = null; var selectedCourse = null; var selectModule = null; var parentOrgHref; function loadQuizEditor(modal, data) { modal.find("#quizQuestions").html(data.body); var olQuiz = modal.find("ol.quiz"); if( olQuiz.length == 0 ) { olQuiz = $("<ol class='quiz'>...
(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
// aaa var $content; var selectedProgram = null; var selectedCourse = null; var selectModule = null; var parentOrgHref; function loadQuizEditor(modal, data) { modal.find("#quizQuestions").html(data.body); var olQuiz = modal.find("ol.quiz"); if( olQuiz.length == 0 ) { olQuiz = $("<ol class='quiz'>...
el.addClass(prefix + suffix); }
{ $.each(classes.split(" "), function(i, n) { if( n.startsWith(prefix)) { el.removeClass(n); } }); }
conditional_block
PaymentChannelsClient.js
import Engine from './Engine'; import Logger from '../util/Logger'; import AsyncStorage from '@react-native-community/async-storage'; // eslint-disable-next-line import * as Connext from 'connext'; import EthQuery from 'ethjs-query'; import TransactionsNotificationManager from './TransactionsNotificationManager'; impor...
(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
import Engine from './Engine'; import Logger from '../util/Logger'; import AsyncStorage from '@react-native-community/async-storage'; // eslint-disable-next-line import * as Connext from 'connext'; import EthQuery from 'ethjs-query'; import TransactionsNotificationManager from './TransactionsNotificationManager'; impor...
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
import Engine from './Engine'; import Logger from '../util/Logger'; import AsyncStorage from '@react-native-community/async-storage'; // eslint-disable-next-line import * as Connext from 'connext'; import EthQuery from 'ethjs-query'; import TransactionsNotificationManager from './TransactionsNotificationManager'; impor...
setState = data => { Object.keys(data).forEach(key => { this.state[key] = data[key]; }); }; async setConnext(provider) { const { type } = provider; const infuraProvider = createInfuraProvider({ network: type }); let hubUrl; const ethprovider = new EthQuery(infuraProvider); switch (type) { cas...
{ 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
import Engine from './Engine'; import Logger from '../util/Logger'; import AsyncStorage from '@react-native-community/async-storage'; // eslint-disable-next-line import * as Connext from 'connext'; import EthQuery from 'ethjs-query'; import TransactionsNotificationManager from './TransactionsNotificationManager'; impor...
if (toBN(amount).gt(toBN(maxAmount))) { throw new Error('insufficient_balance'); } try { const data = { meta: { purchaseId: 'payment' }, payments: [ { recipient: sendRecipient.toLowerCase(), amountWei: '0', amountToken: amount } ] }; await connext.bu...
{ amount = maxAmount; }
conditional_block
test_utils.py
# Copyright 2014 The Oppia 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 applicable ...
tasks = self.taskqueue_stub.get_filtered_tasks() self.taskqueue_stub.FlushQueue('default') if feconf.PLATFORM == 'gae': GenericTestBase = AppEngineTestBase else: raise Exception('Invalid platform: expected one of [\'gae\']')
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
# Copyright 2014 The Oppia 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 applicable ...
(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
# Copyright 2014 The Oppia 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 applicable ...
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
# Copyright 2014 The Oppia 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 applicable ...
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
package v1handlers import ( "bytes" "fmt" "github.com/ulule/deepcopier" "text/template" "visualization-api/pkg/database/models" "visualization-api/pkg/http_endpoint/common" "visualization-api/pkg/logging" ) // V1Visualizations implements part of handler interface type V1Visualizations struct{} // Visualizatio...
// 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
package v1handlers import ( "bytes" "fmt" "github.com/ulule/deepcopier" "text/template" "visualization-api/pkg/database/models" "visualization-api/pkg/http_endpoint/common" "visualization-api/pkg/logging" ) // V1Visualizations implements part of handler interface type V1Visualizations struct{} // Visualizatio...
(clients *common.ClientContainer, organizationID, visualizationSlug string) ( *common.VisualizationWithDashboards, error) { log.Logger.Debug("getting data from db matching provided string") visualizationDB, dashboardsDB, err := clients.DatabaseManager.GetVisualizationWithDashboardsBySlug( visualizationSlug, organ...
VisualizationDelete
identifier_name
visualizations.go
package v1handlers import ( "bytes" "fmt" "github.com/ulule/deepcopier" "text/template" "visualization-api/pkg/database/models" "visualization-api/pkg/http_endpoint/common" "visualization-api/pkg/logging" ) // V1Visualizations implements part of handler interface type V1Visualizations struct{} // Visualizatio...
// VisualizationsPost handler creates new visualizations func (h *V1Visualizations) VisualizationsPost(clients *common.ClientContainer, data common.VisualizationPOSTData, organizationID string) ( *common.VisualizationWithDashboards, error) { /* 1 - validate and render all golang templates provided by user, ...
{ // 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
package v1handlers import ( "bytes" "fmt" "github.com/ulule/deepcopier" "text/template" "visualization-api/pkg/database/models" "visualization-api/pkg/http_endpoint/common" "visualization-api/pkg/logging" ) // V1Visualizations implements part of handler interface type V1Visualizations struct{} // Visualizatio...
if dashboardDB.Slug == "" { // in case grafana slug is empty - just remove dashboard from db removedDashboardsFromGrafana = append(removedDashboardsFromGrafana, dashboardsDB[index]) } else { log.Logger.Debugf("Removing grafana dashboard '%s'", dashboardDB.Slug) err = clients.Grafana.DeleteDashboard(...
for index, dashboardDB := range dashboardsDB {
random_line_split
consumers.go
package lexer import ( "bytes" "github.com/amupitan/hero/lexer/fsm" ) // consumeDelimeter consumes a delimeter token func (l *Lexer) consumeDelimeter() Token { c := l.getCurr() t := Token{ Column: l.Column, Line: l.Line, Value: string(c), } switch c { case ',': t.Type = Comma case '(': t.Type =...
if !isBoolOperator(next) { switch op { case '+': t.Type = Plus // check if increment and consume if next == '+' { t.Type = Increment t.Value = "++" l.move() } case '-': t.Type = Minus // check if decrement and consume if next == '-' { t.Type = Decrement t.Value = "--" ...
{ 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() return l.getUnknownTok...
conditional_block
consumers.go
package lexer import ( "bytes" "github.com/amupitan/hero/lexer/fsm" ) // consumeDelimeter consumes a delimeter token func (l *Lexer) consumeDelimeter() Token { c := l.getCurr() t := Token{ Column: l.Column, Line: l.Line, Value: string(c), } switch c { case ',': t.Type = Comma case '(': t.Type =...
() 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
package lexer import ( "bytes" "github.com/amupitan/hero/lexer/fsm" ) // consumeDelimeter consumes a delimeter token func (l *Lexer) consumeDelimeter() Token { c := l.getCurr() t := Token{ Column: l.Column, Line: l.Line, Value: string(c), } switch c { case ',': t.Type = Comma case '(': t.Type =...
Type := String if l.getCurr() == '`' { nextState = &nextRawStringState Type = RawString } fsm := fsm.New(stringStates, stringStates[0], *nextState) buf, ok := fsm.Run(l.input[l.position:]) if !ok { return UnknownToken(string(l.getCurr()), l.Line, l.Column) } length := buf.Len() // remove starting deli...
func (l *Lexer) consumeString() Token { nextState := &nextStringState
random_line_split
consumers.go
package lexer import ( "bytes" "github.com/amupitan/hero/lexer/fsm" ) // consumeDelimeter consumes a delimeter token func (l *Lexer) consumeDelimeter() Token { c := l.getCurr() t := Token{ Column: l.Column, Line: l.Line, Value: string(c), } switch c { case ',': t.Type = Comma case '(': t.Type =...
func (l *Lexer) recognizeLiteral() Token { b := l.getCurr() if beginsIdentifier(b) { return l.consumeIdentifierOrKeyword() } if beginsNumber(b) { if t := l.consumeNumber(); t.Type != Unknown { return t } // if it began with a number literal, it is likely a dot return l.consumeDots() } if beginsS...
{ 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() } } switch char { case '<': if hasEquals ...
identifier_body
lib.rs
use std::fs::File; use std::io::prelude::*; use std::io::{Error}; use std::fs::metadata; use chrono::prelude::*; /* デバッグ用に出力を制御するためのもの */ const PRINT_DEBUG: bool = false; const MAX_BUFFER_SIZE: usize = 1024; // 1回の入力で受けつける最大のバイト const MAX_MATCH_LEN: usize = 258; // 最大でどれだけ一致するかのサイズ const MIN_MATCH_LEN: usize =...
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
use std::fs::File; use std::io::prelude::*; use std::io::{Error}; use std::fs::metadata; use chrono::prelude::*; /* デバッグ用に出力を制御するためのもの */ const PRINT_DEBUG: bool = false; const MAX_BUFFER_SIZE: usize = 1024; // 1回の入力で受けつける最大のバイト const MAX_MATCH_LEN: usize = 258; // 最大でどれだけ一致するかのサイズ const MIN_MATCH_LEN: usize =...
f.crc32, self.hms, self.ymd) } } /* ファイルの最終更新日時を取得してそれぞれをzipに必要な形式にして返す。 下のurlのヘッダ構造の部分から形式を知った。 https://hgotoh.jp/wiki/doku.php/documents/other/other-017 */ fn time_data(filename: &str) -> (u16, u16) { let times; if let Ok(metadata) = metadata(filename) { if let Ok(time) = metadata.modified()...
<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
use std::fs::File; use std::io::prelude::*; use std::io::{Error}; use std::fs::metadata; use chrono::prelude::*; /* デバッグ用に出力を制御するためのもの */ const PRINT_DEBUG: bool = false; const MAX_BUFFER_SIZE: usize = 1024; // 1回の入力で受けつける最大のバイト const MAX_MATCH_LEN: usize = 258; // 最大でどれだけ一致するかのサイズ const MIN_MATCH_LEN: usize =...
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
// Copyright 2012 The Freetype-Go Authors. All rights reserved. // Use of this source code is governed by your choice of either the // FreeType License or the GNU General Public License version 2 (or // any later version), both of which can be found in the LICENSE file. package freetype import ( "errors" "fmt" "lo...
index := 0 // Fixed 0x00010000, maxp format version. version, index := octets_to_u32(font.maxp, index), index+4 if version != 0x00010000 { msg := fmt.Sprintf("UNSUPPORT: font maxp version %v.", version) return errors.New(msg) } // uint16, the number of glyphs in the font font.glyph_num, index = int(octet...
{ msg := fmt.Sprintf("INVALID: bad maxp length %v", len(font.maxp)) return errors.New(msg) }
conditional_block
font.go
// Copyright 2012 The Freetype-Go Authors. All rights reserved. // Use of this source code is governed by your choice of either the // FreeType License or the GNU General Public License version 2 (or // any later version), both of which can be found in the LICENSE file. package freetype import ( "errors" "fmt" "lo...
// https://developer.apple.com/fonts/TTRefMan/RM06/Chap6maxp.html func (font *Font) parse_maxp() error { if len(font.maxp) != 32 { msg := fmt.Sprintf("INVALID: bad maxp length %v", len(font.maxp)) return errors.New(msg) } index := 0 // Fixed 0x00010000, maxp format version. version, index := octets_to_u32(...
{ 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
// Copyright 2012 The Freetype-Go Authors. All rights reserved. // Use of this source code is governed by your choice of either the // FreeType License or the GNU General Public License version 2 (or // any later version), both of which can be found in the LICENSE file. package freetype import ( "errors" "fmt" "lo...
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
// Copyright 2012 The Freetype-Go Authors. All rights reserved. // Use of this source code is governed by your choice of either the // FreeType License or the GNU General Public License version 2 (or // any later version), both of which can be found in the LICENSE file. package freetype import ( "errors" "fmt" "lo...
() 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
// Copyright 2018-2019 Peter Williams <peter@newton.cx> // Licensed under the MIT License. //! The main CLI driver logic. #![deny(missing_docs)] #![allow(proc_macro_derive_resolution_fallback)] extern crate app_dirs; extern crate chrono; #[macro_use] extern crate clap; // for arg_enum! #[macro_use] extern crate dies...
_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
// Copyright 2018-2019 Peter Williams <peter@newton.cx> // Licensed under the MIT License. //! The main CLI driver logic. #![deny(missing_docs)] #![allow(proc_macro_derive_resolution_fallback)] extern crate app_dirs; extern crate chrono; #[macro_use] extern crate clap; // for arg_enum! #[macro_use] extern crate dies...
(self, app: &mut Application) -> Result<i32> { app.maybe_sync_all_accounts()?; let doc = app.get_docs().process_one(self.spec)?; open_url(doc.open_url())?; Ok(0) } } /// List recently-used documents. #[derive(Debug, StructOpt)] pub struct DrorgRecentOptions { #[structopt( ...
cli
identifier_name
finality.rs
// Copyright 2015-2018 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any lat...
/// 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
// Copyright 2015-2018 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any lat...
() { let (signers, key_ids) = get_keys(3); let mut finality = RollingFinality::blank(signers); assert!(finality.push_hash(H256::random(), vec![key_ids[0], 0xAA]).is_err()); } #[test] fn finalize_multiple() { let (signers, key_ids) = get_keys(6); let mut finality = R...
rejects_unknown_signers
identifier_name
finality.rs
// Copyright 2015-2018 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any lat...
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
// Copyright 2015-2018 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any lat...
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
/* * @class Install.installerTools * @parent Install * * ###Installer Tools * * This provides several utility functions used by the site installer. * These functions may also be used after site installation, whenever a new * module is added or removed. * */ /** * @function getPaths * * Returns the s...
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
/* * @class Install.installerTools * @parent Install * * ###Installer Tools * * This provides several utility functions used by the site installer. * These functions may also be used after site installation, whenever a new * module is added or removed. * */ /** * @function getPaths * * Returns the s...
// 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
$(document).ready(function(){ /****************************** VARIABLES ******************************/ /* Element ==> jQuery */ // main navigation var $dashboard = $("#dashboard"); var $members = $("#members"); var $charts = $("#charts"); var $settings = $("#settings"); // notification system var $not...
(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
$(document).ready(function(){ /****************************** VARIABLES ******************************/ /* Element ==> jQuery */ // main navigation var $dashboard = $("#dashboard"); var $members = $("#members"); var $charts = $("#charts"); var $settings = $("#settings"); // notification system var $not...
} // retrive public profile notification if ( typeof(getPublic) !== "undefined") { if ( getPublic !== "true" ) { $publicProfile.switchButton({ checked: false }); } else { $publicProfile.switchButton({ checked: true }); } } // retrieve timezone $timezoneS...
{ $emailNotification.switchButton({ checked: true }); }
conditional_block
main.js
$(document).ready(function(){ /****************************** VARIABLES ******************************/ /* Element ==> jQuery */ // main navigation var $dashboard = $("#dashboard"); var $members = $("#members"); var $charts = $("#charts"); var $settings = $("#settings"); // notification system var $not...
// 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
$(document).ready(function(){ /****************************** VARIABLES ******************************/ /* Element ==> jQuery */ // main navigation var $dashboard = $("#dashboard"); var $members = $("#members"); var $charts = $("#charts"); var $settings = $("#settings"); // notification system var $not...
if ( searched.length > 0 ) { $("#list").removeClass("hide-div"); } else { $("#list").addClass("hide-div"); } }, // Add first result to search field // on [TAB] updateSearchField: function(li, e) { $searchMember.val(li); $list.addClass("hide-div"); }, // Notifies user of vali...
sel.appendChild(li); } // Hide list if no Choices
random_line_split
docker.go
package tiltfile import ( "fmt" "io/ioutil" "path/filepath" "github.com/docker/distribution/reference" "github.com/pkg/errors" "go.starlark.net/starlark" "github.com/windmilleng/tilt/internal/container" "github.com/windmilleng/tilt/internal/dockerfile" "github.com/windmilleng/tilt/internal/model" "github.c...
return result } func reposForPaths(paths []localPath) []model.LocalGitRepo { var result []model.LocalGitRepo repoSet := map[string]bool{} for _, path := range paths { repo := path.repo if repo == nil || repoSet[repo.basePath] { continue } repoSet[repo.basePath] = true result = append(result, model...
{ result = append(result, model.Mount{LocalPath: m.src.path, ContainerPath: m.mountPoint}) }
conditional_block
docker.go
package tiltfile import ( "fmt" "io/ioutil" "path/filepath" "github.com/docker/distribution/reference" "github.com/pkg/errors" "go.starlark.net/starlark" "github.com/windmilleng/tilt/internal/container" "github.com/windmilleng/tilt/internal/dockerfile" "github.com/windmilleng/tilt/internal/model" "github.c...
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
package tiltfile import ( "fmt" "io/ioutil" "path/filepath" "github.com/docker/distribution/reference" "github.com/pkg/errors" "go.starlark.net/starlark" "github.com/windmilleng/tilt/internal/container" "github.com/windmilleng/tilt/internal/dockerfile" "github.com/windmilleng/tilt/internal/model" "github.c...
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 { return true } func (b *fastBuild) Hash() (uin...
type fastBuild struct { s *tiltfileState img *dockerImage }
random_line_split
docker.go
package tiltfile import ( "fmt" "io/ioutil" "path/filepath" "github.com/docker/distribution/reference" "github.com/pkg/errors" "go.starlark.net/starlark" "github.com/windmilleng/tilt/internal/container" "github.com/windmilleng/tilt/internal/dockerfile" "github.com/windmilleng/tilt/internal/model" "github.c...
(image *dockerImage) []model.Dockerignore { var paths []string for _, m := range image.mounts { paths = append(paths, m.src.path) // NOTE(maia): this doesn't reflect the behavior of Docker, which only // looks in the build context for the .dockerignore file. Leaving it // for now, though, for fastbuild case...
dockerignoresForImage
identifier_name
TextRank.py
#from __future__ import division import os import sys from nltk.corpus import wordnet as wn from nltk.corpus import stopwords from nltk.tokenize import sent_tokenize from nltk.stem.wordnet import WordNetLemmatizer from nltk.stem.snowball import SnowballStemmer import nltk.tag import string import networkx as nx from co...
#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
#from __future__ import division import os import sys from nltk.corpus import wordnet as wn from nltk.corpus import stopwords from nltk.tokenize import sent_tokenize from nltk.stem.wordnet import WordNetLemmatizer from nltk.stem.snowball import SnowballStemmer import nltk.tag import string import networkx as nx from co...
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
#from __future__ import division import os import sys from nltk.corpus import wordnet as wn from nltk.corpus import stopwords from nltk.tokenize import sent_tokenize from nltk.stem.wordnet import WordNetLemmatizer from nltk.stem.snowball import SnowballStemmer import nltk.tag import string import networkx as nx from co...
''' 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
#from __future__ import division import os import sys from nltk.corpus import wordnet as wn from nltk.corpus import stopwords from nltk.tokenize import sent_tokenize from nltk.stem.wordnet import WordNetLemmatizer from nltk.stem.snowball import SnowballStemmer import nltk.tag import string import networkx as nx from co...
: 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
// Copyright (c) The Thanos Authors. // Licensed under the Apache License 2.0. package bos import ( "context" "fmt" "io" "math" "math/rand" "net/http" "os" "strings" "testing" "time" "github.com/baidubce/bce-sdk-go/bce" "github.com/baidubce/bce-sdk-go/services/bos" "github.com/baidubce/bce-sdk-go/servic...
c.Bucket = tmpBucketName bc, err := yaml.Marshal(c) if err != nil { return nil, nil, err } b, err := NewBucket(log.NewNopLogger(), bc, "thanos-e2e-test") if err != nil { return nil, nil, err } if _, err := b.client.PutBucket(b.name); err != nil { return nil, nil, err } t.Log("created temporary BOS ...
{ tmpBucketName = tmpBucketName[:31] }
conditional_block
bos.go
// Copyright (c) The Thanos Authors. // Licensed under the Apache License 2.0. package bos import ( "context" "fmt" "io" "math" "math/rand" "net/http" "os" "strings" "testing" "time" "github.com/baidubce/bce-sdk-go/bce" "github.com/baidubce/bce-sdk-go/services/bos" "github.com/baidubce/bce-sdk-go/servic...
(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
// Copyright (c) The Thanos Authors. // Licensed under the Apache License 2.0. package bos import ( "context" "fmt" "io" "math" "math/rand" "net/http" "os" "strings" "testing" "time" "github.com/baidubce/bce-sdk-go/bce" "github.com/baidubce/bce-sdk-go/services/bos" "github.com/baidubce/bce-sdk-go/servic...
_, 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
// Copyright (c) The Thanos Authors. // Licensed under the Apache License 2.0. package bos import ( "context" "fmt" "io" "math" "math/rand" "net/http" "os" "strings" "testing" "time" "github.com/baidubce/bce-sdk-go/bce" "github.com/baidubce/bce-sdk-go/services/bos" "github.com/baidubce/bce-sdk-go/servic...
// 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
from __future__ import print_function from collections import deque import os import queue import socket import sys import threading from time import sleep from urllib.error import URLError import urllib.parse as urlparse from apiclient.discovery import build from apiclient import errors import googleapiclient from h...
@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
from __future__ import print_function from collections import deque import os import queue import socket import sys import threading from time import sleep from urllib.error import URLError import urllib.parse as urlparse from apiclient.discovery import build from apiclient import errors import googleapiclient from ht...
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
from __future__ import print_function from collections import deque import os import queue import socket import sys import threading from time import sleep from urllib.error import URLError import urllib.parse as urlparse from apiclient.discovery import build from apiclient import errors import googleapiclient from h...
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
from __future__ import print_function from collections import deque import os import queue import socket import sys import threading from time import sleep from urllib.error import URLError import urllib.parse as urlparse from apiclient.discovery import build from apiclient import errors import googleapiclient from h...
(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