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
pyunit_link_functions_tweedie_basicGLM.py
import sys sys.path.insert(1, "../../../") import h2o def link_functions_tweedie_basic(ip,port): # Connect to h2o h2o.init(ip,port) print "Read in prostate data." hdf = h2o.upload_file(h2o.locate("smalldata/prostate/prostate_complete.csv.zip")) print "Testing for family: TWEEDIE" print "Set v...
h2o.run_test(sys.argv, link_functions_tweedie_basic)
conditional_block
shipzone.classes.shipzone.ts
import * as plugins from './shipzone.plugins'; import * as paths from './shipzone.paths'; // interfaces import { IAppJSON } from 'smartapp'; import { IShipZoneData } from 'servezone-interfaces'; // classes import { SzConnection } from './shipzone.classes.szconnection'; export class ShipZone { appJson: plugins.smar...
() { await this.readDirectory(); await this.readEnv(); await this.buildShipzoneData(); await this.connectToServeZone(); } /** * deploys an app to servezone */ async deployToServezone() { await this.gatherProjectData(); } // ================= // private functions // ============...
gatherProjectData
identifier_name
shipzone.classes.shipzone.ts
import * as plugins from './shipzone.plugins'; import * as paths from './shipzone.paths'; // interfaces import { IAppJSON } from 'smartapp'; import { IShipZoneData } from 'servezone-interfaces'; // classes import { SzConnection } from './shipzone.classes.szconnection'; export class ShipZone { appJson: plugins.smar...
/** * deploys an app to servezone */ async deployToServezone() { await this.gatherProjectData(); } // ================= // private functions // ================= /** * reads a directory to make sense of whats at cwd */ private async readDirectory() { // handle appJson if (awa...
{ await this.readDirectory(); await this.readEnv(); await this.buildShipzoneData(); await this.connectToServeZone(); }
identifier_body
shipzone.classes.shipzone.ts
import * as plugins from './shipzone.plugins'; import * as paths from './shipzone.paths'; // interfaces import { IAppJSON } from 'smartapp'; import { IShipZoneData } from 'servezone-interfaces'; // classes import { SzConnection } from './shipzone.classes.szconnection'; export class ShipZone { appJson: plugins.smar...
case 'ENV': envVarResult = process.env[generatorDescription]; break; case 'URL': // TODO: break; } } // set it to the dockerEnv object spDockerEnv[appJsonEnvVar.name] = envVarResult; } // Get the docker data that is ...
switch (generatorType) {
random_line_split
shipzone.classes.shipzone.ts
import * as plugins from './shipzone.plugins'; import * as paths from './shipzone.paths'; // interfaces import { IAppJSON } from 'smartapp'; import { IShipZoneData } from 'servezone-interfaces'; // classes import { SzConnection } from './shipzone.classes.szconnection'; export class ShipZone { appJson: plugins.smar...
// set it to the dockerEnv object spDockerEnv[appJsonEnvVar.name] = envVarResult; } // Get the docker data that is used to obtain the built app let spDockerImagePath: string; let spDockerDeploymentKey: string; // the ShipzoneData object this.shipzoneData = { dockerImagePath...
{ let parsedGenerator = appJsonEnvVar.generator.split('|'); let generatorType = parsedGenerator[0]; let generatorDescription = parsedGenerator[1]; switch (generatorType) { case 'ENV': envVarResult = process.env[generatorDescription]; break; cas...
conditional_block
FullSizeUgoira.tsx
import React from 'react' import styled from 'styled-components' import { extend } from '../../components' import { usePlayer, useUgoira } from '../Ugoira' import { FullSizeImg } from './FullSizeImg' interface Props extends Pixiv.Page { illustId: string } interface SuccessProps extends Pixiv.Page { frames: Pixiv....
bg: 'rgba(255, 255, 255, 0.87)' }) ) if (__DEV__) { Loader.displayName = 'FullSizeUgoira.Loader' Success.displayName = 'FullSizeUgoira.Success' Canvas.displayName = 'FullSizeUgoira.Canvas' }
} const Canvas = styled.canvas( extend({ display: 'block',
random_line_split
FullSizeUgoira.tsx
import React from 'react' import styled from 'styled-components' import { extend } from '../../components' import { usePlayer, useUgoira } from '../Ugoira' import { FullSizeImg } from './FullSizeImg' interface Props extends Pixiv.Page { illustId: string } interface SuccessProps extends Pixiv.Page { frames: Pixiv....
{ Loader.displayName = 'FullSizeUgoira.Loader' Success.displayName = 'FullSizeUgoira.Success' Canvas.displayName = 'FullSizeUgoira.Canvas' }
conditional_block
api.service.ts
import { Injectable } from '@angular/core'; import { Http, Response, Headers, RequestOptions } from '@angular/http'; import { AppConfiguration } from '../common/config/app-configuration.service'; import { SessionService } from '../common/session.service'; import { Observable } from 'rxjs/Observable'; import 'rxjs/add...
return innerOptions; } private extractData(res: Response) { return res.json(); } private handleError(error: Response | any) { let errObj: any; if (error instanceof Response) { const body = error.json(); errObj = body; } else { errObj = error.message ? { message: error....
{ headers.append('Authorization', 'Bearer ' + this.sessionService.accessToken); }
conditional_block
api.service.ts
import { Injectable } from '@angular/core'; import { Http, Response, Headers, RequestOptions } from '@angular/http'; import { AppConfiguration } from '../common/config/app-configuration.service'; import { SessionService } from '../common/session.service'; import { Observable } from 'rxjs/Observable'; import 'rxjs/add...
get(url: string, options?: any): Observable<any> { return this.http .get(`${this.config.apiURL}/${url}`, this.getRequestOptions(options)) .map(this.extractData) .catch(this.handleError); } private getRequestOptions(options?: any) { let headers = new Headers({ 'Content-Type': 'applicat...
{ return this.http .post(`${this.config.apiURL}/${url}`, body, this.getRequestOptions(options)) .map(this.extractData) .catch(this.handleError); }
identifier_body
api.service.ts
import { Injectable } from '@angular/core'; import { Http, Response, Headers, RequestOptions } from '@angular/http'; import { AppConfiguration } from '../common/config/app-configuration.service'; import { SessionService } from '../common/session.service'; import { Observable } from 'rxjs/Observable'; import 'rxjs/add...
const innerOptions = new RequestOptions({ headers }); if (!options || options.credentials === undefined || options.credentials === true) { headers.append('Authorization', 'Bearer ' + this.sessionService.accessToken); } return innerOptions; } private extractData(res: Response) { return r...
private getRequestOptions(options?: any) { let headers = new Headers({ 'Content-Type': 'application/json' });
random_line_split
api.service.ts
import { Injectable } from '@angular/core'; import { Http, Response, Headers, RequestOptions } from '@angular/http'; import { AppConfiguration } from '../common/config/app-configuration.service'; import { SessionService } from '../common/session.service'; import { Observable } from 'rxjs/Observable'; import 'rxjs/add...
(res: Response) { return res.json(); } private handleError(error: Response | any) { let errObj: any; if (error instanceof Response) { const body = error.json(); errObj = body; } else { errObj = error.message ? { message: error.message } : { message: error }; } return Obs...
extractData
identifier_name
0019_auto_20160922_1342.py
from __future__ import unicode_literals from django.db import migrations, models import multiselectfield.db.fields class
(migrations.Migration): dependencies = [ ('user', '0018_auto_20160922_1258'), ] operations = [ migrations.AddField( model_name='userprofile', name='activity_cantons', field=multiselectfield.db.fields.MultiSelectField(default='', verbose_name='Défi Vélo m...
Migration
identifier_name
0019_auto_20160922_1342.py
from __future__ import unicode_literals from django.db import migrations, models import multiselectfield.db.fields class Migration(migrations.Migration):
dependencies = [ ('user', '0018_auto_20160922_1258'), ] operations = [ migrations.AddField( model_name='userprofile', name='activity_cantons', field=multiselectfield.db.fields.MultiSelectField(default='', verbose_name='Défi Vélo mobile', choices=[('BS', 'Base...
identifier_body
0019_auto_20160922_1342.py
from __future__ import unicode_literals from django.db import migrations, models import multiselectfield.db.fields class Migration(migrations.Migration): dependencies = [ ('user', '0018_auto_20160922_1258'), ] operations = [ migrations.AddField(
model_name='userprofile', name='activity_cantons', field=multiselectfield.db.fields.MultiSelectField(default='', verbose_name='Défi Vélo mobile', choices=[('BS', 'Basel-Stadt'), ('BE', 'Berne'), ('FR', 'Fribourg'), ('GE', 'Geneva'), ('LU', 'Lucerne'), ('NE', 'Neuchatel'), ('SG', 'St....
random_line_split
ccw_face_normal.rs
use crate::math::{Point, Vector}; use na::{RealField, Unit}; /// Computes the direction pointing toward the right-hand-side of an oriented segment. /// /// Returns `None` if the segment is degenerate. #[inline] #[cfg(feature = "dim2")] pub fn ccw_face_normal<N: RealField>(pts: [&Point<N>; 2]) -> Option<Unit<Vector<N>>...
<N: RealField>(pts: [&Point<N>; 3]) -> Option<Unit<Vector<N>>> { let ab = pts[1] - pts[0]; let ac = pts[2] - pts[0]; let res = ab.cross(&ac); Unit::try_new(res, N::default_epsilon()) }
ccw_face_normal
identifier_name
ccw_face_normal.rs
use crate::math::{Point, Vector}; use na::{RealField, Unit}; /// Computes the direction pointing toward the right-hand-side of an oriented segment. /// /// Returns `None` if the segment is degenerate. #[inline] #[cfg(feature = "dim2")] pub fn ccw_face_normal<N: RealField>(pts: [&Point<N>; 2]) -> Option<Unit<Vector<N>>...
/// Computes the normal of a counter-clock-wise triangle. /// /// Returns `None` if the triangle is degenerate. #[inline] #[cfg(feature = "dim3")] pub fn ccw_face_normal<N: RealField>(pts: [&Point<N>; 3]) -> Option<Unit<Vector<N>>> { let ab = pts[1] - pts[0]; let ac = pts[2] - pts[0]; let res = ab.cross(&...
{ let ab = pts[1] - pts[0]; let res = Vector::new(ab[1], -ab[0]); Unit::try_new(res, N::default_epsilon()) }
identifier_body
ccw_face_normal.rs
use crate::math::{Point, Vector}; use na::{RealField, Unit}; /// Computes the direction pointing toward the right-hand-side of an oriented segment. /// /// Returns `None` if the segment is degenerate. #[inline] #[cfg(feature = "dim2")] pub fn ccw_face_normal<N: RealField>(pts: [&Point<N>; 2]) -> Option<Unit<Vector<N>>...
/// /// Returns `None` if the triangle is degenerate. #[inline] #[cfg(feature = "dim3")] pub fn ccw_face_normal<N: RealField>(pts: [&Point<N>; 3]) -> Option<Unit<Vector<N>>> { let ab = pts[1] - pts[0]; let ac = pts[2] - pts[0]; let res = ab.cross(&ac); Unit::try_new(res, N::default_epsilon()) }
/// Computes the normal of a counter-clock-wise triangle.
random_line_split
BeforePIXI.native.tsx
// tslint:disable max-classes-per-file class DOMNode { nodeName: string; constructor(nodeName: string) { this.nodeName = nodeName; } get ownerDocument() { return window.document; } appendChild(element: any) { // unimplemented } } class DOMElement extends DOMNode { style = {}; // emitt...
getElementById(id: string) { return new DOMElement('div'); } } // @ts-ignore process.browser = true; // @ts-ignore window.emitter = window.emitter || {}; // new EventEmitter(); window.addEventListener = window.addEventListener || ((eventName: string, listener: () => void) => {}); window.removeEventListen...
{ const canvas = this.createElement(tagName); canvas.getContext = () => ({ fillRect: () => ({}), drawImage: () => ({}), getImageData: () => ({}), getContextAttributes: () => ({ stencil: true, }), getExtension: () => ({ loseContext: () => ({}), }), })...
identifier_body
BeforePIXI.native.tsx
// tslint:disable max-classes-per-file class DOMNode { nodeName: string; constructor(nodeName: string) { this.nodeName = nodeName; } get ownerDocument() { return window.document; } appendChild(element: any) { // unimplemented } } class DOMElement extends DOMNode { style = {}; // emitt...
} } // @ts-ignore global.Image = HTMLImageElement2; // @ts-ignore global.HTMLImageElement = HTMLImageElement2;
this.isMap = true;
random_line_split
BeforePIXI.native.tsx
// tslint:disable max-classes-per-file class DOMNode { nodeName: string; constructor(nodeName: string) { this.nodeName = nodeName; } get ownerDocument() { return window.document; } appendChild(element: any) { // unimplemented } } class
extends DOMNode { style = {}; // emitter = new EventEmitter(); constructor(tagName: string) { super(tagName.toUpperCase()); } get tagName() { return this.nodeName; } insertBefore = () => {}; getContext() { // if (global.canvasContext) { // return global.canvasContext; // } r...
DOMElement
identifier_name
watson.js
var NaturalLanguageUnderstandingV1 = require('watson-developer-cloud/natural-language-understanding/v1.js'); var ToneAnalyzerV3 = require('watson-developer-cloud/tone-analyzer/v3'); let fs = require('fs'); let path = require('path'); const directoryName = path.dirname(__filename); const creds = { tone: { "userna...
'sentiment': {} } } toneAnalyzer.tone(toneParams, function(err, res1){ if (err) { console.log(err); } else { nlu.analyze(nluParams, function(err, res2){ if (err) { console.log(err); } else { var result = Object.assign({"title": title}, res1, res2); prettyJ...
},
random_line_split
watson.js
var NaturalLanguageUnderstandingV1 = require('watson-developer-cloud/natural-language-understanding/v1.js'); var ToneAnalyzerV3 = require('watson-developer-cloud/tone-analyzer/v3'); let fs = require('fs'); let path = require('path'); const directoryName = path.dirname(__filename); const creds = { tone: { "userna...
(dirname, onFileContent, onError) { fs.readdir(dirname, function(err, filenames) { if (err) { onError(err); return; } var index = filenames.indexOf(".DS_Store"); if (index >= 0) { filenames.splice(index, 1 ); } filenames.forEach(function(filename) { fs.readFile(path.joi...
readFiles
identifier_name
watson.js
var NaturalLanguageUnderstandingV1 = require('watson-developer-cloud/natural-language-understanding/v1.js'); var ToneAnalyzerV3 = require('watson-developer-cloud/tone-analyzer/v3'); let fs = require('fs'); let path = require('path'); const directoryName = path.dirname(__filename); const creds = { tone: { "userna...
}); } }); } function readFiles(dirname, onFileContent, onError) { fs.readdir(dirname, function(err, filenames) { if (err) { onError(err); return; } var index = filenames.indexOf(".DS_Store"); if (index >= 0) { filenames.splice(index, 1 ); } filenames.forEach(fun...
{ var result = Object.assign({"title": title}, res1, res2); prettyJson = JSON.stringify(result, null, 2); fs.appendFileSync('./sentiments.json', prettyJson, {encoding: 'utf8'}); console.log(`Retrieved Watson Analysis for ${title}`); }
conditional_block
watson.js
var NaturalLanguageUnderstandingV1 = require('watson-developer-cloud/natural-language-understanding/v1.js'); var ToneAnalyzerV3 = require('watson-developer-cloud/tone-analyzer/v3'); let fs = require('fs'); let path = require('path'); const directoryName = path.dirname(__filename); const creds = { tone: { "userna...
nlu.analyze(nluParams, function(err, res2){ if (err) { console.log(err); } else { var result = Object.assign({"title": title}, res1, res2); prettyJson = JSON.stringify(result, null, 2); fs.appendFileSync('./sentiments.json', prettyJson, {encoding: 'utf8'}); ...
{ let toneParams = { 'text': poem, 'isHTML': false, 'sentences': false }; let nluParams = { 'text': poem, 'features': { 'keywords': { 'emotion': true, 'sentiment': true, 'limit': 10 }, 'sentiment': {} } } toneAnalyzer.tone(toneParams, function(...
identifier_body
lib.rs
//! A wrapper around freedesktop's `fontconfig` utility, for locating fontfiles on a //! Linux-based system. Requires `libfontconfig` to be installed. //! //! Use `Font` for a high-level search by family name and optional style (e.g. "FreeSerif" //! and "italic"), and `Pattern` for a more in-depth search. //! //! See t...
let font_match = pat.font_match(); font_match.name().and_then(|name| font_match.filename().map(|filename| Font { name: name.into_string(), path: Path::new(filename), } )) } #[allow(dead_code)] fn print_debug(&self) { ...
{ pat.add_string("style", style); }
conditional_block
lib.rs
//! A wrapper around freedesktop's `fontconfig` utility, for locating fontfiles on a //! Linux-based system. Requires `libfontconfig` to be installed. //! //! Use `Font` for a high-level search by family name and optional style (e.g. "FreeSerif" //! and "italic"), and `Pattern` for a more in-depth search. //! //! See t...
/// This is just to hold the RAII C-strings while the `FcPattern` is alive. strings: Vec<CString>, } impl<'a> Pattern<'a> { pub fn new() -> Pattern<'a> { fc_init(); Pattern { _m: marker::ContravariantLifetime, pat: unsafe{ fontconfig::FcPatternCreate() }, ...
/// A safe wrapper around fontconfig's `FcPattern`. pub struct Pattern<'a> { _m: marker::ContravariantLifetime<'a>, pat: *mut FcPattern,
random_line_split
lib.rs
//! A wrapper around freedesktop's `fontconfig` utility, for locating fontfiles on a //! Linux-based system. Requires `libfontconfig` to be installed. //! //! Use `Font` for a high-level search by family name and optional style (e.g. "FreeSerif" //! and "italic"), and `Pattern` for a more in-depth search. //! //! See t...
} /// A safe wrapper around fontconfig's `FcPattern`. pub struct Pattern<'a> { _m: marker::ContravariantLifetime<'a>, pat: *mut FcPattern, /// This is just to hold the RAII C-strings while the `FcPattern` is alive. strings: Vec<CString>, } impl<'a> Pattern<'a> { pub fn new() -> Pattern<'a> { ...
{ debug!("Name: {}\nPath: {}", self.name, self.path.display()); }
identifier_body
lib.rs
//! A wrapper around freedesktop's `fontconfig` utility, for locating fontfiles on a //! Linux-based system. Requires `libfontconfig` to be installed. //! //! Use `Font` for a high-level search by family name and optional style (e.g. "FreeSerif" //! and "italic"), and `Pattern` for a more in-depth search. //! //! See t...
<'a>(&'a self, name: &str) -> Option<&'a str> { name.with_c_str(|c_str| unsafe { let ret = mem::uninitialized(); if fontconfig::FcPatternGetString(&*self.pat, c_str, 0, ret) == 0 { Some(std::str::from_c_str(*ret as *const i8)) } else { None } }) } ...
get_string
identifier_name
triggers.py
import dbus.service from gi.repository import GObject as gobject from oacids.helpers.dbus_props import GPropSync, Manager, WithProperties, ObjectManager from ifaces import BUS, IFACE, PATH, INTROSPECTABLE_IFACE, TRIGGER_IFACE, OPENAPS_IFACE EVENT_IFACE = 'org.openaps.Service.Instance.Triggers' class Emitter (GPropS...
@dbus.service.method(dbus_interface=OWN_IFACE, in_signature='a{sv}', out_signature='') def Create (self, props): emitter = Emitter(Emitter.PATH_TEMPLATE.format(**props), self, props) self.InterfacesAdded(emitter.path, emitter.GetAll(emitter.OWN_IFACE)) self.events.append(emitter...
print "FOUND NEW", path, spec props = spec[EVENT_IFACE] name = props.get('name') then = props.get('then') print name, then self.Create(props)
conditional_block
triggers.py
import dbus.service from gi.repository import GObject as gobject from oacids.helpers.dbus_props import GPropSync, Manager, WithProperties, ObjectManager from ifaces import BUS, IFACE, PATH, INTROSPECTABLE_IFACE, TRIGGER_IFACE, OPENAPS_IFACE EVENT_IFACE = 'org.openaps.Service.Instance.Triggers' class Emitter (GPropS...
(self, path, spec): if path.startswith('/org/openaps/Services/Instance/Trigger'): print "FOUND NEW", path, spec props = spec[EVENT_IFACE] name = props.get('name') then = props.get('then') print name, then self.Create(props) @dbus.service.method(dbus_interface=OWN_IFACE, ...
AddEvent
identifier_name
triggers.py
import dbus.service from gi.repository import GObject as gobject from oacids.helpers.dbus_props import GPropSync, Manager, WithProperties, ObjectManager from ifaces import BUS, IFACE, PATH, INTROSPECTABLE_IFACE, TRIGGER_IFACE, OPENAPS_IFACE EVENT_IFACE = 'org.openaps.Service.Instance.Triggers' class Emitter (GPropSy...
self.InterfacesAdded(emitter.path, emitter.GetAll(emitter.OWN_IFACE)) self.events.append(emitter) def RemoveEvent (self, path, props): if path.startswith('/org/openaps/Services/Instance/Trigger'): print "REMOVED", path, props @dbus.service.signal(dbus_interface=ObjectManager, ...
in_signature='a{sv}', out_signature='') def Create (self, props): emitter = Emitter(Emitter.PATH_TEMPLATE.format(**props), self, props)
random_line_split
triggers.py
import dbus.service from gi.repository import GObject as gobject from oacids.helpers.dbus_props import GPropSync, Manager, WithProperties, ObjectManager from ifaces import BUS, IFACE, PATH, INTROSPECTABLE_IFACE, TRIGGER_IFACE, OPENAPS_IFACE EVENT_IFACE = 'org.openaps.Service.Instance.Triggers' class Emitter (GPropS...
def get_all_managed (self): paths = dict( ) for thing in self.events: # print thing, thing.trigger.OWN_IFACE # print thing.trigger.OWN_IFACE, thing.trigger spec = { thing.trigger.OWN_IFACE: dict(**thing.trigger.GetAll(thing.trigger.OWN_IFACE)) } paths[thing.trigger.path] = spec ...
print "SUBSCRIBING to master's Interfaces events" self.bus.add_signal_receiver(self.AddEvent, "InterfacesAdded", dbus_interface=ObjectManager, bus_name=BUS) self.bus.add_signal_receiver(self.RemoveEvent, "InterfacesRemoved", dbus_interface=ObjectManager, bus_name=BUS)
identifier_body
index.tsx
from 'react' import { Repository } from '../../models/repository' import { Dispatcher } from '../../lib/dispatcher' import { sanitizedBranchName } from '../../lib/sanitize-branch' import { Branch } from '../../models/branch' import { TextBox } from '../lib/text-box' import { Row } from '../lib/row' import { Button } ...
} /** The Create Branch component. */ export class CreateBranch extends React.Component< ICreateBranchProps, ICreateBranchState > { public constructor(props: ICreateBranchProps) { super(props) this.state = { currentError: null, proposedName: '', sanitizedName: '', startPoint: ge...
{ return StartPoint.Head }
conditional_block
index.tsx
from 'react' import { Repository } from '../../models/repository' import { Dispatcher } from '../../lib/dispatcher' import { sanitizedBranchName } from '../../lib/sanitize-branch' import { Branch } from '../../models/branch' import { TextBox } from '../lib/text-box' import { Row } from '../lib/row' import { Button } ...
() { const tip = this.state.isCreatingBranch ? this.state.tipAtCreateStart : this.props.tip const tipKind = tip.kind if (tip.kind === TipState.Detached) { return ( <p> You do not currently have any branch checked out (your HEAD reference is detached). As such ...
renderBranchSelection
identifier_name
index.tsx
from 'react' import { Repository } from '../../models/repository' import { Dispatcher } from '../../lib/dispatcher' import { sanitizedBranchName } from '../../lib/sanitize-branch' import { Branch } from '../../models/branch' import { TextBox } from '../lib/text-box' import { Row } from '../lib/row' import { Button } ...
enum SelectedBranch { DefaultBranch = 0, CurrentBranch = 1, } function getStartPoint( props: ICreateBranchProps, preferred: StartPoint ): StartPoint { if (preferred === StartPoint.DefaultBranch && props.defaultBranch) { return preferred } if ( preferred === StartPoint.CurrentBranch && props....
random_line_split
index.tsx
from 'react' import { Repository } from '../../models/repository' import { Dispatcher } from '../../lib/dispatcher' import { sanitizedBranchName } from '../../lib/sanitize-branch' import { Branch } from '../../models/branch' import { TextBox } from '../lib/text-box' import { Row } from '../lib/row' import { Button } ...
public componentWillReceiveProps(nextProps: ICreateBranchProps) { this.setState({ startPoint: getStartPoint(nextProps, this.state.startPoint), }) if (!this.state.isCreatingBranch) { this.setState({ tipAtCreateStart: nextProps.tip, defaultBranchAtCreateStart: nextProps.defaul...
{ super(props) this.state = { currentError: null, proposedName: '', sanitizedName: '', startPoint: getStartPoint(props, StartPoint.DefaultBranch), isCreatingBranch: false, tipAtCreateStart: props.tip, defaultBranchAtCreateStart: props.defaultBranch, } }
identifier_body
p27.rs
use rand::{Rng, weak_rng}; use serialize::base64::FromBase64; use ssl::symm::{self, encrypt, decrypt}; use util::xor_bytes; fn encryption_oracle(key: &[u8], input: &[u8]) -> Vec<u8> { let iv = Some(key); encrypt(symm::Cipher::aes_128_cbc(), key, iv, input).unwrap() } fn decryption_oracle(key: &[u8], data: &[...
ptxt } // k=IV recovery attack // --- // C_1' = C_1 // C_2' = 0 // C_3' = C_1 // P_1' = D_k(C_1') ^ k // = D_k(C_1) ^ k // P_3' = D_k(C_3') ^ C_2' // = D_k(C_1) ^ 0 // = D_k(C_1) // k = P_1' ^ P_3' // = D_k(C_1') ^ k ^ D_k(C_1) // = k #[test] fn run() { let mut rng = weak_rng(); ...
{ println!("Oh no there's an error!"); }
conditional_block
p27.rs
use rand::{Rng, weak_rng}; use serialize::base64::FromBase64; use ssl::symm::{self, encrypt, decrypt}; use util::xor_bytes; fn encryption_oracle(key: &[u8], input: &[u8]) -> Vec<u8> { let iv = Some(key); encrypt(symm::Cipher::aes_128_cbc(), key, iv, input).unwrap() } fn decryption_oracle(key: &[u8], data: &[...
// k=IV recovery attack // --- // C_1' = C_1 // C_2' = 0 // C_3' = C_1 // P_1' = D_k(C_1') ^ k // = D_k(C_1) ^ k // P_3' = D_k(C_3') ^ C_2' // = D_k(C_1) ^ 0 // = D_k(C_1) // k = P_1' ^ P_3' // = D_k(C_1') ^ k ^ D_k(C_1) // = k #[test] fn run() { let mut rng = weak_rng(); let key:...
{ let iv = Some(key); let ptxt = decrypt(symm::Cipher::aes_128_cbc(), key, iv, data).unwrap(); let invalid = ptxt.iter() .find(|&&b| b < 32 || b >= 127) .is_some(); if invalid { println!("Oh no there's an error!"); } ptxt }
identifier_body
p27.rs
use rand::{Rng, weak_rng}; use serialize::base64::FromBase64; use ssl::symm::{self, encrypt, decrypt}; use util::xor_bytes; fn encryption_oracle(key: &[u8], input: &[u8]) -> Vec<u8> { let iv = Some(key); encrypt(symm::Cipher::aes_128_cbc(), key, iv, input).unwrap() } fn decryption_oracle(key: &[u8], data: &[...
.unwrap(); let ctxt = encryption_oracle(&key, &msg); let mut new_ctxt = ctxt[0..16].to_vec(); new_ctxt.extend_from_slice(&[0_u8; 16]); new_ctxt.extend_from_slice(&ctxt[0..16]); new_ctxt.extend_from_slice(&ctxt[48..]); let ptxt = decryption_oracle(&key, &new_ctxt); let key_recovere...
let msg = "RE9TJ1QgVEhPVSBQUkFURSwgUk9HVUU/PyBET1MnVCBUSE9VIEpFRVIgQU5EIFQ\ tVEFVTlQgTUUgSU4gVEhFIFRFRVRIPz8K" .from_base64()
random_line_split
p27.rs
use rand::{Rng, weak_rng}; use serialize::base64::FromBase64; use ssl::symm::{self, encrypt, decrypt}; use util::xor_bytes; fn encryption_oracle(key: &[u8], input: &[u8]) -> Vec<u8> { let iv = Some(key); encrypt(symm::Cipher::aes_128_cbc(), key, iv, input).unwrap() } fn decryption_oracle(key: &[u8], data: &[...
() { let mut rng = weak_rng(); let key: [u8; 16] = rng.gen(); let msg = "RE9TJ1QgVEhPVSBQUkFURSwgUk9HVUU/PyBET1MnVCBUSE9VIEpFRVIgQU5EIFQ\ tVEFVTlQgTUUgSU4gVEhFIFRFRVRIPz8K" .from_base64() .unwrap(); let ctxt = encryption_oracle(&key, &msg); let mut new_ctxt = ctxt[0..16].to_ve...
run
identifier_name
enumeration.rs
use crate::model::create::{CreateError, CreateResult}; use crate::model::enumeration::Enumeration; use crate::model::symbol::Symbol; use crate::model::Def; use crate::xsd::restriction::Facet; use crate::xsd::simple_type::{Payload, SimpleType}; use crate::xsd::{simple_type, Xsd}; pub(super) fn is_enumeration(st: &Simpl...
pub(super) fn model_enumeration(st: &SimpleType, xsd: &Xsd) -> CreateResult { let restriction = if let simple_type::Payload::Restriction(r) = &st.payload { r } else { return Err(CreateError::new("expected restriction")); }; let mut members = Vec::new(); for facet in &restriction.fa...
{ match &st.payload { Payload::Restriction(r) => { if r.facets.is_empty() { return false; } for facet in &r.facets { match facet { Facet::Enumeration(_) => continue, _ => return false, ...
identifier_body
enumeration.rs
use crate::model::create::{CreateError, CreateResult}; use crate::model::enumeration::Enumeration; use crate::model::symbol::Symbol; use crate::model::Def; use crate::xsd::restriction::Facet; use crate::xsd::simple_type::{Payload, SimpleType}; use crate::xsd::{simple_type, Xsd}; pub(super) fn is_enumeration(st: &Simpl...
(st: &SimpleType, xsd: &Xsd) -> CreateResult { let restriction = if let simple_type::Payload::Restriction(r) = &st.payload { r } else { return Err(CreateError::new("expected restriction")); }; let mut members = Vec::new(); for facet in &restriction.facets { let s = if let Fac...
model_enumeration
identifier_name
enumeration.rs
use crate::model::create::{CreateError, CreateResult}; use crate::model::enumeration::Enumeration; use crate::model::symbol::Symbol; use crate::model::Def; use crate::xsd::restriction::Facet; use crate::xsd::simple_type::{Payload, SimpleType}; use crate::xsd::{simple_type, Xsd}; pub(super) fn is_enumeration(st: &Simpl...
Facet::Enumeration(_) => continue, _ => return false, } } return true; } _ => false, } } pub(super) fn model_enumeration(st: &SimpleType, xsd: &Xsd) -> CreateResult { let restriction = if let simple_type::Payload::R...
random_line_split
mod.rs
mod ffi; pub mod error; pub mod vars; pub mod options; pub mod status; pub mod chat; pub mod file; mod friend; mod network; mod custom; mod events; #[cfg(feature = "groupchat")] pub mod group; #[cfg(feature = "groupchat")] mod peer; pub use self::options::ToxOptions; pub use self::status::Status; pub use self::netwo...
/// Get Address. pub fn address(&self) -> ::address::Address { out!( get out <- vec_with!(vars::TOX_ADDRESS_SIZE), ffi::tox_self_get_address(self.core, out.as_mut_ptr()) ).into() } /// Get SecretKey. pub fn secretkey(&self) -> Vec<u8> { out!( get ...
{ out!( get out <- vec_with!(ffi::tox_get_savedata_size(self.core)), ffi::tox_get_savedata(self.core, out.as_mut_ptr()) ) }
identifier_body
mod.rs
mod ffi; pub mod error; pub mod vars; pub mod options; pub mod status; pub mod chat; pub mod file; mod friend; mod network; mod custom; mod events; #[cfg(feature = "groupchat")] pub mod group; #[cfg(feature = "groupchat")] mod peer; pub use self::options::ToxOptions; pub use self::status::Status; pub use self::netwo...
<S: AsRef<[u8]>>(&self, message: S) -> Result<(), error::InfoSetErr> { let message = message.as_ref(); out!( bool err, ffi::tox_self_set_status_message( self.core, message.as_ptr(), message.len(), &mut err ...
set_status_message
identifier_name
mod.rs
mod ffi; pub mod error; pub mod vars; pub mod options; pub mod status; pub mod chat; pub mod file; mod friend; mod network; mod custom; mod events; #[cfg(feature = "groupchat")] pub mod group; #[cfg(feature = "groupchat")] mod peer; pub use self::options::ToxOptions; pub use self::status::Status; pub use self::netwo...
pub use self::peer::Peer; /// Tox. #[derive(Clone, Debug)] pub struct Tox { pub core: *mut ffi::Tox } impl Tox { /// from ToxOptions create Tox. pub fn new(opts: ToxOptions) -> Result<Tox, error::NewErr> { out!(err err, ffi::tox_new(&opts.opts, &mut err)) .map(Tox::from) } //...
#[cfg(feature = "groupchat")]
random_line_split
Camera.js
* regarding copyright ownership. The ASF licenses this file * to you 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 appli...
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information
random_line_split
planner.page.ts
import { $, browser } from 'protractor'; import { v4 as uuid } from 'uuid'; import { AppPage } from '../app.page'; import * as planner from './../../ui/planner'; import * as support from './../../support'; // this is what you see when you click on the Plan Tab button export class PlannerPage extends AppPage { workIt...
(item: planner.WorkItem) { this.debug('create item', JSON.stringify(item)); await this.quickAdd.addWorkItem(item); } async createUniqueWorkItem(): Promise<string> { let workItemTitle = uuid(); await this.createWorkItem({"title" : workItemTitle}); return workItemTitle; } async createInlineWo...
createWorkItem
identifier_name
planner.page.ts
import { $, browser } from 'protractor'; import { v4 as uuid } from 'uuid'; import { AppPage } from '../app.page'; import * as planner from './../../ui/planner'; import * as support from './../../support'; // this is what you see when you click on the Plan Tab button export class PlannerPage extends AppPage { workIt...
header = new planner.ToolbarHeader($('#header-div')); settings = new planner.Settings($('div.f8-wi-list__settings')); iteration = new planner.Iteration($('fab-planner-iteration-modal')); detailPage = new planner.WorkItemDetailPage($('work-item-detail')); constructor(url: string){ super(url); } async...
inlineQuickAdd = new planner.WorkItemInlineQuickAdd($('#workItemList_quickAdd_inline')); sidePanel = new planner.SidePanel($('aside.f8-sidepanel')); quickPreview = new planner.WorkItemQuickPreview($('work-item-detail'));
random_line_split
planner.page.ts
import { $, browser } from 'protractor'; import { v4 as uuid } from 'uuid'; import { AppPage } from '../app.page'; import * as planner from './../../ui/planner'; import * as support from './../../support'; // this is what you see when you click on the Plan Tab button export class PlannerPage extends AppPage { workIt...
async ready() { support.debug(' ... check if Planner page is Ready'); await super.ready(); await this.workItemList.ready(); await this.quickAdd.ready(); await this.sidePanel.ready(); support.debug(' ... check if Planner page is Ready - OK'); } async createWorkItem(item: planner.WorkItem...
{ super(url); }
identifier_body
permissions.js
/* This file is part of Aaron Rest Server. Aaron Rest Server is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Aaron Rest Server is ...
module.exports.activateRoute = activateRoute;
{ pool = mysqlPool; server.post('/permissions/user/:email', checkAuth, updatePermissions); server.get('/permissions/user/:email', checkAuth, getPermissions); }
identifier_body
permissions.js
/* This file is part of Aaron Rest Server. Aaron Rest Server is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Aaron Rest Server is d...
console.error(err); return res.send(500, new Error('mysql')); } var post = {}; if(typeof req.params.email !== 'string') { console.error('updatePermissions: invalid-input-data'); return res.send(400, new Error('invalid-input-data')); } else if(!config.r.email.test(req.params.email...
if(err) {
random_line_split
permissions.js
/* This file is part of Aaron Rest Server. Aaron Rest Server is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Aaron Rest Server is ...
(req, res) { permissionLog('update request!'); pool.getConnection(function(err, connection) { if(err) { console.error(err); return res.send(500, new Error('mysql')); } var post = {}; if(typeof req.params.email !== 'string') { console.error('updatePermissions: invalid-input-data'); ...
updatePermissions
identifier_name
localnotifications.ts
'./plugin'; export interface ILocalNotification { /** * A unique identifier required to clear, cancel, update or retrieve the local notification in the future * Default: 0 */ id?: number; /** * First row of the notification * Default: Empty string (iOS) or the app name (Android) */ title?:...
@Cordova() static hasPermission(): Promise<boolean> { return; } /** * Sets a callback for a specific event * @param eventName The name of the event. Available events: schedule, trigger, click, update, clear, clearall, cancel, cancelall * @param callback Call back function. All events return notificatio...
* @returns {Promise<boolean>} */
random_line_split
localnotifications.ts
plugin'; export interface ILocalNotification { /** * A unique identifier required to clear, cancel, update or retrieve the local notification in the future * Default: 0 */ id?: number; /** * First row of the notification * Default: Empty string (iOS) or the app name (Android) */ title?: str...
/** * Checks presence of a notification * @param notificationId {number} * @returns {Promise<boolean>} */ @Cordova() static isPresent(notificationId: number): Promise<boolean> { return; } /** * Checks is a notification is scheduled * @param notificationId {number} * @returns {Promise<boo...
{ return; }
identifier_body
localnotifications.ts
plugin'; export interface ILocalNotification { /** * A unique identifier required to clear, cancel, update or retrieve the local notification in the future * Default: 0 */ id?: number; /** * First row of the notification * Default: Empty string (iOS) or the app name (Android) */ title?: str...
(notificationId: number): Promise<boolean> { return; } /** * Get all the notification ids * @returns {Promise<Array<number>>} */ @Cordova() static getAllIds(): Promise<Array<number>> { return; } /** * Get the ids of triggered notifications * @returns {Promise<Array<number>>} */ @Cordova() ...
isTriggered
identifier_name
l10n-fetch-po-files.py
import os import re import subprocess # Copied from Trojita """Fetch the .po files from KDE's SVN for GCompris Run me from GCompris's top-level directory. """ SVN_PATH = "svn://anonsvn.kde.org/home/kde/trunk/l10n-kf5/" SOURCE_PO_PATH = "/messages/kdereview/gcompris_qt.po" OUTPUT_PO_PATH = "./po/" OUTPUT_PO_PATTERN ...
file(OUTPUT_PO_PATH + OUTPUT_PO_PATTERN % lang, "wb").write(transformed) except subprocess.CalledProcessError: print "No data for %s" % lang # Inform qmake about the updated file list #os.utime("CMakeLists.txt", None)
print "Fetched %s" % lang
conditional_block
l10n-fetch-po-files.py
import os import re import subprocess # Copied from Trojita """Fetch the .po files from KDE's SVN for GCompris Run me from GCompris's top-level directory. """ SVN_PATH = "svn://anonsvn.kde.org/home/kde/trunk/l10n-kf5/" SOURCE_PO_PATH = "/messages/kdereview/gcompris_qt.po" OUTPUT_PO_PATH = "./po/" OUTPUT_PO_PATTERN ...
# Inform qmake about the updated file list #os.utime("CMakeLists.txt", None)
random_line_split
mod.rs
/* copyright: (c) 2013-2018 by Blockstack PBC, a public benefit corporation. This file is part of Blockstack. Blockstack is free software. You may redistribute 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...
} impl<A: Address> FromColumn<A> for A { fn from_column<'a>(row: &'a Row, column_name: &str) -> Result<A, db_error> { let address_str : String = row.get(column_name); match A::from_string(&address_str) { Some(a) => Ok(a), None => Err(db_error::ParseError) } } }
{ let pubkey_hex : String = row.get(column_name); match VRFPublicKey::from_hex(&pubkey_hex) { Some(pubk) => Ok(pubk), None => Err(db_error::ParseError) } }
identifier_body
mod.rs
/* copyright: (c) 2013-2018 by Blockstack PBC, a public benefit corporation. This file is part of Blockstack. Blockstack is free software. You may redistribute 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...
} } impl<A: Address> FromColumn<A> for A { fn from_column<'a>(row: &'a Row, column_name: &str) -> Result<A, db_error> { let address_str : String = row.get(column_name); match A::from_string(&address_str) { Some(a) => Ok(a), None => Err(db_error::ParseError) } ...
let pubkey_hex : String = row.get(column_name); match VRFPublicKey::from_hex(&pubkey_hex) { Some(pubk) => Ok(pubk), None => Err(db_error::ParseError) }
random_line_split
mod.rs
/* copyright: (c) 2013-2018 by Blockstack PBC, a public benefit corporation. This file is part of Blockstack. Blockstack is free software. You may redistribute 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...
<'a>(row: &'a Row, column_name: &str) -> Result<A, db_error> { let address_str : String = row.get(column_name); match A::from_string(&address_str) { Some(a) => Ok(a), None => Err(db_error::ParseError) } } }
from_column
identifier_name
query_scorebot.py
import fragmon import irc from fragmon import Player #some CTCP command handlers def on_version(mask, location, cmd, args): irc.ctcp(mask.nick, 'VERSION', fragmon.APPNAME, fragmon.VERSION, fragmon.WEBSITE) irc.on_ctcp('*', 'version', on_version) class SumBot(fragmon.ScoreBot): """ This is an example scorebot...
#These options appear in the extended list of options in the scorebot dialog #The first in the tuple is the name of the option, and the second is its default value. #By default, the variables are accessable as members like self.do_sum bot_options = [ ('do_sum', 'False'), ('private_player...
#This name will appear in the list of custom scorebots in the scorebot dialog bot_name = 'Team Score Sum'
random_line_split
query_scorebot.py
import fragmon import irc from fragmon import Player #some CTCP command handlers def on_version(mask, location, cmd, args): irc.ctcp(mask.nick, 'VERSION', fragmon.APPNAME, fragmon.VERSION, fragmon.WEBSITE) irc.on_ctcp('*', 'version', on_version) class SumBot(fragmon.ScoreBot): """ This is an example scorebot...
(self): """ Constructor. Call the base constructor, and set up IRC callbacks, etc. """ fragmon.ScoreBot.__init__(self) irc.on_text('#*', '!players*', self.on_players) def __cleanup__(self): """ This is called by Fragmon before it destroys the bot's base obje...
__init__
identifier_name
query_scorebot.py
import fragmon import irc from fragmon import Player #some CTCP command handlers def on_version(mask, location, cmd, args): irc.ctcp(mask.nick, 'VERSION', fragmon.APPNAME, fragmon.VERSION, fragmon.WEBSITE) irc.on_ctcp('*', 'version', on_version) class SumBot(fragmon.ScoreBot): """ This is an example scorebot...
def get_option(self, key): """ With this bot, simply use the base get_option method, which calls getattr with string conversion, to obtain the option value. More complex bots may wish to use their own system to access options. """ return fragmon.ScoreBot.get...
""" Convert options from string values. In this case there's only two options, both bool type. Conversion errors, which will appear in a message box, can be triggered by returning a string. """ if key in ('private_players_display', 'do_sum'): value = value.str...
identifier_body
query_scorebot.py
import fragmon import irc from fragmon import Player #some CTCP command handlers def on_version(mask, location, cmd, args): irc.ctcp(mask.nick, 'VERSION', fragmon.APPNAME, fragmon.VERSION, fragmon.WEBSITE) irc.on_ctcp('*', 'version', on_version) class SumBot(fragmon.ScoreBot): """ This is an example scorebot...
def sum_score(self, newlist): """ sum player scores """ #XXX: note that this example is very basic and likely doesn't account for lineup changes score = 0 for p in newlist: score += p.score return score def broadcast(self): """ Pri...
irc.msg(self.channel, 'No players')
conditional_block
recreate_webassets.py
from django.core.management.base import BaseCommand, CommandError from django.db.models import Q from django.template.defaultfilters import filesizeformat from hav.apps.media.models import Media from hav.apps.hav_collections.models import Collection from hav.apps.archive.models import ArchiveFile from ...tasks import c...
self.stdout.write(f"Processed {af_count} files.")
self.process_file(af)
conditional_block
recreate_webassets.py
from django.core.management.base import BaseCommand, CommandError from django.db.models import Q from django.template.defaultfilters import filesizeformat from hav.apps.media.models import Media from hav.apps.hav_collections.models import Collection from hav.apps.archive.models import ArchiveFile from ...tasks import c...
(self, archived_file): archived_file.webasset_set.all().delete() create.delay(archived_file.pk) def handle(self, *args, **options): # gather all options to limit the resulting queryset media_ids = options.get("media", []) collection_slugs = options.get("collection", []) ...
process_file
identifier_name
recreate_webassets.py
from django.core.management.base import BaseCommand, CommandError from django.db.models import Q from django.template.defaultfilters import filesizeformat from hav.apps.media.models import Media from hav.apps.hav_collections.models import Collection from hav.apps.archive.models import ArchiveFile from ...tasks import c...
class Command(BaseCommand): help = "Forces the recreation of webassets." def add_arguments(self, parser): # Named (optional) arguments parser.add_argument( "--dry-run", action="store_true", default=False, help="Only display which files would be ...
random_line_split
recreate_webassets.py
from django.core.management.base import BaseCommand, CommandError from django.db.models import Q from django.template.defaultfilters import filesizeformat from hav.apps.media.models import Media from hav.apps.hav_collections.models import Collection from hav.apps.archive.models import ArchiveFile from ...tasks import c...
type=str, default=[], action="append", help="Limit to media in specific collection", ) parser.add_argument( "--extension", type=str, action="append", default=[], help="Filter by file extension (a...
help = "Forces the recreation of webassets." def add_arguments(self, parser): # Named (optional) arguments parser.add_argument( "--dry-run", action="store_true", default=False, help="Only display which files would be affected.", ) pars...
identifier_body
DNSInject.py
#!/usr/bin/env python # by Chris Truncer # Script to attempt to forge a packet that will inject a new value # for a dns record. Check nessus plugin #35372 # Some great documentation and sample code came from: # http://bb.secdev.org/scapy/src/46e0b3e619547631d704c133a0247cf4683c0784/scapy/layers/dns.py import argpar...
type="A", ttl=120, rdata=ip_value)])) print add_packet[DNS].summary() print "\n[*] Packet created and sent!" def cli_parser(): # Command line argument parser parser = argparse.ArgumentParser( add_help=False, description="DNSInject is a tool for modifying DNS records on ...
os.system('clear') title() # Verifying all required options have a populated value if name_server is None or new_dns_record is None or ip_value is None: print "[*] ERROR: You did not provide all the required command line options!" print "[*] ERROR: Please re-run with required options." ...
identifier_body
DNSInject.py
#!/usr/bin/env python # by Chris Truncer # Script to attempt to forge a packet that will inject a new value # for a dns record. Check nessus plugin #35372 # Some great documentation and sample code came from: # http://bb.secdev.org/scapy/src/46e0b3e619547631d704c133a0247cf4683c0784/scapy/layers/dns.py import argpar...
(): print "######################################################################" print "# DNS Injector #" print "######################################################################\n" return if __name__ == '__main__': # Parse command lin...
title
identifier_name
DNSInject.py
#!/usr/bin/env python # by Chris Truncer # Script to attempt to forge a packet that will inject a new value # for a dns record. Check nessus plugin #35372 # Some great documentation and sample code came from: # http://bb.secdev.org/scapy/src/46e0b3e619547631d704c133a0247cf4683c0784/scapy/layers/dns.py import argpar...
print "[*] Crafting packet for record injection..." print "[*] Sending DNS packet adding " + new_dns_record print "[*] and pointing it to " + ip_value + "\n" dns_zone = new_dns_record[new_dns_record.find(".")+1:] # Craft the packet with scapy add_packet = sr1(IP(dst=name_server)/UDP()/DNS( ...
print "[*] ERROR: You did not provide all the required command line options!" print "[*] ERROR: Please re-run with required options." sys.exit()
conditional_block
DNSInject.py
#!/usr/bin/env python # by Chris Truncer # Script to attempt to forge a packet that will inject a new value # for a dns record. Check nessus plugin #35372 # Some great documentation and sample code came from: # http://bb.secdev.org/scapy/src/46e0b3e619547631d704c133a0247cf4683c0784/scapy/layers/dns.py import argpar...
print "[*] ERROR: You didn't provide a valid action." print "[*] ERROR: Restart and provide your desired action!" sys.exit() except AttributeError: os.system('clear') title() print "[*] ERROR: You didn't provide a valid action." print "[*] ERROR: R...
random_line_split
unittest.py
""" discovery and running of std-library "unittest" style tests. """ from __future__ import absolute_import, division, print_function import sys import traceback # for transferring markers import _pytest._code from _pytest.config import hookimpl from _pytest.outcomes import fail, skip, xfail from _pytest.python impor...
(self, testcase, rawexcinfo, reason=""): try: xfail(str(reason)) except xfail.Exception: self._addexcinfo(sys.exc_info()) def addUnexpectedSuccess(self, testcase, reason=""): self._unexpectedsuccess = reason def addSuccess(self, testcase): pass def ...
addExpectedFailure
identifier_name
unittest.py
""" discovery and running of std-library "unittest" style tests. """ from __future__ import absolute_import, division, print_function import sys import traceback # for transferring markers import _pytest._code from _pytest.config import hookimpl from _pytest.outcomes import fail, skip, xfail from _pytest.python impor...
ut.Failure.__init__ = excstore yield ut.Failure.__init__ = Failure__init__ else: yield def check_testcase_implements_trial_reporter(done=[]): if done: return from zope.interface import classImplements from twisted.trial.itrial import IReporter classImplem...
if exc_value is None: self._rawexcinfo = sys.exc_info() else: if exc_type is None: exc_type = type(exc_value) self._rawexcinfo = (exc_type, exc_value, exc_tb) try: Failure__init__( self, exc_v...
identifier_body
unittest.py
""" discovery and running of std-library "unittest" style tests. """ from __future__ import absolute_import, division, print_function import sys import traceback # for transferring markers import _pytest._code from _pytest.config import hookimpl from _pytest.outcomes import fail, skip, xfail from _pytest.python impor...
class TestCaseFunction(Function): nofuncargs = True _excinfo = None _testcase = None def setup(self): self._testcase = self.parent.obj(self.name) self._fix_unittest_skip_decorator() self._obj = getattr(self._testcase, self.name) if hasattr(self._testcase, "setup_metho...
runtest = getattr(self.obj, "runTest", None) if runtest is not None: ut = sys.modules.get("twisted.trial.unittest", None) if ut is None or runtest != ut.TestCase.runTest: yield TestCaseFunction("runTest", parent=self)
conditional_block
unittest.py
""" discovery and running of std-library "unittest" style tests. """ from __future__ import absolute_import, division, print_function import sys import traceback # for transferring markers import _pytest._code from _pytest.config import hookimpl from _pytest.outcomes import fail, skip, xfail from _pytest.python impor...
See issue #1169 """ if sys.version_info[0] == 2: setattr(self._testcase, "__name__", self.name) def teardown(self): if hasattr(self._testcase, "teardown_method"): self._testcase.teardown_method(self._obj) # Allow garbage collection on TestCase instanc...
The call to functools.wraps() fails unless self._testcase has a __name__ attribute. This is usually automatically supplied if the test is a function or method, but we need to add manually here.
random_line_split
imageVisual.ts
/* * Power BI Visualizations * * Copyright (c) Microsoft Corporation * All rights reserved. * MIT License * * 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 restrict...
* * THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER ...
* * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software.
random_line_split
imageVisual.ts
/* * Power BI Visualizations * * Copyright (c) Microsoft Corporation * All rights reserved. * MIT License * * 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 restrict...
(viewport: IViewport): void { } } }
onResizing
identifier_name
convex_polygon.rs
use crate::math::{Isometry, Point, Vector}; use crate::shape::{ConvexPolygonalFeature, ConvexPolyhedron, FeatureId, SupportMap}; use crate::transformation; use crate::utils; use na::{self, RealField, Unit}; use std::f64; /// A 2D convex polygon. #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] #[derive(C...
if normals[i1].dot(&*normals[i2]) > N::one() - eps { // Remove nremoved += 1; } else { points[i2 - nremoved] = points[i2]; normals[i2 - nremoved] = normals[i2]; } } let new_length = points.len() - nremov...
{ let eps = N::default_epsilon().sqrt(); let mut normals = Vec::with_capacity(points.len()); // First, compute all normals. for i1 in 0..points.len() { let i2 = (i1 + 1) % points.len(); normals.push(utils::ccw_face_normal([&points[i1], &points[i2]])?); } ...
identifier_body
convex_polygon.rs
use crate::math::{Isometry, Point, Vector}; use crate::shape::{ConvexPolygonalFeature, ConvexPolyhedron, FeatureId, SupportMap}; use crate::transformation; use crate::utils; use na::{self, RealField, Unit}; use std::f64; /// A 2D convex polygon. #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] #[derive(C...
} impl<N: RealField> ConvexPolyhedron<N> for ConvexPolygon<N> { fn vertex(&self, id: FeatureId) -> Point<N> { self.points[id.unwrap_vertex()] } fn face(&self, id: FeatureId, out: &mut ConvexPolygonalFeature<N>) { out.clear(); let ia = id.unwrap_face(); let ib = (ia + 1) % ...
}
random_line_split
convex_polygon.rs
use crate::math::{Isometry, Point, Vector}; use crate::shape::{ConvexPolygonalFeature, ConvexPolyhedron, FeatureId, SupportMap}; use crate::transformation; use crate::utils; use na::{self, RealField, Unit}; use std::f64; /// A 2D convex polygon. #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] #[derive(C...
(&self, id: FeatureId) -> Point<N> { self.points[id.unwrap_vertex()] } fn face(&self, id: FeatureId, out: &mut ConvexPolygonalFeature<N>) { out.clear(); let ia = id.unwrap_face(); let ib = (ia + 1) % self.points.len(); out.push(self.points[ia], FeatureId::Vertex(ia)); ...
vertex
identifier_name
practice.srv.js
/** * Practice Session Service * @ngInject */ angular.module('flocs.practice') .factory('practiceService', function ($state, $timeout, $q, practiceDao, taskEnvironme...
} function startCurrentTask() { var returnedSession = taskInstance.session; if (returnedSession !== null) { session.taskInstances = returnedSession['task-instances']; session.task = returnedSession.task; session.max = returnedSession.max; session.progress = (100 / session.max) * (s...
{ return $timeout(function() { startCurrentTask(); return taskInstance; }); }
conditional_block
practice.srv.js
/** * Practice Session Service * @ngInject */ angular.module('flocs.practice') .factory('practiceService', function ($state, $timeout, $q, practiceDao, taskEnvironme...
taskInstance = newTaskInstance; startCurrentTask(); return taskInstance; }, function(response) { if (response.status == 404) { $state.go('httpErrors', {'event': 'taskNotExists'}, {'location': false}); } if (response.status == 403) { $state.go('ht...
if (taskInstance === null || taskInstance.task['task-id'] != taskId) { return practiceDao.gettingTaskById(taskId).then(function (newTaskInstance) {
random_line_split
practice.srv.js
/** * Practice Session Service * @ngInject */ angular.module('flocs.practice') .factory('practiceService', function ($state, $timeout, $q, practiceDao, taskEnvironme...
() { return (session.active && (session.task == session.max)); } function settingNextTask() { return practiceDao.gettingNextTask().then(function(newTaskInstance) { taskInstance = newTaskInstance; var newTaskId = taskInstance.task['task-id']; $state.go('practice-task', {taskId: newTaskId},...
isSessionOver
identifier_name
practice.srv.js
/** * Practice Session Service * @ngInject */ angular.module('flocs.practice') .factory('practiceService', function ($state, $timeout, $q, practiceDao, taskEnvironme...
/* * Return time the user spent solving the task as a number of seconds. */ function calculateSolvingTime() { var taskFinishedTimestamp = Date.now(); var milisecondsSpent = taskFinishedTimestamp - taskStartTimestamp; var secondsSpent = Math.ceil(milisecondsSpent / 1000); return secondsSpent;...
{ return attemptEvaluationDeferred.promise; }
identifier_body
lib.rs
)] extern { /** * Your plugin must implement this function. * ```get_ladspa_descriptor``` returns a description of a supported plugin for a given plugin * index. When the index is out of bounds for the number of plugins supported by your library, * you are expected to return ```None```. * ...
<'a> { AudioInput(&'a [Data]), AudioOutput(RefCell<&'a mut [Data]>), ControlInput(&'a Data), ControlOutput(RefCell<&'a mut Data>), } unsafe impl<'a> Sync for PortData<'a> { } impl<'a> PortConnection<'a> { /// Returns a slice pointing to the internal data of an audio input port. Panics if this port...
PortData
identifier_name
lib.rs
suggested to pick one under 1000, but it should be changed before release. More information /// is available here: http://www.ladspa.org/ladspa_sdk/unique_ids.html pub unique_id: u64, /// Plugin labels are expected to be a unique descriptor string for this specific plugin within /// the library. Label...
{ panic!("PortConnection::unwrap_control called on a non control input port!") }
conditional_block
lib.rs
ladspa::PluginDescriptor> { * None * } * ``` */ pub fn get_ladspa_descriptor(index: u64) -> Option<PluginDescriptor>; } /// The data type used internally by LADSPA for audio and control ports. pub type Data = f32; /// Describes the properties of a ```Plugin``` to be exposed as a LADSPA plu...
/// this port is not an ```AudioOut``` port. pub fn unwrap_audio_mut(&'a self) -> RefMut<'a, &'a mut [Data]> { if let PortData::AudioOutput(ref data) = self.data { data.borrow_mut()
random_line_split
lib.rs
for PortDescriptor { fn default() -> PortDescriptor { PortDescriptor::Invalid } } bitflags!( #[doc="Represents the special properties a control port may hold. These are merely hints as to the use of the port and may be completely ignored by the host. For audio ports, use ```CONTROL_HINT_NONE``...
{ }
identifier_body
wrappedexec.js
const execWrapPath = require.resolve('./exec-wrap') , os = require('os') , path = require('path') , fs = require('fs') , assert = require('assert') , xtend = require('xtend') , after = require('after') function
(exercise) { var dataPath = path.join(os.tmpDir(), '~workshopper.wraptmp.' + process.pid) var submissionPath = dataPath + '-submission' var solutionPath = dataPath + '-solution' exercise.wrapData = {} exercise.wrapMods = [] exercise.addVerifySetup(function setup (callback) { this.solutionArgs.unsh...
fix
identifier_name
wrappedexec.js
const execWrapPath = require.resolve('./exec-wrap') , os = require('os') , path = require('path') , fs = require('fs') , assert = require('assert') , xtend = require('xtend') , after = require('after') function fix (exercise)
this.submission = execWrapPath var wrapData = JSON.stringify(exercise.wrapData) var files = [ submissionPath , solutionPath ] var done = after(files.length, function(err) { if (err) return callback(new Error('Error writing execwrap data: ' + (err.message || err), err)) callback() ...
{ var dataPath = path.join(os.tmpDir(), '~workshopper.wraptmp.' + process.pid) var submissionPath = dataPath + '-submission' var solutionPath = dataPath + '-solution' exercise.wrapData = {} exercise.wrapMods = [] exercise.addVerifySetup(function setup (callback) { this.solutionArgs.unshift('$execwr...
identifier_body
wrappedexec.js
const execWrapPath = require.resolve('./exec-wrap') , os = require('os') , path = require('path') , fs = require('fs') , assert = require('assert') , xtend = require('xtend') , after = require('after') function fix (exercise) { var dataPath = pa...
module.exports = wrappedexec
random_line_split
get_modification_date.py
# -*- coding: utf-8 -*- ## ## This file is part of Invenio. ## Copyright (C) 2013 CERN. ## ## Invenio 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 (at your option) a...
""" Returns creation date for given record. @param recid: @return: Creation date """ from invenio.modules.records.models import Record as Bibrec try: return Bibrec.query.get(recid).modification_date except AttributeError: return None
identifier_body
get_modification_date.py
# -*- coding: utf-8 -*- ## ## This file is part of Invenio. ## Copyright (C) 2013 CERN. ## ## Invenio 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 (at your option) a...
(recid): """ Returns creation date for given record. @param recid: @return: Creation date """ from invenio.modules.records.models import Record as Bibrec try: return Bibrec.query.get(recid).modification_date except AttributeError: return None
get_modification_date
identifier_name
get_modification_date.py
# -*- coding: utf-8 -*- ## ## This file is part of Invenio. ## Copyright (C) 2013 CERN. ## ## Invenio 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 (at your option) a...
@param recid: @return: Creation date """ from invenio.modules.records.models import Record as Bibrec try: return Bibrec.query.get(recid).modification_date except AttributeError: return None
random_line_split
LevelRowColumnUrlBuilder.js
/* * Copyright (C) 2014 United States Government as represented by the Administrator of the * National Aeronautics and Space Administration. All Rights Reserved. */ /** * @exports LevelRowColumnUrlBuilder * @version $Id: LevelRowColumnUrlBuilder.js 2643 2015-01-09 20:37:58Z tgaskins $ */ define([ ...
sb = sb + "/" + tile.level.levelNumber.toString(); sb = sb + "/" + tile.row.toString(); sb = sb + "/" + tile.row.toString() + "_" + tile.column.toString(); sb = sb + "." + WWUtil.suffixForMimeType(imageFormat); sb = sb.replace(" ", "%20"); ...
{ sb = sb + "/" + this.pathToData; }
conditional_block
LevelRowColumnUrlBuilder.js
/* * Copyright (C) 2014 United States Government as represented by the Administrator of the * National Aeronautics and Space Administration. All Rights Reserved. */ /** * @exports LevelRowColumnUrlBuilder * @version $Id: LevelRowColumnUrlBuilder.js 2643 2015-01-09 20:37:58Z tgaskins $ */ define([ ...
* suffix to the image mime type specified when a URL is requested. For example, if the specified server * address is <em>http://worldwindserver.net/webworldwind</em> and the specified path-to-data is * <em>../data/Earth/BMNG256</em>, and the requested tile's level, row and column are 0, 5 a...
* @constructor * @classdesc Provides a factory to create URLs for level/row/column tile REST requests. * <p> * URLs are formed by appending the specified server address with the specified path and appending * a path of the form <em>/level/row/row_column.image-format</em>...
random_line_split
webpack.config.js
/* eslint-disable @typescript-eslint/no-var-requires */ const path = require('path'); const VueLoaderPlugin = require('vue-loader/lib/plugin'); const webpack = require('webpack'); const { version, author, license } = require('./package.json'); module.exports = { entry: './src/index.js', output: { filename: 'to...
}, externals: { '@toast-ui/editor': { commonjs: '@toast-ui/editor', commonjs2: '@toast-ui/editor', }, '@toast-ui/editor/dist/toastui-editor-viewer': { commonjs: '@toast-ui/editor/dist/toastui-editor-viewer', commonjs2: '@toast-ui/editor/dist/toastui-editor-viewer', }, }, ...
random_line_split
drift_utils_test.py
# Copyright 2021 DeepMind Technologies Limited and Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applic...
self.assertEqual(drift_coeffs.gen.self_norm, 0.5 * gen_lr) self.assertEqual(drift_coeffs.gen.other_norm, 0.0) self.assertEqual(drift_coeffs.gen.other_dot_prod, 0.5 * gen_lr) if __name__ == '__main__': absltest.main()
drift_coeffs.disc.other_dot_prod, 0.5 * disc_lr * (1 - 2 * gen_lr / disc_lr))
random_line_split