file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
12.1k
suffix
large_stringlengths
0
12k
middle
large_stringlengths
0
7.51k
fim_type
large_stringclasses
4 values
normalizeFiles.py
#!/usr/bin/python # -*- coding: UTF-8 -*- # Normalize soundfiles in a folder, and write them to a new folder # called normalized/ # Import Python modules import contextlib import os import shutil import sys import wave # Import user modules def normalize(): """ Normalizes a set of sound files to norm-To dB return ...
information. argValues ---> a list of the scripts command-line parameters. """ return 1 # Check that the input parameters are valid. Get the name of the folder # that contains the sound files and the sort type from the command-line # arguments. argValues = sys.argv inputCheck(argValues) folderToSort = argValues[...
def inputCheck(argValues): """ Check whether the input data is valid. If not print usage
random_line_split
test_attach.py
# encoding: utf-8 ''' Tests for various attachment thingies Created on Oct 21, 2013 @author: pupssman ''' import pytest from hamcrest import has_entries, assert_that, is_, contains, has_property from allure.constants import AttachmentType from allure.utils import all_of @pytest.mark.parametrize('package', ['pytes...
def test_unicode(self, attach_contents): assert_that(attach_contents(u'ололо пыщьпыщь').decode('utf-8'), is_(u'ололо пыщьпыщь')) def test_broken_unicode(self, attach_contents): assert_that(attach_contents(u'ололо пыщьпыщь'.encode('cp1251')), is_(u'ололо пыщьпыщь'.encode('cp1251'))) def test_...
@pytest.fixture def attach_contents(self, report_for, reportdir): """ Fixture that returns contents of the attachment file for given attach body """ def impl(body): report = report_for(""" from pytest import allure as A def test_x(): ...
identifier_body
test_attach.py
# encoding: utf-8 ''' Tests for various attachment thingies Created on Oct 21, 2013 @author: pupssman ''' import pytest from hamcrest import has_entries, assert_that, is_, contains, has_property from allure.constants import AttachmentType from allure.utils import all_of @pytest.mark.parametrize('package', ['pytes...
import pytest @pytest.yield_fixture(scope='function') def myfix(): yield pytest.allure.attach('Foo', 'Bar') def test_x(myfix): assert True """) assert_that(report.find('.//attachment').attrib, has_entries(title='Foo'))
""" report = report_for("""
random_line_split
test_attach.py
# encoding: utf-8 ''' Tests for various attachment thingies Created on Oct 21, 2013 @author: pupssman ''' import pytest from hamcrest import has_entries, assert_that, is_, contains, has_property from allure.constants import AttachmentType from allure.utils import all_of @pytest.mark.parametrize('package', ['pytes...
(self, attach_contents): assert_that(attach_contents(u'ололо пыщьпыщь').decode('utf-8'), is_(u'ололо пыщьпыщь')) def test_broken_unicode(self, attach_contents): assert_that(attach_contents(u'ололо пыщьпыщь'.encode('cp1251')), is_(u'ололо пыщьпыщь'.encode('cp1251'))) def test_attach_in_fixture_tea...
test_unicode
identifier_name
convert-csv-to-json.py
# coding=utf-8 #Converts a csv contining country codes and numerical values, to json #Years should be given in the header, like this: # # land, 1980, 1981, 1982 # se, 12, 13, 11 # fi 7, 10, 14 import csv import json import argparse import os.path import sys import math #Check if file exists def is_...
#Check if values are years def isYear(s): try: float(s) if 4 is len(s): return True else: return False except ValueError: return False #Define command line arguments parser = argparse.ArgumentParser(description='Converts a csv contining country codes and numerical values, to json.') #Input file par...
return int(str(round(float(s),d))[:-2])
conditional_block
convert-csv-to-json.py
# coding=utf-8 #Converts a csv contining country codes and numerical values, to json #Years should be given in the header, like this: # # land, 1980, 1981, 1982 # se, 12, 13, 11 # fi 7, 10, 14 import csv import json import argparse import os.path import sys import math #Check if file exists def is_...
#Define command line arguments parser = argparse.ArgumentParser(description='Converts a csv contining country codes and numerical values, to json.') #Input file parser.add_argument("-i", "--input", dest="infile", required=True, help="input file", metavar="FILE", type=lambda x: is_valid_file(parser,x)) #Outp...
try: float(s) if 4 is len(s): return True else: return False except ValueError: return False
identifier_body
convert-csv-to-json.py
# coding=utf-8 #Converts a csv contining country codes and numerical values, to json #Years should be given in the header, like this: # # land, 1980, 1981, 1982 # se, 12, 13, 11 # fi 7, 10, 14 import csv import json import argparse import os.path import sys import math #Check if file exists def is_...
print "Writing %s..." % outputFile with open(outputFile, 'w') as outfile: json.dump(outdata, outfile) print "done"
except IOError: print ("Could not open input file")
random_line_split
convert-csv-to-json.py
# coding=utf-8 #Converts a csv contining country codes and numerical values, to json #Years should be given in the header, like this: # # land, 1980, 1981, 1982 # se, 12, 13, 11 # fi 7, 10, 14 import csv import json import argparse import os.path import sys import math #Check if file exists def
(parser, arg): if not os.path.exists(arg): parser.error("The file %s does not exist!" % arg) else: return arg #Check if values are numbers, for our purposes def is_number(s): try: float(s) return True except ValueError: return False def doRounding(s,d): i...
is_valid_file
identifier_name
index.d.ts
// Type definitions for easy-jsend // Project: https://github.com/DeadAlready/easy-jsend // Definitions by: Karl Düüna <https://github.com/DeadAlready/> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare namespace Express { interface MakePartialInput { model:any; opts: { ...
partial? (data: PartialInput, status?: number): void; makePartial? (data: MakePartialInput): void; } } declare module "easy-jsend" { export function init(conf?:{partial:boolean}): void; }
fail (data: any, status?: number): void; error (err: any, status?: number): void;
random_line_split
list_issues.rs
extern crate gitlab_api as gitlab; use std::env; #[macro_use] extern crate log; extern crate env_logger; use gitlab::GitLab; // use gitlab::Pagination; use gitlab::issues; use gitlab::Lister; use gitlab::errors::*; fn main() { if let Err(ref e) = run() { println!("error: {}", e); for e in e.it...
} }; let gl = GitLab::new(&hostname, &token).chain_err(|| "failure to create GitLab instance")?; // let gl = GitLab::new(&hostname, &token) // .chain_err(|| "failure to create GitLab instance")? // .scheme("http").port(80); // let gl = gl.scheme("http").port(80); let issues...
{ env_logger::init().unwrap(); info!("starting up"); let hostname = match env::var("GITLAB_HOSTNAME") { Ok(val) => val, Err(_) => { let default = String::from("gitlab.com"); println!("Please set environment variable 'GITLAB_HOSTNAME'. Using default '{}'.", ...
identifier_body
list_issues.rs
extern crate gitlab_api as gitlab; use std::env; #[macro_use] extern crate log; extern crate env_logger; use gitlab::GitLab; // use gitlab::Pagination; use gitlab::issues; use gitlab::Lister; use gitlab::errors::*; fn
() { if let Err(ref e) = run() { println!("error: {}", e); for e in e.iter().skip(1) { println!("caused by: {}", e); } // The backtrace is not always generated. Try to run this example // with `RUST_BACKTRACE=1`. if let Some(backtrace) = e.backtrace() { ...
main
identifier_name
list_issues.rs
extern crate gitlab_api as gitlab; use std::env; #[macro_use] extern crate log; extern crate env_logger; use gitlab::GitLab; // use gitlab::Pagination; use gitlab::issues; use gitlab::Lister; use gitlab::errors::*; fn main() { if let Err(ref e) = run() { println!("error: {}", e); for e in e.it...
let hostname = match env::var("GITLAB_HOSTNAME") { Ok(val) => val, Err(_) => { let default = String::from("gitlab.com"); println!("Please set environment variable 'GITLAB_HOSTNAME'. Using default '{}'.", default); default } }; ...
info!("starting up");
random_line_split
course.py
# -*- coding: utf-8 -*- from __future__ import print_function, unicode_literals import requests from bs4 import BeautifulSoup import re import six from libulb.tools import Slug class Course: def __init__(self, slug, year, infos): self.slug = slug self.year = year self._fill(infos) ...
def _fill(self, d): self.name = d["Intitulé de l'unité d'enseignement"] language = d.get("Langue d'enseignement", None) if "français" in language: self.language = "french" elif "anglais" in language: self.language = "english" elif "néerlandais" in la...
rl = "http://banssbfr.ulb.ac.be/PROD_frFR/bzscrse.p_disp_course_detail" params = { 'cat_term_in': year, 'subj_code_in': slug.domain.upper(), 'crse_numb_in': slug.faculty.upper() + slug.number.upper(), } return requests.get(url, params=params)
identifier_body
course.py
# -*- coding: utf-8 -*- from __future__ import print_function, unicode_literals import requests from bs4 import BeautifulSoup import re import six from libulb.tools import Slug class Course: def __init__(self, slug, year, infos): self.slug = slug self.year = year self._fill(infos) ...
self.requirements = d.get("Connaissances et compétences pré-requises", None) self.sections = [] sections_str = d.get("Programme(s) d'études comprenant l'unité d'enseignement", None) # import ipdb; ipdb.set_trace() if sections_str is not None and sections_str.strip() != "": ...
f in prof_str.split(','): prof = prof.replace("(coordonnateur)", "") prof = prof.strip() prof = prof.title() self.profs.append(prof)
conditional_block
course.py
# -*- coding: utf-8 -*- from __future__ import print_function, unicode_literals import requests from bs4 import BeautifulSoup import re import six from libulb.tools import Slug class Course: def __init__(self, slug, year, infos): self.slug = slug self.year = year self._fill(infos) ...
if not response.ok: raise Exception("Error with ulb") soup = BeautifulSoup(response.text, "html.parser") table = soup.find('table', 'bordertable') tr_list = table('tr') infos = {} for line in tr_list: if len(line('td')) != 2: co...
random_line_split
course.py
# -*- coding: utf-8 -*- from __future__ import print_function, unicode_literals import requests from bs4 import BeautifulSoup import re import six from libulb.tools import Slug class Course: def __init__(self, slug, year, infos): self.slug = slug self.year = year self._fill(infos) ...
cls, slug, year): slug = Slug.match_all(slug) response = cls._query_ulb(year, slug) if not response.ok: raise Exception("Error with ulb") soup = BeautifulSoup(response.text, "html.parser") table = soup.find('table', 'bordertable') tr_list = table('tr') ...
et_from_slug(
identifier_name
jobs.component.ts
import { Component, OnInit, OnDestroy } from '@angular/core'; import { Router } from '@angular/router'; import { Subscription, Subject } from 'rxjs'; import { Page } from '../../shared/model'; import { JobsService } from '../jobs.service'; import { JobExecution } from '../model/job-execution.model'; import { takeUntil ...
(item: JobExecution) { const title = `Confirm restart the job execution`; const description = `This action will restart the steps failed of the ` + `<strong>job execution ${item.name} (${item.jobExecutionId})</strong>. Are you sure?`; this.confirmService.open(title, description, { confirm: 'Restart' ...
restartJob
identifier_name
jobs.component.ts
import { Component, OnInit, OnDestroy } from '@angular/core'; import { Router } from '@angular/router'; import { Subscription, Subject } from 'rxjs'; import { Page } from '../../shared/model'; import { JobsService } from '../jobs.service'; import { JobExecution } from '../model/job-execution.model'; import { takeUntil ...
* * @param {JobsService} jobsService * @param {NotificationService} notificationService * @param {ConfirmService} confirmService * @param {LoggerService} loggerService * @param {Router} router * @param {GrafanaService0} grafanaService */ constructor(private jobsService: JobsService, ...
/** * Constructor
random_line_split
jobs.component.ts
import { Component, OnInit, OnDestroy } from '@angular/core'; import { Router } from '@angular/router'; import { Subscription, Subject } from 'rxjs'; import { Page } from '../../shared/model'; import { JobsService } from '../jobs.service'; import { JobExecution } from '../model/job-execution.model'; import { takeUntil ...
this.jobExecutions = page; // this.changeCheckboxes(); this.updateContext(); }, error => { this.notificationService.error(error); }); } /** * Refresh action */ refresh() { this.loadJobExecutions(); } /** * Update event from the Paginator Pager * @...
{ this.params.page = 0; this.loadJobExecutions(); return; }
conditional_block
jobs.component.ts
import { Component, OnInit, OnDestroy } from '@angular/core'; import { Router } from '@angular/router'; import { Subscription, Subject } from 'rxjs'; import { Page } from '../../shared/model'; import { JobsService } from '../jobs.service'; import { JobExecution } from '../model/job-execution.model'; import { takeUntil ...
/** * Refresh action */ refresh() { this.loadJobExecutions(); } /** * Update event from the Paginator Pager * @param params */ changePaginationPager(params) { this.params.page = params.page; this.params.size = params.size; this.updateContext(); this.loadJobExecutions(); ...
{ this.jobsService.getJobExecutions(this.params) .pipe(takeUntil(this.ngUnsubscribe$)) .subscribe(page => { if (page.items.length === 0 && this.params.page > 0) { this.params.page = 0; this.loadJobExecutions(); return; } this.jobExecutions = page; ...
identifier_body
table.rs
_values::table_layout; use geom::{Point2D, Rect, Size2D}; use gfx::display_list::DisplayListCollection; use servo_util::geometry::Au; /// A table flow corresponded to the table's internal table box under a table wrapper flow. /// The properties `position`, `float`, and `margin-*` are used on the table wrapper box, ///...
TableFlow { block_flow: block_flow, col_widths: ~[], table_layout: table_layout } } pub fn teardown(&mut self) { self.block_flow.teardown(); self.col_widths = ~[]; } /// Assign height for table flow. /// /// inline(always) be...
AutoLayout };
conditional_block
table.rs
_values::table_layout; use geom::{Point2D, Rect, Size2D}; use gfx::display_list::DisplayListCollection; use servo_util::geometry::Au; /// A table flow corresponded to the table's internal table box under a table wrapper flow. /// The properties `position`, `float`, and `margin-*` are used on the table wrapper box, ///...
pub fn teardown(&mut self) { self.block_flow.teardown(); self.col_widths = ~[]; } /// Assign height for table flow. /// /// inline(always) because this is only ever called by in-order or non-in-order top-level /// methods #[inline(always)] fn assign_height_table_base(&m...
let mut block_flow = BlockFlow::float_from_node(constructor, node, float_kind); let table_layout = if block_flow.box_().style().Table.get().table_layout == table_layout::fixed { FixedLayout } else { AutoLayout }; TableFlow { ...
identifier_body
table.rs
_values::table_layout; use geom::{Point2D, Rect, Size2D}; use gfx::display_list::DisplayListCollection; use servo_util::geometry::Au; /// A table flow corresponded to the table's internal table box under a table wrapper flow. /// The properties `position`, `float`, and `margin-*` are used on the table wrapper box, ///...
constructor: &mut FlowConstructor, node: &ThreadSafeLayoutNode, float_kind: FloatKind) -> TableFlow { let mut block_flow = BlockFlow::float_from_node(constructor, node, float_kind); let table_layout = if block_flow.box_().s...
loat_from_node(
identifier_name
table.rs
computed_values::table_layout; use geom::{Point2D, Rect, Size2D}; use gfx::display_list::DisplayListCollection; use servo_util::geometry::Au; /// A table flow corresponded to the table's internal table box under a table wrapper flow. /// The properties `position`, `float`, and `margin-*` are used on the table wrapper ...
/// Column widths col_widths: ~[Au], /// Table-layout property table_layout: TableLayout, } impl TableFlow { pub fn from_node_and_box(node: &ThreadSafeLayoutNode, box_: Box) -> TableFlow { let mut block_flow = BlockFlow::from_node_a...
random_line_split
bokeh-magma-7.js
forEach(function (attribute) { characterAttributes[attribute] = styleAttributes[attribute]; }); charStyles[style.name] = characterStyle; }); // Removes default swatches and swatch groups created by Illustrator. removeAllSwatchGroups(); removeAllSwatches(); // Creates and adds swatch groups and swatches. buil...
/** * Returns an array of unique group names. * * @param {Array} colors * @returns {Array) */ function getColorGroups(colors) { var colorGroups = []; colors.forEach(function (color) { if (colorGroups.indexOf(color.group) < 0) { colorGroups.push(color.group); } }); return colorGroups; } ...
{ var layer = doc.layers[0]; var rect = layer.pathItems.rectangle(top, left, width, height); rect.filled = true; rect.fillColor = color; rect.stroked = false; var textBounds = layer.pathItems.rectangle(top - height * config.swatchRect.textPosition, left + width * config.swatchRect.textPosition, width * (1...
identifier_body
bokeh-magma-7.js
forEach(function (attribute) { characterAttributes[attribute] = styleAttributes[attribute]; }); charStyles[style.name] = characterStyle; }); // Removes default swatches and swatch groups created by Illustrator. removeAllSwatchGroups(); removeAllSwatches(); // Creates and adds swatch groups and swatches. buil...
(name, color) { var swatch = doc.swatches.add(); swatch.color = color; swatch.name = name; return swatch; } /** * Removes all swatches. */ function removeAllSwatches() { for (var i = 0; i < doc.swatches.length; i++) { doc.swatches[i].remove(); } } /** * Removes all swatch groups. */ function remo...
addSwatch
identifier_name
bokeh-magma-7.js
).forEach(function (attribute) { characterAttributes[attribute] = styleAttributes[attribute]; }); charStyles[style.name] = characterStyle; }); // Removes default swatches and swatch groups created by Illustrator. removeAllSwatchGroups(); removeAllSwatches(); // Creates and adds swatch groups and swatches. bu...
doc.swatches[i].remove(); } } /** * Removes all swatch groups. */ function removeAllSwatchGroups() { for (var i = 0; i < doc.swatchGroups.length; i++) { doc.swatchGroups[i].remove(); } } /** * Draws rectangle on artboard. * * @param {Number} top * @param {Number} left * @param {Number} widt...
for (var i = 0; i < doc.swatches.length; i++) {
random_line_split
api.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ export enum UpdateCacheStatus { NOT_CACHED, CACHED_BUT_UNUSED, CACHED, } /** * A source for old versions of ...
* Lookup an older version of a resource for which the hash is not known. * * This will return the most recent previous version of the resource, if * it exists. It returns a `CacheState` object which encodes not only the * `Response`, but the cache metadata needed to re-cache the resource in * a newer ...
* not match the hash given, this returns null. */ lookupResourceWithHash(url: string, hash: string): Promise<Response|null>; /**
random_line_split
ColorDefinitionDlg.py
# # Copyright 2001 - 2016 Ludek Smid [http://www.ospace.net/] # # This file is part of Outer Space. # # Outer Space is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (...
def onChangeRed(self, widget, action, data): self.color = (int(self.win.vRS.slider.position), self.color[1], self.color[2]) self.win.vR.text = hex(self.color[0]) self.win.vColor.color = (int(self.win.vRS.slider.position), self.color[1], self.color[2]) def onChangeGreen(self, widget, ...
self.show()
identifier_body
ColorDefinitionDlg.py
# # Copyright 2001 - 2016 Ludek Smid [http://www.ospace.net/] # # This file is part of Outer Space. # # Outer Space is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (...
(self): w, h = gdata.scrnSize cols = 14 rows = 8 width = cols * 20 + 5 height = rows * 20 + 4 self.win = ui.Window(self.app, modal = 1, escKeyClose = 1, movable = 0, title = _('Color Definition'), rect = ui.Rect(...
createUI
identifier_name
ColorDefinitionDlg.py
# # Copyright 2001 - 2016 Ludek Smid [http://www.ospace.net/] # # This file is part of Outer Space. # # Outer Space is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (...
def hide(self): self.win.setStatus(_("Ready.")) self.win.hide() # unregister updates if self in gdata.updateDlgs: gdata.updateDlgs.remove(self) def update(self): self.show() def onChangeRed(self, widget, action, data): self.color = (int(self.wi...
gdata.updateDlgs.append(self)
conditional_block
ColorDefinitionDlg.py
# # Copyright 2001 - 2016 Ludek Smid [http://www.ospace.net/] # # This file is part of Outer Space. # # Outer Space is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (...
self.color = (self.color[0], int(self.win.vGS.slider.position), self.color[2]) self.win.vG.text = hex(self.color[1]) self.win.vColor.color = (self.color[0], int(self.win.vGS.slider.position), self.color[2]) def onChangeBlue(self, widget, action, data): self.color = ( self.color[0], ...
self.win.vColor.color = (int(self.win.vRS.slider.position), self.color[1], self.color[2]) def onChangeGreen(self, widget, action, data):
random_line_split
EventController.py
# -*- coding: utf-8 -*- from datetime import datetime from datetime import date from datetime import timedelta import re import Entity.User as User import Entity.Event as Event import Entity.RepeatingEvent as RepeatingEvent import Responder def createSingleEvent(name, place, date): event = Event.getByDate(date) ...
user, additional): rep = RepeatingEvent.get(int(additional.split()[0])) events = Event.getByRepeating(rep.key) i = 0 for event in events: event.date = event.date + timedelta(minutes=int(additional.split()[1])) event.put() i = i +1 return str(i) + ' events updated' def create...
pdateRepeating(
identifier_name
EventController.py
# -*- coding: utf-8 -*- from datetime import datetime from datetime import date from datetime import timedelta import re import Entity.User as User import Entity.Event as Event import Entity.RepeatingEvent as RepeatingEvent import Responder def createSingleEvent(name, place, date): event = Event.getByDate(date) ...
date = datetime.strptime(dateOrDayString, "%d.%m.%Y").date() return createSingleEvent(name, place, datetime.combine(date, time)) except ValueError as err: try: if dateOrDayString: dateOrDayString = dateOrDayString.lower() day = Event.DAY_DICT[dateOrDay...
f not additional: return u'Um ein Event zu erstellen müssen entsprechende Angaben gemacht werden: Name;[Ort];Datum/Tag;Zeit;[EndDatum])' split = additional.split(';') if (len(split) != 4) and (len(split) != 5): return u'Anzahl der Argumente ist Falsch! Es müssen 4 oder 5 sein. (erstelle Name;[O...
identifier_body
EventController.py
# -*- coding: utf-8 -*- from datetime import datetime from datetime import date from datetime import timedelta import re import Entity.User as User import Entity.Event as Event import Entity.RepeatingEvent as RepeatingEvent import Responder def createSingleEvent(name, place, date): event = Event.getByDate(date) ...
answer = u'Events an diesen Daten erstellt:' for created in events[0]: answer = answer + u'\n' + created.strftime("%d.%m.%Y") if events[1]: answer = answer + u'\nFolgende Daten übersprungen, da an diesen schon ein Event existiert:' for skipped in events[1]: answer = answe...
events = rep.createEvents()
random_line_split
EventController.py
# -*- coding: utf-8 -*- from datetime import datetime from datetime import date from datetime import timedelta import re import Entity.User as User import Entity.Event as Event import Entity.RepeatingEvent as RepeatingEvent import Responder def createSingleEvent(name, place, date): event = Event.getByDate(date) ...
return answer def updateRepeating(user, additional): rep = RepeatingEvent.get(int(additional.split()[0])) events = Event.getByRepeating(rep.key) i = 0 for event in events: event.date = event.date + timedelta(minutes=int(additional.split()[1])) event.put() i = i +1 return...
nswer = answer + u'\n' + skipped.strftime("%d.%m.%Y")
conditional_block
implementation.js
'use strict'; var CreateDataProperty = require('es-abstract/2019/CreateDataProperty'); var IsCallable = require('es-abstract/2019/IsCallable'); var RequireObjectCoercible = require('es-abstract/2019/RequireObjectCoercible'); var ToObject = require('es-abstract/2019/ToObject'); var callBound = require('es-abstract/help...
return acc; }, {} ); };
{ CreateDataProperty(acc, key, descriptor); }
conditional_block
implementation.js
'use strict'; var CreateDataProperty = require('es-abstract/2019/CreateDataProperty'); var IsCallable = require('es-abstract/2019/IsCallable'); var RequireObjectCoercible = require('es-abstract/2019/RequireObjectCoercible'); var ToObject = require('es-abstract/2019/ToObject'); var callBound = require('es-abstract/help...
return $reduce( getAll(O), function (acc, key) { var descriptor = $gOPD(O, key); if (typeof descriptor !== 'undefined') { CreateDataProperty(acc, key, descriptor); } return acc; }, {} ); };
random_line_split
instance.rs
use std::io::{self, BufRead, BufReader, ErrorKind, Result}; use std::net::TcpStream; use std::process::{Child, Command, Stdio}; use std::sync::mpsc::{channel, Receiver, Sender, TryRecvError}; use std::sync::Arc; use std::thread::{self, JoinHandle}; use std::time::Duration; use avro_rs::{from_value, Reader, Schema, Wri...
{ request: Request, response: Option<Response>, } #[derive(Debug)] struct InstanceContext { stream: TcpStream, receiver: Receiver<Arc<InstanceMessage>>, } impl Instance { pub fn new(config: InstanceConfig) -> Result<Instance> { let mut child = Command::new(&config.command) .st...
InstanceMessage
identifier_name
instance.rs
use std::io::{self, BufRead, BufReader, ErrorKind, Result}; use std::net::TcpStream; use std::process::{Child, Command, Stdio}; use std::sync::mpsc::{channel, Receiver, Sender, TryRecvError}; use std::sync::Arc; use std::thread::{self, JoinHandle};
use super::config::InstanceConfig; use super::request::Request; use super::response::Response; fn initial_connect(child: &mut Child) -> Result<TcpStream> { let child_stdout = child .stdout .as_mut() .expect("Failed to retrieve child stdout"); let mut reader = BufReader::new(child_stdou...
use std::time::Duration; use avro_rs::{from_value, Reader, Schema, Writer};
random_line_split
app.js
'use strict'; /* jshint node: true */ var logger = require('nlogger').logger(module); var express = require('express'); var _ = require('underscore'); var config = require('./config'); var poller = require('./poller'); var app = module.exports = express.createServer(); var reports = {}; function reapOldReports()
poller.emitter.on('report', function(report) { var key = report.host + ':' + report.port; reports[key] = report; }); app.configure(function() { app.use(express.bodyParser()); app.use(express.methodOverride()); app.use(app.router); app.use(express.static(__dirname + '/pages', { maxAge: 60*60*1000 ...
{ logger.info('starting reap cycle on reports: ', _.keys(reports).length); _.each(_.keys(reports), function(key) { var report = reports[key]; var age = Math.round(((new Date()).getTime() - report.reported)/1000); if (age >= config.reapAge) { logger.info('reaping stale report for: {}:{}', report.ho...
identifier_body
app.js
'use strict'; /* jshint node: true */ var logger = require('nlogger').logger(module); var express = require('express'); var _ = require('underscore'); var config = require('./config'); var poller = require('./poller'); var app = module.exports = express.createServer(); var reports = {}; function reapOldReports() {...
}); } poller.emitter.on('report', function(report) { var key = report.host + ':' + report.port; reports[key] = report; }); app.configure(function() { app.use(express.bodyParser()); app.use(express.methodOverride()); app.use(app.router); app.use(express.static(__dirname + '/pages', { maxAge: 60*...
{ logger.info('reaping stale report for: {}:{}', report.host, report.port); delete reports[key]; }
conditional_block
app.js
'use strict'; /* jshint node: true */ var logger = require('nlogger').logger(module); var express = require('express'); var _ = require('underscore'); var config = require('./config'); var poller = require('./poller'); var app = module.exports = express.createServer(); var reports = {}; function
() { logger.info('starting reap cycle on reports: ', _.keys(reports).length); _.each(_.keys(reports), function(key) { var report = reports[key]; var age = Math.round(((new Date()).getTime() - report.reported)/1000); if (age >= config.reapAge) { logger.info('reaping stale report for: {}:{}', report...
reapOldReports
identifier_name
app.js
'use strict'; /* jshint node: true */ var logger = require('nlogger').logger(module); var express = require('express'); var _ = require('underscore'); var config = require('./config'); var poller = require('./poller'); var app = module.exports = express.createServer(); var reports = {}; function reapOldReports() {...
}); app.configure(function() { app.use(express.bodyParser()); app.use(express.methodOverride()); app.use(app.router); app.use(express.static(__dirname + '/pages', { maxAge: 60*60*1000 })); app.use(express.static(__dirname + '/static', { maxAge: 3*24*60*60*1000 })); app.use(express.compress()); ...
poller.emitter.on('report', function(report) { var key = report.host + ':' + report.port; reports[key] = report;
random_line_split
test_short_term_loss_prestress_01.py
# -*- coding: utf-8 -*- from __future__ import division '''Test for checking variation of initial prestress force along a post-tensioned member. Data and rough calculation are taken from Example 4.3 of the topic 4 of course "Prestressed Concrete Design (SAB 4323) by Baderul Hisham Ahmad ocw.utm.my Problem stateme...
print "test ",fname,": ok." else: lmsg.error(fname+' ERROR.')
fname= os.path.basename(__file__) if (ratio1<5.e-3 and ratio2<5.e-4 and ratio3<5.e-3):
random_line_split
test_short_term_loss_prestress_01.py
# -*- coding: utf-8 -*- from __future__ import division '''Test for checking variation of initial prestress force along a post-tensioned member. Data and rough calculation are taken from Example 4.3 of the topic 4 of course "Prestressed Concrete Design (SAB 4323) by Baderul Hisham Ahmad ocw.utm.my Problem stateme...
fname+' ERROR.')
conditional_block
ThumbDownOffAltRounded.js
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", {
exports.default = void 0; var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon")); var _jsxRuntime = require("react/jsx-runtime"); var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", { d: "M14.99 3H6c-.8 0-1.52.48-1.83 1.21L.91 11.82C.06 13.8 1.51 16 3.66 16h...
value: true });
random_line_split
git.py
# -*- coding: utf-8 -*- """Git tools.""" from shlex import split from plumbum import ProcessExecutionError from plumbum.cmd import git DEVELOPMENT_BRANCH = "develop" def run_git(*args, dry_run=False, quiet=False):
def branch_exists(branch): """Return True if the branch exists.""" try: run_git("rev-parse --verify {}".format(branch), quiet=True) return True except ProcessExecutionError: return False def get_current_branch(): """Get the current branch name.""" return run_git("rev-par...
"""Run a git command, print it before executing and capture the output.""" command = git[split(" ".join(args))] if not quiet: print("{}{}".format("[DRY-RUN] " if dry_run else "", command)) if dry_run: return "" rv = command() if not quiet and rv: print(rv) return rv
identifier_body
git.py
# -*- coding: utf-8 -*- """Git tools.""" from shlex import split from plumbum import ProcessExecutionError from plumbum.cmd import git DEVELOPMENT_BRANCH = "develop" def run_git(*args, dry_run=False, quiet=False): """Run a git command, print it before executing and capture the output.""" command = git[split...
rv = command() if not quiet and rv: print(rv) return rv def branch_exists(branch): """Return True if the branch exists.""" try: run_git("rev-parse --verify {}".format(branch), quiet=True) return True except ProcessExecutionError: return False def get_current_...
return ""
conditional_block
git.py
# -*- coding: utf-8 -*- """Git tools.""" from shlex import split from plumbum import ProcessExecutionError from plumbum.cmd import git DEVELOPMENT_BRANCH = "develop" def run_git(*args, dry_run=False, quiet=False): """Run a git command, print it before executing and capture the output.""" command = git[split...
if not quiet: print("{}{}".format("[DRY-RUN] " if dry_run else "", command)) if dry_run: return "" rv = command() if not quiet and rv: print(rv) return rv def branch_exists(branch): """Return True if the branch exists.""" try: run_git("rev-parse --verify {}"...
random_line_split
git.py
# -*- coding: utf-8 -*- """Git tools.""" from shlex import split from plumbum import ProcessExecutionError from plumbum.cmd import git DEVELOPMENT_BRANCH = "develop" def
(*args, dry_run=False, quiet=False): """Run a git command, print it before executing and capture the output.""" command = git[split(" ".join(args))] if not quiet: print("{}{}".format("[DRY-RUN] " if dry_run else "", command)) if dry_run: return "" rv = command() if not quiet and ...
run_git
identifier_name
rc.rs
// destroyed as well. } ``` If our requirements change, and we also need to be able to traverse from Owner->Gadget, we will run into problems: an Rc pointer from Owner->Gadget introduces a cycle between the objects. This means that their reference counts can never reach 0, and the objects will stay alive: a memory l...
impl<T: Ord> Ord for Rc<T> { #[inline] fn cmp(&self, other: &Rc<T>)
#[inline(always)] fn ge(&self, other: &Rc<T>) -> bool { **self >= **other } }
random_line_split
rc.rs
> // ...other fields } fn main() { // Create a reference counted Owner. Note the fact that we've put the // Owner's vector of Gadgets inside a RefCell so that we can mutate it // through a shared reference. let gadget_owner : Rc<Owner> = Rc::new( Owner { name: "Gadget M...
{ deallocate(self._ptr as *mut u8, size_of::<RcBox<T>>(), min_align_of::<RcBox<T>>()) }
conditional_block
rc.rs
destroyed as well. } ``` If our requirements change, and we also need to be able to traverse from Owner->Gadget, we will run into problems: an Rc pointer from Owner->Gadget introduces a cycle between the objects. This means that their reference counts can never reach 0, and the objects will stay alive: a memory leak...
(&self) -> Rc<T> { self.inc_strong(); Rc { _ptr: self._ptr, _nosend: marker::NoSend, _noshare: marker::NoShare } } } impl<T: Default> Default for Rc<T> { #[inline] fn default() -> Rc<T> { Rc::new(Default::default()) } } impl<T: PartialEq> PartialEq for Rc<T> { #[inline(alwa...
clone
identifier_name
rc.rs
stored inside the strong one. _ptr: transmute(box RcBox { value: value, strong: Cell::new(1), weak: Cell::new(1) }), _nosend: marker::NoSend, _noshare: marker::NoShare } } ...
{ // see issue #11532 use std::gc::GC; let a = Rc::new(RefCell::new(box(GC) 1i)); assert!(a.try_borrow_mut().is_some()); }
identifier_body
main.rs
/// Returns true if the string is a palindrome fn
(string: &str) -> bool { // The first part of the string let forward = string.chars().take(string.len() / 2); // The second part of the string in reverse order let reverse = string.chars().rev().take(string.len() / 2); // We group the two parts of the string in tuples let mut both_directions =...
palindrome
identifier_name
main.rs
/// Returns true if the string is a palindrome fn palindrome(string: &str) -> bool { // The first part of the string let forward = string.chars().take(string.len() / 2); // The second part of the string in reverse order let reverse = string.chars().rev().take(string.len() / 2); // We group the two...
#[test] fn test_palindromes() { let palindromes = ["eevee", "lalalal", "オオオオ", "", "anna"]; let non_palindromes = ["nope", "lalala", "car", "rain", "house", "computer", "rust"]; assert!(palindromes.iter().all(|&s| palindrome(s))); assert!(non_palindromes.iter().all(|&s| !palindrome(s))); }
{ let test_strings = ["nope", "eevee", "lalala", "rust", "lalalal"]; for &string in &test_strings { println!("{}: {}", string, palindrome(string)); } }
identifier_body
main.rs
/// Returns true if the string is a palindrome fn palindrome(string: &str) -> bool { // The first part of the string let forward = string.chars().take(string.len() / 2); // The second part of the string in reverse order let reverse = string.chars().rev().take(string.len() / 2); // We group the two...
}
let palindromes = ["eevee", "lalalal", "オオオオ", "", "anna"]; let non_palindromes = ["nope", "lalala", "car", "rain", "house", "computer", "rust"]; assert!(palindromes.iter().all(|&s| palindrome(s))); assert!(non_palindromes.iter().all(|&s| !palindrome(s)));
random_line_split
team.component.ts
import { Component, Input, OnInit } from '@angular/core'; import { Router, ActivatedRoute, Params } from '@angular/router'; import { Team } from './team.model'; import { PlayerService } from "../player/player.service"; import { Player } from '../player/player.model'; import { TeamService } from "./team.service"; impor...
}); //Obtener delanteros this.playerService.getRightWings(teamId).subscribe(players => { Observable.from(players).subscribe(player => { this.forwards.push(player); }); }); this.playerService.getLeftWings(teamId).subscribe(players => { Observable.from(players).subscribe(pl...
{ let teamId: number = this.activatedRoute.snapshot.params['id']; //Buscamos el equipo por id this.teamService.getTeamById(teamId).subscribe(team => this.team = team); //Como tenemos el ID del equipo, hay que obtener los jugadores del equipo //Obtener porteros this.playerService.getGoalies(te...
identifier_body
team.component.ts
import { Component, Input, OnInit } from '@angular/core'; import { Router, ActivatedRoute, Params } from '@angular/router'; import { Team } from './team.model'; import { PlayerService } from "../player/player.service"; import { Player } from '../player/player.model'; import { TeamService } from "./team.service"; impor...
(private playerService: PlayerService, private teamService: TeamService, private activatedRoute: ActivatedRoute, private router: Router ) {} ngOnInit() { let teamId: number = this.activatedRoute.snapshot.params['id']; //Buscamos el equipo por id this.teamServi...
constructor
identifier_name
team.component.ts
import { Component, Input, OnInit } from '@angular/core'; import { Router, ActivatedRoute, Params } from '@angular/router'; import { Team } from './team.model'; import { PlayerService } from "../player/player.service"; import { Player } from '../player/player.model'; import { TeamService } from "./team.service";
@Component({ selector: 'app-team', templateUrl: './team.component.html', styleUrls: ['./team.component.css'] }) export class TeamComponent implements OnInit { team: Team = null; goalies: Player[] = []; defenders: Player[] = []; forwards: Player[] = []; constructor(private playerService: PlayerService,...
import {Observable} from "rxjs/Observable"; import 'rxjs/add/observable/from';
random_line_split
lib.rs
#![feature(pub_restricted, slice_patterns)] #[macro_use] extern crate gfx; extern crate gfx_core; extern crate gfx_device_gl; extern crate gfx_window_glutin; extern crate glutin; extern crate rusttype; extern crate conrod; extern crate cgmath; extern crate image; extern crate quickersort; extern crate rayon; pub mod ...
(&mut self, bind: TextureBind, color: TextureView<ColorFormat>) { self.texture_binds.get_mut(bind).color = color; } pub fn update_bound_normal(&mut self, bind: TextureBind, normal: TextureView<NormalFormat>) { self.texture_binds.get_mut(bind).normal = normal; } pub fn unbind_textures(&...
update_bound_color
identifier_name
lib.rs
#![feature(pub_restricted, slice_patterns)] #[macro_use] extern crate gfx; extern crate gfx_core; extern crate gfx_device_gl; extern crate gfx_window_glutin; extern crate glutin; extern crate rusttype; extern crate conrod; extern crate cgmath; extern crate image; extern crate quickersort; extern crate rayon; pub mod ...
should_flush: false, } } pub fn clear(&mut self, color: NormalizedColor) { self.graphics.encoder.clear(&self.graphics.output_color, color.to_array()); self.should_flush(); } pub fn should_flush(&mut self) { self.should_flush = true; } pub fn flush(&...
fn new(graphics: &'a mut Graphics) -> Self { Frame { graphics: graphics,
random_line_split
lib.rs
#![feature(pub_restricted, slice_patterns)] #[macro_use] extern crate gfx; extern crate gfx_core; extern crate gfx_device_gl; extern crate gfx_window_glutin; extern crate glutin; extern crate rusttype; extern crate conrod; extern crate cgmath; extern crate image; extern crate quickersort; extern crate rayon; pub mod ...
pub fn flush(&mut self) { self.graphics.encoder.flush(&mut self.graphics.device); self.should_flush = false; } pub fn ensure_flushed(&mut self) { if self.should_flush { self.flush(); } } pub fn present(mut self, window: &'a Window) { use gfx::traits::*; s...
{ self.should_flush = true; }
identifier_body
lib.rs
#![feature(pub_restricted, slice_patterns)] #[macro_use] extern crate gfx; extern crate gfx_core; extern crate gfx_device_gl; extern crate gfx_window_glutin; extern crate glutin; extern crate rusttype; extern crate conrod; extern crate cgmath; extern crate image; extern crate quickersort; extern crate rayon; pub mod ...
} pub fn present(mut self, window: &'a Window) { use gfx::traits::*; self.ensure_flushed(); window.swap_buffers().unwrap(); self.graphics.device.cleanup(); } }
{ self.flush(); }
conditional_block
zzzTestRuleConfigurePasswordPolicy.py
#!/usr/bin/env python3 ############################################################################### # # # Copyright 2019. Triad National Security, LLC. All rights reserved. # # This program was produced under U.S. Government contrac...
(RuleTest): def setUp(self): RuleTest.setUp(self) self.rule = ConfigurePasswordPolicy(self.config, self.environ, self.logdispatch, self.statechglogger) self.rulename = self.rule.rulename self.rul...
zzzTestRuleConfigurePasswordPolicy
identifier_name
zzzTestRuleConfigurePasswordPolicy.py
#!/usr/bin/env python3 ############################################################################### # # # Copyright 2019. Triad National Security, LLC. All rights reserved. # # This program was produced under U.S. Government contrac...
def runTest(self): self.simpleRuleTest() def setConditionsForRule(self): '''@author: dwalker @note: This unit test will install two incorrect profiles on purpose to force system non-compliancy ''' success = True goodprofiles = {} pwprofile...
pass
identifier_body
zzzTestRuleConfigurePasswordPolicy.py
#!/usr/bin/env python3 ############################################################################### # # # Copyright 2019. Triad National Security, LLC. All rights reserved. # # This program was produced under U.S. Government contrac...
else: success = False return success def checkReportForRule(self, pCompliance, pRuleSuccess): '''check on whether report was correct :param self: essential if you override this definition :param pCompliance: the self.iscompliant value of rule :param pRu...
cmd = ["/usr/bin/profiles", "-I", "-F,", item + "fake"] if not self.ch.executeCommand(cmd): success = False
conditional_block
zzzTestRuleConfigurePasswordPolicy.py
#!/usr/bin/env python3 ############################################################################### # # # Copyright 2019. Triad National Security, LLC. All rights reserved. # # This program was produced under U.S. Government contrac...
spprofiledict = {"com.apple.screensaver": "", "com.apple.loginwindow": "", "com.apple.systempolicy.managed": "", "com.apple.SubmitDiagInfo": "", "com.apple.preference.security": "", ...
"pinHistory": ["5", "int", "more"], "requireAlphanumeric": ["1", "bool"]}}
random_line_split
service.d.ts
/** * Copyright 2017 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to i...
constructor(service: Service); /** * Called when the associated app is deleted. * @see {!fbs.AuthWrapper.prototype.deleteApp} */ delete(): Promise<void>; }
service_: Service;
random_line_split
service.d.ts
/** * Copyright 2017 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to i...
{ service_: Service; constructor(service: Service); /** * Called when the associated app is deleted. * @see {!fbs.AuthWrapper.prototype.deleteApp} */ delete(): Promise<void>; }
ServiceInternals
identifier_name
__init__.py
# 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, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the Licen...
# Copyright 2019 Canonical Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License.
random_line_split
token_parser.py
from tokens.andd import And from tokens.expression import Expression from tokens.iff import Iff from tokens.kfalse import ConstantFalse from tokens.ktrue import ConstantTrue from tokens.nop import Not from tokens.orr import Or from tokens.then import Then from tokens.variable import Variable class TokenParser: ""...
# Get all the tokens words = string.split() # Store the found nested expressions on the stack expressions_stack = [Expression()] for w in words: done = False for operator in operators: # We replaced all the operator with their single char...
for representation in operator.representations: string = string.replace(representation, ' '+operator.single_char_representation+' ')
random_line_split
token_parser.py
from tokens.andd import And from tokens.expression import Expression from tokens.iff import Iff from tokens.kfalse import ConstantFalse from tokens.ktrue import ConstantTrue from tokens.nop import Not from tokens.orr import Or from tokens.then import Then from tokens.variable import Variable class TokenParser: ""...
(string): # Separate parenthesis so they're new tokens # Also convert [ or { to the same parenthesis ( for s in '([{': string = string.replace(s, ' ( ') for s in ')]}': string = string.replace(s, ' ) ') # Get all operators so we can iterate over them ...
parse_expression
identifier_name
token_parser.py
from tokens.andd import And from tokens.expression import Expression from tokens.iff import Iff from tokens.kfalse import ConstantFalse from tokens.ktrue import ConstantTrue from tokens.nop import Not from tokens.orr import Or from tokens.then import Then from tokens.variable import Variable class TokenParser: ""...
# Get all operators so we can iterate over them # # Note that the order here is important. We first need to replace long # expressions, such as '<->' with their single character representations. # # If we didn't do this, after we tried to separate the tokens from other ...
string = string.replace(s, ' ) ')
conditional_block
token_parser.py
from tokens.andd import And from tokens.expression import Expression from tokens.iff import Iff from tokens.kfalse import ConstantFalse from tokens.ktrue import ConstantTrue from tokens.nop import Not from tokens.orr import Or from tokens.then import Then from tokens.variable import Variable class TokenParser: ""...
# Find all the representations on the string and add surrounding spaces, # this will allow us to call 'string.split()' to separate variable names # from the operators so the user doesn't need to enter them separated for operator in operators: for representation in operator.r...
for s in '([{': string = string.replace(s, ' ( ') for s in ')]}': string = string.replace(s, ' ) ') # Get all operators so we can iterate over them # # Note that the order here is important. We first need to replace long # expressions, such as '<->' with...
identifier_body
main.rs
// Copyright 2019 Yin Guanhao <sopium@mysterious.site> // This file is part of TiTun. // TiTun is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any la...
Ok(()) }
{ let dirs = ["src", "benches"]; let mut has_error = false; for entry in dirs.iter().map(WalkDir::new).flatten() { let entry = entry?; if entry.file_type().is_file() && entry.path().extension() == Some(OsStr::new("rs")) { let file_content = std::fs::read_to_string(entry.path()) ...
identifier_body
main.rs
// Copyright 2019 Yin Guanhao <sopium@mysterious.site> // This file is part of TiTun. // TiTun is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any la...
() -> anyhow::Result<()> { let dirs = ["src", "benches"]; let mut has_error = false; for entry in dirs.iter().map(WalkDir::new).flatten() { let entry = entry?; if entry.file_type().is_file() && entry.path().extension() == Some(OsStr::new("rs")) { let file_content = std::fs::read_...
main
identifier_name
main.rs
// Copyright 2019 Yin Guanhao <sopium@mysterious.site> // This file is part of TiTun. // TiTun is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any la...
entry.path().display() ); has_error = true; } } } if has_error { bail!("Error occurred"); } Ok(()) }
if !file_content.starts_with("// Copyright") { eprintln!( "Missing copyright claim in file: {}",
random_line_split
main.rs
// Copyright 2019 Yin Guanhao <sopium@mysterious.site> // This file is part of TiTun. // TiTun is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any la...
} } if has_error { bail!("Error occurred"); } Ok(()) }
{ eprintln!( "Missing copyright claim in file: {}", entry.path().display() ); has_error = true; }
conditional_block
development.ts
'use strict'; //ds011732.mlab.com:11732/heroku_4xk8f5vr var defaultEnvConfig = require('./default'); module.exports = { db: { // uri: process.env.MONGOHQ_URL || process.env.MONGOLAB_URI || 'mongodb://ds011732.mlab.com:11732/heroku_4xk8f5vr', uri: process.env.MONGOHQ_URL || process.env.MONGOLAB_URI || 'mong...
// fileName: 'access-%DATE%.log', // if rotating logs are active, this fileName setting will be used // frequency: 'daily', // verbose: false // } // } } }, app: { title: defaultEnvConfig.app.title + ' - Development Environment' }, facebook: { clientID: proces...
// rotatingLogs: { // for more info on rotating logs - https://github.com/holidayextras/file-stream-rotator#usage // active: false, // activate to use rotating logs
random_line_split
framerate.rs
//! Framerate control use libc; use libc::{c_void, uint32_t, size_t}; use std::mem; use sdl2::get_error; mod ll { /* automatically generated by rust-bindgen */ use libc::*; #[repr(C)] pub struct FPSmanager { pub framecount: uint32_t, pub rateticks: c_float, pub baseticks: uin...
unsafe { let size = mem::size_of::<ll::FPSmanager>() as size_t; let raw = libc::malloc(size) as *mut ll::FPSmanager; ll::SDL_initFramerate(raw); FPSManager { raw: raw } } } /// Set the framerate in Hz. pub fn set_framerate(&mut self, rate: u32...
} impl FPSManager { /// Create the framerate manager. pub fn new() -> FPSManager {
random_line_split
framerate.rs
//! Framerate control use libc; use libc::{c_void, uint32_t, size_t}; use std::mem; use sdl2::get_error; mod ll { /* automatically generated by rust-bindgen */ use libc::*; #[repr(C)] pub struct FPSmanager { pub framecount: uint32_t, pub rateticks: c_float, pub baseticks: uin...
(&mut self) -> u32 { unsafe { ll::SDL_framerateDelay(self.raw) as u32 } } } impl Drop for FPSManager { fn drop(&mut self) { unsafe { libc::free(self.raw as *mut c_void) } } }
delay
identifier_name
framerate.rs
//! Framerate control use libc; use libc::{c_void, uint32_t, size_t}; use std::mem; use sdl2::get_error; mod ll { /* automatically generated by rust-bindgen */ use libc::*; #[repr(C)] pub struct FPSmanager { pub framecount: uint32_t, pub rateticks: c_float, pub baseticks: uin...
/// Delay execution to maintain a constant framerate and calculate fps. pub fn delay(&mut self) -> u32 { unsafe { ll::SDL_framerateDelay(self.raw) as u32 } } } impl Drop for FPSManager { fn drop(&mut self) { unsafe { libc::free(self.raw as *mut c_void) } } }
{ // will not get an error unsafe { ll::SDL_getFramecount(self.raw) as i32 } }
identifier_body
environment.js
/* jshint node: true */ module.exports = function(environment) { var ENV = { modulePrefix: 'chapter4-components', environment: environment, baseURL: '/', locationType: 'auto', EmberENV: { FEATURES: { // Here you can enable experimental features on an ember canary build // e....
if (environment === 'test') { // Testem prefers this... ENV.baseURL = '/'; ENV.locationType = 'none'; // keep test console output quieter ENV.APP.LOG_ACTIVE_GENERATION = false; ENV.APP.LOG_VIEW_LOOKUPS = false; ENV.APP.rootElement = '#ember-testing'; } if (environment === 'product...
{ // ENV.APP.LOG_RESOLVER = true; // ENV.APP.LOG_ACTIVE_GENERATION = true; // ENV.APP.LOG_TRANSITIONS = true; // ENV.APP.LOG_TRANSITIONS_INTERNAL = true; // ENV.APP.LOG_VIEW_LOOKUPS = true; }
conditional_block
environment.js
/* jshint node: true */ module.exports = function(environment) { var ENV = { modulePrefix: 'chapter4-components', environment: environment,
locationType: 'auto', EmberENV: { FEATURES: { // Here you can enable experimental features on an ember canary build // e.g. 'with-controller': true } }, APP: { // Here you can pass flags/options to your application instance // when it is created }, conten...
baseURL: '/',
random_line_split
SearchBox.tsx
/* * SonarQube * Copyright (C) 2009-2022 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, o...
else { this.props.onChange(value); } } }; handleInputChange = (event: React.SyntheticEvent<HTMLInputElement>) => { const { value } = event.currentTarget; this.setState({ value }); this.changeValue(value); }; handleInputKeyDown = (event: React.KeyboardEvent<HTMLInputElement>) => ...
{ this.debouncedOnChange(value); }
conditional_block
SearchBox.tsx
/* * SonarQube * Copyright (C) 2009-2022 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, o...
changeValue = (value: string, debounced = true) => { const { minLength } = this.props; if (value.length === 0) { // immediately notify when value is empty this.props.onChange(''); // and cancel scheduled callback this.debouncedOnChange.cancel(); } else if (!minLength || minLength...
{ if ( // input is controlled this.props.value !== undefined && // parent is aware of last change // can happen when previous value was less than min length this.state.value === prevProps.value && this.state.value !== this.props.value ) { this.setState({ value: this.pro...
identifier_body
SearchBox.tsx
/* * SonarQube * Copyright (C) 2009-2022 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, o...
); } }
random_line_split
SearchBox.tsx
/* * SonarQube * Copyright (C) 2009-2022 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, o...
(props: Props) { super(props); this.state = { value: props.value || '' }; this.debouncedOnChange = debounce(this.props.onChange, 250); } componentDidUpdate(prevProps: Props) { if ( // input is controlled this.props.value !== undefined && // parent is aware of last change // ...
constructor
identifier_name
storage.js
(function ( root , factory ) { if ( 'function' === typeof define && define.amd ) { define( [ '../lib/jquery' ] , factory ); } else { root.storage = factory( jQuery ); } }( this , function ( $ ) { var ls = chrome.storage.local , changeCallbacks = $.Callbacks( 'uniqu...
if ( 2 === arguments.length ) { obj = {}; obj[ key ] = value; } else { obj = key; } ls.set( obj , function () { var err = chrome.runtime.lastError; if ( er...
set : function ( key , value ) { var def = $.Deferred() , obj;
random_line_split
storage.js
(function ( root , factory ) { if ( 'function' === typeof define && define.amd ) { define( [ '../lib/jquery' ] , factory ); } else { root.storage = factory( jQuery ); } }( this , function ( $ ) { var ls = chrome.storage.local , changeCallbacks = $.Callbacks( 'uniqu...
() { var def = $.Deferred() , defaultConfig = { enable : true , // 是否开启划词翻译 autoPlay : false , // 翻译之后是否自动阅读单词或短语 ignoreChinese : false , // 是否忽略中文 ignoreNumLike : true , // 忽略类纯...
erred} */ restore : function
conditional_block
KML.py
# Expect the query set self.qs_mp to be a collection of value lists data = [(mp['measurement__instantpoint__timevalue'], mp['measurement__geom'].x, mp['measurement__geom'].y, mp['measurement__depth'], mp['parameter__name'], mp['datavalue'], mp['measurement__instantpoint__activ...
_buildKMLpoints
identifier_name
KML.py
. ''' response = HttpResponse() if self.qs_mp is None: raise Exception('self.qs_mp is None.') # If both selected parameter__name takes priority over parameter__standard_name. If parameter__id supplied that takes overall precedence. pName = None if 'parame...
if not dataHash: logger.exception('No data collected for making KML within the constraints provided') return response descr = self.request.get_full_path().replace('&', '&amp;') logger.debug(descr) try: kml = self.makeKML(self.request.META['dbAlias']...
try: dataHash[d[6]].append(d) except KeyError: dataHash[d[6]] = [] dataHash[d[6]].append(d)
conditional_block
KML.py
class KML(object): ''' Manage the construcion of KML files from stoqs. Several options may be set on initialization and clients can get KML output with the kmlResponse() method. ''' def __init__(self, request, qs_mp, qparams, stoqs_object_name, **kwargs): ''' Possible kwargs and ...
''' Read the color lookup table from disk and return a python list of rgb tuples. ''' cltList = [] for rgb in open(fileName, 'r'): ##logger.debug("rgb = %s", rgb) (r, g, b) = rgb.strip().split() cltList.append([float(r), float(g), float(b)]) return cltList
identifier_body
KML.py
data. ''' response = HttpResponse() if self.qs_mp is None: raise Exception('self.qs_mp is None.') # If both selected parameter__name takes priority over parameter__standard_name. If parameter__id supplied that takes overall precedence. pName = None if 'p...
<Style id="Gulper_AUV"> <LineStyle> <color>ff00ffff</color> <width>2</width> </LineStyle> </Style> <Style id="John Martin"> <LineStyle> <color>ffffffff</color> <width>1</width> </LineStyle> </Style> ''' # # Build the LineString for the points # lineKml = ''
random_line_split
network.py
# coding=utf-8 """ The NetworkCollector class collects metrics on network interface usage using /proc/net/dev. #### Dependencies * /proc/net/dev """ import diamond.collector from diamond.collector import str_to_bool import diamond.convertor import os import re try: import psutil except ImportError: psuti...
# Publish Metric Derivative self.publish(metric_name, metric_value) return None
# Public Converted Metric self.publish(metric_name.replace('bytes', u), convertor.get(unit=u), 2) else:
random_line_split
network.py
# coding=utf-8 """ The NetworkCollector class collects metrics on network interface usage using /proc/net/dev. #### Dependencies * /proc/net/dev """ import diamond.collector from diamond.collector import str_to_bool import diamond.convertor import os import re try: import psutil except ImportError: psuti...
return None
self.publish(metric_name, metric_value)
conditional_block
network.py
# coding=utf-8 """ The NetworkCollector class collects metrics on network interface usage using /proc/net/dev. #### Dependencies * /proc/net/dev """ import diamond.collector from diamond.collector import str_to_bool import diamond.convertor import os import re try: import psutil except ImportError: psuti...
(self): """ Returns the default collector settings """ config = super(NetworkCollector, self).get_default_config() config.update({ 'path': 'network', 'interfaces': ['eth', 'bond', 'em', 'p1p', 'eno', 'enp', 'ens', 'en...
get_default_config
identifier_name
network.py
# coding=utf-8 """ The NetworkCollector class collects metrics on network interface usage using /proc/net/dev. #### Dependencies * /proc/net/dev """ import diamond.collector from diamond.collector import str_to_bool import diamond.convertor import os import re try: import psutil except ImportError: psuti...
'(?P<rx_drop>\d+)(?:\s*)' + '(?P<rx_fifo>\d+)(?:\s*)' + '(?P<rx_frame>\d+)(?:\s*)' + '(?P<rx_compressed>\d+)(?:\s*)' + '(?P<rx_multicast>\d+)(?:\s*)' + '(?P<tx_bytes>\d+)(?:\s*)' + ...
""" Collect network interface stats. """ # Initialize results results = {} if os.access(self.PROC, os.R_OK): # Open File file = open(self.PROC) # Build Regular Expression greed = '' if str_to_bool(self.config['greedy'...
identifier_body