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
classifier.d15b2d9b.js
// modules are defined as an array // [ module function, map of requires ] // // map of requires is short require name -> numeric require // // anything defined in a previous bundle is accessed via the // orig method which is the require for previous bundles // eslint-disable-next-line no-global-assign parcelRequire =...
var singleNormalizedData = []; for (var i = 0; i < arrayLikeData[song].length; i++) { var norm = this.normalize(arrayLikeData[song][i], featuresRange[i].min, featuresRange[i].max); singleNormalizedData.push(norm); } normalizedData.push(sing...
for (var song in arrayLikeData) {
random_line_split
classifier.d15b2d9b.js
// modules are defined as an array // [ module function, map of requires ] // // map of requires is short require name -> numeric require // // anything defined in a previous bundle is accessed via the // orig method which is the require for previous bundles // eslint-disable-next-line no-global-assign parcelRequire =...
(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __generator = this && this.__generator || funct...
step
identifier_name
classifier.d15b2d9b.js
// modules are defined as an array // [ module function, map of requires ] // // map of requires is short require name -> numeric require // // anything defined in a previous bundle is accessed via the // orig method which is the require for previous bundles // eslint-disable-next-line no-global-assign parcelRequire =...
function loadJSON(url) { return new Promise(function (resolve, reject) { var xobj = new XMLHttpRequest(); xobj.overrideMimeType("application/json"); xobj.open('GET', url, true); xobj.onreadystatechange = function () { if (xobj.readyState == 4 ...
{ var features = []; for (var _i = 0, data_1 = data; _i < data_1.length; _i++) { var singleSong = data_1[_i]; for (var _a = 0, _b = data[singleSong]; _a < _b.length; _a++) { var singleFeature = _b[_a]; console.log(data[singleSong][singleFeature]); ...
identifier_body
wfq.go
package wfq import ( "container/heap" "sync" ) /***************************************************************************** * *****************************************************************************/ // An implementation of this interface is passed to NewQueue // and used to obtain properties of items pa...
func getOverflowHeapItem() *overflowHeapItem { return ohi_pool.Get().(*overflowHeapItem) } func putOverflowHeapItem(ohi *overflowHeapItem) { ohi.hi = nil ohi_pool.Put(ohi) } /***************************************************************************** * ********************************************************...
{ return new(overflowHeapItem) }
identifier_body
wfq.go
package wfq import ( "container/heap" "sync" ) /***************************************************************************** * *****************************************************************************/ // An implementation of this interface is passed to NewQueue // and used to obtain properties of items pa...
(o *overflowHeapItem) bool { if i.hi.weight > o.hi.weight { return true } else if i.hi.weight == o.hi.weight && i.arrord < o.arrord { return true } return false } var ohi_pool sync.Pool func newOverflowHeapItem() interface{} { return new(overflowHeapItem) } func getOverflowHeapItem() *overflowHeapItem { re...
less
identifier_name
wfq.go
package wfq import ( "container/heap" "sync" ) /***************************************************************************** * *****************************************************************************/ // An implementation of this interface is passed to NewQueue // and used to obtain properties of items pa...
} else { q.size += hi.size // The queue has room, place our item in the main heap heap.Push(&q.items, hi) q.cond.Signal() q.lock.Unlock() } return true } // DeQueue removes the next item from the queue. DeQueue will not return (i.e. block) until an item can // be returned or the queue is empty and close...
{ return false }
conditional_block
wfq.go
package wfq import ( "container/heap" "sync" ) /***************************************************************************** * *****************************************************************************/ // An implementation of this interface is passed to NewQueue // and used to obtain properties of items pa...
// Queue will panic if the size of the item is greater then maxFlowSize (set in NewQueue). // Queue is safe for concurrent use. // func (q *Queue) Queue(item interface{}) bool { hi := getHeapItem() hi.value = item hi.key = q.helper.Key(item) hi.size = q.helper.Size(item) hi.weight = q.helper.Weight(item) if hi.s...
} // Place on item on the queue. Queue will not return (i.e. block) until the item can be placed on the queue // or the queue was closed. If Queue returns true, then DeQueue will eventually return the item. // If Queue returns false, then the item was not placed on the queue because the queue has been closed.
random_line_split
mod.rs
// Import the rendering contract use crate::traits::RendererBase; use crate::traits::UIElement; use crate::traits::UIEvent; // We make use of the arguments of the event loop use piston::input::{UpdateArgs, RenderArgs, Key}; // Used to send events to the application use std::sync::mpsc; // Use the GlGraphics backend ...
if sample > self.max_amp { self.max_amp = sample } } // Min/max frequency // Buffer size text::Text::new_color(fg_color, self.base_font_size as u32).draw( format!( "Analyzed frequencies: {} Hz to {} Hz (channels: {})", format_number(audio.bin_frequency.round()...
{ self.min_amp = sample }
conditional_block
mod.rs
// Import the rendering contract use crate::traits::RendererBase; use crate::traits::UIElement; use crate::traits::UIEvent; // We make use of the arguments of the event loop use piston::input::{UpdateArgs, RenderArgs, Key}; // Used to send events to the application use std::sync::mpsc; // Use the GlGraphics backend ...
}
{ // ... }
identifier_body
mod.rs
// Import the rendering contract use crate::traits::RendererBase; use crate::traits::UIElement; use crate::traits::UIEvent; // We make use of the arguments of the event loop use piston::input::{UpdateArgs, RenderArgs, Key}; // Used to send events to the application use std::sync::mpsc; // Use the GlGraphics backend ...
// Font size relative to UI overlay (always three lines high) self.base_font_size = (overlay_height / 3.0 * 0.95).floor(); if self.base_font_size > 14.0 { self.base_font_size = 14.0; // Don't overdo it } // Colors let bg_color = [0.0, 0.0, 0.0, self.ui_opacity as f32]; // Overlay ar...
let overlay_top = self.height as f64 * 0.8; let overlay_height = self.height as f64 * 0.2;
random_line_split
mod.rs
// Import the rendering contract use crate::traits::RendererBase; use crate::traits::UIElement; use crate::traits::UIEvent; // We make use of the arguments of the event loop use piston::input::{UpdateArgs, RenderArgs, Key}; // Used to send events to the application use std::sync::mpsc; // Use the GlGraphics backend ...
(&mut self, begin_point: [f64; 2], text: String, gl: &mut GlGraphics, context: Context) -> [f64; 4] { // Draws a text button with the UIs style let padding = 5.0; let real_width = self.ui_font.width(self.base_font_size as u32, text.as_str()).unwrap() + 2.0 * padding; let real_height = self.base_font_si...
draw_text_button
identifier_name
mod.rs
#![allow(dead_code)] pub mod hypotheses; use std::collections::HashMap; use std::hash::Hash; use std::cmp::{Eq, Ordering}; use std::iter::FromIterator; use ansi_term::Style; use triangles::Study; use inference::triangle::hypotheses::BasicHypothesis; use inference::triangle::hypotheses::JoinedHypothesis; pub use inf...
nch] fn concerning_the_expense_of_prediction(bencher: &mut Bencher) { let distribution = complexity_prior(standard_basic_hypotheses()); bencher.iter(|| { distribution.predict(&Study::sample(), true); }); } #[bench] fn concerning_the_expense_of_the_value(bencher: &mut...
let distribution = complexity_prior(standard_basic_hypotheses()); bencher.iter(|| { distribution.entropy() }); } #[be
identifier_body
mod.rs
#![allow(dead_code)] pub mod hypotheses; use std::collections::HashMap; use std::hash::Hash; use std::cmp::{Eq, Ordering}; use std::iter::FromIterator; use ansi_term::Style; use triangles::Study; use inference::triangle::hypotheses::BasicHypothesis; use inference::triangle::hypotheses::JoinedHypothesis; pub use inf...
// that I ran into when I was first sketching out the number game, as // accounted in the README: if the true meaning of the complexity // penalty is that the hypothesis "A" gets to sum over the unspecified // details borne by the more complicated hypotheses "A ∧ B" and "A ∧ // C...
// ⎳ i=1 1/2^i = 1 // // So ... I want to give conjunctions and disjunctions a lower prior // probability, but I'm running into the same philosophical difficulty
random_line_split
mod.rs
#![allow(dead_code)] pub mod hypotheses; use std::collections::HashMap; use std::hash::Hash; use std::cmp::{Eq, Ordering}; use std::iter::FromIterator; use ansi_term::Style; use triangles::Study; use inference::triangle::hypotheses::BasicHypothesis; use inference::triangle::hypotheses::JoinedHypothesis; pub use inf...
(&self, desired_bits: f64, sample_cap: usize) -> Study { let mut study = Study::sample(); let mut value = self.value_of_information(&study); let mut top_study = study.clone(); let mut top_value = value; let mut samples = 1; loop { i...
burning_question
identifier_name
mod.rs
#![allow(dead_code)] pub mod hypotheses; use std::collections::HashMap; use std::hash::Hash; use std::cmp::{Eq, Ordering}; use std::iter::FromIterator; use ansi_term::Style; use triangles::Study; use inference::triangle::hypotheses::BasicHypothesis; use inference::triangle::hypotheses::JoinedHypothesis; pub use inf...
study = Study::sample(); value = self.value_of_information(&study); samples += 1; } top_study } pub fn inspect(&self, n: usize) { let mut backing = self.backing().iter().collect::<Vec<_>>(); backing.sort_by(|a, b| b.1.partial_cmp(a.1).unwrap_...
{ break; }
conditional_block
ppno.py
# -*- coding: utf-8 -*- """PRESSURIZED PIPE NETWORK OPTIMIZER Andrés García Martínez (ppnoptimizer@gmail.com) Licensed under the Apache License 2.0. http://www.apache.org/licenses/ """ from sys import argv from time import clock, localtime, strftime import numpy as np import toolkit as et import htxt as ht...
return deficits def save_file(self,fn): '''Save inp file updating d and roughness''' # UPDATE AND SAVE MODEL et.ENsaveinpfile(fn) def get_cost(self): '''Return the network cost. Sum of length x price for each pipe''' acumulate = 0.0 ...
elif mode == 'PD':
random_line_split
ppno.py
# -*- coding: utf-8 -*- """PRESSURIZED PIPE NETWORK OPTIMIZER Andrés García Martínez (ppnoptimizer@gmail.com) Licensed under the Apache License 2.0. http://www.apache.org/licenses/ """ from sys import argv from time import clock, localtime, strftime import numpy as np import toolkit as et import htxt as ht...
def main(argv): #RUN AN OPTIMIZATION print('*'*80) print('PRESSURIZED PIPE NETWORK OPTIMIZER') print('v0.0', 'ppnoptimizer@gmail.com') print('Licensed under the Apache License 2.0. http://www.apache.org/licenses/') print('*'*80) # LOAD PROBLEM myopt = Ppn(argv[1]...
int the solution in a readable format''' # PRINT SOLUTION cost = 0 print('*** SOLUTION ***') print('-'*80) m = '{:>16} {:>16} {:>8} {:>9} {:>6} {:>6} {:>10}'.format( \ 'Epanet Pipe ID', 'series name', 'diameter',\ ...
identifier_body
ppno.py
# -*- coding: utf-8 -*- """PRESSURIZED PIPE NETWORK OPTIMIZER Andrés García Martínez (ppnoptimizer@gmail.com) Licensed under the Apache License 2.0. http://www.apache.org/licenses/ """ from sys import argv from time import clock, localtime, strftime import numpy as np import toolkit as et import htxt as ht...
if status: solution = self.get_x().copy() if self.algorithm in [A_DE, A_DA]: # DIFFEERENTIAL EVOLUTION / DUAL ANNEALING ALGORITHM # SET BOUNDS tmp = list(zip(self.lbound,self.ubound)) self.boun...
elf.get_x() if x[index] < self.ubound[index]: x[index] += 1 self.set_x(x) break
conditional_block
ppno.py
# -*- coding: utf-8 -*- """PRESSURIZED PIPE NETWORK OPTIMIZER Andrés García Martínez (ppnoptimizer@gmail.com) Licensed under the Apache License 2.0. http://www.apache.org/licenses/ """ from sys import argv from time import clock, localtime, strftime import numpy as np import toolkit as et import htxt as ht...
): '''Return x ''' return self._x def _update(self): '''Update pipe diameter and roughness in the epanet model ''' for index,pipe in np.ndenumerate(self.pipes): ix = pipe['ix'] series = self.catalog[pipe['series']] ...
(self
identifier_name
Scanner3D.py
import math from dataclasses import dataclass from typing import List, Optional, Tuple import cv2 as cv import numpy as np import open3d as o3d from sklearn.cluster import DBSCAN from src.utils import ( ExtremePoints, Plane, Point, Rectangle, draw_circles, fit_plane, line_p...
( self, original_image: np.ndarray, image: np.ndarray, extreme_points: ExtremePoints, ) -> Tuple[ Optional[np.ndarray], Optional[np.ndarray], Optional[np.ndarray], Optional[np.ndarray], ]: """ Given the interesting regio...
get_laser_points
identifier_name
Scanner3D.py
import math from dataclasses import dataclass from typing import List, Optional, Tuple import cv2 as cv import numpy as np import open3d as o3d from sklearn.cluster import DBSCAN from src.utils import ( ExtremePoints, Plane, Point, Rectangle, draw_circles, fit_plane, line_p...
def sort_corners(self, corners: np.ndarray): """ Sort the 4 corners clockwise of a rectangle so that the top-left corner is the first one. """ center = np.sum(corners, axis=0) / 4 sorted_corners = sorted( corners, key=lambda p: math...
""" Given a thresholded image of the scene (ideally, the first frame), return the masks for the two known rectangles: one on the wall and one on the desk. """ contours = cv.findContours(thresh, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)[0] mask = np.zeros(thresh.shape, np.uint8) ...
identifier_body
Scanner3D.py
import math from dataclasses import dataclass from typing import List, Optional, Tuple import cv2 as cv import numpy as np import open3d as o3d from sklearn.cluster import DBSCAN from src.utils import ( ExtremePoints, Plane, Point, Rectangle, draw_circles, fit_plane, line_p...
first_frame_thresh = threshold_image(first_frame) desk_corners, wall_corners = self.get_desk_wall_corners(first_frame_thresh) extreme_points = self.get_extreme_points(wall_corners, desk_corners) desk_plane = self.get_H_R_t(desk_corners) wall_plane = self.get_H_R_t(wall_corne...
urn
conditional_block
Scanner3D.py
import math from dataclasses import dataclass from typing import List, Optional, Tuple import cv2 as cv import numpy as np import open3d as o3d from sklearn.cluster import DBSCAN from src.utils import ( ExtremePoints, Plane, Point, Rectangle, draw_circles, fit_plane, line_p...
laser_wall = self.offset_points( points=laser_wall, offset=Point(xmin, ymin_wall) ) laser_obj = self.remove_obj_outliers(laser_obj) if laser_obj is not None: laser_obj = self.offset_point...
points=laser_desk, offset=Point(xmin, ymin_desk) )
random_line_split
blackjack (1).py
# -*- coding: utf-8 -*- from card import BJCard, Deck class BJCards(list): """Blackjack Cards Class Attributes: possible_sums: all the possible sum of card hand: -1 if bust highest sum of possible sums, otherwise """ def __init__(self): list.__init__(self) ...
print dealer bob.restart() dealer.restart() dealer.deal() print "== Run BJGame" game = BJGame() dealer = Dealer() dealer.join(game) bob = Player('bob', 100) bob.join(game) tom = Player('tom', 200) tom.join(game) game.start() game.start() # game.repeat() ...
dealer.deal_self() print dealer
conditional_block
blackjack (1).py
# -*- coding: utf-8 -*- from card import BJCard, Deck class BJCards(list): """Blackjack Cards Class Attributes: possible_sums: all the possible sum of card hand: -1 if bust highest sum of possible sums, otherwise """ def __init__(self): list.__init__(self) ...
(self): self.players = [] self.dealer = None def join(self, player): self.players.append(player) def leave(self, player): self.players.remove(player) def dealer_join(self, dealer): self.dealer = dealer def dealer_leave(self, dealer): self.dealer = None ...
__init__
identifier_name
blackjack (1).py
# -*- coding: utf-8 -*- from card import BJCard, Deck class BJCards(list): """Blackjack Cards Class Attributes: possible_sums: all the possible sum of card hand: -1 if bust highest sum of possible sums, otherwise """ def __init__(self): list.__init__(self) ...
def join(self, game): """join a Blackjack game""" self.game = game self.game.dealer_join(self) return self.game def leave(self): """Leave the Blackjack game""" self.game.dealer_leave(self) return self.game def showdown(self): """Face up dealer...
"""Get a card from the deck""" return self.deck.pop()
identifier_body
blackjack (1).py
# -*- coding: utf-8 -*- from card import BJCard, Deck class BJCards(list): """Blackjack Cards Class Attributes: possible_sums: all the possible sum of card hand: -1 if bust highest sum of possible sums, otherwise """ def __init__(self): list.__init__(self) ...
player.restart() self.dealer.restart() return True def repeat(self): while self.start(): pass if __name__ == '__main__': print "==Testing BJCards" def test_cards(card_list): cards = BJCards() for c in card_list: ...
random_line_split
classes.component.ts
import { Component, OnInit, ViewChild, ViewContainerRef } from '@angular/core'; import { CommonService } from 'app/service/common.service'; import { ClassesConfigService } from 'app/service/general/api/classes-config.service'; import { MatDialog, MatSnackBar } from '@angular/material'; import { ClassFilterView } from '...
}
{ this.classForm.controls[key].setValue(this.commonService.trimSpaces(this.classForm.controls[key].value)); // modify value here) }
identifier_body
classes.component.ts
import { Component, OnInit, ViewChild, ViewContainerRef } from '@angular/core'; import { CommonService } from 'app/service/common.service'; import { ClassesConfigService } from 'app/service/general/api/classes-config.service'; import { MatDialog, MatSnackBar } from '@angular/material'; import { ClassFilterView } from '...
if (res.statusCode === HttpStatus.OK) { this.openSnackBar(res.messages.ResultMessage); this.myClassForm.resetForm(); if (!onContinue){ this.closeForm = true; this.getAllFilteredClasses(); } } else { ...
this.isdisableBtn = true; this.classesConfigService.createClass(form) .subscribe((res: ValidationMessageView) => {
random_line_split
classes.component.ts
import { Component, OnInit, ViewChild, ViewContainerRef } from '@angular/core'; import { CommonService } from 'app/service/common.service'; import { ClassesConfigService } from 'app/service/general/api/classes-config.service'; import { MatDialog, MatSnackBar } from '@angular/material'; import { ClassFilterView } from '...
}, error => { // this.isdisableBtn = false; this.errorResponse(error); }); this.isdisableBtn = false; } else if (this.classForm.valid) { this.isdisableBtn = true; this.classesConfigService.updateClass(form).subscribe((res: ValidationMessageView) => { ...
{ this.openSnackBar(res.messages.ResultMessage, true); this.closeForm = false; }
conditional_block
classes.component.ts
import { Component, OnInit, ViewChild, ViewContainerRef } from '@angular/core'; import { CommonService } from 'app/service/common.service'; import { ClassesConfigService } from 'app/service/general/api/classes-config.service'; import { MatDialog, MatSnackBar } from '@angular/material'; import { ClassFilterView } from '...
(form: ClassResultViewModel, onContinue = false): void { this.isFormSubmitted = true; if (this.classForm.invalid) { return; } if (!form.id && this.classForm.status === AppSettings.VALID) { this.isdisableBtn = true; this.classesConfigService.createClass(form) .subscribe((res: V...
createOrUpdateClass
identifier_name
lib.rs
#![allow(clippy::many_single_char_names, non_snake_case)] pub mod chase; pub mod mvd; mod parser; mod sorted_uvec; use itertools::Itertools; use mvd::MVD; use rand::prelude::Distribution; use sorted_uvec::SortedUVec; use std::{borrow::Borrow, mem, ops::Not}; use std::{ collections::HashMap, fmt::{self, Displa...
} bcnf } pub struct NumberOfAttrs(u32); impl NumberOfAttrs { pub fn new(n: u32) -> Self { Self(n) } } impl Distribution<FD> for NumberOfAttrs { fn sample<R: rand::Rng + ?Sized>(&self, rng: &mut R) -> FD { let n = self.0; let mut source = vec![]; let mut target = ...
{ bcnf.push(rel); }
conditional_block
lib.rs
#![allow(clippy::many_single_char_names, non_snake_case)] pub mod chase; pub mod mvd; mod parser; mod sorted_uvec; use itertools::Itertools; use mvd::MVD; use rand::prelude::Distribution; use sorted_uvec::SortedUVec; use std::{borrow::Borrow, mem, ops::Not}; use std::{ collections::HashMap, fmt::{self, Displa...
(&self, f: &mut Formatter) -> fmt::Result { <Self as fmt::Debug>::fmt(self, f) } } pub fn categorize(sub: &Attrs, rel: &Attrs, FDs: &[FD]) -> Category { let closure = closure_of(sub, FDs); if !closure.is_superset(&rel) { return Category::Nonkey; } let has_subkey = sub .iter...
fmt
identifier_name
lib.rs
#![allow(clippy::many_single_char_names, non_snake_case)] pub mod chase; pub mod mvd; mod parser; mod sorted_uvec; use itertools::Itertools; use mvd::MVD; use rand::prelude::Distribution; use sorted_uvec::SortedUVec; use std::{borrow::Borrow, mem, ops::Not}; use std::{ collections::HashMap, fmt::{self, Displa...
while let Some((rel, FDs)) = candidates.pop() { // every 2-attribute relation is in BCNF if rel.len() <= 2 { bcnf.push(rel); continue; } if let Some(fd) = violation(&rel, &FDs) { let rel_0 = closure_of(&fd.source, &FDs); let FDs_0 = p...
pub fn bcnf_decomposition(rel: &Attrs, FDs: &[FD]) -> Vec<Attrs> { let rel: Attrs = rel.clone(); let mut candidates: Vec<(Attrs, Vec<FD>)> = vec![(rel, FDs.to_vec())]; let mut bcnf: Vec<Attrs> = vec![];
random_line_split
lib.rs
#![allow(clippy::many_single_char_names, non_snake_case)] pub mod chase; pub mod mvd; mod parser; mod sorted_uvec; use itertools::Itertools; use mvd::MVD; use rand::prelude::Distribution; use sorted_uvec::SortedUVec; use std::{borrow::Borrow, mem, ops::Not}; use std::{ collections::HashMap, fmt::{self, Displa...
pub fn with_names<'a>(&'a self, register: &'a NameRegister) -> DepWithNames<'a> { DepWithNames { arrow: "->", source: &self.source, target: &self.target, register, } } } pub struct DepWithNames<'a> { arrow: &'a str, source: &'a Attrs, ...
{ self.target .iter() .map(move |&v| FD::new(self.source.clone(), attrs(&[v]))) }
identifier_body
main.py
import tensorflow as tf import numpy as np import time import os from sklearn.metrics import roc_curve import matplotlib.pyplot as plt from src.model import get_args from src.funcs import linear from src.youtubeface import load_ytf_data from src.lfw import load_lfw_data from src.facescrub import load_fs_data from src...
elif eval_dataset == 'LFW': image['gallery'], label['gallery'], iterator['gallery'] = load_lfw_data(batch_size, 'gallery') image['test'], label['test'], iterator['test'] = load_lfw_data(batch_size, 'probe') ### Backbone network (Arcface) embedding_tensor = tf.placeholder(name='img_inputs...
image['gallery'], label['gallery'], iterator['gallery'] = load_ytf_data(batch_size, 'train', eval=True) image['test'], label['test'], iterator['test'] = load_ytf_data(batch_size, 'test')
conditional_block
main.py
import tensorflow as tf import numpy as np import time import os from sklearn.metrics import roc_curve import matplotlib.pyplot as plt from src.model import get_args from src.funcs import linear from src.youtubeface import load_ytf_data from src.lfw import load_lfw_data from src.facescrub import load_fs_data from src...
embedding_tensor = tf.placeholder(name='img_inputs', shape=[None, 512], dtype=tf.float32) labels = tf.placeholder(name='label', shape=[None, ], dtype=tf.int32) ### Global step & learning rate global_step = tf.Variable(0, trainable=False) starter_learning_rate = 0.003 learning_rate = tf.train.ex...
random_line_split
sentiment_clustering_speech_classification_v0.py
import nltk import sklearn_crfsuite from sklearn_crfsuite import metrics import pandas as pd from sklearn.preprocessing import label_binarize import string # nltk.download('conll2002') flatten = lambda l: [item for sublist in l for item in sublist] print(__doc__) import numpy as np import matplotlib.pyplot as plt fr...
(): parser = argparse.ArgumentParser(description="") # Add options parser.add_argument("-v", "--verbosity", action="count", default=0, help="increase output verbosity") # Add arguments parser.add_argument("input_file", help="The input file to be projected") # parser.add_argument("speech_feats_file", h...
main
identifier_name
sentiment_clustering_speech_classification_v0.py
import nltk import sklearn_crfsuite from sklearn_crfsuite import metrics import pandas as pd from sklearn.preprocessing import label_binarize import string # nltk.download('conll2002') flatten = lambda l: [item for sublist in l for item in sublist] print(__doc__) import numpy as np import matplotlib.pyplot as plt fr...
def main(): parser = argparse.ArgumentParser(description="") # Add options parser.add_argument("-v", "--verbosity", action="count", default=0, help="increase output verbosity") # Add arguments parser.add_argument("input_file", help="The input file to be projected") # pa...
hyper_parm_turning=OrderedDict() for n_clusters in range_n_clusters: # Initialize the clusterer with n_clusters value and a random generator # seed of 10 for reproducibility. # clusterer = MiniBatchKMeans(n_clusters=n_clusters,init='k-means++', random_state=10) from sklearn.mixture import GaussianMixture ...
identifier_body
sentiment_clustering_speech_classification_v0.py
import nltk import sklearn_crfsuite from sklearn_crfsuite import metrics import pandas as pd from sklearn.preprocessing import label_binarize import string # nltk.download('conll2002') flatten = lambda l: [item for sublist in l for item in sublist] print(__doc__) import numpy as np import matplotlib.pyplot as plt fr...
print("For n_clusters =", n_clusters, "The average silhouette_score is :", silhouette_avg) return df,hyper_parm_turning def main(): parser = argparse.ArgumentParser(description="") # Add options parser.add_argument("-v", "--verbosity", action="count", default=0, hel...
hyper_parm_turning['sample_dist_avrg'].append(sample_dist_avrg)
conditional_block
sentiment_clustering_speech_classification_v0.py
import nltk import sklearn_crfsuite from sklearn_crfsuite import metrics import pandas as pd from sklearn.preprocessing import label_binarize import string # nltk.download('conll2002') flatten = lambda l: [item for sublist in l for item in sublist] print(__doc__) import numpy as np import matplotlib.pyplot as plt fr...
from sklearn.multiclass import OneVsRestClassifier from scipy import interp from sklearn.metrics import roc_auc_score import argparse import matplotlib.cm as cm import codecs from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.decomposition import NMF # nltk.corpus.conll2002.fileids() from tqdm i...
from sklearn import svm, datasets from sklearn.metrics import roc_curve, auc from sklearn.model_selection import train_test_split from sklearn.preprocessing import label_binarize
random_line_split
menus.ts
import logger from "../lib/logger"; import options from "../lib/options"; import { stringify } from "../lib/utils"; import * as menuIds from "../menuIds"; import castManager from "./castManager"; const _ = browser.i18n.getMessage; const URL_PATTERN_HTTP = "http://*/*"; const URL_PATTERN_HTTPS = "https://*/*"; const...
(pageUrl?: string) { /** * If page URL doesn't exist, we're not on a page and have nothing * to whitelist, so disable the menu and return. */ if (!pageUrl) { browser.menus.update(menuIdWhitelist, { enabled: false }); browser.menus.refresh(); return; ...
updateWhitelistMenu
identifier_name
menus.ts
import logger from "../lib/logger"; import options from "../lib/options"; import { stringify } from "../lib/utils"; import * as menuIds from "../menuIds"; import castManager from "./castManager"; const _ = browser.i18n.getMessage; const URL_PATTERN_HTTP = "http://*/*"; const URL_PATTERN_HTTPS = "https://*/*"; const...
}); } /** Handle updating menus when shown. */ async function onMenuShown(info: browser.menus._OnShownInfo) { const menuIds = info.menuIds as unknown as number[]; // Only rebuild menus if whitelist menu present if (menuIds.includes(menuIdWhitelist as number)) { updateWhitelistMenu(info.pageUr...
{ browser.menus.update(menuIdCastMedia, { targetUrlPatterns: newOpts.localMediaEnabled ? URL_PATTERNS_ALL : URL_PATTERNS_REMOTE }); }
conditional_block
menus.ts
import logger from "../lib/logger"; import options from "../lib/options"; import { stringify } from "../lib/utils"; import * as menuIds from "../menuIds"; import castManager from "./castManager"; const _ = browser.i18n.getMessage; const URL_PATTERN_HTTP = "http://*/*"; const URL_PATTERN_HTTPS = "https://*/*"; const...
/** Handle menu click events */ async function onMenuClicked( info: browser.menus.OnClickData, tab?: browser.tabs.Tab ) { // Handle whitelist menus if (info.parentMenuItemId === menuIdWhitelist) { const pattern = whitelistChildMenuPatterns.get(info.menuItemId); if (!pattern) { ...
{ const menuIds = info.menuIds as unknown as number[]; // Only rebuild menus if whitelist menu present if (menuIds.includes(menuIdWhitelist as number)) { updateWhitelistMenu(info.pageUrl); return; } }
identifier_body
menus.ts
import logger from "../lib/logger"; import options from "../lib/options"; import { stringify } from "../lib/utils"; import * as menuIds from "../menuIds"; import castManager from "./castManager"; const _ = browser.i18n.getMessage; const URL_PATTERN_HTTP = "http://*/*"; const URL_PATTERN_HTTPS = "https://*/*"; const...
const pattern = whitelistChildMenuPatterns.get(info.menuItemId); if (!pattern) { throw logger.error( `Whitelist pattern not found for menu item ID ${info.menuItemId}.` ); } const whitelist = await options.get("siteWhitelist"); if (!whiteli...
if (info.parentMenuItemId === menuIdWhitelist) {
random_line_split
wordcount.py
"""Using word frequencies to create a summary. """ import argparse import json import string import random import pprint from nltk import pos_tag from nltk.collocations import BigramAssocMeasures from nltk.collocations import BigramCollocationFinder from nltk.corpus import wordnet from nltk.tokenize imp...
print('Total number of words after filtering: {:d}'.format(len(lemmatized_records))) return lemmatized_records # End of lemmatize_words() def filter_stopwords(tagged_records): """Filters stopwords, punctuation, and contractions from the tagged records. This is done after tagging to make sure ...
try: lemmatized_record = list(map(lambda word: lemmatizer.lemmatize(word[0], POS_TRANSLATOR[word[1]]), record)) except Exception as err: print(record) raise err lemmatized_records.append(lemmatized_record)
conditional_block
wordcount.py
"""Using word frequencies to create a summary. """ import argparse import json import string import random import pprint from nltk import pos_tag from nltk.collocations import BigramAssocMeasures from nltk.collocations import BigramCollocationFinder from nltk.corpus import wordnet from nltk.tokenize imp...
(records): """Tokenizes the records into word lists. Filters out any stopwords in the list. Params: - records (list<dict>): The non-empty records from the JSON file Returns: - tokenized_records (list<list<str>>): The tokenized text content of the records """ contents = map(lambda ...
tokenize_records
identifier_name
wordcount.py
"""Using word frequencies to create a summary. """ import argparse import json import string import random import pprint from nltk import pos_tag from nltk.collocations import BigramAssocMeasures from nltk.collocations import BigramCollocationFinder from nltk.corpus import wordnet from nltk.tokenize imp...
Returns: - lemmatized_records (list<str>)): The lemmatized words from all the records """ print('Length of tagged_records: {:d}'.format(len(records))) print('Total number of words: {:d}'.format(sum([len(record) for record in records]))) tagged_records = map(lambda record: pos_tag(record),...
Params: - records (list<list<str>>): The word-tokenized records
random_line_split
wordcount.py
"""Using word frequencies to create a summary. """ import argparse import json import string import random import pprint from nltk import pos_tag from nltk.collocations import BigramAssocMeasures from nltk.collocations import BigramCollocationFinder from nltk.corpus import wordnet from nltk.tokenize imp...
# End of extract_frequent_words() def extract_collocations(records, num_collocations, collocation_window, compare_collocations = False): """Extracts the most common collocations present in the records. Params: - records (list<list<str>>): The tokenized and lemmatized records from the JSON file ...
"""Stems the words in the given records, and then counts the words using NLTK FreqDist. Stemming is done using the English Snowball stemmer as per the recommendation from http://www.nltk.org/howto/stem.html NB: There is also a Lancaster stemmer available, but it is apparently very aggressive and can...
identifier_body
client.ts
/** * * client * */ import type { ExecutionResult } from 'graphql'; import { RequestParams, Sink } from './common'; import { isObject } from './utils'; /** This file is the entry point for browsers, re-export common elements. */ export * from './common'; /** @category Client */ export interface ClientOptions { ...
if (disposed) return; disposed = true; // we copy the listeners so that onDispose unlistens dont "pull the rug under our feet" for (const listener of [...listeners]) { listener(); } }, }; })(); return { subscribe(request, sink) { if (client.dispo...
e() {
identifier_name
client.ts
/** * * client * */ import type { ExecutionResult } from 'graphql'; import { RequestParams, Sink } from './common'; import { isObject } from './utils'; /** This file is the entry point for browsers, re-export common elements. */ export * from './common'; /** @category Client */ export interface ClientOptions { ...
}; })(); return { subscribe(request, sink) { if (client.disposed) throw new Error('Client has been disposed'); const control = new AbortControllerImpl(); const unlisten = client.onDispose(() => { unlisten(); control.abort(); }); (async () => { let retryin...
if (disposed) return; disposed = true; // we copy the listeners so that onDispose unlistens dont "pull the rug under our feet" for (const listener of [...listeners]) { listener(); } },
identifier_body
client.ts
/** * * client * */ import type { ExecutionResult } from 'graphql'; import { RequestParams, Sink } from './common'; import { isObject } from './utils'; /** This file is the entry point for browsers, re-export common elements. */ export * from './common'; /** @category Client */ export interface ClientOptions { ...
try { const url = typeof options.url === 'function' ? await options.url(request) : options.url; if (control.signal.aborted) return; const headers = typeof options.headers === 'function' ? await options...
const should = await shouldRetry(retryingErr, retries); // requst might've been canceled while waiting for retry if (control.signal.aborted) return; if (!should) throw retryingErr; retries++; }
conditional_block
client.ts
/** * * client * */ import type { ExecutionResult } from 'graphql'; import { RequestParams, Sink } from './common'; import { isObject } from './utils'; /** This file is the entry point for browsers, re-export common elements. */ export * from './common'; /** @category Client */ export interface ClientOptions { ...
isObject(val) && typeof val['ok'] === 'boolean' && typeof val['status'] === 'number' && typeof val['statusText'] === 'string' ); }
random_line_split
test_language.py
import torch import triton import triton.language as tl import copy import pytest import ast import itertools torch.manual_seed(0) # convert from string to torch.dtype # Necessary because doesn't print torch.dtype properly cvt = { 'bool': torch.bool, 'int8': torch.int8, 'int16': torch.int16, 'int32': ...
if mode == 'min_neg': idx = torch.randint(n_programs, size=(1, )).item() x_tri[idx] = -torch.max(torch.abs(x_tri)) - 1 if mode == 'max_pos': idx = torch.randint(n_programs, size=(1, )).item() x_tri[idx] = torch.max(torch.abs(x_tri)) + 1 z_tri = torch.empty([], dtype=dtype_x...
x_tri = torch.abs(x_tri)
conditional_block
test_language.py
import torch import triton import triton.language as tl import copy import pytest import ast import itertools torch.manual_seed(0) # convert from string to torch.dtype # Necessary because doesn't print torch.dtype properly cvt = { 'bool': torch.bool, 'int8': torch.int8, 'int16': torch.int16, 'int32': ...
(template, to_replace): kernel = copy.deepcopy(template) for key, value in to_replace.items(): kernel.src = kernel.src.replace(key, value) return kernel # generic test functions def _test_unary(dtype_x, expr, torch_expr=None, device='cuda'): SIZE = 128 # define the kernel / launch-grid ...
patch_kernel
identifier_name
test_language.py
import torch import triton import triton.language as tl import copy import pytest import ast import itertools torch.manual_seed(0) # convert from string to torch.dtype # Necessary because doesn't print torch.dtype properly cvt = { 'bool': torch.bool, 'int8': torch.int8, 'int16': torch.int16, 'int32': ...
kernel = patch_kernel(kernel, {'GENERATE_TEST_HERE': expr}) # inputs x = triton.testing.random(SIZE, dtype=cvt[dtype_x], device=device) y = triton.testing.random(SIZE, dtype=cvt[dtype_y], device=device) # reference result z_ref = eval(expr) # triton result z_tri = torch.empty(SIZE, dtyp...
y = tl.load(Y + off) z = GENERATE_TEST_HERE tl.store(Z + off, z)
random_line_split
test_language.py
import torch import triton import triton.language as tl import copy import pytest import ast import itertools torch.manual_seed(0) # convert from string to torch.dtype # Necessary because doesn't print torch.dtype properly cvt = { 'bool': torch.bool, 'int8': torch.int8, 'int16': torch.int16, 'int32': ...
# --------------- # test atomics # --------------- @pytest.mark.parametrize("op, dtype_x, mode", itertools.chain.from_iterable([ [('add', 'int32', mode), ('add', 'float16', mode), ('add', 'float32', mode), \ ('max', 'int32', mode), ('max', 'float32', mode),\ ('min', 'int32', mode), ('min', 'float32', mod...
device = 'cuda' @triton.jit def with_fn(X, Y, A, B, C): x = tl.load(X) y = tl.load(Y) a, b, c = fn(x, y) tl.store(A, a) tl.store(B, b) tl.store(C, c) @triton.jit def without_fn(X, Y, A, B, C): x = tl.load(X) y = tl.load(Y) a, b, c...
identifier_body
variant.go
package variant import ( "context" "errors" "fmt" "io" "os" "path/filepath" "sort" "strconv" "strings" "sync" "github.com/hashicorp/hcl/v2/ext/typeexpr" "github.com/mattn/go-isatty" "github.com/spf13/cobra" "github.com/zclconf/go-cty/cty" "golang.org/x/xerrors" "github.com/mumoshu/variant2/pkg/app" )...
if m.Stderr == nil { m.Stderr = os.Stderr } if m.Getenv == nil { m.Getenv = os.Getenv } if m.Getwd == nil { m.Getwd = os.Getwd } cmdNameFromEnv := m.Getenv("VARIANT_NAME") if cmdNameFromEnv != "" { m.Command = cmdNameFromEnv } return m } type Config struct { Parameters func([]string) (map[stri...
{ m.Stdout = os.Stdout }
conditional_block
variant.go
package variant import ( "context" "errors" "fmt" "io" "os" "path/filepath" "sort" "strconv" "strings" "sync" "github.com/hashicorp/hcl/v2/ext/typeexpr" "github.com/mattn/go-isatty" "github.com/spf13/cobra" "github.com/zclconf/go-cty/cty" "golang.org/x/xerrors" "github.com/mumoshu/variant2/pkg/app" )...
cmd = r.variantCmd } var err error { cmdStdout := cmd.OutOrStdout() cmdStderr := cmd.OutOrStderr() appStdout := r.ap.Stdout appStderr := r.ap.Stderr cmd.SetArgs(arguments) if opts.Stdout != nil { cmd.SetOut(opts.Stdout) r.ap.Stdout = opts.Stdout } if opts.Stderr != nil { cmd.SetErr...
r.variantCmd = r.createVariantRootCommand() }
random_line_split
variant.go
package variant import ( "context" "errors" "fmt" "io" "os" "path/filepath" "sort" "strconv" "strings" "sync" "github.com/hashicorp/hcl/v2/ext/typeexpr" "github.com/mattn/go-isatty" "github.com/spf13/cobra" "github.com/zclconf/go-cty/cty" "golang.org/x/xerrors" "github.com/mumoshu/variant2/pkg/app" )...
func (r *Runner) createVariantRootCommand() *cobra.Command { const VariantBinName = "variant" rootCmd := &cobra.Command{ Use: VariantBinName, Version: Version, } testCmd := &cobra.Command{ Use: "test [NAME]", Short: "Run test(s)", Args: cobra.MaximumNArgs(1), RunE: func(c *cobra.Command, args ...
{ return e.Message }
identifier_body
variant.go
package variant import ( "context" "errors" "fmt" "io" "os" "path/filepath" "sort" "strconv" "strings" "sync" "github.com/hashicorp/hcl/v2/ext/typeexpr" "github.com/mattn/go-isatty" "github.com/spf13/cobra" "github.com/zclconf/go-cty/cty" "golang.org/x/xerrors" "github.com/mumoshu/variant2/pkg/app" )...
(setup Setup) *Runner { r, err := Load(setup) if err != nil { panic(err) } return r } func New() Main { return Init(Main{}) } type Env struct { Args []string Getenv func(name string) string Getwd func() (string, error) } func GetPathAndArgsFromEnv(env Env) (string, string, []string) { osArgs := env.Ar...
MustLoad
identifier_name
image_build.py
""" Copyright (c) 2017 Cyberhaven Copyright (c) 2017 Dependable Systems Laboratory, EPFL Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the right...
def _get_user_name(): """ Get the current user. """ return pwd.getpwuid(os.getuid())[0] def _user_belongs_to(group_name): """ Check that the current user belongs to the ``group_name`` group. """ user_name = _get_user_name() groups = _get_user_groups(user_name) return group_n...
""" Get a list of groups for the user ``user_name``. """ groups = [g.gr_name for g in grp.getgrall() if user_name in g.gr_mem] gid = pwd.getpwnam(user_name).pw_gid groups.append(grp.getgrgid(gid).gr_name) return groups
identifier_body
image_build.py
""" Copyright (c) 2017 Cyberhaven Copyright (c) 2017 Dependable Systems Laboratory, EPFL Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the right...
(): """ Check if VMWare is running. VMware conflicts with S2E's requirement for KVM, so VMWare must *not* be running together with S2E. """ for proc in psutil.process_iter(): try: if proc.name() == 'vmware-vmx': raise CommandError('S2E uses KVM to build images. VM...
_check_vmware
identifier_name
image_build.py
""" Copyright (c) 2017 Cyberhaven Copyright (c) 2017 Dependable Systems Laboratory, EPFL Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the right...
missing_keys = [] for image_name in image_names: image = image_descriptors[image_name] if 'product_key' in image: if not image['product_key']: missing_keys.append(image_name) ios = image_descriptors[image_name].get('os', {}) if 'product_key' in ios:...
random_line_split
image_build.py
""" Copyright (c) 2017 Cyberhaven Copyright (c) 2017 Dependable Systems Laboratory, EPFL Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the right...
iso_dir = os.path.abspath(options['iso_dir']) if options['iso_dir'] else None # Check for optional product keys and iso directories. # These may or may not be required, depending on the set of images. _check_product_keys(image_descriptors, image_names) _check_iso(templates, ap...
rule_names = _get_archive_rules(self.image_path(), image_names)
conditional_block
ChangeSwimlanesJira.user.js
// ==UserScript== // @name ChangeSwimlanesJira // @namespace http://tampermonkey.net/ // @version 3.3.3 // @description I'm sad that I've to say goodbye! // @author WLAD // @updateSite https://github.com/tepesware/TepesColors/raw/master/ChangeSwimlanesJira.user.js // @downloadURL https://github.c...
function addIssueAdditionalInfo(issue, ussueID, data, parrsedSubtasks) { var temp = $(issue).children("div.ghx-heading"); var html = "<span class='issueInfo "; html = html.concat(ussueID); html = html.concat("'>"); var subtaskHtml = addSubtaskRectangles(ussueID, data.field...
{ //debugger var temp = $(issue).children("div.ghx-heading"); var html = "<div class=\"testexec-status-block\">"; var statuses = stat.statuses; for (var i = 0; i < statuses.length; i++) { if (statuses[i].statusCount > 0) { html = html.concat("<span sty...
identifier_body
ChangeSwimlanesJira.user.js
// ==UserScript== // @name ChangeSwimlanesJira // @namespace http://tampermonkey.net/ // @version 3.3.3 // @description I'm sad that I've to say goodbye! // @author WLAD // @updateSite https://github.com/tepesware/TepesColors/raw/master/ChangeSwimlanesJira.user.js // @downloadURL https://github.c...
html = html.concat("</span>"); return html; } } return ""; } function getAssigneAvatarForIssue(key) { var result; // debugger; result = jsonpath.query(allData, "$.issuesData.issues[?(@.key=='" + key + "')].avatarUrl"); ...
random_line_split
ChangeSwimlanesJira.user.js
// ==UserScript== // @name ChangeSwimlanesJira // @namespace http://tampermonkey.net/ // @version 3.3.3 // @description I'm sad that I've to say goodbye! // @author WLAD // @updateSite https://github.com/tepesware/TepesColors/raw/master/ChangeSwimlanesJira.user.js // @downloadURL https://github.c...
() { getAllData(); var swimlanes = document.getElementsByClassName("ghx-info"); if (swimlanes.length > 0) { for (var i = 0; i < swimlanes.length; i++) { if (swimlanes[i].getElementsByTagName("span")[0].textContent == "To Do") { $(document.getEl...
updateTheBoard
identifier_name
ChangeSwimlanesJira.user.js
// ==UserScript== // @name ChangeSwimlanesJira // @namespace http://tampermonkey.net/ // @version 3.3.3 // @description I'm sad that I've to say goodbye! // @author WLAD // @updateSite https://github.com/tepesware/TepesColors/raw/master/ChangeSwimlanesJira.user.js // @downloadURL https://github.c...
} html = html.concat("</span>"); return html; } function addPoints(storyPoints, issue) { var text = ""; var temp = $(issue).find("div.ghx-heading > span.ghx-info") var html = "<span class='storyPoints "; html = html.concat("'>" + storyPoints); ...
{ if (parrseedSubtasks[i].status === order[j]) { html = html.concat(" <span class='" + orderClass[j] + "'>" + parrseedSubtasks[i].name); var avatarUrl = parrseedSubtasks[i].avatarForSubtask; var size = ""; if (order[j] ===...
conditional_block
avi.go
// A detailed description of the format is at // https://msdn.microsoft.com/en-us/library/ms779636.aspx package avi import ( "bytes" "errors" "fmt" "io" "os" ) var ( errMissingKeywordHeader = errors.New("avi: missing keyword") errMissingRIFFChunkHeader = errors.New("avi: missing RIFF chunk header") errMissi...
(u uint32) *FOURCC { return &FOURCC{byte(u >> 0), byte(u >> 8), byte(u >> 16), byte(u >> 24)} } func (fcc *FOURCC) String() string { return string([]byte{fcc[0], fcc[1], fcc[2], fcc[3]}) } func equal(a, b FOURCC) bool { if a[0] != b[0] || a[1] != b[1] || a[2] != b[2] || a[3] != b[3] { return false } return true...
encodeU32
identifier_name
avi.go
// A detailed description of the format is at // https://msdn.microsoft.com/en-us/library/ms779636.aspx package avi import ( "bytes" "errors" "fmt" "io" "os" ) var ( errMissingKeywordHeader = errors.New("avi: missing keyword") errMissingRIFFChunkHeader = errors.New("avi: missing RIFF chunk header") errMissi...
lists []*List chunks []*Chunk imagechunks []*ImageChunk imageNum int } // ckID ckSize ckData // ckSize includes size of ckData. // actual size is ckSize + 8 // The data is always padded to nearest WORD boundary. type Chunk struct { ID FOURCC Size uint32 Data map[string]uint32 } type ImageChunk ...
JunkSize uint32 // JUNK is only in
random_line_split
avi.go
// A detailed description of the format is at // https://msdn.microsoft.com/en-us/library/ms779636.aspx package avi import ( "bytes" "errors" "fmt" "io" "os" ) var ( errMissingKeywordHeader = errors.New("avi: missing keyword") errMissingRIFFChunkHeader = errors.New("avi: missing RIFF chunk header") errMissi...
avi.r = bytes.NewReader(data) buf := make([]byte, size) if n, err := io.ReadFull(avi.r, buf); err != nil { if err == io.EOF || err == io.ErrUnexpectedEOF { err = errShortData } fmt.Println(n, " out of ", size) return nil, err } return buf, nil } // NewReader returns the RIFF stream's form type, such...
{ return nil, err }
conditional_block
avi.go
// A detailed description of the format is at // https://msdn.microsoft.com/en-us/library/ms779636.aspx package avi import ( "bytes" "errors" "fmt" "io" "os" ) var ( errMissingKeywordHeader = errors.New("avi: missing keyword") errMissingRIFFChunkHeader = errors.New("avi: missing RIFF chunk header") errMissi...
func (avi *AVI) ExtendedAVIHeaderReader(size uint32) (map[string]uint32, error) { buf, err := avi.readData(size) if err != nil { return nil, err } m := make(map[string]uint32) m["dwTotalFrames"] = decodeU32(buf[:4]) return m, nil }
{ buf, err := avi.readData(size) if err != nil { return nil, err } m := make(map[string]uint32) m["wLongsPerEntry"] = decodeU32(buf[:2]) m["bIndexSubType"] = decodeU32(buf[2:3]) m["bIndexType"] = decodeU32(buf[3:4]) m["nEntriesInUse"] = decodeU32(buf[4:8]) m["dwChunkId"] = decodeU32(buf[8:12]) m["dwReserv...
identifier_body
parser.py
# ------------------------------------------------------------------------------ # # Project: pycql <https://github.com/geopython/pycql> # Authors: Fabian Schindler <fabian.schindler@eox.at> # # ------------------------------------------------------------------------------ # Copyright (C) 2019 EOX IT Services GmbH # # ...
elif p[2] in ("=", "<>", "<", "<=", ">", ">="): p[0] = ast.ComparisonPredicateNode(p[1], p[3], p[2]) else: not_ = False op = p[2] if op == 'NOT': not_ = True op = p[3] if op == "BETWEEN": p[0] ...
p[0] = p[1]
conditional_block
parser.py
# ------------------------------------------------------------------------------ # # Project: pycql <https://github.com/geopython/pycql> # Authors: Fabian Schindler <fabian.schindler@eox.at> # # ------------------------------------------------------------------------------ # Copyright (C) 2019 EOX IT Services GmbH # # ...
: def __init__(self, geometry_factory=values.Geometry, bbox_factory=values.BBox, time_factory=values.Time, duration_factory=values.Duration): self.lexer = CQLLexer( # lextab='ecql.lextab', # outputdir="ecql" geometry_factory, bbox_factory, ...
CQLParser
identifier_name
parser.py
# ------------------------------------------------------------------------------ # # Project: pycql <https://github.com/geopython/pycql> # Authors: Fabian Schindler <fabian.schindler@eox.at> # # ------------------------------------------------------------------------------ # Copyright (C) 2019 EOX IT Services GmbH # # ...
| BBOX LPAREN expression COMMA number COMMA number COMMA number COMMA number COMMA QUOTED RPAREN """ op = p[1] lhs = p[3] rhs = p[5] if op == "RELATE": p[0] = ast.SpatialPredicateNode(lhs, rhs, op, pattern=p[7]) elif op in ("DWIT...
| EQUALS LPAREN expression COMMA expression RPAREN | RELATE LPAREN expression COMMA expression COMMA QUOTED RPAREN | DWITHIN LPAREN expression COMMA expression COMMA number COMMA UNITS RPAREN | BEYOND...
random_line_split
parser.py
# ------------------------------------------------------------------------------ # # Project: pycql <https://github.com/geopython/pycql> # Authors: Fabian Schindler <fabian.schindler@eox.at> # # ------------------------------------------------------------------------------ # Copyright (C) 2019 EOX IT Services GmbH # # ...
def p_condition(self, p): """ condition : predicate | condition AND condition | condition OR condition | NOT condition | LPAREN condition RPAREN | LBRACKET condition RBRACKET """ ...
""" condition_or_empty : condition | empty """ p[0] = p[1]
identifier_body
driver.go
package ipfs import ( "bytes" "fmt" "io" "io/ioutil" _path "path" "runtime" "strings" "sync" "time" log "github.com/Sirupsen/logrus" "github.com/docker/distribution/context" storagedriver "github.com/docker/distribution/registry/storage/driver" "github.com/docker/distribution/registry/storage/driver/base...
// List returns a list of the objects that are direct descendants of the given // path. func (d *driver) List(ctx context.Context, path string) ([]string, error) { defer debugTime()() output, err := d.shell.FileList(d.fullPath(path)) if err != nil { if strings.HasPrefix(err.Error(), "no link named") { return ...
{ defer debugTime()() d.rootlock.Lock() defer d.rootlock.Unlock() output, err := d.shell.FileList(d.fullPath(path)) if err != nil { if strings.HasPrefix(err.Error(), "no link named") { return nil, storagedriver.PathNotFoundError{Path: path} } return nil, err } fi := storagedriver.FileInfoFields{ Pat...
identifier_body
driver.go
package ipfs import ( "bytes" "fmt" "io" "io/ioutil" _path "path" "runtime" "strings" "sync" "time" log "github.com/Sirupsen/logrus" "github.com/docker/distribution/context" storagedriver "github.com/docker/distribution/registry/storage/driver" "github.com/docker/distribution/registry/storage/driver/base...
() string { return driverName } // GetContent retrieves the content stored at "path" as a []byte. func (d *driver) GetContent(ctx context.Context, path string) ([]byte, error) { defer debugTime()() reader, err := d.shell.Cat(d.fullPath(path)) if err != nil { if strings.HasPrefix(err.Error(), "no link named") { ...
Name
identifier_name
driver.go
package ipfs import ( "bytes" "fmt" "io" "io/ioutil" _path "path" "runtime" "strings" "sync" "time" log "github.com/Sirupsen/logrus" "github.com/docker/distribution/context" storagedriver "github.com/docker/distribution/registry/storage/driver" "github.com/docker/distribution/registry/storage/driver/base...
if err != nil { log.Error("failed to get new empty dir: ", err) return nil } hash = h } d := &driver{ shell: shell, root: root, roothash: hash, } d.publish = d.runPublisher(info.ID) return &Driver{ baseEmbed: baseEmbed{ Base: base.Base{ StorageDriver: d, }, }, } } // Imp...
log.Error("failed to resolve docker-registry dir: ", err) return nil } h, err := shell.NewObject("unixfs-dir")
random_line_split
driver.go
package ipfs import ( "bytes" "fmt" "io" "io/ioutil" _path "path" "runtime" "strings" "sync" "time" log "github.com/Sirupsen/logrus" "github.com/docker/distribution/context" storagedriver "github.com/docker/distribution/registry/storage/driver" "github.com/docker/distribution/registry/storage/driver/base...
}() return out } func (d *driver) publishChild(ipnskey, dirname, hash string) error { val, err := d.shell.Resolve(ipnskey) if err != nil { return err } newIpnsRoot, err := d.shell.PatchLink(val, dirname, hash, true) if err != nil { return err } err = d.shell.Publish(ipnskey, "/ipfs/"+newIpnsRoot) if e...
{ select { case k := <-out: if topub == "" { long = time.After(time.Second * 5) short = time.After(time.Second * 1) } else { short = time.After(time.Second * 1) } topub = k case <-long: k := topub topub = "" long = nil short = nil err := d.publishChild(ipnske...
conditional_block
tracker.py
import random import socket import string import struct import asyncio import logging import time import ipaddress from collections import namedtuple from functools import reduce from typing import Optional from lbry.dht.node import get_kademlia_peers_from_hosts from lbry.utils import resolve_host, async_timed_cache, ...
def encode_peer(ip_address: str, port: int): compact_ip = reduce(lambda buff, x: buff + bytearray([int(x)]), ip_address.split('.'), bytearray()) return compact_ip + port.to_bytes(2, "big", signed=False)
req = decode(AnnounceRequest, data) if req.connection_id not in self.known_conns: resp = encode(ErrorResponse(3, req.transaction_id, b'Connection ID missmatch.\x00')) else: compact_address = encode_peer(addr[0], req.port) if req.event != 3: ...
conditional_block
tracker.py
import random import socket import string import struct import asyncio import logging import time import ipaddress from collections import namedtuple from functools import reduce from typing import Optional from lbry.dht.node import get_kademlia_peers_from_hosts from lbry.utils import resolve_host, async_timed_cache, ...
class UDPTrackerServerProtocol(asyncio.DatagramProtocol): # for testing. Not suitable for production def __init__(self): self.transport = None self.known_conns = set() self.peers = {} def connection_made(self, transport: asyncio.DatagramTransport) -> None: self.transport = t...
peers = [ (str(ipaddress.ip_address(peer.address)), peer.port) for announcement in announcements for peer in announcement.peers if peer.port > 1024 # no privileged or 0 ] return get_kademlia_peers_from_hosts(peers)
identifier_body
tracker.py
import random import socket import string import struct import asyncio import logging import time import ipaddress from collections import namedtuple from functools import reduce from typing import Optional from lbry.dht.node import get_kademlia_peers_from_hosts from lbry.utils import resolve_host, async_timed_cache, ...
info_hash for (info_hash, (next_announcement, _)) in self.results.get(tracker_ip, {}).items() if time.time() < next_announcement } results = await asyncio.gather( *[self._probe_server(info_hash, tracker_ip, server[1], stopped=stopped) for info_hash in in...
async def _announce_many(self, server, info_hashes, stopped=False): tracker_ip = await resolve_host(*server, 'udp') still_good_info_hashes = {
random_line_split
tracker.py
import random import socket import string import struct import asyncio import logging import time import ipaddress from collections import namedtuple from functools import reduce from typing import Optional from lbry.dht.node import get_kademlia_peers_from_hosts from lbry.utils import resolve_host, async_timed_cache, ...
(*announcements: AnnounceResponse): peers = [ (str(ipaddress.ip_address(peer.address)), peer.port) for announcement in announcements for peer in announcement.peers if peer.port > 1024 # no privileged or 0 ] return get_kademlia_peers_from_hosts(peers) class UDPTrackerServerProtocol(asyncio...
announcement_to_kademlia_peers
identifier_name
endpoints_calculator.go
/* Copyright 2020 The Kubernetes 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 in writing, so...
(_ []types.EndpointsData, currentMap map[string]types.NetworkEndpointSet) (map[string]types.NetworkEndpointSet, types.EndpointPodMap, error) { // this should be the same as CalculateEndpoints for L4 ec subsetMap, _, _, err := l.CalculateEndpoints(nil, currentMap) return subsetMap, nil, err } func (l *ClusterL4ILBEn...
CalculateEndpointsDegradedMode
identifier_name
endpoints_calculator.go
/* Copyright 2020 The Kubernetes 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 in writing, so...
} if countFromEndpointData != countFromPodMap { l.logger.Info("Detected error when comparing endpoint counts", "countFromEndpointData", countFromEndpointData, "countFromPodMap", countFromPodMap, "endpointData", endpointData, "endpointPodMap", endpointPodMap, "dupCount", dupCount) return fmt.Errorf("%w: Detect en...
if countFromEndpointData == 0 { l.logger.Info("Detected endpoint count from endpointData going to zero", "endpointData", endpointData) return fmt.Errorf("%w: Detect endpoint count goes to zero", types.ErrEPSEndpointCountZero)
random_line_split
endpoints_calculator.go
/* Copyright 2020 The Kubernetes 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 in writing, so...
func (l *LocalL4ILBEndpointsCalculator) ValidateEndpoints(endpointData []types.EndpointsData, endpointPodMap types.EndpointPodMap, dupCount int) error { // this should be a no-op for now return nil } // ClusterL4ILBEndpointGetter implements the NetworkEndpointsCalculator interface. // It exposes methods to calcula...
{ // this should be the same as CalculateEndpoints for L4 ec subsetMap, _, _, err := l.CalculateEndpoints(nil, currentMap) return subsetMap, nil, err }
identifier_body
endpoints_calculator.go
/* Copyright 2020 The Kubernetes 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 in writing, so...
} if numEndpoints == 0 { // Not having backends will cause clients to see connection timeout instead of an "ICMP ConnectionRefused". return nil, nil, 0, nil } // Compute the networkEndpoints, with total endpoints count <= l.subsetSizeLimit klog.V(2).Infof("Got zoneNodeMap as input for service", "zoneNodeMap",...
{ if addr.NodeName == nil { l.logger.V(2).Info("Address inside Endpoints does not have an associated node. Skipping", "address", addr.Addresses, "endpoints", klog.KRef(ed.Meta.Namespace, ed.Meta.Name)) continue } if addr.TargetRef == nil { l.logger.V(2).Info("Address inside Endpoints does not have ...
conditional_block
api.go
package php import ( "context" "encoding/json" "fmt" "log" "net/http" "net/url" "os" "path/filepath" "strconv" "sync/atomic" "time" radio "github.com/R-a-dio/valkyrie" "github.com/R-a-dio/valkyrie/config" "github.com/R-a-dio/valkyrie/errors" "github.com/R-a-dio/valkyrie/search" "github.com/R-a-dio/val...
submissionTime, err := a.storage.Submissions(r.Context()).LastSubmissionTime(identifier) if err != nil { // TODO: look at error handling log.Println(err) return } _, ok := radio.CalculateCooldown( time.Duration(a.Conf().UserUploadDelay), submissionTime, ) response := userCooldownResponse{ Cooldown: ...
random_line_split
api.go
package php import ( "context" "encoding/json" "fmt" "log" "net/http" "net/url" "os" "path/filepath" "strconv" "sync/atomic" "time" radio "github.com/R-a-dio/valkyrie" "github.com/R-a-dio/valkyrie/config" "github.com/R-a-dio/valkyrie/errors" "github.com/R-a-dio/valkyrie/search" "github.com/R-a-dio/val...
func (a *API) getSong(w http.ResponseWriter, r *http.Request) { http.Error(w, http.StatusText(410), 410) } func (a *API) getMetadata(w http.ResponseWriter, r *http.Request) { http.Error(w, http.StatusText(410), 410) } func (a *API) getUserCooldown(w http.ResponseWriter, r *http.Request) { identifier := r.RemoteA...
{ r := chi.NewRouter() r.Use(chiware.SetHeader("Content-Type", "application/json")) r.Method("GET", "/", a.status) r.Get("/ping", func(w http.ResponseWriter, _ *http.Request) { w.Write([]byte(`{"ping":true}`)) }) r.Get("/user-cooldown", a.getUserCooldown) r.Get("/news", a.getNews) r.Get("/search/{query}", a....
identifier_body
api.go
package php import ( "context" "encoding/json" "fmt" "log" "net/http" "net/url" "os" "path/filepath" "strconv" "sync/atomic" "time" radio "github.com/R-a-dio/valkyrie" "github.com/R-a-dio/valkyrie/config" "github.com/R-a-dio/valkyrie/errors" "github.com/R-a-dio/valkyrie/search" "github.com/R-a-dio/val...
(w http.ResponseWriter, r *http.Request) { status, err := a.manager.Status(r.Context()) if err != nil { return } response := canRequestResponse{} // send our response when we return defer func() { // but not if an error occured if err != nil { // TODO: handle error http.Error(w, http.StatusText(501)...
getCanRequest
identifier_name
api.go
package php import ( "context" "encoding/json" "fmt" "log" "net/http" "net/url" "os" "path/filepath" "strconv" "sync/atomic" "time" radio "github.com/R-a-dio/valkyrie" "github.com/R-a-dio/valkyrie/config" "github.com/R-a-dio/valkyrie/errors" "github.com/R-a-dio/valkyrie/search" "github.com/R-a-dio/val...
response.Main.Requests = true return } type canRequestResponse struct { Main struct { Requests bool `json:"requests"` } } func (a *API) getDJImage(w http.ResponseWriter, r *http.Request) { ctx := r.Context() w.Header().Del("Content-Type") w.Header().Set("Content-Type", "image/png") user, ok := ctx.Value...
{ return }
conditional_block
assets.responsive.js
/************************************************************************* Namespaced method to use in conjunction with responsive methods. **************************************************************************/ var A11yResp = { Core: function() { //Set responsive indicator in body var...
var context = this, args = arguments; var later = function() { timeout = null; if (!immediate) func.apply(context, args); }; var callNow = immediate && !timeout; clearTimeout(timeout); timeout...
}, debounce: function(func, wait, immediate) { var timeout; return function() {
random_line_split
assets.responsive.js
/************************************************************************* Namespaced method to use in conjunction with responsive methods. **************************************************************************/ var A11yResp = { Core: function() { //Set responsive indicator in body var...
// Make the links expand collapse if the parent menu contains more than 1 link if ($(jPMmenu).find('> li ul > li').length > 1) { $('#jPanelMenu-menu > li > a') .wrapInner('<span>') .attr('href', 'javascript:void(...
{ // Remove jquery ui stuff $('#jPanelMenu-menu li').removeClass('ui-menu-item'); $('#jPanelMenu-menu li a').removeAttr('id aria-haspopup').removeClass('ui-corner-all'); $('#jPanelMenu-menu .submenu-separator-container, #jPanelMenu-menu...
conditional_block
table_1.py
from datetime import date import numpy as np from os import mkdir import pandas as pd import xarray as xr import xlsxwriter from db_queries import (get_covariate_estimates, get_location_metadata, get_population) from fbd_core import argparse, YearRange from fbd_core.etl import expand_dimensions...
Worksheet to which the data is written. curr_row (int): Starting row number for the header. cols (list): List of characters representing the columns. data_cols (pandas series): Columns to be written. header_format(xlsxwriter Format object):...
worksheet (Worksheet object):
random_line_split
table_1.py
from datetime import date import numpy as np from os import mkdir import pandas as pd import xarray as xr import xlsxwriter from db_queries import (get_covariate_estimates, get_location_metadata, get_population) from fbd_core import argparse, YearRange from fbd_core.etl import expand_dimensions...
(df): """Melts GBD data with 'mean', 'lower', and 'upper' columns to a single 'quantile' column; converts to xarray dataarray; and adds a scenario dimension. Args: df (pandas dataframe): Dataframe with 'year_id', 'location_id', 'mean', 'lower', and 'upper' columns. ...
melt_to_xarray
identifier_name
table_1.py
from datetime import date import numpy as np from os import mkdir import pandas as pd import xarray as xr import xlsxwriter from db_queries import (get_covariate_estimates, get_location_metadata, get_population) from fbd_core import argparse, YearRange from fbd_core.etl import expand_dimensions...
def pull_reshape_tfr(gbd_round_id, tfr_version, location_ids): """Pulls year 2017 GBD round 5 TFR, converts it an xarray dataarray, pulls forecast TFR, and concatenates the dataarrays. The new array is then converted to a pandas dataframe. All required data are then reshaped and merged for downstream...
"""Pulls year 2017 GBD round 5 populations, converts it an xarray dataarray, pulls forecast population, and concatenates the dataarrays. The new array is then converted to a pandas dataframe. Peak population and peak population year are pulled for each location in the dataframe. All required data are th...
identifier_body
table_1.py
from datetime import date import numpy as np from os import mkdir import pandas as pd import xarray as xr import xlsxwriter from db_queries import (get_covariate_estimates, get_location_metadata, get_population) from fbd_core import argparse, YearRange from fbd_core.etl import expand_dimensions...
else: worksheet.merge_range(row_range, row[col], data_fmt_obj) col_idx += 1 curr_row = end_row+1 worksheet.set_h_pagebreaks(page_breaks[1:]) worksheet.fit_to_pages(1, 0) workbook.close() if __name__ == "__main__": parser = argparse.ArgumentParser( ...
loc_name = INDENT_MAP[row["level"]] + row[col] worksheet.merge_range(row_range, loc_name, loc_fmt_obj)
conditional_block
response.rs
// rust imports use std::io::Read; use std::ffi::OsStr; use std::path::{PathBuf, Path}; use std::fs::{self, File}; use std::collections::HashMap; // 3rd-party imports use rusqlite::Connection; use rusqlite::types::ToSql; use hyper::http::h1::HttpReader; use hyper::buffer::BufReader; use hyper::net::NetworkStream; u...
() -> Self { ExpenseTracker(HashMap::new()) } fn add(&mut self, date: NaiveDate, expenses: f64) { let month = match date.month() { 1 => Month::January, 2 => Month::February, 3 => Month::March, 4 => Month::April, 5 => Month::May, ...
new
identifier_name