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
scanner.rs
use crate::file::{FileContent, FileSet}; use crate::metadata::Metadata; use std::cell::RefCell; use std::cmp; use std::collections::btree_map::Entry as BTreeEntry; use std::collections::hash_map::Entry as HashEntry; use std::collections::BTreeMap; use std::collections::BinaryHeap; use std::collections::HashMap; use std...
, HashEntry::Occupied(mut e) => { // This case may require a deferred deduping later, // if the new link belongs to an old fileset that has already been deduped. let mut t = e.get_mut().borrow_mut(); t.push(path); None ...
{ let fileset = Rc::new(RefCell::new(FileSet::new(path, metadata.nlink()))); e.insert(Rc::clone(&fileset)); // clone just bumps a refcount here Some(fileset) }
conditional_block
scanner.rs
use crate::file::{FileContent, FileSet}; use crate::metadata::Metadata; use std::cell::RefCell; use std::cmp; use std::collections::btree_map::Entry as BTreeEntry; use std::collections::hash_map::Entry as HashEntry; use std::collections::BTreeMap; use std::collections::BinaryHeap; use std::collections::HashMap; use std...
fn add(&mut self, path: Box<Path>, metadata: &fs::Metadata) -> io::Result<()> { self.scan_listener.file_scanned(&path, &self.stats); let ty = metadata.file_type(); if ty.is_dir() { // Inode is truncated to group scanning of roughly close inodes together, // But sti...
{ // Errors are ignored here, since it's super common to find permission denied and unreadable symlinks, // and it'd be annoying if that aborted the whole operation. // FIXME: store the errors somehow to report them in a controlled manner for entry in fs::read_dir(path)?.filter_map(|p| p...
identifier_body
scanner.rs
use crate::file::{FileContent, FileSet}; use crate::metadata::Metadata; use std::cell::RefCell; use std::cmp; use std::collections::btree_map::Entry as BTreeEntry; use std::collections::hash_map::Entry as HashEntry; use std::collections::BTreeMap; use std::collections::BinaryHeap; use std::collections::HashMap; use std...
(&mut self, fileset: RcFileSet, path: Box<Path>, metadata: &fs::Metadata) -> io::Result<()> { let mut deferred = false; match self.by_content.entry(FileContent::new(path, Metadata::new(metadata))) { BTreeEntry::Vacant(e) => { // Seems unique so far e.insert(ve...
dedupe_by_content
identifier_name
index.js
/* * * This sample demonstrates handling intents from an Alexa skill using the Alexa Skills Kit SDK (v2). * Please visit https://alexa.design/cookbook for additional examples on implementing slots, dialog management, * session persistence, api calls, and more. * */ const Alexa = require('ask-sdk-core'); const persi...
(handlerInput) { const speakOutput = 'Goodbye!'; return handlerInput.responseBuilder .speak(speakOutput) .getResponse(); } }; /* * * FallbackIntent triggers when a customer says something that doesn’t map to any intents in your skill * It must also be defined in the langua...
handle
identifier_name
index.js
/* * * This sample demonstrates handling intents from an Alexa skill using the Alexa Skills Kit SDK (v2). * Please visit https://alexa.design/cookbook for additional examples on implementing slots, dialog management, * session persistence, api calls, and more. * */ const Alexa = require('ask-sdk-core'); const persi...
, handle(handlerInput) { const speakOutput = 'Hello! Welcome to Caketime. What is your birthday?'; const repromptText = 'I was born Nov. 6th, 2014. When were you born?'; return handlerInput.responseBuilder .speak(speakOutput) .reprompt(repromptText) .get...
{ return Alexa.getRequestType(handlerInput.requestEnvelope) === 'LaunchRequest'; }
identifier_body
index.js
/* * * This sample demonstrates handling intents from an Alexa skill using the Alexa Skills Kit SDK (v2). * Please visit https://alexa.design/cookbook for additional examples on implementing slots, dialog management, * session persistence, api calls, and more. * */ const Alexa = require('ask-sdk-core'); const persi...
.speak(speakOutput) //.reprompt('add a reprompt if you want to keep the session open for the user to respond') .getResponse(); } }; /** * Generic error handling to capture any syntax or routing errors. If you receive an error * stating the request handler chain is not found, yo...
const intentName = Alexa.getIntentName(handlerInput.requestEnvelope); const speakOutput = `You just triggered ${intentName}`; return handlerInput.responseBuilder
random_line_split
index.js
/* * * This sample demonstrates handling intents from an Alexa skill using the Alexa Skills Kit SDK (v2). * Please visit https://alexa.design/cookbook for additional examples on implementing slots, dialog management, * session persistence, api calls, and more. * */ const Alexa = require('ask-sdk-core'); const persi...
return handlerInput.responseBuilder .speak(speakOutput) .getResponse(); } }; const CaptureBirthdayIntentHandler = { canHandle(handlerInput) { return Alexa.getRequestType(handlerInput.requestEnvelope) === 'IntentRequest' && Alexa.getIntentName(handlerInput.r...
{ const diffDays = Math.round(Math.abs((currentDate.getTime() - nextBirthdayDate.getTime()) / oneDay)); speakOutput = `Welcome back. It looks like there are ${diffDays} days until your ${nextBirthdayDate.getFullYear() - year}th birthday.` }
conditional_block
Trainer.py
import csv import time import unicodedata import tensorflow as tf from tensorflow import keras import ErrorClassifier from TokenHelper import tokenize, tokenize_pure_words, find_all_delta_from_tokens from NeuralNetworkHelper import PATH_REPLACE_CHECKPOINT, PATH_ARRANGE_CHECKPOINT, FILE_NAME, TESTING_RANGE from Neural...
(): # create the dataset samples = 0 max_length = 0 if ENABLE_PROCESS_ARRANGE_DATA: # saves the data to a file assert len(train_arrange_x) == len(train_arrange_y) max_length = len(max(train_arrange_x, key=len)) samples = len(train_arrange_x) with open(PATH_ARRANGE...
train_arrange_nn
identifier_name
Trainer.py
import csv import time import unicodedata import tensorflow as tf from tensorflow import keras import ErrorClassifier from TokenHelper import tokenize, tokenize_pure_words, find_all_delta_from_tokens from NeuralNetworkHelper import PATH_REPLACE_CHECKPOINT, PATH_ARRANGE_CHECKPOINT, FILE_NAME, TESTING_RANGE from Neural...
with open(PATH_REPLACE_DATA) as file_replace: max_start, max_end, samples = list(map(int, file_replace.readline().strip().split())) dataset = tf.data.Dataset.from_generator(replace_nn_generator, ({'start': tf.int32, 'end': tf.int32, 'delta': tf.int32}, tf.f...
with open(PATH_REPLACE_DATA) as file_replace: file_replace.readline() for replace_line in file_replace: start, end, delta1, delta2 = replace_line.rstrip().split('\t') start = list(map(int, start.split())) end = list(map(int, end.split())) ...
identifier_body
Trainer.py
import csv import time import unicodedata import tensorflow as tf from tensorflow import keras import ErrorClassifier from TokenHelper import tokenize, tokenize_pure_words, find_all_delta_from_tokens from NeuralNetworkHelper import PATH_REPLACE_CHECKPOINT, PATH_ARRANGE_CHECKPOINT, FILE_NAME, TESTING_RANGE from Neural...
line = line.strip() line = unicodedata.normalize('NFKD', line) p1, p2 = line.split('\t') t1, t2 = line_tag.split('\t') error_type = ErrorClassifier.classify_error_labeled(p1, p2) train(p1, p2, error_type, t1, t2) ...
continue
conditional_block
Trainer.py
import csv import time import unicodedata import tensorflow as tf from tensorflow import keras import ErrorClassifier from TokenHelper import tokenize, tokenize_pure_words, find_all_delta_from_tokens from NeuralNetworkHelper import PATH_REPLACE_CHECKPOINT, PATH_ARRANGE_CHECKPOINT, FILE_NAME, TESTING_RANGE from Neural...
def save_word_frequencies(): with open('learned_frequencies.csv', 'w', newline='') as fout: csv_writer = csv.writer(fout) for word, freq in word_freqs.items(): # don't bother with the little words if freq > 1: csv_writer.writerow([word, freq]) test1 = 0 te...
word_freqs[word] = 1
random_line_split
__init__.py
from bs4 import BeautifulSoup from unicodedata import normalize import re import requests from requests.exceptions import RequestException from time import sleep from pathlib import Path import pandas as pd def requests_get(*args, **kwargs): """ Retries if a RequestException is raised (could be a connection e...
def print_binary_and_numeric_options(search_options): print("\n") for option_title, option_value in search_options['Filters'].items(): print("\t" + option_title + ":") print("\t-----") for option, option_api_value in option_value.items(): print("...
print("\t" + option_title + ":") print("\t-----") print("\t\t URL key:", "'" + option_value['url_key'] + "'") print("\t\t URL key options:") for option, option_api_value in option_value['value'].items(): print("\t\t\t* " + option + ":", "'" + option_api_va...
conditional_block
__init__.py
from bs4 import BeautifulSoup from unicodedata import normalize import re import requests from requests.exceptions import RequestException from time import sleep from pathlib import Path import pandas as pd def requests_get(*args, **kwargs): """ Retries if a RequestException is raised (could be a connection e...
show_search_filters()
print_binary_and_numeric_options(eval(selection))
random_line_split
__init__.py
from bs4 import BeautifulSoup from unicodedata import normalize import re import requests from requests.exceptions import RequestException from time import sleep from pathlib import Path import pandas as pd def requests_get(*args, **kwargs): """ Retries if a RequestException is raised (could be a connection e...
def get_pages(self, **kwargs): """ :param kwargs: max_num_pages: maximum number of pages to be processed. If left empty, it is set to its maximum number 100. :return: a generator of HTML parsed result pages. """ max_num_pages = kwargs.get('max_num_pages') or 100...
""" Retrieve search parameters from the html page of a search on Seloger.com :param search_url: The page url is passed as an input (True) or a parsed page (False). :param args: A BeautifulSoup parsed page. :param kwargs: write_to: a string with the path and name of a file to ...
identifier_body
__init__.py
from bs4 import BeautifulSoup from unicodedata import normalize import re import requests from requests.exceptions import RequestException from time import sleep from pathlib import Path import pandas as pd def requests_get(*args, **kwargs): """ Retries if a RequestException is raised (could be a connection e...
(object): """ Base class for all Seloger wrapper Parameters ---------- class_filters : dict Main search options ex. {'transaction_type':['achat'], 'bien': ['appartement', 'maison'], 'naturebien': ['ancien', 'neuf']} type_of_search: str Can be either 'base', for ads of pr...
SelogerBase
identifier_name
PositionAPI.py
# -*- coding: utf-8 -*- # @Time : 2019/2/22 16:45 # @Author : ZouJunLin """爬取持仓共用的API""" import re import csv,os,codecs,datetime import pandas as pd import xlwt import threading import json import zipfile def ResultToDatabase(info,result,sql): info.mysql.ExecmanysNonQuery(sql,result) def GetDCEPosition(info...
ksheet = writer.sheets['Sheet1'] worksheet.set_column('A:J', 15) # Add a header format. header_format = workbook.add_format({ 'bold': True, 'text_wrap': True, 'valign': 'vcenter', 'border': 1 }) header_format.set_align('center') header_format.set_align('vcenter')...
= writer.book wor
conditional_block
PositionAPI.py
# -*- coding: utf-8 -*- # @Time : 2019/2/22 16:45 # @Author : ZouJunLin """爬取持仓共用的API""" import re import csv,os,codecs,datetime import pandas as pd import xlwt import threading import json import zipfile def ResultToDatabase(info,result,sql): info.mysql.ExecmanysNonQuery(sql,result) def GetDCEPosition(info...
if str(i[0]).strip()=="合计" or str(i[0]).strip()=="名次": continue temp= re.findall("[A-Za-z0-9]+",str(i[0]).strip()) if len(temp)==4: TradeInstrument=temp[0] continue if len(temp)==1 and temp[0] in top20list: TradingDay=startdate.strftime("%Y...
random_line_split
PositionAPI.py
# -*- coding: utf-8 -*- # @Time : 2019/2/22 16:45 # @Author : ZouJunLin """爬取持仓共用的API""" import re import csv,os,codecs,datetime import pandas as pd import xlwt import threading import json import zipfile def ResultToDatabase(info,result,sql): info.mysql.ExecmanysNonQuery(sql,result) def GetDCEPosition(info...
5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.84 Safari/537.36', 'Accept-Language': 'zh-CN,zh;q=0.9', 'Cookie': 'JSESSIONID=1311697EA3395C8127FD0BB9D51B1742; WMONID=j1TJsMZrARA; Hm_lvt_a50228174de2a93aee654389576b60fb=1550114491,1550801897,1550826990,1550890979; Hm...
ent': 'Mozilla/
identifier_name
PositionAPI.py
# -*- coding: utf-8 -*- # @Time : 2019/2/22 16:45 # @Author : ZouJunLin """爬取持仓共用的API""" import re import csv,os,codecs,datetime import pandas as pd import xlwt import threading import json import zipfile def ResultToDatabase(info,result,sql): info.mysql.ExecmanysNonQuery(sql,result) def GetDCEPosition(info...
identifier_body
ch8.go
package main import ( "bufio" "flag" "fmt" "log" "net" "time" ) func main() { listener, err := net.Listen("tcp", "localhost: 8000") if err != nil { log.Fatal(err) } go broadcaster() for { conn, err := listener.Accept() if err != nil { log.Print(err) continue } go handleConn(conn) } } type...
// "log" // "gopl.io/ch5/links" // ) // // tokens a counting semaphore used to enforce a limit of 20 concurrent requests // var tokens = make(chan struct{}, 20) // func crawl(url string) []string { // fmt.Println(url) // tokens <- struct{}{} // list, err := links.Extract(url) // <-tokens // release the token /...
// } // import ( // "fmt"
random_line_split
ch8.go
package main import ( "bufio" "flag" "fmt" "log" "net" "time" ) func main() { listener, err := net.Listen("tcp", "localhost: 8000") if err != nil { log.Fatal(err) } go broadcaster() for { conn, err := listener.Accept() if err != nil { log.Print(err) continue } go handleConn(conn) } } type...
func handleConn(conn net.Conn) { ch := make(chan string) go clientWriter(conn, ch) who := conn.RemoteAddr().String() ch <- "You are " + who messages <- who + " has arrived" entering <- ch input := bufio.NewScanner(conn) for input.Scan() { messages <- who + ": " + input.Text() } // NOTE: ignoreing potent...
{ clients := make(map[client]bool) // all connected clients for { select { case msg := <-messages: // Broadcase incoming message to all // clients' outgoing message channels. for cli := range clients { cli <- msg } case cli := <-entering: clients[cli] = true case cli := <-leaving: delete...
identifier_body
ch8.go
package main import ( "bufio" "flag" "fmt" "log" "net" "time" ) func
() { listener, err := net.Listen("tcp", "localhost: 8000") if err != nil { log.Fatal(err) } go broadcaster() for { conn, err := listener.Accept() if err != nil { log.Print(err) continue } go handleConn(conn) } } type client chan<- string // an outgoing message channel var ( entering = make(chan...
main
identifier_name
ch8.go
package main import ( "bufio" "flag" "fmt" "log" "net" "time" ) func main() { listener, err := net.Listen("tcp", "localhost: 8000") if err != nil { log.Fatal(err) } go broadcaster() for { conn, err := listener.Accept() if err != nil { log.Print(err) continue } go handleConn(conn) } } type...
// NOTE: ignoreing potentian errors from input.Err() leaving <- ch messages <- who + " has left" conn.Close() } func clientWriter(conn net.Connj, ch <-chan string) { for msg := range ch { fmt.Fprintln(conn, msg) // NOTE: ignoring network errors } } // var done = make(chan struct{}) // func cancelled() bool ...
{ messages <- who + ": " + input.Text() }
conditional_block
server.rs
extern crate hashbrown; extern crate rand; use crate::command; use self::ServerError::*; use command::{Command, CommandHandler}; use hashbrown::HashMap; use rand::Rng; use std::convert::TryFrom; use std::fmt; use std::io; use std::io::prelude::*; use std::net::TcpListener; use std::net::TcpStream; use std::sync::m...
(&self) -> Vec<usize> { use self::FinishedStatus::*; use self::HandlerAsync::*; self.handlers .iter() .filter(|(id, handler)| { if let Finished(status) = handler.check_status() { match status { TimedOut => { ...
check_handlers
identifier_name
server.rs
extern crate hashbrown; extern crate rand; use crate::command; use self::ServerError::*; use command::{Command, CommandHandler}; use hashbrown::HashMap; use rand::Rng; use std::convert::TryFrom; use std::fmt; use std::io; use std::io::prelude::*; use std::net::TcpListener; use std::net::TcpStream; use std::sync::m...
msg_sender, msg_recver, handlers, cmd_handler, }) } #[allow(unused)] pub fn from_cfg() -> Result<Server, &'static str> { unimplemented!(); } pub fn cmd<C: Command + 'static>(mut self, name: &'static str, command: C) -> Self { ...
Ok(Server { size,
random_line_split
main.rs
#![allow(unused_imports)] mod texture; mod model; mod camera; // means -> mod camera { // contents of camera.rs } mod light; use winit::{ event::*, event_loop::{ControlFlow, EventLoop}, window::{Window, WindowBuilder}, dpi::PhysicalSize, }; use futures::executor::block_on; use wgpu::util::DeviceExt; ...
( device: &wgpu::Device, layout: &wgpu::PipelineLayout, color_format: wgpu::TextureFormat, depth_format: Option<wgpu::TextureFormat>, vertex_descs: &[wgpu::VertexBufferDescriptor], vs_src: wgpu::ShaderModuleSource, fs_src: wgpu::ShaderModuleSource, ) -> wgpu::RenderPipeline { // Create S...
create_render_pipeline
identifier_name
main.rs
#![allow(unused_imports)] mod texture; mod model; mod camera; // means -> mod camera { // contents of camera.rs } mod light; use winit::{ event::*, event_loop::{ControlFlow, EventLoop}, window::{Window, WindowBuilder}, dpi::PhysicalSize, }; use futures::executor::block_on; use wgpu::util::DeviceExt; ...
WindowEvent::CloseRequested => *control_flow = ControlFlow::Exit, _ => {} } } fn handle_redraw_requested(state: &mut State, control_flow: &mut ControlFlow, dt: std::time::Duration) { state.update(dt); match state.render() { Err(wgpu::SwapChainError::Lost) => state.resize(state.size)...
state.resize(physical_size) }, WindowEvent::ScaleFactorChanged {new_inner_size, ../*scale_factor*/ } => { state.resize(*new_inner_size) },
random_line_split
main.rs
#![allow(unused_imports)] mod texture; mod model; mod camera; // means -> mod camera { // contents of camera.rs } mod light; use winit::{ event::*, event_loop::{ControlFlow, EventLoop}, window::{Window, WindowBuilder}, dpi::PhysicalSize, }; use futures::executor::block_on; use wgpu::util::DeviceExt; ...
DeviceEvent::Button { button: 1, // Left Mouse Button state, } => { self.mouse_pressed = *state == ElementState::Pressed; true } DeviceEvent::MouseMotion { delta } => { if self.mouse_pressed ...
{ self.camera_controller.process_scroll(delta); true }
conditional_block
assethook.py
"""Assethook: A flask application to listen for webhook calls to send computer names and asset tags to the Jamf Pro Server. """ import logging from logging.handlers import RotatingFileHandler import os import sqlite3 import time import requests from flask import (Flask, flash, g, redirect, render_template, ...
if r.status_code == 200: device_type_xml = 'mobile_device' device_type_url = 'mobiledevices' device_type = 'MobileDevice' if device_type is None: url = settings_dict['jsshost'] + ':' + settings_dict['jss_port'] + settings_dict['jss_path'] + \ '/JSSRes...
'/JSSResource/mobiledevices/serialnumber/' + serial_number r = requests.get(url, auth=(settings_dict['jss_username'], settings_dict['jss_password']))
random_line_split
assethook.py
"""Assethook: A flask application to listen for webhook calls to send computer names and asset tags to the Jamf Pro Server. """ import logging from logging.handlers import RotatingFileHandler import os import sqlite3 import time import requests from flask import (Flask, flash, g, redirect, render_template, ...
(): """Initializes the database.""" init_db() print('Initialized the database.') def load_settings(): '''Loads settings from the database, if the table is empty, it will be initalized ''' db = get_db() try: cur = db.execute('select setting_name, setting_value from settings') ...
initdb_command
identifier_name
assethook.py
"""Assethook: A flask application to listen for webhook calls to send computer names and asset tags to the Jamf Pro Server. """ import logging from logging.handlers import RotatingFileHandler import os import sqlite3 import time import requests from flask import (Flask, flash, g, redirect, render_template, ...
@app.cli.command('initdb') # if you want to do it from the command line def initdb_command(): """Initializes the database.""" init_db() print('Initialized the database.') def load_settings(): '''Loads settings from the database, if the table is empty, it will be initalized ''' db = get...
"""Initialized the db file""" db = get_db() with app.open_resource('schema.sql', mode='r') as f: db.cursor().executescript(f.read()) db.commit()
identifier_body
assethook.py
"""Assethook: A flask application to listen for webhook calls to send computer names and asset tags to the Jamf Pro Server. """ import logging from logging.handlers import RotatingFileHandler import os import sqlite3 import time import requests from flask import (Flask, flash, g, redirect, render_template, ...
else: return 'Invalid Webhook format', 403 submit_to_jss(serial_number=device['event'][u'serialNumber'], device_type=device_type) return '', 200 @app.route('/upload_file', methods=['GET', 'POST']) def upload_file(): '''Upload a csv file and import into the database''' if not session.get(...
device_type = 'MobileDevice'
conditional_block
lib.rs
#![recursion_limit = "256"] extern crate proc_macro; use proc_macro::TokenStream; use proc_macro2; use quote::quote; use regex::Regex; use std::collections::HashSet; use syn::{parse_macro_input, DeriveInput}; #[derive(Debug, PartialEq)] enum RouteToRegexError { MissingLeadingForwardSlash, NonAsciiChars, InvalidIde...
st_route_to_regex_characters_after_wildcard() { let regex = route_to_regex("/p/:project_id/exams/:exam*ID/submissions_expired"); assert_eq!( regex, Err(RouteToRegexError::CharactersAfterWildcard) ); } #[test] fn test_route_to_regex_invalid_ending() { let regex = route_to_regex("/p/:project_id/exams/:exam_id/su...
route_to_regex("/p/:project_id/exams/:_exam_id/submissions_expired"); assert_eq!( regex, Err(RouteToRegexError::InvalidIdentifier("_exam_id".to_string())) ); } #[test] fn te
identifier_body
lib.rs
#![recursion_limit = "256"] extern crate proc_macro; use proc_macro::TokenStream; use proc_macro2; use quote::quote; use regex::Regex; use std::collections::HashSet; use syn::{parse_macro_input, DeriveInput}; #[derive(Debug, PartialEq)] enum RouteToRegexError { MissingLeadingForwardSlash, NonAsciiChars, InvalidIde...
} query_string }); Ok(#struct_constructor) } } }; let impl_wrapper = syn::Ident::new( &format!("_IMPL_APPROUTE_FOR_{}", name.to_string()), proc_macro2::Span::call_site(), ); let out = quote! { const #impl_wrapper: () = { extern crate app_route; #app_route_impl }; }; out.i...
if query_string.starts_with('?') { query_string = &query_string[1..];
random_line_split
lib.rs
#![recursion_limit = "256"] extern crate proc_macro; use proc_macro::TokenStream; use proc_macro2; use quote::quote; use regex::Regex; use std::collections::HashSet; use syn::{parse_macro_input, DeriveInput}; #[derive(Debug, PartialEq)] enum RouteToRegexError { MissingLeadingForwardSlash, NonAsciiChars, InvalidIde...
ta) -> Vec<syn::Field> { match data { syn::Data::Struct(data_struct) => match data_struct.fields { syn::Fields::Named(ref named_fields) => named_fields.named.iter().cloned().collect(), _ => panic!("Struct fields must be named"), }, _ => panic!("AppRoute derive is only supported for structs"), } } fn fiel...
ds(data: &syn::Da
identifier_name
lib.rs
#![recursion_limit = "256"] extern crate proc_macro; use proc_macro::TokenStream; use proc_macro2; use quote::quote; use regex::Regex; use std::collections::HashSet; use syn::{parse_macro_input, DeriveInput}; #[derive(Debug, PartialEq)] enum RouteToRegexError { MissingLeadingForwardSlash, NonAsciiChars, InvalidIde...
regex += &format!("(?P<{}>[^/]+)/", name); format_str += &format!("{}}}/", name); parse_state = ParseState::Static; } else if byte == '*' { // Found a wildcard - add the var name to the regex // Validate 'name' as a Rust identifier if !ident_regex.is_match(&name) { return Err(...
{ return Err(RouteToRegexError::InvalidIdentifier(name)); }
conditional_block
dockeranchor.js
'use strict'; const Docker = require('node-docker-api').Docker const fs = require('fs'); const compiler = require('./models/Compiler') const execenv = require('./models/ExecEnv') const tar = require('tar') const path = require('path') const { promisify } = require('util') const unlinkAsync = promisify(fs.unlink) const...
ime) { return new Promise((resolve) => { setTimeout(resolve, time); }) } const splitEx = /(["'].*?["']|[^"'\s]+)/g function splitCommands(str) { return str.match(splitEx).map( (el) => el.replace(/^["']|["']$/g, '') ); } async function pingDocker() { try{ const info = await docker.info(); return[true, ...
yncWait(t
identifier_name
dockeranchor.js
'use strict'; const Docker = require('node-docker-api').Docker const fs = require('fs'); const compiler = require('./models/Compiler') const execenv = require('./models/ExecEnv') const tar = require('tar') const path = require('path') const { promisify } = require('util') const unlinkAsync = promisify(fs.unlink) const...
const infilename = fileBasename;//infile.replace(pathToFile, '') let stdininfilename = ''; if(stdinfile)stdininfilename = path.basename(stdinfile); console.log(`Let's execute! ${fileBasename}`); if((await pingDocker())[0] == false){ reject([1, 'Cannot reach docker machine']); return; } ...
const fileBasename = path.basename(infile); const fileDirname = path.dirname(infile); const tarfile = `${fileDirname}/${crypto.randomBytes(10).toString('hex')}.tar`;
random_line_split
dockeranchor.js
'use strict'; const Docker = require('node-docker-api').Docker const fs = require('fs'); const compiler = require('./models/Compiler') const execenv = require('./models/ExecEnv') const tar = require('tar') const path = require('path') const { promisify } = require('util') const unlinkAsync = promisify(fs.unlink) const...
async function nukeContainers(quit) { const shouldQuit = quit !== false; const conts = await docker.container.list({ all: true }); console.log(`NUKING DOCKER!, containers=${conts.length}`); const promises = conts.map(cont => { const cname = cont.data.Names[0] return cont.start() //.then(() => cont.kill()) ...
return new Promise(async (resolve, reject) => { const _execInstance = await execenv.findOne({ name: exname }); const opts = optz || {}; if (!_execInstance) { reject([1, 'Invalid ExecEnv']); return; } let _container try { const fileBasename = path.basename(infile); const fileDirname = pat...
identifier_body
dockeranchor.js
'use strict'; const Docker = require('node-docker-api').Docker const fs = require('fs'); const compiler = require('./models/Compiler') const execenv = require('./models/ExecEnv') const tar = require('tar') const path = require('path') const { promisify } = require('util') const unlinkAsync = promisify(fs.unlink) const...
var _unpromStream = await _container.fs.put(tarfile, { path: '.' }) await promisifyStreamNoSpam(_unpromStream); await unlinkAsync(tarfile); await _container.start(); //await _container.wait(); await asyncWait(_execInstance.time); const inspection = await _container.status(); if (inspect...
/*console.log("Redirecting input."); var [_stdinstream,] = await _container.attach({ stream: true, stderr: true }); var _fstrm = fs.createReadStream(stdinfile); _fstrm.pipe(_stdinstream) //readable->writable await promisifyStream(_fstrm);*/ await tar.r({ file: tarfile, cwd: fileDirnam...
conditional_block
Employees.component.ts
import {Component, ViewChild} from "@angular/core"; import {FormGroup, FormBuilder} from "@angular/forms"; import {FTable} from "qCommon/app/directives/footable.directive"; import {Router} from "@angular/router"; import {TOAST_TYPE} from "qCommon/app/constants/Qount.constants"; import {ToastService} from "qCommon/app/...
getEmployeesTableData(inputData) { let tempData = _.cloneDeep(inputData); let newTableData: Array<any> = []; let tempJsonArray: any; for( var i in tempData) { tempJsonArray = {}; tempJsonArray["FirstName"] = tempData[i].first_name; tempJsonArray["LastName"] = tempData[i].last_nam...
{ this.titleService.setPageTitle("Employees"); this.row = {}; this.showFlyout = !this.showFlyout; }
identifier_body
Employees.component.ts
import {Component, ViewChild} from "@angular/core"; import {FormGroup, FormBuilder} from "@angular/forms"; import {FTable} from "qCommon/app/directives/footable.directive"; import {Router} from "@angular/router"; import {TOAST_TYPE} from "qCommon/app/constants/Qount.constants"; import {ToastService} from "qCommon/app/...
() { this.active = false; setTimeout(()=> this.active=true, 0); } handleError(error) { this.loadingService.triggerLoadingEvent(false); this._toastService.pop(TOAST_TYPE.error, "Failed To Perform Operation"); } hideFlyout(){ this.titleService.setPageTitle("Employees"); this.row = {}; ...
newCustomer
identifier_name
Employees.component.ts
import {Component, ViewChild} from "@angular/core"; import {FormGroup, FormBuilder} from "@angular/forms"; import {FTable} from "qCommon/app/directives/footable.directive"; import {Router} from "@angular/router"; import {TOAST_TYPE} from "qCommon/app/constants/Qount.constants"; import {ToastService} from "qCommon/app/...
this.routeSubscribe = switchBoard.onClickPrev.subscribe(title => { if(this.showFlyout){ this.hideFlyout(); }else { this.toolsRedirect(); } }); } toolsRedirect(){ let link = ['tools']; this._router.navigate(link); } ngOnDestroy(){ this.routeSubscribe.unsu...
{ this._toastService.pop(TOAST_TYPE.error, "Please Add Company First"); }
conditional_block
Employees.component.ts
import {Component, ViewChild} from "@angular/core"; import {FormGroup, FormBuilder} from "@angular/forms"; import {FTable} from "qCommon/app/directives/footable.directive"; import {Router} from "@angular/router"; import {TOAST_TYPE} from "qCommon/app/constants/Qount.constants"; import {ToastService} from "qCommon/app/s...
let link = ['tools']; this._router.navigate(link); } ngOnDestroy(){ this.routeSubscribe.unsubscribe(); this.confirmSubscription.unsubscribe(); } buildTableData(employees) { this.employees = employees; this.hasEmployeesList = false; this.tableOptions.search = true; this.tableOp...
}); } toolsRedirect(){
random_line_split
gestalt.go
// Copyright 2012-2015 Joubin Houshyar. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Gestalt provides basic property file utility. // // Property keys are typed. // // The key suffixes `[]` and `[:]` specify []string and map[string]stri...
urns nil/zero-value if no such key or not a map, or if key type is not map func (p Properties) GetMap(key string) map[string]string { if isMapKey(key) { if v := p[key]; v == nil { return nil } return p[key].(map[string]string) } return nil } // returns prop value or default values if nil func (p Properties...
= p.GetArray(key); v == nil { v = defval } return } // ret
identifier_body
gestalt.go
// Copyright 2012-2015 Joubin Houshyar. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Gestalt provides basic property file utility. // // Property keys are typed. // // The key suffixes `[]` and `[:]` specify []string and map[string]stri...
} // Return a clone of the argument Properties object func (p Properties) Clone() (clone Properties) { for k, v := range p { clone[k] = v } return } // Copy all entries from specified Properties to the receiver // Note this will overwrite existing matching values if overwrite is true, // otherwise if overwrite ...
return loadBuffer(spec)
random_line_split
gestalt.go
// Copyright 2012-2015 Joubin Houshyar. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Gestalt provides basic property file utility. // // Property keys are typed. // // The key suffixes `[]` and `[:]` specify []string and map[string]stri...
n p[key].([]string) } return nil } // returns prop value or default values if nil func (p Properties) GetArrayOrDefault(key string, defval []string) (v []string) { if v = p.GetArray(key); v == nil { v = defval } return } // returns nil/zero-value if no such key or not a map, or if key type is not map func (p P...
urn nil } retur
conditional_block
gestalt.go
// Copyright 2012-2015 Joubin Houshyar. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Gestalt provides basic property file utility. // // Property keys are typed. // // The key suffixes `[]` and `[:]` specify []string and map[string]stri...
t.Print(p) } // ---------------------------------------------------------------------- // internal ops // REVU: this simplistic approach to parsing places too many constraints: // 1 - continuations for maps/arrays are redundant given the ',' element delims // 2 - can't use ':' or '#' in k/v - these are fairly useful/c...
{ fm
identifier_name
gran_model.py
# Copyright (c) 2021 PaddlePaddle 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 app...
from __future__ import absolute_import from __future__ import division from __future__ import print_function import logging import paddle.fluid as fluid from model.graph_encoder import encoder, pre_process_layer logging.basicConfig( format='%(asctime)s - %(levelname)s - %(name)s - %(message)s', datefmt='%m/%...
# distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """GRAN model."""
random_line_split
gran_model.py
# Copyright (c) 2021 PaddlePaddle 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 app...
def _build_model(self, input_ids, input_mask, edge_labels): # get node embeddings of input tokens emb_out = fluid.layers.embedding( input=input_ids, size=[self._voc_size, self._emb_size], dtype=self._dtype, param_attr=fluid.ParamAttr( ...
self._n_layer = config['num_hidden_layers'] self._n_head = config['num_attention_heads'] self._emb_size = config['hidden_size'] self._intermediate_size = config['intermediate_size'] self._hidden_act = config['hidden_act'] self._prepostprocess_dropout = config['hidden_dropout_prob...
identifier_body
gran_model.py
# Copyright (c) 2021 PaddlePaddle 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 app...
(self, input_ids, input_mask, edge_labels, config, weight_sharing=True, use_fp16=False): self._n_layer = config['num_hidden_layers'] self._n_head = config['num_attention_heads'] self._emb_size ...
__init__
identifier_name
gran_model.py
# Copyright (c) 2021 PaddlePaddle 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 app...
special_indicator = fluid.layers.fill_constant_batch_size_like( input=mask_label, shape=[-1, 2], dtype='int64', value=-1) relation_indicator = fluid.layers.fill_constant_batch_size_like( input=mask_label, shape=[-1, self._n_relation], dtype='int64', ...
fc_out = fluid.layers.fc(input=mask_trans_feat, size=self._voc_size, param_attr=fluid.ParamAttr( name="mask_lm_out_fc.w_0", initializer=self._param_initializer), ...
conditional_block
generate_primers.go
package main import ( "fmt" "os" "strings" "bufio" "strconv" "sort" "flag" ) type Sequence struct { name string seq string isForward bool val int } // Generates the primers func generatePrimers(seqFile, fastaFile string, ignore int) (map[string]string){ degens := findDegens(seqFile, fastaFil...
// Returns the reverse complement of a sequence of nucleotides // Only works with 'A', 'C', 'G', 'T' chars func reverseComplement(sequence string) (out string) { for i := len(sequence)-1; i >= 0; i-- { switch sequence[i] { case 65: out += "T" break case 84: out += "A" break ...
{ var out []Sequence // Open the .seq file fi, err := os.Open(seqFile) if err != nil { fmt.Println("Error - couldn't open .seq file") os.Exit(1) } scanner := bufio.NewScanner(fi) // For each line in the file for scanner.Scan() { var temp Sequence // Get name line := scanner.Text...
identifier_body
generate_primers.go
package main import ( "fmt" "os" "strings" "bufio" "strconv" "sort" "flag" ) type Sequence struct { name string seq string isForward bool val int } // Generates the primers func generatePrimers(seqFile, fastaFile string, ignore int) (map[string]string){ degens := findDegens(seqFile, fastaFil...
sequences := getSeqs(seqFile) genomes := getGenomes(fastaFile) // For each sequence for _, sequence := range sequences { // If sequence is a reverse, perform the reverse complement on it if !(sequence.isForward) { sequence.seq = reverseComplement(sequence.seq) } out[sequence.name] = m...
random_line_split
generate_primers.go
package main import ( "fmt" "os" "strings" "bufio" "strconv" "sort" "flag" ) type Sequence struct { name string seq string isForward bool val int } // Generates the primers func generatePrimers(seqFile, fastaFile string, ignore int) (map[string]string){ degens := findDegens(seqFile, fastaFil...
(sequence string) (out string) { for i := len(sequence)-1; i >= 0; i-- { switch sequence[i] { case 65: out += "T" break case 84: out += "A" break case 71: out += "C" break case 67: out += "G" break default: fmt.Println("Error -- Encounter...
reverseComplement
identifier_name
generate_primers.go
package main import ( "fmt" "os" "strings" "bufio" "strconv" "sort" "flag" ) type Sequence struct { name string seq string isForward bool val int } // Generates the primers func generatePrimers(seqFile, fastaFile string, ignore int) (map[string]string){ degens := findDegens(seqFile, fastaFil...
return out } // Gets the sequences from the .seq file and returns them in an array of Sequence structs // Assuming you have the following in the .seq file: // >99_forward // ACGT // You will get a Sequence struct with the following fields: // name = "99_forward" // seq = "ACGT" // isForward = true ...
{ line := scanner.Text() // If the line begins with '>', assume it's a header if line[0] == 62 { out = append(out, temp) temp = "" // If the line doesn't begin with '>', assume it's a seuence of nucleotides } else { temp += line } }
conditional_block
views.py
from django.shortcuts import render_to_response, redirect from django.views.generic.detail import DetailView from django.views.generic import TemplateView from django.template.context import RequestContext from django.contrib.auth.decorators import login_required from django.http import HttpResponse from django.db.mode...
(TemplateView): template_name = "index.html" class PledgeDetail(DetailView): queryset = Pledge.objects.all() template_name = 'pledge_detail.html' @login_required(login_url='/radiothon/accounts/login') def rthon_pledge(request): pledge_form = PledgeForm(request.POST or None, prefix="pledge_form") ...
MainView
identifier_name
views.py
from django.shortcuts import render_to_response, redirect from django.views.generic.detail import DetailView from django.views.generic import TemplateView from django.template.context import RequestContext from django.contrib.auth.decorators import login_required from django.http import HttpResponse from django.db.mode...
def rthon_plain_logs(request, timespan): ip = get_client_ip(request) #if (ip != '192.168.0.59'): # should probably de-hardcode this # return HttpResponse('Error, not authorized.', content_type="text/plain") response = HttpResponse(content_type="text/plain") pledges = Pledge.objects.all() ...
subject = 'Radiothon Pledge System: %s' % pledge.donor.name message = pledge.as_email() sender = 'WUVT.IT@gmail.com' current_bm = BusinessManager.objects.order_by('-terms__year', 'terms__semester')[0] simple_send_email(sender, current_bm.email, subject, message)
identifier_body
views.py
from django.shortcuts import render_to_response, redirect from django.views.generic.detail import DetailView from django.views.generic import TemplateView from django.template.context import RequestContext from django.contrib.auth.decorators import login_required from django.http import HttpResponse from django.db.mode...
'errors': errors, 'pledge': pledge_form, 'donor': donor_form, 'address': address_form, 'credit': credit_form, 'hokiepassport': hokiepassport_form, 'premium_formsets': premium_choice_forms, 'sending_to': BusinessManager.objects.order_by('-terms__year', 'ter...
random_line_split
views.py
from django.shortcuts import render_to_response, redirect from django.views.generic.detail import DetailView from django.views.generic import TemplateView from django.template.context import RequestContext from django.contrib.auth.decorators import login_required from django.http import HttpResponse from django.db.mode...
else: donor.save() pledge.donor = donor else: errors.append(donor_form.errors) if len(errors) == 0: pledge.save() if pledge.premium_delivery != 'N': for form in premium_c...
errors.append('You must ask the donor for their email or their phone number')
conditional_block
analysiscore.go
package webconnectivitylte import ( "fmt" "net" "net/url" "github.com/ooni/probe-engine/pkg/model" "github.com/ooni/probe-engine/pkg/netxlite" ) // // Core analysis // // These flags determine the context of TestKeys.Blocking. However, while .Blocking // is an enumeration, these flags allow to describe multipl...
} // analysisNullNullDetectNoAddrs attempts to see whether we // ended up into the .Blocking = nil, .Accessible = nil case because // the domain is expired and all queries returned no addresses. // // See https://github.com/ooni/probe/issues/2290 for further // documentation about the issue we're solving here. // // I...
// safety net in case we're passed empty lists/maps return false
random_line_split
analysiscore.go
package webconnectivitylte import ( "fmt" "net" "net/url" "github.com/ooni/probe-engine/pkg/model" "github.com/ooni/probe-engine/pkg/netxlite" ) // // Core analysis // // These flags determine the context of TestKeys.Blocking. However, while .Blocking // is an enumeration, these flags allow to describe multipl...
// analysisNullNullDetectNoAddrs attempts to see whether we // ended up into the .Blocking = nil, .Accessible = nil case because // the domain is expired and all queries returned no addresses. // // See https://github.com/ooni/probe/issues/2290 for further // documentation about the issue we're solving here. // // It...
{ if tk.Control == nil { // we need control data to say we're in this case return false } for _, entry := range tk.TCPConnect { if entry.Status.Failure == nil { // we need all connect attempts to fail return false } epnt := net.JoinHostPort(entry.IP, fmt.Sprintf("%d", entry.Port)) thEntry, found :...
identifier_body
analysiscore.go
package webconnectivitylte import ( "fmt" "net" "net/url" "github.com/ooni/probe-engine/pkg/model" "github.com/ooni/probe-engine/pkg/netxlite" ) // // Core analysis // // These flags determine the context of TestKeys.Blocking. However, while .Blocking // is an enumeration, these flags allow to describe multipl...
(logger model.Logger) bool { if tk.Control == nil || tk.Control.TLSHandshake == nil { // we need TLS control data to say we are in this case return false } for _, entry := range tk.TLSHandshakes { if entry.Failure == nil { // we need all attempts to fail to flag this state return false } thEntry, fo...
analysisNullNullDetectTLSMisconfigured
identifier_name
analysiscore.go
package webconnectivitylte import ( "fmt" "net" "net/url" "github.com/ooni/probe-engine/pkg/model" "github.com/ooni/probe-engine/pkg/netxlite" ) // // Core analysis // // These flags determine the context of TestKeys.Blocking. However, while .Blocking // is an enumeration, these flags allow to describe multipl...
epnt := net.JoinHostPort(entry.IP, fmt.Sprintf("%d", entry.Port)) thEntry, found := tk.Control.TCPConnect[epnt] if !found { // we need to have seen exactly the same attempts return false } if thEntry.Failure == nil { // we need all TH attempts to fail return false } } // only if we have had ...
{ // we need all connect attempts to fail return false }
conditional_block
lc0_analyzer.py
#!/usr/bin/env python3 # # lc0_analyzer.py --help # # See https://github.com/killerducky/lc0_analyzer/README.md for description # # See example.sh # import chess import chess.pgn import chess.uci import chess.svg import re import matplotlib.pyplot as plt import matplotlib.axes import pandas as pd import numpy as np i...
analyze_game(args.pgn, args.round, round(args.move*2-3), args.numplies) for m in np.arange(args.move, args.move+args.numplies/2, 0.5*args.ply_per_page): compose(args.pgn, args.round, m, min(args.ply_per_page, min(args.ply_per_page, args.numplies-(m-args.move)*2))) elif args.fen: ...
args.numplies = gamelen-plynum
conditional_block
lc0_analyzer.py
#!/usr/bin/env python3
# # See https://github.com/killerducky/lc0_analyzer/README.md for description # # See example.sh # import chess import chess.pgn import chess.uci import chess.svg import re import matplotlib.pyplot as plt import matplotlib.axes import pandas as pd import numpy as np import os import math import argparse from collectio...
# # lc0_analyzer.py --help
random_line_split
lc0_analyzer.py
#!/usr/bin/env python3 # # lc0_analyzer.py --help # # See https://github.com/killerducky/lc0_analyzer/README.md for description # # See example.sh # import chess import chess.pgn import chess.uci import chess.svg import re import matplotlib.pyplot as plt import matplotlib.axes import pandas as pd import numpy as np i...
def analyze_game(pgn_filename, gamenum, plynum, plies): try: # In case you have the data files already, but no lc0 exe. engine = chess.uci.popen_engine(LC0) info_handler = Lc0InfoHandler(None) engine.info_handlers.append(info_handler) except: print("Warning: Could not ...
savedir = "plots/%s_%s_%05.1f" % (pgn_filename, gamenum, (plynum+3)/2.0) # Parse data into pandas move_infos = [] with open("%s/data.html" % savedir) as infile: for line in infile.readlines(): info = parse_info(line) if not info: continue move_infos.append(info) ...
identifier_body
lc0_analyzer.py
#!/usr/bin/env python3 # # lc0_analyzer.py --help # # See https://github.com/killerducky/lc0_analyzer/README.md for description # # See example.sh # import chess import chess.pgn import chess.uci import chess.svg import re import matplotlib.pyplot as plt import matplotlib.axes import pandas as pd import numpy as np i...
(self): if "string" in self.info: #self.strings.append(self.info["string"]) # "c7f4 (268 ) N: 40 (+37) (P: 20.23%) (Q: -0.04164) (U: 0.08339) (Q+U: 0.04175) (V: 0.1052)" (move, info) = self.info["string"].split(maxsplit=1) move = self.board.san(self.board....
post_info
identifier_name
connection_test.go
package test import ( "context" "github.com/ethereum/go-ethereum/ethclient" "github.com/offchainlabs/arbitrum/packages/arb-tx-aggregator/arbostestcontracts" "github.com/offchainlabs/arbitrum/packages/arb-tx-aggregator/rpc" utils2 "github.com/offchainlabs/arbitrum/packages/arb-tx-aggregator/utils" "github.com/pkg...
logger.Info().Msg("Launched aggregator, connecting to RPC") l2Client, err := ethclient.Dial("http://localhost:9546") if err != nil { t.Fatal(err) } t.Log("Connected to aggregator") logger.Info().Hex("account4", auths[4].From.Bytes()).Msg("Account being used to deploy fibonacci") // Do not wrap with MakeC...
{ t.Fatal(err) }
conditional_block
connection_test.go
package test import ( "context" "github.com/ethereum/go-ethereum/ethclient" "github.com/offchainlabs/arbitrum/packages/arb-tx-aggregator/arbostestcontracts" "github.com/offchainlabs/arbitrum/packages/arb-tx-aggregator/rpc" utils2 "github.com/offchainlabs/arbitrum/packages/arb-tx-aggregator/utils" "github.com/pkg...
( client bind.DeployBackend, tx *types.Transaction, timeout time.Duration, ) (*types.Receipt, error) { ticker := time.NewTicker(timeout) for { select { case <-ticker.C: return nil, errors.Errorf("timed out waiting for receipt for tx %v", tx.Hash().Hex()) default: } receipt, err := client.TransactionRe...
waitForReceipt
identifier_name
connection_test.go
package test import ( "context" "github.com/ethereum/go-ethereum/ethclient" "github.com/offchainlabs/arbitrum/packages/arb-tx-aggregator/arbostestcontracts" "github.com/offchainlabs/arbitrum/packages/arb-tx-aggregator/rpc" utils2 "github.com/offchainlabs/arbitrum/packages/arb-tx-aggregator/utils" "github.com/pkg...
func waitForReceipt( client bind.DeployBackend, tx *types.Transaction, timeout time.Duration, ) (*types.Receipt, error) { ticker := time.NewTicker(timeout) for { select { case <-ticker.C: return nil, errors.Errorf("timed out waiting for receipt for tx %v", tx.Hash().Hex()) default: } receipt, err :=...
{ go func() { if err := rpc.LaunchAggregator( context.Background(), client, rollupAddress, contract, db+"/aggregator", "9546", "9547", utils2.RPCFlags{}, time.Second, rpc.StatelessBatcherMode{Auth: auth}, ); err != nil { logger.Fatal().Stack().Err(err).Msg("LaunchAggregator failed"...
identifier_body
connection_test.go
package test import ( "context" "github.com/ethereum/go-ethereum/ethclient" "github.com/offchainlabs/arbitrum/packages/arb-tx-aggregator/arbostestcontracts" "github.com/offchainlabs/arbitrum/packages/arb-tx-aggregator/rpc" utils2 "github.com/offchainlabs/arbitrum/packages/arb-tx-aggregator/utils" "github.com/pkg...
return nil } func launchAggregator(client ethutils.EthClient, auth *bind.TransactOpts, rollupAddress common.Address) error { go func() { if err := rpc.LaunchAggregator( context.Background(), client, rollupAddress, contract, db+"/aggregator", "9546", "9547", utils2.RPCFlags{}, time.Secon...
_ = managers
random_line_split
partition.rs
use arrow_deps::{ arrow::record_batch::RecordBatch, datafusion::logical_plan::Expr, datafusion::logical_plan::Operator, datafusion::optimizer::utils::expr_to_column_names, datafusion::scalar::ScalarValue, }; use generated_types::wal as wb; use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; use wa...
Expr::BinaryExpr { op, .. } => { match op { Operator::Eq | Operator::Lt | Operator::LtEq | Operator::Gt | Operator::GtEq | Operator::Plus | Operator::M...
{}
conditional_block
partition.rs
use arrow_deps::{ arrow::record_batch::RecordBatch, datafusion::logical_plan::Expr, datafusion::logical_plan::Operator, datafusion::optimizer::utils::expr_to_column_names, datafusion::scalar::ScalarValue, }; use generated_types::wal as wb; use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; use wa...
/// Return true if this column is the time column pub fn is_time_column(&self, id: u32) -> bool { self.time_column_id == id } /// Creates a DataFusion predicate for appliying a timestamp range: /// /// range.start <= time and time < range.end` fn make_timestamp_predicate_expr(&sel...
{ match &self.field_restriction { None => true, Some(field_restriction) => field_restriction.contains(&field_id), } }
identifier_body
partition.rs
use arrow_deps::{ arrow::record_batch::RecordBatch, datafusion::logical_plan::Expr, datafusion::logical_plan::Operator, datafusion::optimizer::utils::expr_to_column_names, datafusion::scalar::ScalarValue, }; use generated_types::wal as wb; use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; use wa...
/// of this dictionary. If there are no matching Strings in the /// partitions dictionary, those strings are ignored and a /// (potentially empty) set is returned. fn compile_string_list(&self, names: Option<&BTreeSet<String>>) -> Option<BTreeSet<u32>> { names.map(|names| { names ...
range, }) } /// Converts a potential set of strings into a set of ids in terms
random_line_split
partition.rs
use arrow_deps::{ arrow::record_batch::RecordBatch, datafusion::logical_plan::Expr, datafusion::logical_plan::Operator, datafusion::optimizer::utils::expr_to_column_names, datafusion::scalar::ScalarValue, }; use generated_types::wal as wb; use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; use wa...
{ /// At least one of the strings was not present in the partitions' /// dictionary. /// /// This is important when testing for the presence of all ids in /// a set, as we know they can not all be present AtLeastOneMissing, /// All strings existed in this partition's dictionary Present...
PartitionIdSet
identifier_name
mod.rs
pub mod canned_histories; mod history_builder; mod history_info; pub(crate) use history_builder::{TestHistoryBuilder, DEFAULT_WORKFLOW_TYPE}; use crate::{ pollers::{ BoxedActPoller, BoxedPoller, BoxedWFPoller, MockManualPoller, MockPoller, MockServerGatewayApis, }, task_token::TaskToken, ...
num_expected_fails, mock_gateway: MockServerGatewayApis::new(), expect_fail_wft_matcher: Box::new(|_, _, _| true), } } pub fn from_resp_batches( wf_id: &str, t: TestHistoryBuilder, resps: impl IntoIterator<Item = impl Into<ResponseType>>, ...
num_expected_fails: Option<usize>, ) -> Self { Self { hists, enforce_correct_number_of_polls,
random_line_split
mod.rs
pub mod canned_histories; mod history_builder; mod history_info; pub(crate) use history_builder::{TestHistoryBuilder, DEFAULT_WORKFLOW_TYPE}; use crate::{ pollers::{ BoxedActPoller, BoxedPoller, BoxedWFPoller, MockManualPoller, MockPoller, MockServerGatewayApis, }, task_token::TaskToken, ...
else { Some(Err(tonic::Status::out_of_range( "Ran out of mock responses!", ))) } }); Box::new(mock_poller) as BoxedPoller<T> } pub fn mock_poller<T>() -> MockPoller<T> where T: Send + Sync + 'static, { let mut mock_poller = MockPoller::new(); mock_po...
{ Some(Ok(t)) }
conditional_block
mod.rs
pub mod canned_histories; mod history_builder; mod history_info; pub(crate) use history_builder::{TestHistoryBuilder, DEFAULT_WORKFLOW_TYPE}; use crate::{ pollers::{ BoxedActPoller, BoxedPoller, BoxedWFPoller, MockManualPoller, MockPoller, MockServerGatewayApis, }, task_token::TaskToken, ...
(mut cfg: MockPollCfg) -> MocksHolder<MockServerGatewayApis> { // Maps task queues to maps of wfid -> responses let mut task_queues_to_resps: HashMap<String, BTreeMap<String, VecDeque<_>>> = HashMap::new(); let outstanding_wf_task_tokens = Arc::new(RwLock::new(BiMap::new())); let mut correct_num_polls =...
build_mock_pollers
identifier_name
mod.rs
pub mod canned_histories; mod history_builder; mod history_info; pub(crate) use history_builder::{TestHistoryBuilder, DEFAULT_WORKFLOW_TYPE}; use crate::{ pollers::{ BoxedActPoller, BoxedPoller, BoxedWFPoller, MockManualPoller, MockPoller, MockServerGatewayApis, }, task_token::TaskToken, ...
pub(crate) fn gen_assert_and_reply( asserter: &dyn Fn(&WfActivation), reply_commands: Vec<workflow_command::Variant>, ) -> AsserterWithReply<'_> { ( asserter, workflow_completion::Success::from_variants(reply_commands).into(), ) } pub(crate) fn gen_assert_and_fail(asserter: &dyn Fn(&W...
{ let mut evictions = 0; let expected_evictions = expect_and_reply.len() - 1; let mut executed_failures = HashSet::new(); let expected_fail_count = expect_and_reply .iter() .filter(|(_, reply)| !reply.is_success()) .count(); 'outer: loop { let expect_iter = expect_an...
identifier_body
main.rs
#[macro_use] extern crate clap; extern crate curl; extern crate formdata; extern crate hex; extern crate hmac; extern crate hyper; #[macro_use] extern crate log; extern crate pipe; extern crate rand; extern crate sha_1; #[macro_use] extern crate serde_json; #[macro_use] extern crate serde_derive; extern crate stderrlog...
use std::io::{BufReader, BufWriter, Read}; use std::str; use std::thread::spawn; use url::Url; use curl::easy::{Easy, List}; const FORM_MAX_FILE_SIZE: u64 = 1099511627776; const FORM_MAX_FILE_COUNT: usize = 1048576; const FORM_EXPIRES: u64 = 4102444800; #[derive(Debug)] struct OpenStackConfig { auth_url: String, ...
use std::fs::File; use std::path::Path;
random_line_split
main.rs
#[macro_use] extern crate clap; extern crate curl; extern crate formdata; extern crate hex; extern crate hmac; extern crate hyper; #[macro_use] extern crate log; extern crate pipe; extern crate rand; extern crate sha_1; #[macro_use] extern crate serde_json; #[macro_use] extern crate serde_derive; extern crate stderrlog...
{ url: String, redirect: String, max_file_size: u64, max_file_count: usize, expires: u64, signature: String } #[derive(Debug)] struct MissingToken; impl fmt::Display for MissingToken { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Token not found in Keystone response headers") ...
FormTemplate
identifier_name
transaction_builder_test.go
package cnlib import "testing" import "github.com/stretchr/testify/assert" func TestTransactionBuilderBuildsTxCorrect(t *testing.T) { inputPath := NewDerivationPath(BaseCoinBip49MainNet, 1, 53) utxo := NewUTXO("1a08dafe993fdc17fdc661988c88f97a9974013291e759b9b5766b8e97c78f87", 1, 2788424, inputPath, nil, true) amo...
{ path := NewDerivationPath(BaseCoinBip49MainNet, 0, 80) utxo := NewUTXO("94b5bcfbd52a405b291d906e636c8e133407e68a75b0a1ccc492e131ff5d8f90", 0, 10261, path, nil, true) amount := 5000 feeAmount := 1000 changeAmount := 4261 changePath := NewDerivationPath(BaseCoinBip49MainNet, 1, 102) toAddress := "bc1ql2sdag2nm9c...
identifier_body
transaction_builder_test.go
package cnlib import "testing" import "github.com/stretchr/testify/assert" func TestTransactionBuilderBuildsTxCorrect(t *testing.T) { inputPath := NewDerivationPath(BaseCoinBip49MainNet, 1, 53) utxo := NewUTXO("1a08dafe993fdc17fdc661988c88f97a9974013291e759b9b5766b8e97c78f87", 1, 2788424, inputPath, nil, true) amo...
expectedTxid := "5eb44c7faaa9c17c886588a1e20461d60fbfe1e504e7bac5af3469fdd9039837" expectedChangeAddress := "2MvdUi5o3f2tnEFh9yGvta6FzptTZtkPJC8" wallet := NewHDWalletFromWords(w, BaseCoinBip49TestNet) meta, err := wallet.BuildTransactionMetadata(data.TransactionData) assert.Nil(t, err) assert.Equal(t, toAddres...
expectedEncodedTx := "0100000000010126af32df83e27e27711f48d8ca76ee8776ea765d0a9b498bc448e2fb0e00fd1c000000001716001438971f73930f6c141d977ac4fd4a727c854935b3fdffffff02625291000000000017a914aa8f293a04a7df8794b743e14ffb96c2a30a1b2787e026f0490000000017a914251dd11457a259c3ba47e5cca3717fe4214e02988702483045022100f24650e94fd...
random_line_split
transaction_builder_test.go
package cnlib import "testing" import "github.com/stretchr/testify/assert" func TestTransactionBuilderBuildsTxCorrect(t *testing.T) { inputPath := NewDerivationPath(BaseCoinBip49MainNet, 1, 53) utxo := NewUTXO("1a08dafe993fdc17fdc661988c88f97a9974013291e759b9b5766b8e97c78f87", 1, 2788424, inputPath, nil, true) amo...
(t *testing.T) { path := NewDerivationPath(BaseCoinBip49MainNet, 1, 7) utxo := NewUTXO("f14914f76ad26e0c1aa5a68c82b021b854c93850fde12f8e3188c14be6dc384e", 1, 33255, path, nil, true) amount := 23147 feeAmount := 10108 changePath := NewDerivationPath(BaseCoinBip49MainNet, 1, 2) toAddress := "1HT6WtD5CAToc8wZdacCgY4...
TestTransactionBuilder_BuildP2KH_NoChange
identifier_name
interpolation.rs
/* * Copyright 2018 The Starlark in Rust Authors. * Copyright (c) Facebook, Inc. and its affiliates. * * 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 * * https://www.apache.org/lic...
NamedOrPositional::Named(..) => { result.named_count += 1; } } result .parameters .push((named_or_positional, format, String::new())); } } Ok(result) }...
{ result.positional_count += 1; }
conditional_block
interpolation.rs
/* * Copyright 2018 The Starlark in Rust Authors. * Copyright (c) Facebook, Inc. and its affiliates. * * 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 * * https://www.apache.org/lic...
{ Named(String), Positional, } /// Implement Python `%` format strings. pub struct Interpolation { /// String before first parameter init: String, /// Number of positional arguments positional_count: usize, /// Number of named arguments named_count: usize, /// Arguments followed by...
NamedOrPositional
identifier_name
interpolation.rs
/* * Copyright 2018 The Starlark in Rust Authors. * Copyright (c) Facebook, Inc. and its affiliates. * * 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 * * https://www.apache.org/lic...
box owned_tuple.iter() } None => box iter::once(argument), } }; for (named_or_positional, format, tail) in self.parameters { let arg = match named_or_positional { NamedOrPositional::Positional...
random_line_split
interpolation.rs
/* * Copyright 2018 The Starlark in Rust Authors. * Copyright (c) Facebook, Inc. and its affiliates. * * 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 * * https://www.apache.org/lic...
/// Apply a percent-interpolation string to a value. pub fn apply<'v>(self, argument: Value<'v>, heap: &'v Heap) -> anyhow::Result<String> { let mut r = self.init; let owned_tuple; let mut arg_iter: Box<dyn Iterator<Item = Value>> = if self.named_count > 0 && self.positiona...
{ let mut result = Self { init: String::new(), positional_count: 0, named_count: 0, parameters: Vec::new(), }; let mut chars = format.chars(); while let Some(c) = chars.next() { if c != '%' { result.append_litera...
identifier_body
play.go
// Copyright 2018 The ChromiumOS Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Package play provides common code for playing videos on Chrome. package play import ( "context" "image" "image/color" "image/png" "math" "net/http" "net/http/httpt...
if mode == VerifyNoHWAcceleratorUsed && usesPlatformVideoDecoder { return errors.New("software decoding was not used when it was expected to") } if mode == VerifyHWDRMUsed && !isHwDrmPipeline { return errors.New("HW DRM video pipeline was not used when it was expected to") } return nil } // TestSeek checks t...
{ return errors.New("video decode acceleration was not used when it was expected to") }
conditional_block
play.go
// Copyright 2018 The ChromiumOS Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Package play provides common code for playing videos on Chrome. package play import ( "context" "image" "image/color" "image/png" "math" "net/http" "net/http/httpt...
// ColorDistance returns the maximum absolute difference between each component of a and b. // Both a and b are assumed to be RGBA colors. func ColorDistance(a, b color.Color) int { aR, aG, aB, aA := a.RGBA() bR, bG, bB, bA := b.RGBA() abs := func(a int) int { if a < 0 { return -a } return a } max := fu...
{ ctx, st := timing.Start(ctx, "play_seek_video") defer st.End() // Establish a connection to a video play page conn, err := loadPage(ctx, cs, baseURL+"/video.html") if err != nil { return err } defer conn.Close() defer conn.CloseTarget(ctx) if err := conn.Call(ctx, nil, "playRepeatedly", videoFile); err !...
identifier_body
play.go
// Copyright 2018 The ChromiumOS Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Package play provides common code for playing videos on Chrome. package play import ( "context" "image" "image/color" "image/png" "math" "net/http" "net/http/httpt...
(ctx context.Context, s *testing.State, tconn *chrome.TestConn, cs ash.ConnSource, filename, refFilename string) error { server := httptest.NewServer(http.FileServer(s.DataFileSystem())) defer server.Close() url := path.Join(server.URL, "video.html") conn, err := cs.NewConn(ctx, url) if err != nil { return error...
TestPlayAndScreenshot
identifier_name
play.go
// Copyright 2018 The ChromiumOS Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Package play provides common code for playing videos on Chrome. package play import ( "context" "image" "image/color"
"path" "path/filepath" "time" "chromiumos/tast/common/perf" "chromiumos/tast/errors" "chromiumos/tast/local/audio/crastestclient" "chromiumos/tast/local/chrome" "chromiumos/tast/local/chrome/ash" "chromiumos/tast/local/colorcmp" "chromiumos/tast/local/graphics" "chromiumos/tast/local/input" "chromiumos/tas...
"image/png" "math" "net/http" "net/http/httptest" "os"
random_line_split
redisquota.go
// Copyright 2018 Istio Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to i...
if quotas.ValidDuration > 0 && quotas.BucketDuration > 0 && quotas.ValidDuration <= quotas.BucketDuration { ce = ce.Appendf("valid_duration", "quotas.valid_duration: %v should be longer than quotas.bucket_duration: %v for ROLLING_WINDOW algorithm", quotas.ValidDuration, quotas.BucketDuration) cont...
{ ce = ce.Appendf("bucket_duration", "quotas.bucket_duration should be > 0 for ROLLING_WINDOW algorithm") continue }
conditional_block
redisquota.go
// Copyright 2018 Istio Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to i...
// getOverrideHash returns hash key of the given dimension in sorted by key func getDimensionHash(dimensions map[string]string) string { var keys []string for k := range dimensions { keys = append(keys, k) } sort.Strings(keys) h := fnv.New32a() for _, key := range keys { _, _ = io.WriteString(h, key+"\t"+d...
{ info := GetInfo() if len(b.adapterConfig.Quotas) == 0 { ce = ce.Appendf("quotas", "quota should not be empty") } limits := make(map[string]*config.Params_Quota, len(b.adapterConfig.Quotas)) for idx := range b.adapterConfig.Quotas { quotas := &b.adapterConfig.Quotas[idx] if len(quotas.Name) == 0 { ce ...
identifier_body
redisquota.go
// Copyright 2018 Istio Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to i...
key + ".data", // KEY[2] }, maxAmount, // ARGV[1] credit limit.GetValidDuration().Nanoseconds(), // ARGV[2] window length limit.GetBucketDuration().Nanoseconds(), // ARGV[3] bucket length args.BestEffort, // ARGV[4] best effort args.QuotaAmount, ...
result, err := script.Run( h.client, []string{ key + ".meta", // KEY[1]
random_line_split
redisquota.go
// Copyright 2018 Istio Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to i...
(dimensions map[string]string) string { var keys []string for k := range dimensions { keys = append(keys, k) } sort.Strings(keys) h := fnv.New32a() for _, key := range keys { _, _ = io.WriteString(h, key+"\t"+dimensions[key]+"\n") } return strconv.Itoa(int(h.Sum32())) } func (b *builder) Build(context con...
getDimensionHash
identifier_name
answer_identification.old.py
from src.question_classifier import * from nltk.corpus import stopwords import nltk import text_analyzer import re import string def num_occurrences_time_regex(tokens): dates_pattern = r'[[0-9]{1,2}/]*[0-9]{1,2}/[0-9]{2,4}|[0-9]{4}|january|february|march|april|may|june|july|' \ r'august|septem...
def test_why_to(): question_sentence = "Why did someone sleep in a tent on a sidewalk in front of a theater in Montreal?" answer_sentence = "In Montreal someone actually slept in a tent out on the sidewalk in front of a movie " \ "theatre to make sure he got the first ticket." test ...
question_sentence = "When did Babe play for \"the finest basketball team that ever stepped out on a floor\"?" answer_sentence = "Babe Belanger played with the Grads from 1929 to 1937." test = get_answer_phrase(question_sentence, answer_sentence) print(test)
identifier_body
answer_identification.old.py
from src.question_classifier import * from nltk.corpus import stopwords import nltk import text_analyzer import re import string def num_occurrences_time_regex(tokens): dates_pattern = r'[[0-9]{1,2}/]*[0-9]{1,2}/[0-9]{2,4}|[0-9]{4}|january|february|march|april|may|june|july|' \ r'august|septem...
elif question['qword'][0].lower() == "why": # q_verb = question.tuple # a_verb = answer.tuple parse_tree = next(CoreNLPParser().raw_parse(answer_sentence)) to_vp_phrases = [] prev_was_to = False for tree in parse_tree.subtrees(): ...
question_chunks = get_top_ner_chunk_of_each_tag(question_sentence) answer_chunks = get_top_ner_chunk_of_each_tag(answer_sentence) # todo: try something with checking the question tag with the answer tag # todo: consider stripping out the part of the answer with question entity in it...
conditional_block
answer_identification.old.py
from src.question_classifier import * from nltk.corpus import stopwords import nltk import text_analyzer import re import string def num_occurrences_time_regex(tokens): dates_pattern = r'[[0-9]{1,2}/]*[0-9]{1,2}/[0-9]{2,4}|[0-9]{4}|january|february|march|april|may|june|july|' \ r'august|septem...
(): question_sentence = "When did Babe play for \"the finest basketball team that ever stepped out on a floor\"?" answer_sentence = "Babe Belanger played with the Grads from 1929 to 1937." test = get_answer_phrase(question_sentence, answer_sentence) print(test) def test_why_to(): question_sentence...
test_when
identifier_name