file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
index.js | import React, { Component, PropTypes } from 'react';
import ItemTypes from './ItemTypes';
import { DragSource, DropTarget } from 'react-dnd';
import flow from 'lodash.flow';
function isNullOrUndefined(o) {
return o == null;
}
const cardSource = {
beginDrag(props) {
return {
id: props.id,
index: pr... | () {
const {
id,
index,
source,
createItem,
noDropOutside, // remove from restProps
moveCard, // remove from restProps
endDrag, // remove from restProps
isDragging,
connectDragSource,
connectDropTarget,
...restProps
} = this.props;
... | render | identifier_name |
index.js | import React, { Component, PropTypes } from 'react';
import ItemTypes from './ItemTypes';
import { DragSource, DropTarget } from 'react-dnd';
import flow from 'lodash.flow';
function isNullOrUndefined(o) {
return o == null;
}
const cardSource = {
beginDrag(props) | ,
endDrag(props, monitor) {
if (props.noDropOutside) {
const { id, index, originalIndex } = monitor.getItem();
const didDrop = monitor.didDrop();
if (!didDrop) {
props.moveCard(isNullOrUndefined(id) ? index : id, originalIndex);
}
}
if (props.endDrag) {
props.endDr... | {
return {
id: props.id,
index: props.index,
originalIndex: props.index
};
} | identifier_body |
sensor.py | """
Support for EBox.
Get data from 'My Usage Page' page: https://client.ebox.ca/myusage
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.ebox/
"""
import logging
from datetime import timedelta
import voluptuous as vol
import homeassistant.helper... |
async_add_entities(sensors, True)
class EBoxSensor(Entity):
"""Implementation of a EBox sensor."""
def __init__(self, ebox_data, sensor_type, name):
"""Initialize the sensor."""
self.client_name = name
self.type = sensor_type
self._name = SENSOR_TYPES[sensor_type][0]
... | sensors.append(EBoxSensor(ebox_data, variable, name)) | conditional_block |
sensor.py | """
Support for EBox.
Get data from 'My Usage Page' page: https://client.ebox.ca/myusage
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.ebox/
"""
import logging
from datetime import timedelta
import voluptuous as vol
import homeassistant.helper... |
@Throttle(MIN_TIME_BETWEEN_UPDATES)
async def async_update(self):
"""Get the latest data from Ebox."""
from pyebox.client import PyEboxError
try:
await self.client.fetch_data()
except PyEboxError as exp:
_LOGGER.error("Error on receive last EBox data: %... | """Initialize the data object."""
from pyebox import EboxClient
self.client = EboxClient(username, password, REQUESTS_TIMEOUT, httpsession)
self.data = {} | identifier_body |
sensor.py | """
Support for EBox.
Get data from 'My Usage Page' page: https://client.ebox.ca/myusage
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.ebox/
"""
import logging
from datetime import timedelta
import voluptuous as vol
import homeassistant.helper... | (self):
"""Get the latest data from Ebox."""
from pyebox.client import PyEboxError
try:
await self.client.fetch_data()
except PyEboxError as exp:
_LOGGER.error("Error on receive last EBox data: %s", exp)
return
# Update data
self.data ... | async_update | identifier_name |
sensor.py | """
Support for EBox.
Get data from 'My Usage Page' page: https://client.ebox.ca/myusage
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.ebox/
"""
import logging
from datetime import timedelta
import voluptuous as vol
import homeassistant.helper... | def unit_of_measurement(self):
"""Return the unit of measurement of this entity, if any."""
return self._unit_of_measurement
@property
def icon(self):
"""Icon to use in the frontend, if any."""
return self._icon
async def async_update(self):
"""Get the latest da... |
@property | random_line_split |
contextKeyService.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... |
getValue(key: string): any {
if (key.indexOf(ConfigAwareContextValuesContainer._keyPrefix) !== 0) {
return super.getValue(key);
}
if (this._values.has(key)) {
return this._values.get(key);
}
const configKey = key.substr(ConfigAwareContextValuesContainer._keyPrefix.length);
const configValue = th... | {
this._listener.dispose();
} | identifier_body |
contextKeyService.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | this._keys = this._keys.concat(oneOrManyKeys);
}
affectsSome(keys: IReadableSet<string>): boolean {
for (const key of this._keys) {
if (keys.has(key)) {
return true;
}
}
return false;
}
}
export abstract class AbstractContextKeyService implements IContextKeyService {
public _serviceBrand: any;
... | private _keys: string[] = [];
collect(oneOrManyKeys: string | string[]): void { | random_line_split |
contextKeyService.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | extends AbstractContextKeyService implements IContextKeyService {
private _lastContextId: number;
private _contexts: {
[contextId: string]: Context;
};
private _toDispose: IDisposable[] = [];
constructor(@IConfigurationService configurationService: IConfigurationService) {
super(0);
this._lastContextId =... | ContextKeyService | identifier_name |
bufferstream.d.ts | // Type definitions for bufferstream v0.6.2
// Project: https://github.com/dodo/node-bufferstream
// Definitions by: Bart van der Schoor <https://github.com/Bartvds>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="../node/node.d.ts" />
declare module 'bufferstream' {
import st... | xtends BufferStream {
/*
for if you want to get all the post data from a http server request and do some db reqeust before.
http client buffer
*/
constructor(req: http.IncomingMessage);
/*
set a callback to get all post data from a http server request
*/
onEnd(callback: (data: any) => void): void;... | stBuffer e | identifier_name |
bufferstream.d.ts | // Type definitions for bufferstream v0.6.2
// Project: https://github.com/dodo/node-bufferstream
// Definitions by: Bart van der Schoor <https://github.com/Bartvds>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="../node/node.d.ts" />
declare module 'bufferstream' {
import st... | returns Buffer.
*/
getBuffer(): Buffer;
/*
returns Buffer.
*/
buffer: Buffer;
/*
shortcut for buffer.toString()
*/
toString(): string;
/*
shortcut for buffer.length
*/
length: number;
}
namespace BufferStream {
export interface Opts {
/*
default encoding for writing strings... | split(tokens: Buffer[]): void; // Array
/* | random_line_split |
hints.py | import datetime
import typing
from . import helpers
from .tl import types, custom
Phone = str
Username = str
PeerID = int
Entity = typing.Union[types.User, types.Chat, types.Channel]
FullEntity = typing.Union[types.UserFull, types.messages.ChatFull, types.ChatFull, types.ChannelFull]
EntityLike = typing.Union[
P... |
ProgressCallback = typing.Callable[[int, int], None] | MessageIDLike = typing.Union[int, types.Message, types.TypeInputMessage] | random_line_split |
link-type.effects.ts | import { Injectable } from '@angular/core';
import { Actions, Effect } from '@ngrx/effects';
import * as LinkTypeActions from './../actions/link-type.actions';
import { Observable } from 'rxjs';
import { map, switchMap } from 'rxjs/operators';
import { LinkTypeUI } from './../models/link-type';
import { SpaceQuery } f... | {
constructor(
private actions$: Actions,
private workItemService: WorkItemService,
private spaceQuery: SpaceQuery,
) {}
@Effect() getLinkTypes$: Observable<Action> = this.actions$.pipe(
filterTypeWithSpace(LinkTypeActions.GET, this.spaceQuery.getCurrentSpace),
map(([action, space]) => {
... | LinkTypeEffects | identifier_name |
link-type.effects.ts | import { Injectable } from '@angular/core';
import { Actions, Effect } from '@ngrx/effects';
import * as LinkTypeActions from './../actions/link-type.actions';
import { Observable } from 'rxjs';
import { map, switchMap } from 'rxjs/operators';
import { LinkTypeUI } from './../models/link-type';
import { SpaceQuery } f... | lts.forwardLinks.forEach((linkType) => {
linkTypes.push({
name: linkType.attributes['forward_name'],
id: linkType.id,
linkType: 'forward',
description: linkType.attributes['forward_description']
? linkType.attributes['forward_... | lts['forwardLinks'] = data;
lts['backwardLinks'] = data; | random_line_split |
route.py | #
# This file is part of nmgr.
# Copyright (C) 2015 Leo Gaspard
#
# nmgr is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# nmgr is di... | args.append(key)
args.append(kwargs[key])
sh.ip.route.add(subnet, *args)
_send_message('add', subnet, kwargs) | random_line_split | |
route.py | #
# This file is part of nmgr.
# Copyright (C) 2015 Leo Gaspard
#
# nmgr is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# nmgr is di... | (action, subnet, meta):
data = _RouteMetadata(
action = action,
subnet = subnet,
meta = meta
)
msg = "route/" + data.action + "/" + data.subnet
nmgr.broadcast(msg, data)
def add(subnet, **kwargs):
args = []
for key in kwargs:
args.append(key)
args.appen... | _send_message | identifier_name |
route.py | #
# This file is part of nmgr.
# Copyright (C) 2015 Leo Gaspard
#
# nmgr is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# nmgr is di... |
sh.ip.route.add(subnet, *args)
_send_message('add', subnet, kwargs)
| args.append(key)
args.append(kwargs[key]) | conditional_block |
route.py | #
# This file is part of nmgr.
# Copyright (C) 2015 Leo Gaspard
#
# nmgr is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# nmgr is di... |
def add(subnet, **kwargs):
args = []
for key in kwargs:
args.append(key)
args.append(kwargs[key])
sh.ip.route.add(subnet, *args)
_send_message('add', subnet, kwargs)
| data = _RouteMetadata(
action = action,
subnet = subnet,
meta = meta
)
msg = "route/" + data.action + "/" + data.subnet
nmgr.broadcast(msg, data) | identifier_body |
test_ajax.py | import json
from django.test import TestCase, Client
from django.core.urlresolvers import reverse
from src.apps.hotel.models import City, Hotel
class AjaxTestCase(TestCase):
def setUp(self):
|
def test_hotel_city(self):
client = getattr(self, 'client')
response = client.get('%s?q=Amsterdam' % reverse('city'), HTTP_X_REQUESTED_WITH='XMLHttpRequest')
self.assertEqual(response.status_code, 200)
content = json.loads(response.content)
self.assertEqual(1, len(content))... | setattr(self, 'client', Client())
amsterdam = City.objects.create(code="AMS", name="Amsterdam")
Hotel.objects.create(code="CAT", name="Ibis Amsterdam Airport", city=amsterdam) | identifier_body |
test_ajax.py | import json
from django.test import TestCase, Client
from django.core.urlresolvers import reverse
from src.apps.hotel.models import City, Hotel
class AjaxTestCase(TestCase):
def setUp(self):
setattr(self, 'client', Client())
amsterdam = City.objects.create(code="AMS", name="Amsterdam")
Ho... | (self):
client = getattr(self, 'client')
city_response = client.get('%s?q=Amsterdam' % reverse('city'), HTTP_X_REQUESTED_WITH='XMLHttpRequest')
city_content = json.loads(city_response.content)
city_pk = city_content[0]['pk']
hotel_response = client.get(
reverse('hotel... | test_hotel_hotel | identifier_name |
test_ajax.py | import json
from django.test import TestCase, Client
from django.core.urlresolvers import reverse
from src.apps.hotel.models import City, Hotel
class AjaxTestCase(TestCase):
| Hotel.objects.create(code="CAT", name="Ibis Amsterdam Airport", city=amsterdam)
def test_hotel_city(self):
client = getattr(self, 'client')
response = client.get('%s?q=Amsterdam' % reverse('city'), HTTP_X_REQUESTED_WITH='XMLHttpRequest')
self.assertEqual(response.status_code, 200)
... | def setUp(self):
setattr(self, 'client', Client())
amsterdam = City.objects.create(code="AMS", name="Amsterdam") | random_line_split |
test_spiderForPEDAILY.py | # -*- coding: utf-8 -*-
"""
Copyright (C) 2015, MuChu Hsu
Contributed by Muchu Hsu (muchu1983@gmail.com)
This file is part of BSD license
<https://opensource.org/licenses/BSD-3-Clause>
"""
import unittest
import logging
from cameo.spiderForPEDAILY import SpiderForPEDAILY
"""
測試 抓取 PEDAILY
"""
class SpiderForPEDAILYTe... | conditional_block | ||
test_spiderForPEDAILY.py | # -*- coding: utf-8 -*-
"""
Copyright (C) 2015, MuChu Hsu
Contributed by Muchu Hsu (muchu1983@gmail.com)
This file is part of BSD license
<https://opensource.org/licenses/BSD-3-Clause>
"""
import unittest
import logging
from cameo.spiderForPEDAILY import SpiderForPEDAILY
"""
測試 抓取 PEDAILY
"""
class SpiderForPEDAILYTe... | #收尾
def tearDown(self):
self.spider.quitDriver()
"""
#測試抓取 index page
def test_downloadIndexPage(self):
logging.info("SpiderForPEDAILYTest.test_downloadIndexPage")
self.spider.downloadIndexPage()
#測試抓取 category page
def test_downloadCategoryPage(self):
logg... | cConfig(level=logging.INFO)
self.spider = SpiderForPEDAILY()
self.spider.initDriver()
| identifier_body |
test_spiderForPEDAILY.py | # -*- coding: utf-8 -*-
"""
Copyright (C) 2015, MuChu Hsu
Contributed by Muchu Hsu (muchu1983@gmail.com)
This file is part of BSD license
<https://opensource.org/licenses/BSD-3-Clause>
"""
import unittest
import logging
from cameo.spiderForPEDAILY import SpiderForPEDAILY
"""
測試 抓取 PEDAILY
"""
class SpiderForPEDAILYTe... | logging.basicConfig(level=logging.INFO)
self.spider = SpiderForPEDAILY()
self.spider.initDriver()
#收尾
def tearDown(self):
self.spider.quitDriver()
"""
#測試抓取 index page
def test_downloadIndexPage(self):
logging.info("SpiderForPEDAILYTest.test_downloadIndex... | identifier_name | |
test_spiderForPEDAILY.py | # -*- coding: utf-8 -*-
"""
Copyright (C) 2015, MuChu Hsu
Contributed by Muchu Hsu (muchu1983@gmail.com)
This file is part of BSD license
<https://opensource.org/licenses/BSD-3-Clause>
"""
import unittest | 測試 抓取 PEDAILY
"""
class SpiderForPEDAILYTest(unittest.TestCase):
#準備
def setUp(self):
logging.basicConfig(level=logging.INFO)
self.spider = SpiderForPEDAILY()
self.spider.initDriver()
#收尾
def tearDown(self):
self.spider.quitDriver()
"""
#測試抓取 index page... | import logging
from cameo.spiderForPEDAILY import SpiderForPEDAILY
""" | random_line_split |
upload_msi.py | #!/usr/bin/python
import os
import requests
from requests.exceptions import HTTPError
import hashlib
import json
from optparse import OptionParser
from glob import glob
from msilib import *
CHUNK_SIZE = 1048576 # 1 Mb chunk size
class MsiUploader():
def __init__(self, url, user, password):
self.base_url ... |
if __name__ == '__main__':
main()
| options = parse_options()
files = glob(options.files)
if not files:
raise OSError("File not found")
m = MsiUploader(options.base_url, options.username, options.password)
## Check if repo exists else create it.
if not m.get_repo(options.repo_id):
m.create_repo(options.repo_id)
... | identifier_body |
upload_msi.py | #!/usr/bin/python
import os
import requests
from requests.exceptions import HTTPError
import hashlib
import json
from optparse import OptionParser
from glob import glob
from msilib import *
CHUNK_SIZE = 1048576 # 1 Mb chunk size
class MsiUploader():
def __init__(self, url, user, password):
self.base_url ... |
# calc md5
m.update(data)
# Server request
upload_path = "/pulp/api/v2/content/uploads/%s/%s/" % (upload_id, offset)
r = requests.put(self.base_url + upload_path, auth=self.basic_auth, verify=False, data=data)
r.raise_for_s... | break | conditional_block |
upload_msi.py | #!/usr/bin/python
import os
import requests
from requests.exceptions import HTTPError
import hashlib
import json
from optparse import OptionParser
from glob import glob
from msilib import *
CHUNK_SIZE = 1048576 # 1 Mb chunk size
class MsiUploader():
def __init__(self, url, user, password):
self.base_url ... | ():
parser = OptionParser()
parser.add_option('-f', '--files', type="string", dest="files",
help="MSI file[s] to upload (wild cards are supported, e.g *.msi)")
parser.add_option('-u', '--username', type="string", dest="username",
help="Username")
parser.add_opt... | parse_options | identifier_name |
upload_msi.py | #!/usr/bin/python
import os
import requests
from requests.exceptions import HTTPError
import hashlib
import json
from optparse import OptionParser
from glob import glob
from msilib import *
CHUNK_SIZE = 1048576 # 1 Mb chunk size
class MsiUploader():
def __init__(self, url, user, password):
self.base_url ... | }
# Post metadata for unit
r = requests.post(self.base_url + import_path, auth=self.basic_auth, verify=False, data=json.dumps(unit_metadata))
r.raise_for_status()
print "%s (%s): OK!" % (filename, md5sum)
except (HTTPError, IOError), e:
r... | "unit_type_id": "msi",
"unit_key": { "name": name, "checksum": md5sum, "version": version, "checksumtype": "md5" },
"unit_metadata": { "filename": os.path.basename(filename) } | random_line_split |
TimespanSpecifier.py | import abjad
from abjad.tools import abctools
class TimespanSpecifier(abctools.AbjadValueObject):
### CLASS VARIABLES ###
__slots__ = (
'_forbid_fusing',
'_forbid_splitting',
'_minimum_duration',
)
### INITIALIZER ###
def __init__(
self,
forbid_fusin... | (self):
return self._forbid_fusing
@property
def forbid_splitting(self):
return self._forbid_splitting
@property
def minimum_duration(self):
return self._minimum_duration
| forbid_fusing | identifier_name |
TimespanSpecifier.py | import abjad
from abjad.tools import abctools
class TimespanSpecifier(abctools.AbjadValueObject):
### CLASS VARIABLES ###
__slots__ = (
'_forbid_fusing',
'_forbid_splitting',
'_minimum_duration',
)
### INITIALIZER ###
def __init__(
self,
forbid_fusin... |
self._forbid_splitting = forbid_splitting
if minimum_duration is not None:
minimum_duration = abjad.Duration(minimum_duration)
self._minimum_duration = minimum_duration
### PUBLIC PROPERTIES ###
@property
def forbid_fusing(self):
return self._forbid_fusing
... | forbid_splitting = bool(forbid_splitting) | conditional_block |
TimespanSpecifier.py | import abjad
from abjad.tools import abctools
class TimespanSpecifier(abctools.AbjadValueObject):
### CLASS VARIABLES ###
| __slots__ = (
'_forbid_fusing',
'_forbid_splitting',
'_minimum_duration',
)
### INITIALIZER ###
def __init__(
self,
forbid_fusing=None,
forbid_splitting=None,
minimum_duration=None,
):
if forbid_fusing is not None:
for... | identifier_body | |
TimespanSpecifier.py | import abjad
from abjad.tools import abctools
class TimespanSpecifier(abctools.AbjadValueObject):
### CLASS VARIABLES ###
__slots__ = (
'_forbid_fusing',
'_forbid_splitting',
'_minimum_duration',
)
### INITIALIZER ###
def __init__(
self,
forbid_fusin... | return self._minimum_duration |
@property
def minimum_duration(self): | random_line_split |
mergeDeep.ts | import {merge} from "./merge";
import {shallowMerge} from "./shallowMerge";
export const mergeDeep = mergeDeepFactory(merge);
export const shallowMergeDeep = mergeDeepFactory(shallowMerge);
function mergeDeepFactory<A, B>(mrg: Merge<A, B>): Merge<A, B> {
let mrgDeep;
mrgDeep = <MA, MB>(a: MA, b: MB): (MA & MB) => {... |
function isObject(b, p) {
return (null !== b[p] && typeof b[p] === "object" && !Array.isArray(b[p]));
}
export type Merge<A, B> = <MA, MB>(a: MA, b: MB) => (MA & MB);
| {
if (a.hasOwnProperty(p)) {
return mrgDeep(a[p as any], b[p], mrg);
}
return b[p];
} | identifier_body |
mergeDeep.ts | import {merge} from "./merge";
import {shallowMerge} from "./shallowMerge";
export const mergeDeep = mergeDeepFactory(merge);
export const shallowMergeDeep = mergeDeepFactory(shallowMerge);
function mergeDeepFactory<A, B>(mrg: Merge<A, B>): Merge<A, B> { | if (b.hasOwnProperty(p)) {
const v = isObject(b, p) ? mergeProperty<MA, MB>(a, b, p, mrg, mrgDeep) : b[p];
r = mrg(r, {[p]: v});
}
}
return r as (MA & MB);
};
return mrgDeep;
}
function mergeProperty<A, B>(a: A, b: B, p, mrg: Merge<A, B>, mrgDeep): (A & B) {
if (a.hasOwnProperty(p)) {
return mrg... | let mrgDeep;
mrgDeep = <MA, MB>(a: MA, b: MB): (MA & MB) => {
let r = a;
for (const p in b) { | random_line_split |
mergeDeep.ts | import {merge} from "./merge";
import {shallowMerge} from "./shallowMerge";
export const mergeDeep = mergeDeepFactory(merge);
export const shallowMergeDeep = mergeDeepFactory(shallowMerge);
function mergeDeepFactory<A, B>(mrg: Merge<A, B>): Merge<A, B> {
let mrgDeep;
mrgDeep = <MA, MB>(a: MA, b: MB): (MA & MB) => {... | (b, p) {
return (null !== b[p] && typeof b[p] === "object" && !Array.isArray(b[p]));
}
export type Merge<A, B> = <MA, MB>(a: MA, b: MB) => (MA & MB);
| isObject | identifier_name |
mergeDeep.ts | import {merge} from "./merge";
import {shallowMerge} from "./shallowMerge";
export const mergeDeep = mergeDeepFactory(merge);
export const shallowMergeDeep = mergeDeepFactory(shallowMerge);
function mergeDeepFactory<A, B>(mrg: Merge<A, B>): Merge<A, B> {
let mrgDeep;
mrgDeep = <MA, MB>(a: MA, b: MB): (MA & MB) => {... |
}
return r as (MA & MB);
};
return mrgDeep;
}
function mergeProperty<A, B>(a: A, b: B, p, mrg: Merge<A, B>, mrgDeep): (A & B) {
if (a.hasOwnProperty(p)) {
return mrgDeep(a[p as any], b[p], mrg);
}
return b[p];
}
function isObject(b, p) {
return (null !== b[p] && typeof b[p] === "object" && !Array.isArray... | {
const v = isObject(b, p) ? mergeProperty<MA, MB>(a, b, p, mrg, mrgDeep) : b[p];
r = mrg(r, {[p]: v});
} | conditional_block |
school.py | # -*- coding: utf-8 -*-
from openerp import models, fields, api
class | (models.Model):
_name = 'royalty.school'
name = fields.Char('Name', size=255, required=True)
address_line1 = fields.Char( 'Address 1', size=255 )
address_line2 = fields.Char( 'Address 2', size=255 )
city = fields.Char( 'City', size=30 )
state = fields.Char... | School | identifier_name |
school.py | # -*- coding: utf-8 -*-
from openerp import models, fields, api
class School(models.Model):
_name = 'royalty.school'
name = fields.Char('Name', size=255, required=True)
address_line1 = fields.Char( 'Address 1', size=255 ) | abbreviation = fields.Char( 'Organization Abbreviation', size=75 )
active = fields.Boolean( 'Organization Active', default=True )
old_id = fields.Integer( 'Legacy ID' )
products = fields.One2many( 'product.product', 'school_id', 'Products' )
contacts = fields.One2many( ... | address_line2 = fields.Char( 'Address 2', size=255 )
city = fields.Char( 'City', size=30 )
state = fields.Char( 'State', size=2 )
zip_code = fields.Char( 'ZipCode', size=10 ) | random_line_split |
school.py | # -*- coding: utf-8 -*-
from openerp import models, fields, api
class School(models.Model):
| _name = 'royalty.school'
name = fields.Char('Name', size=255, required=True)
address_line1 = fields.Char( 'Address 1', size=255 )
address_line2 = fields.Char( 'Address 2', size=255 )
city = fields.Char( 'City', size=30 )
state = fields.Char( 'State', size=2 )
... | identifier_body | |
set.spec.js | (function() {
'use strict';
require('structure/iterator');
var Set = require('structure/set'),
Map = require('structure/map');
describe('set', function() {
it('should be defined if required', function() {
(Set != null).should.be.true;
});
it('should instantiate correctly, and w... |
});
});
})(); | {
values[index].should.be.exactly(source[index]);
} | conditional_block |
set.spec.js | (function() {
'use strict';
require('structure/iterator');
var Set = require('structure/set'),
Map = require('structure/map');
describe('set', function() {
it('should be defined if required', function() {
(Set != null).should.be.true;
});
it('should instantiate correctly, and w... | values = set.toArray();
for(var index = 0, length = values.length; index < length; index++) {
values[index].should.be.exactly(source[index]);
}
});
});
})(); | set = new Set(source),
| random_line_split |
readingProgress.ts | import { requestFrame } from './window/requestFrame'
import { element } from 'estimate'
interface Progress {
getFurthestRead: () => number
start: () => void
}
type UpdateCallback = (progress: number, furthest: number) => void
/**
* Reading progress factory.
*
* @param content Content element.
* @param onU... | /**
* Handles scroll and resize events.
*/
function update() {
reading.update()
if (onUpdate) {
onUpdate(reading.progress, furthest)
}
if (reading.progress > furthest) {
furthest = reading.progress
}
}
function throttledUpdate() {
requestFrame(update)
}
/**
*... | let furthest = 0
| random_line_split |
readingProgress.ts | import { requestFrame } from './window/requestFrame'
import { element } from 'estimate'
interface Progress {
getFurthestRead: () => number
start: () => void
}
type UpdateCallback = (progress: number, furthest: number) => void
/**
* Reading progress factory.
*
* @param content Content element.
* @param onU... |
if (reading.progress > furthest) {
furthest = reading.progress
}
}
function throttledUpdate() {
requestFrame(update)
}
/**
* Initialize reading progress updates.
*/
function start() {
window.addEventListener('scroll', throttledUpdate)
window.addEventListener('resize', throt... | {
onUpdate(reading.progress, furthest)
} | conditional_block |
readingProgress.ts | import { requestFrame } from './window/requestFrame'
import { element } from 'estimate'
interface Progress {
getFurthestRead: () => number
start: () => void
}
type UpdateCallback = (progress: number, furthest: number) => void
/**
* Reading progress factory.
*
* @param content Content element.
* @param onU... | () {
requestFrame(update)
}
/**
* Initialize reading progress updates.
*/
function start() {
window.addEventListener('scroll', throttledUpdate)
window.addEventListener('resize', throttledUpdate)
window.addEventListener('orientationchange', throttledUpdate)
}
/**
* Get the furthest Y... | throttledUpdate | identifier_name |
readingProgress.ts | import { requestFrame } from './window/requestFrame'
import { element } from 'estimate'
interface Progress {
getFurthestRead: () => number
start: () => void
}
type UpdateCallback = (progress: number, furthest: number) => void
/**
* Reading progress factory.
*
* @param content Content element.
* @param onU... |
function throttledUpdate() {
requestFrame(update)
}
/**
* Initialize reading progress updates.
*/
function start() {
window.addEventListener('scroll', throttledUpdate)
window.addEventListener('resize', throttledUpdate)
window.addEventListener('orientationchange', throttledUpdate)
}
... | {
reading.update()
if (onUpdate) {
onUpdate(reading.progress, furthest)
}
if (reading.progress > furthest) {
furthest = reading.progress
}
} | identifier_body |
local.py | """Dev server used for running a chalice app locally.
This is intended only for local development purposes.
"""
from __future__ import print_function
import re
import threading
import time
import uuid
import base64
import functools
import warnings
from collections import namedtuple
import json
from six.moves.BaseHTT... | (self, headers):
# type: (HeaderType) -> None
for header_name, header_value in headers.items():
if isinstance(header_value, list):
for value in header_value:
self.send_header(header_name, value)
else:
self.send_header(header_nam... | _send_headers | identifier_name |
local.py | """Dev server used for running a chalice app locally.
This is intended only for local development purposes.
"""
from __future__ import print_function
import re
import threading
import time
import uuid
import base64
import functools
import warnings
from collections import namedtuple
import json
from six.moves.BaseHTT... | lambda_context)
auth_result = authorizer(auth_event, lambda_context)
if auth_result is None:
raise InvalidAuthorizerError(
{'x-amzn-RequestId': lambda_context.aws_request_id,
'x-amzn-ErrorType': 'AuthorizerC... | arn = self._arn_builder.build_arn(method, raw_path)
auth_event = self._prepare_authorizer_event(arn, lambda_event, | random_line_split |
local.py | """Dev server used for running a chalice app locally.
This is intended only for local development purposes.
"""
from __future__ import print_function
import re
import threading
import time
import uuid
import base64
import functools
import warnings
from collections import namedtuple
import json
from six.moves.BaseHTT... |
if i != j:
break
else:
return MatchResult(route_url, captured, query_params)
raise ValueError("No matching route found for: %s" % url)
class LambdaEventConverter(object):
LOCAL_SOURCE_IP = '127.0.0.1'
"""Convert an HTTP... | captured[j[1:-1]] = i
continue | conditional_block |
local.py | """Dev server used for running a chalice app locally.
This is intended only for local development purposes.
"""
from __future__ import print_function
import re
import threading
import time
import uuid
import base64
import functools
import warnings
from collections import namedtuple
import json
from six.moves.BaseHTT... |
class HTTPServerThread(threading.Thread):
"""Thread that manages starting/stopping local HTTP server.
This is a small wrapper around a normal threading.Thread except
that it adds shutdown capability of the HTTP server, which is
not part of the normal threading.Thread interface.
"""
def __in... | def __init__(self, app_object, config, host, port,
handler_cls=ChaliceRequestHandler,
server_cls=ThreadedHTTPServer):
# type: (Chalice, Config, str, int, HandlerCls, ServerCls) -> None
self.app_object = app_object
self.host = host
self.port = port
... | identifier_body |
api.py | """Translate cli commands to non-cli code."""
import logging
from urllib.error import HTTPError, URLError
import requests
from kytos.utils.config import KytosConfig
LOG = logging.getLogger(__name__)
class WebAPI: # pylint: disable=too-few-public-methods
"""An API for the command-line interface."""
@class... | LOG.info("Web UI updated.") | conditional_block | |
api.py | """Translate cli commands to non-cli code."""
import logging
from urllib.error import HTTPError, URLError
import requests
from kytos.utils.config import KytosConfig
LOG = logging.getLogger(__name__)
class WebAPI: # pylint: disable=too-few-public-methods
| """An API for the command-line interface."""
@classmethod
def update(cls, args):
"""Call the method to update the Web UI."""
kytos_api = KytosConfig().config.get('kytos', 'api')
url = f"{kytos_api}api/kytos/core/web/update"
version = args["<version>"]
if version:
... | identifier_body | |
api.py | """Translate cli commands to non-cli code."""
import logging
from urllib.error import HTTPError, URLError
import requests
from kytos.utils.config import KytosConfig | LOG = logging.getLogger(__name__)
class WebAPI: # pylint: disable=too-few-public-methods
"""An API for the command-line interface."""
@classmethod
def update(cls, args):
"""Call the method to update the Web UI."""
kytos_api = KytosConfig().config.get('kytos', 'api')
url = f"{kyto... | random_line_split | |
api.py | """Translate cli commands to non-cli code."""
import logging
from urllib.error import HTTPError, URLError
import requests
from kytos.utils.config import KytosConfig
LOG = logging.getLogger(__name__)
class | : # pylint: disable=too-few-public-methods
"""An API for the command-line interface."""
@classmethod
def update(cls, args):
"""Call the method to update the Web UI."""
kytos_api = KytosConfig().config.get('kytos', 'api')
url = f"{kytos_api}api/kytos/core/web/update"
version... | WebAPI | identifier_name |
test_capture.py | # -*- coding: utf-8 -*-
'''
Tests for basic capturing
'''
import os
import os.path
import shutil
import tempfile
import unittest
from pyca import capture, config, db, utils
from tests.tools import should_fail, terminate_fn, reload
class TestPycaCapture(unittest.TestCase):
def | (self):
utils.http_request = lambda x, y=False: b'xxx'
self.fd, self.dbfile = tempfile.mkstemp()
self.cadir = tempfile.mkdtemp()
preview = os.path.join(self.cadir, 'preview.png')
open(preview, 'a').close()
config.config()['agent']['database'] = 'sqlite:///' + self.dbfile
... | setUp | identifier_name |
test_capture.py | # -*- coding: utf-8 -*-
'''
Tests for basic capturing
'''
import os
import os.path
import shutil
import tempfile
import unittest
from pyca import capture, config, db, utils
from tests.tools import should_fail, terminate_fn, reload
class TestPycaCapture(unittest.TestCase):
def setUp(self):
utils.http_r... | 'fmttype': 'application/xml',
'x-apple-filename': 'episode.xml'},
{'data': u'äüÄÜß',
'fmttype': 'application/xml',
'x-apple-filename': 'series.xml'},
{'data': u'event.title=äüÄÜß\n' +
u'org.openc... | self.event.status = db.Status.UPCOMING
data = [{'data': u'äüÄÜß', | random_line_split |
test_capture.py | # -*- coding: utf-8 -*-
'''
Tests for basic capturing
'''
import os
import os.path
import shutil
import tempfile
import unittest
from pyca import capture, config, db, utils
from tests.tools import should_fail, terminate_fn, reload
class TestPycaCapture(unittest.TestCase):
def setUp(self):
utils.http_r... | _capture_sigterm(self):
config.config()['capture']['command'] = 'sleep 10'
config.config()['capture']['sigterm_time'] = 0
capture.start_capture(self.event)
def test_start_capture_sigkill(self):
config.config()['capture']['command'] = 'sleep 10'
config.config()['capture']['si... | ture']['command'] = 'false'
with self.assertRaises(RuntimeError):
capture.start_capture(self.event)
def test_start | identifier_body |
client.py |
from __future__ import print_function, division
import json
import socket
import random
import time
import numpy as np
class Client(object):
SYNC_ON = b'1'
SYNC_OFF = b'2'
EVENT_ON = b'A'
EVENT_OFF = b'D'
ACQ = b'Y'
QUIT = b'X'
def __init__(self, cfgfile='servic... | (self, value=True):
if self.timed == True:
start = time.perf_counter() * 1e6 # in microsec
self.socket.sendall(Client.SYNC_ON if value == True else Client.SYNC_OFF)
resp = self.read()
if self.timed == True:
stop = time.perf_counter() * 1e6 # in microsec
... | sync | identifier_name |
client.py | from __future__ import print_function, division
import json
import socket
import random
import time
import numpy as np
class Client(object):
SYNC_ON = b'1'
SYNC_OFF = b'2'
EVENT_ON = b'A'
EVENT_OFF = b'D'
ACQ = b'Y'
QUIT = b'X'
def __init__(self, cfgfile='service... |
# read config file
with open(cfgfile, 'r') as fp:
self.config = json.load(fp)
self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.socket.connect((host, self.config['port']))
self.interactive = interactive
self.showresponse = s... | timed -- whether or not to measure response latencies
""" | random_line_split |
client.py |
from __future__ import print_function, division
import json
import socket
import random
import time
import numpy as np
class Client(object):
SYNC_ON = b'1'
SYNC_OFF = b'2'
EVENT_ON = b'A'
EVENT_OFF = b'D'
ACQ = b'Y'
QUIT = b'X'
def __init__(self, cfgfile='servic... |
def read(self):
return self.socket.recv(1)
def sync(self, value=True):
if self.timed == True:
start = time.perf_counter() * 1e6 # in microsec
self.socket.sendall(Client.SYNC_ON if value == True else Client.SYNC_OFF)
resp = self.read()
if self.timed == True:... | """creates a Client object.
[parameters]
cfgfile -- the path of the configuration file to read from.
host -- the host name of the server.
interactive -- whether or not to run the instance in 'interactive' mode.
showresponse -- whether or not to show responses from ... | identifier_body |
client.py |
from __future__ import print_function, division
import json
import socket
import random
import time
import numpy as np
class Client(object):
SYNC_ON = b'1'
SYNC_OFF = b'2'
EVENT_ON = b'A'
EVENT_OFF = b'D'
ACQ = b'Y'
QUIT = b'X'
def __init__(self, cfgfile='servic... |
def close(self):
if self.closed == False:
self.socket.send(Client.QUIT)
self.socket.close()
self.closed = True
if self.timed == True:
latency = np.array(self.latency, dtype=float)
print('-'*30)
print('latency: ... | print("value={}".format("ON" if value == True else "OFF")) | conditional_block |
lexical-scope-in-match.rs | // Copyright 2013-2014 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-MI... | () {
let shadowed = 231;
let not_shadowed = 232;
zzz();
sentinel();
match (233, 234) {
(shadowed, local_to_arm) => {
zzz();
sentinel();
}
}
match (235, 236) {
// with literal
(235, shadowed) => {
zzz();
sen... | main | identifier_name |
lexical-scope-in-match.rs | // Copyright 2013-2014 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-MI... | // gdb-command:finish
// gdb-command:print shadowed
// gdb-check:$17 = 231
// gdb-command:print not_shadowed
// gdb-check:$18 = 232
// gdb-command:continue
struct Struct {
x: int,
y: int
}
fn main() {
let shadowed = 231;
let not_shadowed = 232;
zzz();
sentinel();
match (233, 234) {
... | random_line_split | |
lexical-scope-in-match.rs | // Copyright 2013-2014 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-MI... |
fn sentinel() {()}
| {()} | identifier_body |
export_resultset_csv_sensor_false_code.py | # import the basic python packages we need
import os
import sys
import tempfile
import pprint
import traceback
# disable python from generating a .pyc file
sys.dont_write_bytecode = True
# change me to the path of pytan if this script is not running from EXAMPLES/PYTAN_API
pytan_loc = "~/gh/pytan"
pytan_static_path =... |
print "...OUTPUT: print the export_str returned from export_obj():"
print out
| out = out.splitlines()[0:15]
out.append('..trimmed for brevity..')
out = '\n'.join(out) | conditional_block |
export_resultset_csv_sensor_false_code.py | # import the basic python packages we need
import os
import sys
import tempfile
import pprint
import traceback
# disable python from generating a .pyc file
sys.dont_write_bytecode = True
# change me to the path of pytan if this script is not running from EXAMPLES/PYTAN_API
pytan_loc = "~/gh/pytan"
pytan_static_path =... | # very useful for capturing the full exchange of XML requests and responses
handler_args['record_all_requests'] = True
# instantiate a handler using all of the arguments in the handler_args dictionary
print "...CALLING: pytan.handler() with args: {}".format(handler_args)
handler = pytan.Handler(**handler_args)
# prin... |
# optional, this saves all response objects to handler.session.ALL_REQUESTS_RESPONSES | random_line_split |
templates.js | 'use strict';
/**
* @ngdoc function
* @name freshcardUiApp.controller:TemplatesCtrl
* @description
* # TemplatesCtrl
* Controller of the freshcardUiApp
*/
angular.module('freshcardUiApp')
.controller('TemplatesCtrl', function (
$scope,
$rootScope,
$localStorage,
$filter,
$timeout,
FileUploader,
Organizati... | function() {
$scope.templateLayoutPublished = false;
$scope.templateLayoutPublishError = true;
$scope.templateLayoutSaved = false;
$scope.templateLayoutError = false;
}
);
};
}); | $scope.templateLayoutPublished = false;
},
5000
);
}, | random_line_split |
templates.js | 'use strict';
/**
* @ngdoc function
* @name freshcardUiApp.controller:TemplatesCtrl
* @description
* # TemplatesCtrl
* Controller of the freshcardUiApp
*/
angular.module('freshcardUiApp')
.controller('TemplatesCtrl', function (
$scope,
$rootScope,
$localStorage,
$filter,
$timeout,
FileUploader,
Organizati... |
OrganizationService.update(
{
id: $rootScope.user.currentOrganizationId,
templateLayout: JSON.stringify($scope.templateLayout),
templateAsSVG: svgResult
},
function() {
$scope.templateLayoutPublished = false;
$scope.templateLayoutPublishError = false;
$scope.templateLayoutSaved = tr... | {
svgResult = svgResult.replace($scope.fieldMappings[i], $scope.fieldNames[i]);
} | conditional_block |
testp3.py | # -*- coding: utf-8 -*-
import time
from multiprocessing.pool import Pool
import colored
import numpy as np
from dnutils import out, stop, trace, getlogger, ProgressBar, StatusMsg, bf, loggers, newlogger, logs, edict, ifnone, \
ifnot, allnone, allnot, first, sleep, __version__ as version, waitabout
import unitt... | wait()
bar.finish() | random_line_split | |
testp3.py | # -*- coding: utf-8 -*-
import time
from multiprocessing.pool import Pool
import colored
import numpy as np
from dnutils import out, stop, trace, getlogger, ProgressBar, StatusMsg, bf, loggers, newlogger, logs, edict, ifnone, \
ifnot, allnone, allnot, first, sleep, __version__ as version, waitabout
import unitt... | (self):
self.assertEqual(ifnot(None, 'hello'), 'hello')
self.assertEqual(ifnot('hello', None), 'hello')
self.assertEqual(ifnot('', None), None)
self.assertEqual(ifnot(None, 1, transform=str), 1)
self.assertEqual(ifnot(1, 1, transform=str), '1')
self.assertEqual(ifnot(0, 1... | test_ifnot | identifier_name |
testp3.py | # -*- coding: utf-8 -*-
import time
from multiprocessing.pool import Pool
import colored
import numpy as np
from dnutils import out, stop, trace, getlogger, ProgressBar, StatusMsg, bf, loggers, newlogger, logs, edict, ifnone, \
ifnot, allnone, allnot, first, sleep, __version__ as version, waitabout
import unitt... |
if __name__ == '__main__':
print('Welcome to dnutils version %s.' % version)
logger = getlogger('results', logs.DEBUG)
logger.info('Initialized. Running all tests...')
wait()
logger.info('Testing log levels...')
logger.debug('this is the debug level')
logger.info('this is the info level')... | expose('/vars/myexposure', 'a', 'b', 'c')
self.assertEqual(inspect('/vars/myexposure'), ['a', 'b', 'c'])
expose('/vars/myexposure2', 2)
self.assertEqual(inspect('/vars/myexposure2'), 2)
expose('/vars/myexposure', 0)
pool = Pool(4)
pool.map(exposure_proc, [[] for _ in rang... | identifier_body |
testp3.py | # -*- coding: utf-8 -*-
import time
from multiprocessing.pool import Pool
import colored
import numpy as np
from dnutils import out, stop, trace, getlogger, ProgressBar, StatusMsg, bf, loggers, newlogger, logs, edict, ifnone, \
ifnot, allnone, allnot, first, sleep, __version__ as version, waitabout
import unitt... |
for e1, e2 in zip(gauss.mean, mean):
self.assertAlmostEqual(e1, e2, 1, 'means differ too much:\n%s\n!=\n%s' % (mean, gauss.mean))
for e1, e2 in zip(np.nditer(np.array(gauss.cov)), np.nditer(np.array(cov))):
self.assertAlmostEqual(round(float(e1), 1), e2, 1, 'covariances differ t... | gauss.update(d) | conditional_block |
mut-in-ident-patterns.rs | // Copyright 2013 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 ... | () {
let (a, mut b) = (23i, 4i);
assert_eq!(a, 23);
assert_eq!(b, 4);
b = a + b;
assert_eq!(b, 27);
assert_eq!(X.foo(2), 76);
enum Bar {
Foo(int),
Baz(f32, u8)
}
let (x, mut y) = (32i, Bar::Foo(21));
match x {
mut z @ 32 => {
assert_eq!(z, 3... | main | identifier_name |
mut-in-ident-patterns.rs | // Copyright 2013 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 ... | impl Foo for X {}
pub fn main() {
let (a, mut b) = (23i, 4i);
assert_eq!(a, 23);
assert_eq!(b, 4);
b = a + b;
assert_eq!(b, 27);
assert_eq!(X.foo(2), 76);
enum Bar {
Foo(int),
Baz(f32, u8)
}
let (x, mut y) = (32i, Bar::Foo(21));
match x {
mut z @ 32 =>... | val + x
}
}
struct X; | random_line_split |
mut-in-ident-patterns.rs | // Copyright 2013 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 ... |
_ => {}
}
check_bar(&y);
y = Bar::Baz(10.0, 3);
check_bar(&y);
fn check_bar(y: &Bar) {
match y {
&Bar::Foo(a) => {
assert_eq!(a, 21);
}
&Bar::Baz(a, b) => {
assert_eq!(a, 10.0);
assert_eq!(b, 3);
... | {
assert_eq!(z, 32);
z = 34;
assert_eq!(z, 34);
} | conditional_block |
tasks.py | import re
from django.core import urlresolvers
from django.db import IntegrityError
from cl.citations import find_citations, match_citations
from cl.custom_filters.templatetags.text_filters import best_case_name
from cl.search.models import Opinion, OpinionsCited
from celery import task
def get_document_citations(opi... | except Opinion.MultipleObjectsReturned:
if DEBUG >= 2:
print "Multiple Opinions returned for id %s" % match_id
continue
else:
#create_stub([citation])
if DEBUG >= 2:
# TODO: Don't print 1 line per citation. ... | continue | random_line_split |
tasks.py | import re
from django.core import urlresolvers
from django.db import IntegrityError
from cl.citations import find_citations, match_citations
from cl.custom_filters.templatetags.text_filters import best_case_name
from cl.search.models import Opinion, OpinionsCited
from celery import task
def get_document_citations(opi... | """This is not an OK way to do id-based tasks. Needs to be refactored."""
op = Opinion.objects.get(pk=opinion_id)
update_document(op) | identifier_body | |
tasks.py | import re
from django.core import urlresolvers
from django.db import IntegrityError
from cl.citations import find_citations, match_citations
from cl.custom_filters.templatetags.text_filters import best_case_name
from cl.search.models import Opinion, OpinionsCited
from celery import task
def get_document_citations(opi... | (opinion_id):
"""This is not an OK way to do id-based tasks. Needs to be refactored."""
op = Opinion.objects.get(pk=opinion_id)
update_document(op)
| update_document_by_id | identifier_name |
tasks.py | import re
from django.core import urlresolvers
from django.db import IntegrityError
from cl.citations import find_citations, match_citations
from cl.custom_filters.templatetags.text_filters import best_case_name
from cl.search.models import Opinion, OpinionsCited
from celery import task
def get_document_citations(opi... |
new_html = u'<pre class="inline">%s</pre>' % inner_html
return new_html.encode('utf-8')
@task
def update_document(opinion, index=True):
"""Get the citations for an item and save it and add it to the index if
requested."""
DEBUG = 0
if DEBUG >= 1:
print "%s at %s" % (
... | repl = u'</pre>%s<pre class="inline">' % citation.as_html()
inner_html = re.sub(citation.as_regex(), repl, inner_html) | conditional_block |
sites.module.ts | // (C) Copyright 2015 Martin Dougiamas
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agre... | import { NgModule } from '@angular/core';
import { IonicPageModule } from 'ionic-angular';
import { TranslateModule } from '@ngx-translate/core';
import { CoreLoginSitesPage } from './sites';
import { CoreDirectivesModule } from '@directives/directives.module';
@NgModule({
declarations: [
CoreLoginSitesPag... | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
| random_line_split |
sites.module.ts | // (C) Copyright 2015 Martin Dougiamas
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agre... | {}
| CoreLoginSitesPageModule | identifier_name |
pl.js | // I18N constants
// LANG: "pl", ENCODING: UTF-8
// translated: Krzysztof Kotowicz koto@webworkers.pl
{
"Align": "Wyrównanie",
"All four sides": "Wszystkie 4 strony",
"Background": "Tło",
"Baseline": "Linia bazowa",
"Border": "Ramka",
"Borders": "Ramki",
"Bottom": "Dół",
"Style [CSS]": "Styl [CSS]",
"... | "The bottom side only": "Tylko dolna linia",
"The left-hand side only": "Tylko lewa linia",
"The right and left sides only": "Lewa i prawa linia",
"The right-hand side only": "Tylko prawa linia",
"The top and bottom sides only": "Górna i dolna linia",
"The top side only": "Tylko górna linia",
"Top": "Góra... | "Row properties": "Właściwości wiersza",
"Split row": "Rozdziel wiersz",
"Table properties": "Właściwości tabeli",
"Table Properties": "Właściwości tabeli",
"Text align": "Wyr. w poziomie", | random_line_split |
identity.js | // Copyright 2017 Joyent, Inc.
module.exports = Identity;
var assert = require('assert-plus');
var algs = require('./algs');
var crypto = require('crypto');
var Fingerprint = require('./fingerprint');
var Signature = require('./signature');
var errs = require('./errors');
var util = require('util');
var utils = requi... |
der._offset = end;
return (new Identity({
components: components
}));
};
Identity.isIdentity = function (obj, ver) {
return (utils.isCompatible(obj, Identity, ver));
};
/*
* API versions for Identity:
* [1,0] -- initial ver
*/
Identity.prototype._sshpkApiVersion = [1, 0];
Identity._oldVer... | {
der.readSequence(asn1.Ber.Constructor | asn1.Ber.Set);
var after = der.offset + der.length;
der.readSequence();
var oid = der.readOID();
var type = der.peek();
var value;
switch (type) {
case asn1.Ber.PrintableString:
case asn1.Ber.IA5Str... | conditional_block |
identity.js | // Copyright 2017 Joyent, Inc.
module.exports = Identity;
var assert = require('assert-plus');
var algs = require('./algs');
var crypto = require('crypto');
var Fingerprint = require('./fingerprint');
var Signature = require('./signature');
var errs = require('./errors');
var util = require('util');
var utils = requi... | (opts) {
var self = this;
assert.object(opts, 'options');
assert.arrayOfObject(opts.components, 'options.components');
this.components = opts.components;
this.componentLookup = {};
this.components.forEach(function (c) {
if (c.name && !c.oid)
c.oid = oids[c.name];
if (... | Identity | identifier_name |
identity.js | // Copyright 2017 Joyent, Inc.
module.exports = Identity;
var assert = require('assert-plus');
var algs = require('./algs');
var crypto = require('crypto');
var Fingerprint = require('./fingerprint');
var Signature = require('./signature');
var errs = require('./errors');
var util = require('util');
var utils = requi... |
Identity.prototype.equals = function (other) {
if (!Identity.isIdentity(other, [1, 0]))
return (false);
if (other.components.length !== this.components.length)
return (false);
for (var i = 0; i < this.components.length; ++i) {
if (this.components[i].oid !== other.components[i].oid)... | {
if (a === '**' || b === '**')
return (true);
var aParts = a.split('.');
var bParts = b.split('.');
if (aParts.length !== bParts.length)
return (false);
for (var i = 0; i < aParts.length; ++i) {
if (aParts[i] === '*' || bParts[i] === '*')
continue;
if (aP... | identifier_body |
identity.js | // Copyright 2017 Joyent, Inc.
module.exports = Identity;
var assert = require('assert-plus'); | var util = require('util');
var utils = require('./utils');
var asn1 = require('asn1');
/*JSSTYLED*/
var DNS_NAME_RE = /^([*]|[a-z0-9][a-z0-9\-]{0,62})(?:\.([*]|[a-z0-9][a-z0-9\-]{0,62}))*$/i;
var oids = {};
oids.cn = '2.5.4.3';
oids.o = '2.5.4.10';
oids.ou = '2.5.4.11';
oids.l = '2.5.4.7';
oids.s = '2.5.4.8';
oids.c... | var algs = require('./algs');
var crypto = require('crypto');
var Fingerprint = require('./fingerprint');
var Signature = require('./signature');
var errs = require('./errors'); | random_line_split |
__init__.py | from __future__ import absolute_import, print_function
from ._version import get_versions
import os
try:
from .__conda_version__ import conda_version
__version__ = conda_version.replace("'","")
del conda_version
except ImportError:
__version__ = get_versions()['version']
del get_versions
_notebook... | """
Runs the full Bokeh test suite, outputting
the results of the tests to sys.stdout.
This uses nose tests to discover which tests to
run, and runs tests in any 'tests' subdirectory
within the Bokeh module.
Parameters
----------
verbosity : int, optional
Value 0 prints very li... | identifier_body | |
__init__.py | from __future__ import absolute_import, print_function
from ._version import get_versions
import os
try:
from .__conda_version__ import conda_version
__version__ = conda_version.replace("'","")
del conda_version
except ImportError:
__version__ = get_versions()['version']
del get_versions
_notebook... | ():
"""Returns all the versions of software that Bokeh relies on."""
import platform as pt
message = """
Bokeh version: %s
Python version: %s-%s
Platform: %s
""" % (__version__, pt.python_version(),
pt.python_implementation(), pt.platform())
return(message)
def print_version... | _print_versions | identifier_name |
__init__.py | from __future__ import absolute_import, print_function
from ._version import get_versions
import os
try:
from .__conda_version__ import conda_version
__version__ = conda_version.replace("'","")
del conda_version
except ImportError:
__version__ = get_versions()['version']
del get_versions
_notebook... |
else:
print("Something failed, please check your GHUSER and GHPASS.")
else:
print("Issue not submitted.")
def test(verbosity=1, xunitfile=None, exit=False):
"""
Runs the full Bokeh test suite, outputting
the results of the tests to sys.stdout.
This uses nose tests to d... | g = requests.get(issues_url)
if number is None:
print("Issue successfully submitted.")
if browser:
webbrowser.open_new(g.json()[0].get("html_url"))
else:
print("Comment successfully submitted.")
g = requests.get(... | conditional_block |
__init__.py | from __future__ import absolute_import, print_function
from ._version import get_versions
import os
try:
from .__conda_version__ import conda_version
__version__ = conda_version.replace("'","")
del conda_version
except ImportError:
__version__ = get_versions()['version']
del get_versions
_notebook... |
# It's possible the IPython folks will chance things in the future, `force` parameter
# provides an escape hatch as long as `displaypub` works
if not force:
notebook = False
try:
notebook = 'notebook' in get_ipython().config['IPKernelApp']['parent_appname']
except Except... | global _notebook_loaded | random_line_split |
strings.js | define({
"instruction": "Wybierz i skonfiguruj warstwy, które będą wyświetlane początkowo w tabeli atrybutów.",
"label": "Warstwa",
"show": "Pokaż", | "field": "Pole",
"alias": "Alias",
"visible": "Widoczne",
"linkField": "Pole łącza",
"noLayers": "Brak warstw obiektu",
"back": "Wstecz",
"exportCSV": "Zezwalaj na eksport do pliku CSV",
"expand": "Wstępnie rozwiń widżet",
"filterByExtent": "Domyślnie włącz opcję Filtruj wg zasięgu mapy",
"restore":... | "actions": "Skonfiguruj pola warstwy", | random_line_split |
one_time_data.py | # Amara, universalsubtitles.org
#
# Copyright (C) 2017 Participatory Culture Foundation
#
# This program 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 op... | (token):
return "one-time-data-" + token
def set_one_time_data(data):
token = str(uuid.uuid4())
key = _mk_key(token)
cache.set(key, data, 60)
return '{}://{}{}'.format(settings.DEFAULT_PROTOCOL,
settings.HOSTNAME,
reverse("one_time_u... | _mk_key | identifier_name |
one_time_data.py | # Amara, universalsubtitles.org
#
# Copyright (C) 2017 Participatory Culture Foundation
#
# This program 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 op... | settings.HOSTNAME,
reverse("one_time_url", kwargs={"token": token}))
def get_one_time_data(token):
key = _mk_key(token)
data = cache.get(key)
# It seems like Brightcove wants to hit it twice
# cache.delete(key)
return data | key = _mk_key(token)
cache.set(key, data, 60)
return '{}://{}{}'.format(settings.DEFAULT_PROTOCOL, | random_line_split |
one_time_data.py | # Amara, universalsubtitles.org
#
# Copyright (C) 2017 Participatory Culture Foundation
#
# This program 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 op... |
def set_one_time_data(data):
token = str(uuid.uuid4())
key = _mk_key(token)
cache.set(key, data, 60)
return '{}://{}{}'.format(settings.DEFAULT_PROTOCOL,
settings.HOSTNAME,
reverse("one_time_url", kwargs={"token": token}))
def get_one_... | return "one-time-data-" + token | identifier_body |
shared-card-australia-images.tsx | import { graphql, useStaticQuery } from "gatsby" | import React, { useEffect } from "react"
import { ExtraImageProps } from "../../../../types/shared"
export const alt = {
fromTownsvilleToCairns: "Koala sleeping in a tree",
greenIsland: "Boat in front of Green Island",
kurandaVillage: "Boat in front of Green Island",
magneticIsland: "Bay Overview From Magnetic... | import Img from "gatsby-image" | random_line_split |
setup.py | import os
from setuptools import setup
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name = "nxtools",
version = "0.8.4",
author = "Martin Wacker",
author_email = "martas@imm.cz",
description = "Set of common utilities and little helpers.",
lice... | ) | random_line_split | |
setup.py | import os
from setuptools import setup
def | (fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name = "nxtools",
version = "0.8.4",
author = "Martin Wacker",
author_email = "martas@imm.cz",
description = "Set of common utilities and little helpers.",
license = "MIT",
keywords = "utilities log loggi... | read | identifier_name |
setup.py | import os
from setuptools import setup
def read(fname):
|
setup(
name = "nxtools",
version = "0.8.4",
author = "Martin Wacker",
author_email = "martas@imm.cz",
description = "Set of common utilities and little helpers.",
license = "MIT",
keywords = "utilities log logging ffmpeg watchfolder media mam time",
url = "https://github.com/immstudios... | return open(os.path.join(os.path.dirname(__file__), fname)).read() | identifier_body |
L0SymMultipleDSYMs_flat_1.ts | import ma = require('vsts-task-lib/mock-answer');
import tmrm = require('vsts-task-lib/mock-run');
import path = require('path');
import fs = require('fs');
import azureBlobUploadHelper = require('../azure-blob-upload-helper');
var Readable = require('stream').Readable
var Writable = require('stream').Writable
var Sta... | files = [
'f.txt',
'd',
'x.dsym',
'y.dsym'
]
} else if (folder === 'a/b/c/d') {
files = [
'f.txt'
]
} else if (folder === 'a/b/c/x.dsym') {
files = [
'x1.txt',
'x2.txt'
]
} els... | random_line_split | |
L0SymMultipleDSYMs_flat_1.ts |
import ma = require('vsts-task-lib/mock-answer');
import tmrm = require('vsts-task-lib/mock-run');
import path = require('path');
import fs = require('fs');
import azureBlobUploadHelper = require('../azure-blob-upload-helper');
var Readable = require('stream').Readable
var Writable = require('stream').Writable
var St... | else if (folder === 'a/b/c') {
files = [
'f.txt',
'd',
'x.dsym',
'y.dsym'
]
} else if (folder === 'a/b/c/d') {
files = [
'f.txt'
]
} else if (folder === 'a/b/c/x.dsym') {
files = [
'x1.txt',
... | {
files = [
'f.txt',
'c'
]
} | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.