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 |
|---|---|---|---|---|
grid.rs | scaling: 1.0,
world,
fps: RefCell::new(FPS::default()),
tps: TPS::default(),
illumination: false,
}
}
pub fn view<'a>(&'a mut self) -> Element<'a, Message> {
Canvas::new(self)
.width(Length::Fill)
.height(Length::Fill)
.into()
}
f... | (&self, position_in_units: Point) -> (isize, isize) {
let x = (position_in_units.x / Self::CELL_SIZE).floor() as isize;
let y = (position_in_units.y / Self::CELL_SIZE).floor() as isize;
(x, y)
}
fn set_translation(&mut self, new_translation: Vector) {
self.translation = new_translation;
... | project_to_world | identifier_name |
grid.rs | scaling: 1.0,
world,
fps: RefCell::new(FPS::default()),
tps: TPS::default(),
illumination: false,
}
}
pub fn view<'a>(&'a mut self) -> Element<'a, Message> {
Canvas::new(self)
.width(Length::Fill)
.height(Length::Fill)
.into()
}
f... | let region = self.visible_region(size);
Point::new(
position.x / self.scaling + region.x,
position.y / self.scaling + region.y,
)
}
fn project_to_world(&self, position_in_units: Point) -> (isize, isize) {
let x = (position_in_units.x / Self::CELL_SIZE).floor() as isize;... | fn project(&self, position: Point, size: Size) -> Point { | random_line_split |
grid.rs | {
fn update(
&mut self,
event: Event,
bounds: Rectangle,
cursor: Cursor,
) -> (event::Status, Option<Message>) {
if let Event::Mouse(mouse::Event::ButtonReleased(_)) = event {
self.interaction = Interaction::None;
}
let cursor_position = if let Some(position) =... | {
// Draw the inner grid
let width = 2.0 / Self::CELL_SIZE;
let color = Color::from_rgb8(70, 74, 83);
frame.translate(Vector::new(-width / 2.0, -width / 2.0));
// Draw horizontal lines
for row in rows {
// There must be a special bor... | conditional_block | |
grid.rs | scaling: 1.0,
world,
fps: RefCell::new(FPS::default()),
tps: TPS::default(),
illumination: false,
}
}
pub fn view<'a>(&'a mut self) -> Element<'a, Message> {
Canvas::new(self)
.width(Length::Fill)
.height(Length::Fill)
.into()
}
f... |
fn project(&self, position: Point, size: Size) -> Point {
let region = self.visible_region(size);
Point::new(
position.x / self.scaling + region.x,
position.y / self.scaling + region.y,
)
}
fn project_to_world(&self, position_in_units: Point) -> (isize, isize) {
le... | {
let width = size.width / self.scaling;
let height = size.height / self.scaling;
Region {
x: -self.translation.x,
y: -self.translation.y,
width,
height,
}
} | identifier_body |
logger.js | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _sparkPlugin = require('../lib/spark-plugin');
var _sparkPlugin2 = _interopRequireDefault(_sparkPlugin);
var _sparkCore = require('../spark-core');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { defaul... | debug: wrapConsoleMethod('debug'),
trace: wrapConsoleMethod('trace')
});
(0, _sparkCore.registerPlugin)('logger', Logger);
exports.default = Logger;
//# sourceMappingURL=logger.js.map | info: wrapConsoleMethod('info'), | random_line_split |
logger.js | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _sparkPlugin = require('../lib/spark-plugin');
var _sparkPlugin2 = _interopRequireDefault(_sparkPlugin);
var _sparkCore = require('../spark-core');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { defaul... | (level) {
/* eslint no-console: [0] */
var impls = precedence[level];
if (impls) {
impls = impls.slice();
while (!console[level]) {
level = impls.pop();
}
}
return function wrappedConsoleMethod() {
var _console;
for (var _len = arguments.length, args = Array(_len), _key = 0; _key <... | wrapConsoleMethod | identifier_name |
logger.js | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _sparkPlugin = require('../lib/spark-plugin');
var _sparkPlugin2 = _interopRequireDefault(_sparkPlugin);
var _sparkCore = require('../spark-core');
function _interopRequireDefault(obj) |
/**!
*
* Copyright (c) 2015-2017 Cisco Systems, Inc. See LICENSE file.
* @private
*/
var precedence = {
error: ['log'],
warn: ['error', 'log'],
info: ['log'],
debug: ['info', 'log'],
trace: ['debug', 'info', 'log']
};
/**
* Assigns the specified console method to Logger; uses `precedence` to fallback... | { return obj && obj.__esModule ? obj : { default: obj }; } | identifier_body |
logger.js | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _sparkPlugin = require('../lib/spark-plugin');
var _sparkPlugin2 = _interopRequireDefault(_sparkPlugin);
var _sparkCore = require('../spark-core');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { defaul... |
return function wrappedConsoleMethod() {
var _console;
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
/* eslint no-invalid-this: [0] */
/* istanbul ignore if */
if (process.env.NODE_ENV === 'test' && this.spark &... | {
impls = impls.slice();
while (!console[level]) {
level = impls.pop();
}
} | conditional_block |
ctmutil.py | #!/usr/bin/python
#_*_ coding: utf-8 _*_
#author:张知临 zhzhl202@163.com
#Filename: ctmutil.py
from random import *
import measure
import math
import os.path
c_p = os.path.dirname(os.getcwd())+"/"
#tc_splitTag="\t"
#str_splitTag = "^" #分词分割的标记
def cons_pro_for_svm(label,text,dic,local_fun=measure.tf,... | text:
term = term.strip()
if dic.has_key(term) :
index = int(dic.get(term))
#vec[index]=math.log(string.count(term)+1)*glo_aff_list[index]
vec[index-1]+=1
if normalization ==1:
#表示需要对向量进行归一化
temp_dic={}
vec_sum=0.0
... |
for term in | identifier_name |
ctmutil.py | #!/usr/bin/python
#_*_ coding: utf-8 _*_
#author:张知临 zhzhl202@163.com
#Filename: ctmutil.py
from random import *
import measure
import math
import os.path
c_p = os.path.dirname(os.getcwd())+"/"
#tc_splitTag="\t"
#str_splitTag = "^" #分词分割的标记
def cons_pro_for_svm(label,text,dic,local_fun=measure.tf,... |
def cons_vec_for_cla(text,dic,glo_aff_list=[],normalization=1):
'''给定词典、全局因子,对文本构造特征向量。需要设定是否需要对向量进行归一化
vector 从0开始算起。
'''
vec = [0]*(len(dic))
if len(glo_aff_list)==0: #如果不输入全局因子,则默认情况下就为1,即词频。
glo_aff_list=[1]*(len(dic))
#string = text.strip().split(str_splitTag)
for ter... | # sorted_keys.sort()
# for key in sorted_keys:
# real_x[key]=x[key]
return y,[x]
| random_line_split |
ctmutil.py | #!/usr/bin/python
#_*_ coding: utf-8 _*_
#author:张知临 zhzhl202@163.com
#Filename: ctmutil.py
from random import *
import measure
import math
import os.path
c_p = os.path.dirname(os.getcwd())+"/"
#tc_splitTag="\t"
#str_splitTag = "^" #分词分割的标记
def cons_pro_for_svm(label,text,dic,local_fun=measure.tf,... | vec[i]=vec[i]*glo_aff_list[i]
return vec
def cons_svm_problem(lab,vec):
'''构造svm的问题格式,lab为标签,1或者-1.vec为一个list'''
y=[float(lab)]
x={}
for i in range(len(vec)):
if vec[i]!=0:
x[i+1]=float(vec[i])
return y,[x]
| dic.has_key(term) :
index = int(dic.get(term))
#vec[index]=math.log(string.count(term)+1)*glo_aff_list[index]
vec[index-1]+=1
if normalization ==1:
#表示需要对向量进行归一化
temp_dic={}
vec_sum=0.0
for i in range(len(vec)):
if vec[i... | identifier_body |
ctmutil.py | #!/usr/bin/python
#_*_ coding: utf-8 _*_
#author:张知临 zhzhl202@163.com
#Filename: ctmutil.py
from random import *
import measure
import math
import os.path
c_p = os.path.dirname(os.getcwd())+"/"
#tc_splitTag="\t"
#str_splitTag = "^" #分词分割的标记
def cons_pro_for_svm(label,text,dic,local_fun=measure.tf,... | conditional_block | ||
tree.py | import pygame, math
pygame.init()
window = pygame.display.set_mode((600, 600))
pygame.display.set_caption("Fractal Tree")
screen = pygame.display.get_surface()
def drawTree(x1, y1, angle, depth):
|
def input(event):
if event.type == pygame.QUIT:
exit(0)
drawTree(300, 550, -90, 9)
pygame.display.flip()
while True:
input(pygame.event.wait()) | if depth:
x2 = x1 + int(math.cos(math.radians(angle)) * depth * 10.0)
y2 = y1 + int(math.sin(math.radians(angle)) * depth * 10.0)
pygame.draw.line(screen, (255,255,255), (x1, y1), (x2, y2), 2)
drawTree(x2, y2, angle - 20, depth - 1)
drawTree(x2, y2, angle + 20, depth - 1) | identifier_body |
tree.py | import pygame, math
pygame.init()
window = pygame.display.set_mode((600, 600))
pygame.display.set_caption("Fractal Tree")
screen = pygame.display.get_surface()
def drawTree(x1, y1, angle, depth):
if depth:
x2 = x1 + int(math.cos(math.radians(angle)) * depth * 10.0)
y2 = y1 + int(math.sin(math.ra... |
drawTree(300, 550, -90, 9)
pygame.display.flip()
while True:
input(pygame.event.wait()) | exit(0) | conditional_block |
tree.py | import pygame, math
pygame.init()
window = pygame.display.set_mode((600, 600))
pygame.display.set_caption("Fractal Tree")
screen = pygame.display.get_surface()
def | (x1, y1, angle, depth):
if depth:
x2 = x1 + int(math.cos(math.radians(angle)) * depth * 10.0)
y2 = y1 + int(math.sin(math.radians(angle)) * depth * 10.0)
pygame.draw.line(screen, (255,255,255), (x1, y1), (x2, y2), 2)
drawTree(x2, y2, angle - 20, depth - 1)
drawTree(x2, y2, an... | drawTree | identifier_name |
tree.py | import pygame, math
pygame.init()
window = pygame.display.set_mode((600, 600))
pygame.display.set_caption("Fractal Tree")
screen = pygame.display.get_surface()
| y2 = y1 + int(math.sin(math.radians(angle)) * depth * 10.0)
pygame.draw.line(screen, (255,255,255), (x1, y1), (x2, y2), 2)
drawTree(x2, y2, angle - 20, depth - 1)
drawTree(x2, y2, angle + 20, depth - 1)
def input(event):
if event.type == pygame.QUIT:
exit(0)
drawTree(300,... | def drawTree(x1, y1, angle, depth):
if depth:
x2 = x1 + int(math.cos(math.radians(angle)) * depth * 10.0) | random_line_split |
restrict-type-argument.rs | fn | <T: Send>(val: T) {}
fn use_impl_sync(val: impl Sync) {
is_send(val); //~ ERROR `impl Sync` cannot be sent between threads safely
}
fn use_where<S>(val: S) where S: Sync {
is_send(val); //~ ERROR `S` cannot be sent between threads safely
}
fn use_bound<S: Sync>(val: S) {
is_send(val); //~ ERROR `S` canno... | is_send | identifier_name |
restrict-type-argument.rs | fn is_send<T: Send>(val: T) {}
fn use_impl_sync(val: impl Sync) {
is_send(val); //~ ERROR `impl Sync` cannot be sent between threads safely
}
| is_send(val); //~ ERROR `S` cannot be sent between threads safely
}
fn use_bound_2<
S // Make sure we can synthezise a correct suggestion span for this case
:
Sync
>(val: S) {
is_send(val); //~ ERROR `S` cannot be sent between threads safely
}
fn use_bound_and_where<S: Sync>(val: S) where S: std::... | fn use_where<S>(val: S) where S: Sync {
is_send(val); //~ ERROR `S` cannot be sent between threads safely
}
fn use_bound<S: Sync>(val: S) { | random_line_split |
restrict-type-argument.rs | fn is_send<T: Send>(val: T) |
fn use_impl_sync(val: impl Sync) {
is_send(val); //~ ERROR `impl Sync` cannot be sent between threads safely
}
fn use_where<S>(val: S) where S: Sync {
is_send(val); //~ ERROR `S` cannot be sent between threads safely
}
fn use_bound<S: Sync>(val: S) {
is_send(val); //~ ERROR `S` cannot be sent between th... | {} | identifier_body |
podium.tsx | import h from "hyperapp-jsx-pragma";
import { get_attachment, get_tag, s_to_mns, title_case } from "../utils";
import { Lyrics, AutoplayCountdown } from "./common";
import { Dequeue, Stop, UpdatePodiumProgress } from "../actions";
import { SendCommand } from "../effects";
export const PodiumScreen = ({ state }: { stat... | (state.progress)} /{" "}
{s_to_mns(state.queue[0].track.duration)})
</small>
</div>
) : (
<div
class={"startButton"}
onclick={(state) => [state, SendCommand(state, "play")]}
style={{
"... | s_to_mns | identifier_name |
podium.tsx | import h from "hyperapp-jsx-pragma";
import { get_attachment, get_tag, s_to_mns, title_case } from "../utils";
import { Lyrics, AutoplayCountdown } from "./common";
import { Dequeue, Stop, UpdatePodiumProgress } from "../actions";
import { SendCommand } from "../effects";
export const PodiumScreen = ({ state }: { stat... |
{s_to_mns(state.queue[0].track.duration)})
</small>
</div>
) : (
<div
class={"startButton"}
onclick={(state) => [state, SendCommand(state, "play")]}
style={{
"background-position":
... | {" "} | identifier_body |
podium.tsx | import h from "hyperapp-jsx-pragma";
import { get_attachment, get_tag, s_to_mns, title_case } from "../utils";
import { Lyrics, AutoplayCountdown } from "./common";
import { Dequeue, Stop, UpdatePodiumProgress } from "../actions";
import { SendCommand } from "../effects";
export const PodiumScreen = ({ state }: { stat... | ({s_to_mns(state.progress)} /{" "}
{s_to_mns(state.queue[0].track.duration)})
</small>
</div>
) : (
<div
class={"startButton"}
onclick={(state) => [state, SendCommand(state, "play")]}
... | "%",
}}
>
Track Playing
<small> | random_line_split |
activateApplicationPackageParameters.js | /*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
* Changes may cause incorrect behavior and will be lost if the code is
* regenerated.
*/
'... | {
/**
* Create a ActivateApplicationPackageParameters.
* @property {string} format The format of the application package binary
* file.
*/
constructor() {
}
/**
* Defines the metadata of ActivateApplicationPackageParameters
*
* @returns {object} metadata of ActivateApplicationPackageParam... | ActivateApplicationPackageParameters | identifier_name |
activateApplicationPackageParameters.js | /*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
* Changes may cause incorrect behavior and will be lost if the code is
* regenerated.
*/
'... | * Create a ActivateApplicationPackageParameters.
* @property {string} format The format of the application package binary
* file.
*/
constructor() {
}
/**
* Defines the metadata of ActivateApplicationPackageParameters
*
* @returns {object} metadata of ActivateApplicationPackageParameters
... | /** | random_line_split |
activateApplicationPackageParameters.js | /*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
* Changes may cause incorrect behavior and will be lost if the code is
* regenerated.
*/
'... |
}
module.exports = ActivateApplicationPackageParameters;
| {
return {
required: false,
serializedName: 'ActivateApplicationPackageParameters',
type: {
name: 'Composite',
className: 'ActivateApplicationPackageParameters',
modelProperties: {
format: {
required: true,
serializedName: 'format',
... | identifier_body |
Observable.ts | import {PartialObserver} from './Observer';
import {Operator} from './Operator';
import {Subscriber} from './Subscriber';
import {Subscription, AnonymousSubscription, TeardownLogic} from './Subscription';
import {root} from './util/root';
import {toSubscriber} from './util/toSubscriber';
import {IfObservable} from './o... | try {
next(value);
} catch (err) {
reject(err);
subscription.unsubscribe();
}
} else {
// if there is NO subscription, then we're getting a nexted
// value synchronously during subscription. We can just call it.
// I... | {
if (!PromiseCtor) {
if (root.Rx && root.Rx.config && root.Rx.config.Promise) {
PromiseCtor = root.Rx.config.Promise;
} else if (root.Promise) {
PromiseCtor = root.Promise;
}
}
if (!PromiseCtor) {
throw new Error('no Promise impl found');
}
return new Promi... | identifier_body |
Observable.ts | import {PartialObserver} from './Observer';
import {Operator} from './Operator';
import {Subscriber} from './Subscriber';
import {Subscription, AnonymousSubscription, TeardownLogic} from './Subscription';
import {root} from './util/root';
import {toSubscriber} from './util/toSubscriber';
import {IfObservable} from './o... | }
}, reject, resolve);
});
}
protected _subscribe(subscriber: Subscriber<any>): TeardownLogic {
return this.source.subscribe(subscriber);
}
// `if` and `throw` are special snow flakes, the compiler sees them as reserved words
static if: typeof IfObservable.create;
static throw: typeo... | next(value); | random_line_split |
Observable.ts | import {PartialObserver} from './Observer';
import {Operator} from './Operator';
import {Subscriber} from './Subscriber';
import {Subscription, AnonymousSubscription, TeardownLogic} from './Subscription';
import {root} from './util/root';
import {toSubscriber} from './util/toSubscriber';
import {IfObservable} from './o... | (subscribe?: <R>(subscriber: Subscriber<R>) => TeardownLogic) {
if (subscribe) {
this._subscribe = subscribe;
}
}
// HACK: Since TypeScript inherits static properties too, we have to
// fight against TypeScript here so Subject can have a different static create signature
/**
* Creates a new co... | constructor | identifier_name |
ac-circle-desc.component.ts | import { Component, forwardRef } from '@angular/core';
import { CesiumProperties } from '../../services/cesium-properties/cesium-properties.service';
import { ComputationCache } from '../../services/computation-cache/computation-cache.service';
import { LayerService } from '../../services/layer-service/layer-service.se... | *
*__Usage :__
* ```
* <ac-circle-desc props="{
* position: data.position,
* radius: 5
* granularity:0.08 // Optional
* }">
* </ac-circle-desc>
* ```
*/
@Component({
selector: 'ac-circle-desc',
template: '',
providers: [{provide: BasicDesc, useExisting: forwardRef(() => AcCirc... | random_line_split | |
ac-circle-desc.component.ts | import { Component, forwardRef } from '@angular/core';
import { CesiumProperties } from '../../services/cesium-properties/cesium-properties.service';
import { ComputationCache } from '../../services/computation-cache/computation-cache.service';
import { LayerService } from '../../services/layer-service/layer-service.se... | (ellipseDrawer: EllipseDrawerService, layerService: LayerService,
computationCache: ComputationCache, cesiumProperties: CesiumProperties) {
super(ellipseDrawer, layerService, computationCache, cesiumProperties);
}
protected _propsEvaluator(context: Object): any {
const cesiumProps = super._pr... | constructor | identifier_name |
glyph.rs | 't actually assert this until asserts are compiled
in/out based on severity, debug/release, etc. This assertion
would wreck the complexity of the lookup.
See Rust Issue #3647, #2228, #3627 for related information.
do self.detail_lookup.borrow |arr| {
assert !arr.contains(en... | random_line_split | ||
glyph.rs | .detail_lookup, &mut unsorted_records);
let mut mut_records : Vec<DetailedGlyphRecord> = unsorted_records;
mut_records.sort_by(|a, b| {
if a < b {
Ordering::Less
} else {
Ordering::Greater
}
});
let mut sorted_records = ... | advance_for_char_range | identifier_name | |
glyph.rs | Less
} else {
Ordering::Greater
}
});
let mut sorted_records = mut_records;
mem::swap(&mut self.detail_lookup, &mut sorted_records);
self.lookup_is_sorted = true;
}
}
// This struct is used by GlyphStore clients to provide new glyph data.
// ... | {
self.iter_glyphs_for_char_range(rang)
.fold(Au(0), |advance, (_, glyph)| advance + glyph.advance())
} | identifier_body | |
glyph.rs | a> GlyphStore {
// Initializes the glyph store, but doesn't actually shape anything.
// Use the set_glyph, set_glyphs() methods to store glyph data.
pub fn new(length: usize, is_whitespace: bool) -> GlyphStore {
assert!(length > 0);
GlyphStore {
entry_buffer: repeat(GlyphEntry::... | {
// No more glyphs for current character. Try to get another.
self.glyph_range = None;
self.next()
} | conditional_block | |
index.tsx | import { __DEV__, cleanChildren, getStylesObject } from '@sajari/react-sdk-utils';
import * as React from 'react';
import tw from 'twin.macro';
import Box from '../Box';
import { colorKeys } from './colors';
import { Color } from './components/Color';
import SwatchContextProvider from './context';
import { SwatchProps... | }: SwatchProps) => {
const styles = getStylesObject({ container: tw`flex flex-wrap -mt-2 -ml-2` }, disableDefaultStyles);
const validChildren = cleanChildren(children);
const setState = React.useCallback(
(color: string) => {
if (checkedColors.includes(color)) {
onChange(checkedColors.filter((c)... | colorCheckedClassName = '',
colorClassName = '',
...rest | random_line_split |
index.tsx | import { __DEV__, cleanChildren, getStylesObject } from '@sajari/react-sdk-utils';
import * as React from 'react';
import tw from 'twin.macro';
import Box from '../Box';
import { colorKeys } from './colors';
import { Color } from './components/Color';
import SwatchContextProvider from './context';
import { SwatchProps... | else {
onChange([...checkedColors, color]);
}
},
[JSON.stringify(checkedColors)],
);
return (
<SwatchContextProvider value={{ state: checkedColors, setState, disableDefaultStyles }}>
<Box css={[styles.container, stylesProp]} {...rest}>
{validChildren.map((child) =>
... | {
onChange(checkedColors.filter((c) => c !== color));
} | conditional_block |
__init__.py | """The Smart Meter Texas integration."""
import asyncio
import logging
from smart_meter_texas import Account, Client
from smart_meter_texas.exceptions import (
SmartMeterTexasAPIError,
SmartMeterTexasAuthError,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_PASSWOR... | (hass: HomeAssistant, config: dict):
"""Set up the Smart Meter Texas component."""
hass.data.setdefault(DOMAIN, {})
return True
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry):
"""Set up Smart Meter Texas from a config entry."""
username = entry.data[CONF_USERNAME]
passwo... | async_setup | identifier_name |
__init__.py | """The Smart Meter Texas integration."""
import asyncio
import logging
from smart_meter_texas import Account, Client
from smart_meter_texas.exceptions import (
SmartMeterTexasAPIError,
SmartMeterTexasAuthError,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_PASSWOR... | """Unload a config entry."""
unload_ok = all(
await asyncio.gather(
*[
hass.config_entries.async_forward_entry_unload(entry, platform)
for platform in PLATFORMS
]
)
)
if unload_ok:
hass.data[DOMAIN].pop(entry.entry_id)
retu... | identifier_body | |
__init__.py | """The Smart Meter Texas integration."""
import asyncio
import logging
from smart_meter_texas import Account, Client
from smart_meter_texas.exceptions import (
SmartMeterTexasAPIError,
SmartMeterTexasAuthError,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_PASSWOR... |
return True
class SmartMeterTexasData:
"""Manages coordinatation of API data updates."""
def __init__(self, hass: HomeAssistant, entry: ConfigEntry, account: Account):
"""Initialize the data coordintator."""
self._entry = entry
self.account = account
websession = aiohttp... | hass.async_create_task(
hass.config_entries.async_forward_entry_setup(entry, platform)
) | conditional_block |
__init__.py | """The Smart Meter Texas integration."""
import asyncio
import logging
from smart_meter_texas import Account, Client
from smart_meter_texas.exceptions import (
SmartMeterTexasAPIError,
SmartMeterTexasAuthError,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_PASSWOR... | DATA_COORDINATOR,
DATA_SMART_METER,
DEBOUNCE_COOLDOWN,
DOMAIN,
SCAN_INTERVAL,
)
_LOGGER = logging.getLogger(__name__)
PLATFORMS = ["sensor"]
async def async_setup(hass: HomeAssistant, config: dict):
"""Set up the Smart Meter Texas component."""
hass.data.setdefault(DOMAIN, {})
return... |
from .const import ( | random_line_split |
myregex.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This file is part of the web2py Web Framework
Copyrighted by Massimo Di Pierro <mdipierro@cs.depaul.edu>
License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html)
"""
import re
| regex_tables = re.compile(
"""^[\w]+\.define_table\(\s*[\'\"](?P<name>\w+)[\'\"]""",
flags=re.M)
# pattern to find exposed functions in controller
regex_expose = re.compile(
'^def\s+(?P<name>(?:[a-zA-Z0-9]\w*)|(?:_[a-zA-Z0-9]\w*))\(\)\s*:',
flags=re.M)
regex_include = re.compile(
'(?P<all>\{\{\s*... | # pattern to find defined tables
| random_line_split |
Functions.js | var util = require('util');
var fs = require('fs');
var path = require('path');
var ltrim = require('underscore.string/ltrim');
exports.isCommand = function (input) {
if (input.toLowerCase().substr(0, prefix.length) === prefix)
return true;
else
return false;
};
exports.isNumber = function (n) {
return ... | return text.split(' ').length - 1;
};
exports.splitInput = function (splitAt, message, intSplit) {
var data = message.split(splitAt)[1];
return data.slice(0, data.length - intSplit);
}; | random_line_split | |
promises-api.ts | import {HttpClient} from 'aurelia-fetch-client';
import _ from 'lodash';
import {HdoApi} from '../util/hdo-api';
import {flattenQuery} from '../util/url';
export interface PromisesQuery {
page?: number;
}
export interface PromisesResponse {
navigators: Object[];
results: Object[];
next_url?: string;
previo... |
fetch(query: PromisesQuery) {
var flattened = flattenQuery(query);
return _.xor(this.previousQuery, flattened).length > 0 ?
this.api.fetch(query)
.then(response => {
this.previousQuery = flattened;
this.previousResponse = response;
return response;
}) :
... | {
this.api = new HdoApi(http, 'https://www.holderdeord.no/promises.json');
this.previousQuery = [];
} | identifier_body |
promises-api.ts | import {HttpClient} from 'aurelia-fetch-client';
import _ from 'lodash';
import {HdoApi} from '../util/hdo-api';
import {flattenQuery} from '../util/url';
export interface PromisesQuery {
page?: number;
}
export interface PromisesResponse {
navigators: Object[];
results: Object[];
next_url?: string;
previo... | (query: PromisesQuery) {
var flattened = flattenQuery(query);
return _.xor(this.previousQuery, flattened).length > 0 ?
this.api.fetch(query)
.then(response => {
this.previousQuery = flattened;
this.previousResponse = response;
return response;
}) :
new P... | fetch | identifier_name |
promises-api.ts | import {HttpClient} from 'aurelia-fetch-client';
import _ from 'lodash';
import {HdoApi} from '../util/hdo-api';
import {flattenQuery} from '../util/url'; |
export interface PromisesResponse {
navigators: Object[];
results: Object[];
next_url?: string;
previous_url?: string;
current_page: number;
total_pages: number;
}
export class PromisesApi {
api: HdoApi;
previousQuery: any[];
previousResponse: any;
constructor(private http: HttpClient) {
this... |
export interface PromisesQuery {
page?: number;
} | random_line_split |
Notification.js | import React, { Component, PropTypes } from 'react' | import { requestGetNotifications, requestDeleteNotification } from './NotificationActions'
import { getNotifications } from './NotificationReducer'
import NotificationList from './components/NotificationList/NotificationList'
// Import Style
import styles from './Notification.css'
class Notification extends Component... | import { connect } from 'react-redux'
import { bindActionCreators } from 'redux' | random_line_split |
Notification.js | import React, { Component, PropTypes } from 'react'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import { requestGetNotifications, requestDeleteNotification } from './NotificationActions'
import { getNotifications } from './NotificationReducer'
import NotificationList from './compone... | (props) {
super(props)
this.state = {}
}
componentDidMount() {
this.props.getNotifications()
}
render() {
return (
<div className={styles.notification}>
<NotificationList
notifications={this.props.notifications}
deleteNotification={this.props.deleteNotificat... | constructor | identifier_name |
Notification.js | import React, { Component, PropTypes } from 'react'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import { requestGetNotifications, requestDeleteNotification } from './NotificationActions'
import { getNotifications } from './NotificationReducer'
import NotificationList from './compone... |
render() {
return (
<div className={styles.notification}>
<NotificationList
notifications={this.props.notifications}
deleteNotification={this.props.deleteNotification}
>Replies</NotificationList>
<NotificationList
notifications={[]}
deleteNo... | {
this.props.getNotifications()
} | identifier_body |
minify.py | # -*- coding: utf-8 -*-
# Copyright 2013 django-htmlmin authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
import re
import six
import bs4
try:
from django.conf import settings
except:
settings = {}
from .util import force_tex... |
else:
new_string = re_end_space.sub('', new_string)
# bs4 sometimes add a lone newline in the body
new_string = re_single_nl.sub('', new_string)
soup.string.replace_with(new_string)
# Conditional comment content is HTML code so it should b... | new_string = re_end_space.sub(' ', new_string) | conditional_block |
minify.py | # -*- coding: utf-8 -*-
# Copyright 2013 django-htmlmin authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
import re
import six
import bs4
try:
from django.conf import settings
except:
settings = {}
from .util import force_tex... | # bs4/element.py for list).
if not is_prestr(soup):
# reduce multiple space characters
new_string = re_multi_space.sub(' ', soup.string)
if not CONSERVATIVE_WHITESPACE:
(prev_flow, next_flow) = is_inflow(soup)
# if the string is in a fl... | """recursive function to reduce space characters in html code.
:param soup: a BeautifulSoup of the code to reduce
:type soup: bs4.BeautifulSoup
:param ignore_comments: whether or not to keep comments in the
result
:type ignore_comments: bool
"""
# if tag excluded fro... | identifier_body |
minify.py | # license that can be found in the LICENSE file.
import re
import six
import bs4
try:
from django.conf import settings
except:
settings = {}
from .util import force_text
EXCLUDE_TAGS = ("pre", "script", "textarea",)
try:
EXCLUDE_TAGS = getattr(settings, "EXCLUDE_TAGS_FROM_MINIFYING", ("pre", "script", ... | # -*- coding: utf-8 -*-
# Copyright 2013 django-htmlmin authors. All rights reserved.
# Use of this source code is governed by a BSD-style | random_line_split | |
minify.py | # -*- coding: utf-8 -*-
# Copyright 2013 django-htmlmin authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
import re
import six
import bs4
try:
from django.conf import settings
except:
settings = {}
from .util import force_tex... | (soup):
"""test whether an element is a Comment, return a boolean.
:param soup: a BeautifulSoup of the code to reduce
:type soup: bs4.BeautifulSoup
"""
return isinstance(soup, bs4.element.Comment) \
and not re_cond_comment.search(soup.string)
def is_cond_comment(soup):
"""test whether... | is_comment | identifier_name |
camera.py | """This component provides support to the Ring Door Bell camera."""
import asyncio
from datetime import timedelta
import logging
import voluptuous as vol
from homeassistant.components.camera import PLATFORM_SCHEMA, Camera
from homeassistant.components.ffmpeg import DATA_FFMPEG
from homeassistant.const import ATTR_ATT... |
@property
def name(self):
"""Return the name of this camera."""
return self._name
@property
def unique_id(self):
"""Return a unique ID."""
return self._camera.id
@property
def device_state_attributes(self):
"""Return the state attributes."""
re... | """Initialize a Ring Door Bell camera."""
super(RingCam, self).__init__()
self._camera = camera
self._hass = hass
self._name = self._camera.name
self._ffmpeg = hass.data[DATA_FFMPEG]
self._ffmpeg_arguments = device_info.get(CONF_FFMPEG_ARGUMENTS)
self._last_video_... | identifier_body |
camera.py | """This component provides support to the Ring Door Bell camera."""
import asyncio
from datetime import timedelta
import logging
import voluptuous as vol
from homeassistant.components.camera import PLATFORM_SCHEMA, Camera
from homeassistant.components.ffmpeg import DATA_FFMPEG
from homeassistant.const import ATTR_ATT... | video_status = last_event['recording']['status']
if video_status == 'ready' and \
(self._last_video_id != last_recording_id or
self._utcnow >= self._expires_at):
video_url = self._camera.recording_url(last_recording_id)
if video_url:
_LO... | random_line_split | |
camera.py | """This component provides support to the Ring Door Bell camera."""
import asyncio
from datetime import timedelta
import logging
import voluptuous as vol
from homeassistant.components.camera import PLATFORM_SCHEMA, Camera
from homeassistant.components.ffmpeg import DATA_FFMPEG
from homeassistant.const import ATTR_ATT... | (hass, config, add_entities, discovery_info=None):
"""Set up a Ring Door Bell and StickUp Camera."""
ring = hass.data[DATA_RING]
cams = []
cams_no_plan = []
for camera in ring.doorbells:
if camera.has_subscription:
cams.append(RingCam(hass, camera, config))
else:
... | setup_platform | identifier_name |
camera.py | """This component provides support to the Ring Door Bell camera."""
import asyncio
from datetime import timedelta
import logging
import voluptuous as vol
from homeassistant.components.camera import PLATFORM_SCHEMA, Camera
from homeassistant.components.ffmpeg import DATA_FFMPEG
from homeassistant.const import ATTR_ATT... |
# show notification for all cameras without an active subscription
if cams_no_plan:
cameras = str(', '.join([camera.name for camera in cams_no_plan]))
err_msg = '''A Ring Protect Plan is required for the''' \
''' following cameras: {}.'''.format(cameras)
_LOGGER.err... | cams_no_plan.append(camera) | conditional_block |
args.rs | use super::abi::usercalls::{alloc, raw::ByteBuffer};
use crate::ffi::OsString;
use crate::fmt;
use crate::slice;
use crate::sync::atomic::{AtomicUsize, Ordering};
use crate::sys::os_str::Buf;
use crate::sys_common::FromInner;
#[cfg_attr(test, linkage = "available_externally")]
#[export_name = "_ZN16__rust_internals3st... |
}
pub fn args() -> Args {
let args = unsafe { (ARGS.load(Ordering::Relaxed) as *const ArgsStore).as_ref() };
if let Some(args) = args { Args(args.iter()) } else { Args([].iter()) }
}
pub struct Args(slice::Iter<'static, OsString>);
impl fmt::Debug for Args {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> ... | {
let args = unsafe { alloc::User::<[ByteBuffer]>::from_raw_parts(argv as _, argc as _) };
let args = args
.iter()
.map(|a| OsString::from_inner(Buf { inner: a.copy_user_buffer() }))
.collect::<ArgsStore>();
ARGS.store(Box::into_raw(Box::new(args)) as _, Order... | conditional_block |
args.rs | use super::abi::usercalls::{alloc, raw::ByteBuffer};
use crate::ffi::OsString;
use crate::fmt;
use crate::slice;
use crate::sync::atomic::{AtomicUsize, Ordering};
use crate::sys::os_str::Buf;
use crate::sys_common::FromInner;
#[cfg_attr(test, linkage = "available_externally")]
#[export_name = "_ZN16__rust_internals3st... |
pub struct Args(slice::Iter<'static, OsString>);
impl fmt::Debug for Args {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.0.as_slice().fmt(f)
}
}
impl Iterator for Args {
type Item = OsString;
fn next(&mut self) -> Option<OsString> {
self.0.next().cloned()
}
... | {
let args = unsafe { (ARGS.load(Ordering::Relaxed) as *const ArgsStore).as_ref() };
if let Some(args) = args { Args(args.iter()) } else { Args([].iter()) }
} | identifier_body |
args.rs | use super::abi::usercalls::{alloc, raw::ByteBuffer};
use crate::ffi::OsString;
use crate::fmt;
use crate::slice;
use crate::sync::atomic::{AtomicUsize, Ordering};
use crate::sys::os_str::Buf;
use crate::sys_common::FromInner;
#[cfg_attr(test, linkage = "available_externally")]
#[export_name = "_ZN16__rust_internals3st... | #[cfg_attr(test, allow(dead_code))]
pub unsafe fn init(argc: isize, argv: *const *const u8) {
if argc != 0 {
let args = unsafe { alloc::User::<[ByteBuffer]>::from_raw_parts(argv as _, argc as _) };
let args = args
.iter()
.map(|a| OsString::from_inner(Buf { inner: a.copy_user... | random_line_split | |
args.rs | use super::abi::usercalls::{alloc, raw::ByteBuffer};
use crate::ffi::OsString;
use crate::fmt;
use crate::slice;
use crate::sync::atomic::{AtomicUsize, Ordering};
use crate::sys::os_str::Buf;
use crate::sys_common::FromInner;
#[cfg_attr(test, linkage = "available_externally")]
#[export_name = "_ZN16__rust_internals3st... | (argc: isize, argv: *const *const u8) {
if argc != 0 {
let args = unsafe { alloc::User::<[ByteBuffer]>::from_raw_parts(argv as _, argc as _) };
let args = args
.iter()
.map(|a| OsString::from_inner(Buf { inner: a.copy_user_buffer() }))
.collect::<ArgsStore>();
... | init | identifier_name |
qgl_mgr.js | const sql = require('./sql');
const fetch = require('node-fetch');
/**
* 管理界面
*/
const query = `
myclass:[class_info]!
mystudent(clsid:Int!):[student_info]!
`;
const typeDefs = `
type class_info{
name:String,
clsid:Int
}
type student_info{
name:String,
lastcommit:St... |
module.exports = {
typeDefs,
resolvers,
query
}; | olv:(root,args,context)=>{
return root.olv;
}
}
}; | random_line_split |
qgl_mgr.js | const sql = require('./sql');
const fetch = require('node-fetch');
/**
* 管理界面
*/
const query = `
myclass:[class_info]!
mystudent(clsid:Int!):[student_info]!
`;
const typeDefs = `
type class_info{
name:String,
clsid:Int
}
type student_info{
name:String,
lastcommit:St... | }).catch(function(e){
return [];
});
},
mystudent:(root,{clsid},context)=>{
return sql(`select Top 100 UserName,lastcommit,olv from UserInfo where cls=${clsid}`).then(result=>result.recordset);
}
},
class_info:{
name:(root,args,c... | return [];
}
| conditional_block |
0013_customprogramsconfig.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.26 on 2019-12-13 07:44
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
| dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('programs', '0012_auto_20170419_0018'),
]
operations = [
migrations.CreateModel(
name='CustomProgramsConfig',
fields=[
('id', models.AutoField(auto_created=True, primary_... | identifier_body | |
0013_customprogramsconfig.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.26 on 2019-12-13 07:44
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
... | ('arguments', models.TextField(blank=True, default='', help_text='Useful for manually running a Jenkins job. Specify like "--usernames A B --program-uuids X Y".')),
('changed_by', models.ForeignKey(editable=False, null=True, on_delete=django.db.models.deletion.PROTECT, to=settings.AUTH_U... | ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('change_date', models.DateTimeField(auto_now_add=True, verbose_name='Change date')),
('enabled', models.BooleanField(default=False, verbose_name='Enabled')), | random_line_split |
0013_customprogramsconfig.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.26 on 2019-12-13 07:44
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class | (migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('programs', '0012_auto_20170419_0018'),
]
operations = [
migrations.CreateModel(
name='CustomProgramsConfig',
fields=[
('id', models.AutoFiel... | Migration | identifier_name |
loadMetadata.ts | const REGEX_STRIP = /^[\t\s\r\n]*(.*?)[\t\s\r\n]*$/;
//
// Load Character
//
interface Character {
id: string;
name: string;
world: string;
fcName: string;
}
const REGEX_CHARACTER = /character\/([0-9a-z]+)/;
function getCharacter(charBox: Element | null): Character {
const ret: Character = { id: '', name: ''... | adata {
const charBox = document.querySelector('div.head-my-character__box');
const character = getCharacter(charBox);
const uls = charBox?.querySelectorAll('ul.my-menu__colmun');
const fcUrl = getFCChestUrl(uls);
const m = fcUrl.match(REGEX_FC_CHEST);
const fcId = m ? m[1] : '';
return {
character: {... | LodestoneMet | identifier_name |
loadMetadata.ts | const REGEX_STRIP = /^[\t\s\r\n]*(.*?)[\t\s\r\n]*$/;
//
// Load Character
//
interface Character {
id: string;
name: string;
world: string;
fcName: string;
}
const REGEX_CHARACTER = /character\/([0-9a-z]+)/;
function getCharacter(charBox: Element | null): Character |
//
// Load FC url
//
function getFCChestUrl(charBoxUls: NodeListOf<Element> | undefined): string {
if (!charBoxUls)
charBoxUls = document.querySelectorAll(
'div.head-my-character__box ul.my-menu__colmun'
);
for (let i = 0; i < charBoxUls.length; i++) {
const liA = charBoxUls[i].querySelectorAll(... | {
const ret: Character = { id: '', name: '', world: '', fcName: '' };
if (!charBox) charBox = document.querySelector('div.head-my-character__box');
if (!charBox) return ret;
const li = charBox.querySelector('ul.my-menu__colmun li');
if (!li) return ret;
const a = li.querySelectorAll('a')[1];
if (!a) retur... | identifier_body |
loadMetadata.ts | const REGEX_STRIP = /^[\t\s\r\n]*(.*?)[\t\s\r\n]*$/;
//
// Load Character
//
interface Character {
id: string; | fcName: string;
}
const REGEX_CHARACTER = /character\/([0-9a-z]+)/;
function getCharacter(charBox: Element | null): Character {
const ret: Character = { id: '', name: '', world: '', fcName: '' };
if (!charBox) charBox = document.querySelector('div.head-my-character__box');
if (!charBox) return ret;
const li =... | name: string;
world: string; | random_line_split |
test_utils.py | # -*- coding: utf-8 -*-
# Copyright 2007-2022 The HyperSpy developers
#
# This file is part of HyperSpy.
#
# HyperSpy 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 y... | assert is_hyperspy_signal(s) is True
assert is_hyperspy_signal(p) is False
def test_strlist2enumeration():
assert strlist2enumeration([]) == ""
assert strlist2enumeration("a") == "a"
assert strlist2enumeration(["a"]) == "a"
assert strlist2enumeration(["a", "b"]) == "a and b"
assert strlist... |
def test_is_hyperspy_signal():
s = signals.Signal1D(np.zeros((5, 5, 5)))
p = object() | random_line_split |
test_utils.py | # -*- coding: utf-8 -*-
# Copyright 2007-2022 The HyperSpy developers
#
# This file is part of HyperSpy.
#
# HyperSpy 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 y... | test_parse_quantity():
# From the metadata specification, the quantity is defined as
# "name (units)" without backets in the name of the quantity
assert parse_quantity("a (b)") == ("a", "b")
assert parse_quantity("a (b/(c))") == ("a", "b/(c)")
assert parse_quantity("a (c) (b/(c))") == ("a (c)", "b/... | assert slugify("a") == "a"
assert slugify("1a") == "1a"
assert slugify("1") == "1"
assert slugify("a a") == "a_a"
assert slugify(42) == "42"
assert slugify(3.14159) == "314159"
assert slugify("├── Node1") == "Node1"
assert slugify("a", valid_variable_name=True) == "a"
assert slugify("1a... | identifier_body |
test_utils.py | # -*- coding: utf-8 -*-
# Copyright 2007-2022 The HyperSpy developers
#
# This file is part of HyperSpy.
#
# HyperSpy 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 y... | assert strlist2enumeration([]) == ""
assert strlist2enumeration("a") == "a"
assert strlist2enumeration(["a"]) == "a"
assert strlist2enumeration(["a", "b"]) == "a and b"
assert strlist2enumeration(["a", "b", "c"]) == "a, b and c"
def test_str2num():
assert (
str2num("2.17\t 3.14\t 42\n 1\... | trlist2enumeration():
| identifier_name |
client.rs | // Copyright (c) 2016 P.Y. Laligand
use hyper::Client as HttpClient;
use serde_json::{self, Map, Value};
use std::io::Read;
use super::clip::Clip;
use super::error::XboxError;
use super::xuid::Xuid;
/// Header definition for the API key.
header! { (XAuth, "X-AUTH") => [String] }
/// Interface to the xboxapi.com API... | .and_then(|json| { json.as_u64().ok_or(XboxError::from("Unexpected id format")) })
.map(|value| { Xuid(value) })
}
/// Builds a clip object from its JSON representation.
fn create_clip(json: &mut Map<String, Value>) -> Result<Clip, XboxError> {
let get_value = |key: &str| ->... | pub fn get_xuid(&self, gamertag: &String) -> Result<Xuid, XboxError> {
let path = format!("xuid/{}", gamertag);
self.send_request(&path) | random_line_split |
client.rs | // Copyright (c) 2016 P.Y. Laligand
use hyper::Client as HttpClient;
use serde_json::{self, Map, Value};
use std::io::Read;
use super::clip::Clip;
use super::error::XboxError;
use super::xuid::Xuid;
/// Header definition for the API key.
header! { (XAuth, "X-AUTH") => [String] }
/// Interface to the xboxapi.com API... |
/// Returns the list of available clips for the given user.
pub fn get_clips(&self, xuid: &Xuid) -> Result<Vec<Clip>, XboxError> {
let path = format!("{}/game-clips", xuid);
let mut json = try!(self.send_request(&path));
let json_string = json.to_string();
let clips = try!(json... | {
let get_value = |key: &str| -> Result<String, XboxError> {
json.get(key)
.and_then(|value| { value.as_str() })
.map(|string| { string.to_owned() })
.ok_or(XboxError::new(format!("Could not get key {}", key)))
};
let id = try!(get_valu... | identifier_body |
client.rs | // Copyright (c) 2016 P.Y. Laligand
use hyper::Client as HttpClient;
use serde_json::{self, Map, Value};
use std::io::Read;
use super::clip::Clip;
use super::error::XboxError;
use super::xuid::Xuid;
/// Header definition for the API key.
header! { (XAuth, "X-AUTH") => [String] }
/// Interface to the xboxapi.com API... | {
/// The API key to authenticate with the service.
api_key: String,
}
/// Base URL for API calls.
const BASE_URL: &'static str = "https://xboxapi.com/v2";
impl Client {
/// Creates a new instance with the given API key.
pub fn new(api_key: String) -> Client {
Client {api_key: api_key}
... | Client | identifier_name |
replay.rs | const REPLAY_BUFFER_SIZE: usize = 256;
const EMPTY_ENTRY: u64 = 0xFFFFFFFFFFFFFFFF;
pub struct ReplayProtection {
most_recent_sequence: u64,
received_packet: [u64; REPLAY_BUFFER_SIZE]
}
impl Clone for ReplayProtection {
fn clone(&self) -> ReplayProtection {
ReplayProtection {
most_rece... | () -> ReplayProtection {
ReplayProtection {
most_recent_sequence: 0,
received_packet: [EMPTY_ENTRY; REPLAY_BUFFER_SIZE]
}
}
pub fn packet_already_received(&mut self, sequence: u64) -> bool {
if sequence & (1 << 63) == (1 << 63) {
return false;
... | new | identifier_name |
replay.rs | const REPLAY_BUFFER_SIZE: usize = 256;
const EMPTY_ENTRY: u64 = 0xFFFFFFFFFFFFFFFF;
pub struct ReplayProtection {
most_recent_sequence: u64,
received_packet: [u64; REPLAY_BUFFER_SIZE]
}
impl Clone for ReplayProtection {
fn clone(&self) -> ReplayProtection {
ReplayProtection {
most_rece... | pub fn packet_already_received(&mut self, sequence: u64) -> bool {
if sequence & (1 << 63) == (1 << 63) {
return false;
}
if sequence + (REPLAY_BUFFER_SIZE as u64) <= self.most_recent_sequence {
return true
}
if sequence > self.most_recent_se... | random_line_split | |
replay.rs | const REPLAY_BUFFER_SIZE: usize = 256;
const EMPTY_ENTRY: u64 = 0xFFFFFFFFFFFFFFFF;
pub struct ReplayProtection {
most_recent_sequence: u64,
received_packet: [u64; REPLAY_BUFFER_SIZE]
}
impl Clone for ReplayProtection {
fn clone(&self) -> ReplayProtection {
ReplayProtection {
most_rece... |
if sequence > self.most_recent_sequence {
self.most_recent_sequence = sequence;
}
let index = sequence as usize % REPLAY_BUFFER_SIZE;
if self.received_packet[index] == EMPTY_ENTRY {
self.received_packet[index] = sequence;
return false
... | {
return true
} | conditional_block |
replay.rs | const REPLAY_BUFFER_SIZE: usize = 256;
const EMPTY_ENTRY: u64 = 0xFFFFFFFFFFFFFFFF;
pub struct ReplayProtection {
most_recent_sequence: u64,
received_packet: [u64; REPLAY_BUFFER_SIZE]
}
impl Clone for ReplayProtection {
fn clone(&self) -> ReplayProtection |
}
impl ReplayProtection {
pub fn new() -> ReplayProtection {
ReplayProtection {
most_recent_sequence: 0,
received_packet: [EMPTY_ENTRY; REPLAY_BUFFER_SIZE]
}
}
pub fn packet_already_received(&mut self, sequence: u64) -> bool {
if sequence & (1 << 63) == (1 ... | {
ReplayProtection {
most_recent_sequence: self.most_recent_sequence,
received_packet: self.received_packet
}
} | identifier_body |
fetch_info.py | # -*- coding: utf-8 -*-
# @Author: karthik
# @Date: 2016-12-10 21:40:07
# @Last Modified by: chandan
# @Last Modified time: 2016-12-11 12:55:27
from models.portfolio import Portfolio
from models.company import Company
from models.position import Position
import tenjin
from tenjin.helpers import *
import wikipedia... | (bot, update, args):
args = list(parse_args(args))
if len(args) == 0 or "portfolio" in [arg.lower() for arg in args] :
send_portfolio_info(bot, update)
else:
info_companies = get_companies(args)
send_companies_info(bot, update, info_companies)
# get portfolio function
def send_portfolio_info(bot, update):
p... | send_info_handler | identifier_name |
fetch_info.py | # -*- coding: utf-8 -*-
# @Author: karthik
# @Date: 2016-12-10 21:40:07
# @Last Modified by: chandan
# @Last Modified time: 2016-12-11 12:55:27
from models.portfolio import Portfolio
from models.company import Company
from models.position import Position
import tenjin
from tenjin.helpers import *
import wikipedia... |
# get portfolio function
def send_portfolio_info(bot, update):
print "Userid: %d requested portfolio information" %(update.message.chat_id)
context = {
'positions': Portfolio.instance.positions,
'wallet_value': Portfolio.instance.wallet_value,
}
html_str = engine.render('portfolio_info.pyhtml', context)
bo... | args = list(parse_args(args))
if len(args) == 0 or "portfolio" in [arg.lower() for arg in args] :
send_portfolio_info(bot, update)
else:
info_companies = get_companies(args)
send_companies_info(bot, update, info_companies) | identifier_body |
fetch_info.py | # -*- coding: utf-8 -*-
# @Author: karthik
# @Date: 2016-12-10 21:40:07
# @Last Modified by: chandan
# @Last Modified time: 2016-12-11 12:55:27
from models.portfolio import Portfolio
from models.company import Company
from models.position import Position
import tenjin
from tenjin.helpers import *
import wikipedia... |
last_n_days = 10
if len(companies) < 4:
create_graph(companies, last_n_days)
history_text = '''
Here's the price history for {} for the last {} days
'''.format(symbol_string, last_n_days)
bot.sendMessage(chat_id=update.message.chat_id, text=history_text)
bot.sendPhoto(chat_id=update.message.chat_id, ... | symbol_string = symbols[0] | conditional_block |
fetch_info.py | # -*- coding: utf-8 -*-
# @Author: karthik
# @Date: 2016-12-10 21:40:07
# @Last Modified by: chandan
# @Last Modified time: 2016-12-11 12:55:27
from models.portfolio import Portfolio
from models.company import Company
from models.position import Position
import tenjin
from tenjin.helpers import *
import wikipedia... | Here's the price history for {} for the last {} days
'''.format(symbol_string, last_n_days)
bot.sendMessage(chat_id=update.message.chat_id, text=history_text)
bot.sendPhoto(chat_id=update.message.chat_id, photo=open("plots/temp.png",'rb'))
def create_graph(companies, timedel):
fig, ax = plt.subplots()
for... | last_n_days = 10
if len(companies) < 4:
create_graph(companies, last_n_days)
history_text = ''' | random_line_split |
weather.py |
"""Support for HomematicIP Cloud weather devices."""
import logging
from homematicip.aio.device import (
AsyncWeatherSensor, AsyncWeatherSensorPlus, AsyncWeatherSensorPro)
from homematicip.aio.home import AsyncHome
from homeassistant.components.weather import WeatherEntity
from homeassistant.config_entries impor... |
class HomematicipWeatherSensor(HomematicipGenericDevice, WeatherEntity):
"""representation of a HomematicIP Cloud weather sensor plus & basic."""
def __init__(self, home: AsyncHome, device) -> None:
"""Initialize the weather sensor."""
super().__init__(home, device)
@property
def na... | async_add_entities(devices) | conditional_block |
weather.py |
"""Support for HomematicIP Cloud weather devices."""
import logging
from homematicip.aio.device import (
AsyncWeatherSensor, AsyncWeatherSensorPlus, AsyncWeatherSensorPro)
from homematicip.aio.home import AsyncHome
from homeassistant.components.weather import WeatherEntity
from homeassistant.config_entries impor... | (self, home: AsyncHome, device) -> None:
"""Initialize the weather sensor."""
super().__init__(home, device)
@property
def name(self) -> str:
"""Return the name of the sensor."""
return self._device.label
@property
def temperature(self) -> float:
"""Return the p... | __init__ | identifier_name |
weather.py |
"""Support for HomematicIP Cloud weather devices."""
import logging
from homematicip.aio.device import (
AsyncWeatherSensor, AsyncWeatherSensorPlus, AsyncWeatherSensorPro)
from homematicip.aio.home import AsyncHome
from homeassistant.components.weather import WeatherEntity
from homeassistant.config_entries impor... |
@property
def wind_speed(self) -> float:
"""Return the wind speed."""
return self._device.windSpeed
@property
def attribution(self) -> str:
"""Return the attribution."""
return "Powered by Homematic IP"
@property
def condition(self) -> str:
"""Return t... | """Return the humidity."""
return self._device.humidity | identifier_body |
weather.py | """Support for HomematicIP Cloud weather devices."""
import logging | AsyncWeatherSensor, AsyncWeatherSensorPlus, AsyncWeatherSensorPro)
from homematicip.aio.home import AsyncHome
from homeassistant.components.weather import WeatherEntity
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import TEMP_CELSIUS
from homeassistant.core import HomeAssistant
fr... |
from homematicip.aio.device import ( | random_line_split |
draw.rs | use std::f32::consts::FRAC_PI_2 as QUARTER_TAU;
use glium::texture::{Texture2d, Texture2dDataSource};
use glium::Display;
use glium::Surface as SurfaceTrait;
use ui::{BB, Px};
use ui::color::Color;
use ui::render::{Renderer, Surface, Buffer, XYAndUV};
use ui::text::{FontFace, FontFaces};
pub use glium::glutin::Mouse... |
pub fn line(&mut self, from: [Px; 2], to: [Px; 2], width: Px, color: Color) {
self.with_surface(|this| this.renderer.colored(&mut this.surface, color, |buffer| {
buffer.line(from, to, width);
}));
}
pub fn fill(&mut self, bb: BB<Px>, color: Color/*, corner_radius: Px*/) {
... | {
self.surface.finish().unwrap();
} | identifier_body |
draw.rs | use std::f32::consts::FRAC_PI_2 as QUARTER_TAU;
use glium::texture::{Texture2d, Texture2dDataSource};
use glium::Display;
use glium::Surface as SurfaceTrait;
use ui::{BB, Px};
use ui::color::Color;
use ui::render::{Renderer, Surface, Buffer, XYAndUV};
use ui::text::{FontFace, FontFaces};
pub use glium::glutin::Mouse... | self.overlay_drawing = false;
self.overlay_requested = false;
}
}
pub fn draw_overlay<F, T>(&mut self, f: F) -> T where F: FnOnce(&mut DrawCx) -> T {
assert!(!self.inside_overlay);
self.inside_overlay = true;
let r = f(self);
self.inside_overlay =... | x.draw(self); | random_line_split |
draw.rs | use std::f32::consts::FRAC_PI_2 as QUARTER_TAU;
use glium::texture::{Texture2d, Texture2dDataSource};
use glium::Display;
use glium::Surface as SurfaceTrait;
use ui::{BB, Px};
use ui::color::Color;
use ui::render::{Renderer, Surface, Buffer, XYAndUV};
use ui::text::{FontFace, FontFaces};
pub use glium::glutin::Mouse... | (&mut self, cursor: MouseCursor) {
self.with_surface(|this| this.cursor = cursor);
}
pub fn clear(&mut self, color: Color) {
self.renderer.clear(&mut self.surface, color);
}
// TODO make DrawCx linear to ensure this method gets called.
pub fn finish(self) {
self.surface.fin... | cursor | identifier_name |
draw.rs | use std::f32::consts::FRAC_PI_2 as QUARTER_TAU;
use glium::texture::{Texture2d, Texture2dDataSource};
use glium::Display;
use glium::Surface as SurfaceTrait;
use ui::{BB, Px};
use ui::color::Color;
use ui::render::{Renderer, Surface, Buffer, XYAndUV};
use ui::text::{FontFace, FontFaces};
pub use glium::glutin::Mouse... |
}));
}
pub fn border(&mut self, bb: BB<Px>, color: Color, border_size: Px, corner_radius: Px) {
self.with_surface(|this| this.renderer.colored(&mut this.surface, color, |buffer| {
if corner_radius == 0.0 {
buffer.rect_border(bb, border_size);
} else {
... | {
let resolution = (QUARTER_TAU * corner_radius).ceil() as u32;
buffer.rect_round(bb, resolution, corner_radius);
} | conditional_block |
lib.rs | // This file is part of Grust, GObject introspection bindings for Rust
//
// Copyright (C) 2013-2015 Mikhail Zabaluev <mikhail.zabaluev@gmail.com>
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Softwa... | // Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
#![crate_name = "grust"]
#![crate_type = "li... | // but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU | random_line_split |
test_counter.py | import uuid
from nose.tools import eq_
from kazoo.testing import KazooTestCase
class KazooCounterTests(KazooTestCase):
def _makeOne(self, **kw):
|
def test_int_counter(self):
counter = self._makeOne()
eq_(counter.value, 0)
counter += 2
counter + 1
eq_(counter.value, 3)
counter -= 3
counter - 1
eq_(counter.value, -1)
def test_float_counter(self):
counter = self._makeOne(default=0.0)... | path = "/" + uuid.uuid4().hex
return self.client.Counter(path, **kw) | identifier_body |
test_counter.py | import uuid
from nose.tools import eq_
from kazoo.testing import KazooTestCase
class KazooCounterTests(KazooTestCase):
def _makeOne(self, **kw):
path = "/" + uuid.uuid4().hex
return self.client.Counter(path, **kw)
def test_int_counter(self):
counter = self._makeOne()
eq_(co... | (self):
counter = self._makeOne(default=0.0)
eq_(counter.value, 0.0)
counter += 2.1
eq_(counter.value, 2.1)
counter -= 3.1
eq_(counter.value, -1.0)
def test_errors(self):
counter = self._makeOne()
self.assertRaises(TypeError, counter.__add__, 2.1)
... | test_float_counter | identifier_name |
test_counter.py | import uuid
from nose.tools import eq_
from kazoo.testing import KazooTestCase
class KazooCounterTests(KazooTestCase):
def _makeOne(self, **kw):
path = "/" + uuid.uuid4().hex
return self.client.Counter(path, **kw)
def test_int_counter(self):
counter = self._makeOne()
eq_(co... |
def test_float_counter(self):
counter = self._makeOne(default=0.0)
eq_(counter.value, 0.0)
counter += 2.1
eq_(counter.value, 2.1)
counter -= 3.1
eq_(counter.value, -1.0)
def test_errors(self):
counter = self._makeOne()
self.assertRaises(TypeError... | random_line_split | |
bulk-access-control.service.ts | import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { KalturaClient } from 'kaltura-ngx-client';
import { KalturaMediaEntry } from 'kaltura-ngx-client';
import { KalturaBaseEntry } from 'kaltura-ngx-client';
import { BaseEntryUpdateAction } from 'kaltura-ngx-client';
import { BulkActi... | (_kalturaServerClient: KalturaClient) {
super(_kalturaServerClient);
}
public execute(selectedEntries: KalturaMediaEntry[], profile : KalturaAccessControl) : Observable<{}>{
return Observable.create(observer =>{
let requests: BaseEntryUpdateAction[] = [];
selectedEntries.forEach(entry => {
... | constructor | identifier_name |
bulk-access-control.service.ts | import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { KalturaClient } from 'kaltura-ngx-client';
import { KalturaMediaEntry } from 'kaltura-ngx-client';
import { KalturaBaseEntry } from 'kaltura-ngx-client';
import { BaseEntryUpdateAction } from 'kaltura-ngx-client';
import { BulkActi... | } | random_line_split | |
bulk-access-control.service.ts | import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { KalturaClient } from 'kaltura-ngx-client';
import { KalturaMediaEntry } from 'kaltura-ngx-client';
import { KalturaBaseEntry } from 'kaltura-ngx-client';
import { BaseEntryUpdateAction } from 'kaltura-ngx-client';
import { BulkActi... |
public execute(selectedEntries: KalturaMediaEntry[], profile : KalturaAccessControl) : Observable<{}>{
return Observable.create(observer =>{
let requests: BaseEntryUpdateAction[] = [];
selectedEntries.forEach(entry => {
let updatedEntry: KalturaBaseEntry = new KalturaBaseEntry();
u... | {
super(_kalturaServerClient);
} | identifier_body |
setup.py | import os
import re
from setuptools import setup
base_path = os.path.dirname(__file__)
def get_long_description():
readme_md = os.path.join(base_path, "README.md")
with open(readme_md) as f:
return f.read()
| VERSION = re.compile(r'.*__version__ = "(.*?)"', re.S).match(f.read()).group(1)
setup(
name="cfscrape",
packages=["cfscrape"],
version=VERSION,
description='A simple Python module to bypass Cloudflare\'s anti-bot page. See https://github.com/Anorov/cloudflare-scrape for more information.',
long... |
with open(os.path.join(base_path, "cfscrape", "__init__.py")) as f: | random_line_split |
setup.py | import os
import re
from setuptools import setup
base_path = os.path.dirname(__file__)
def get_long_description():
|
with open(os.path.join(base_path, "cfscrape", "__init__.py")) as f:
VERSION = re.compile(r'.*__version__ = "(.*?)"', re.S).match(f.read()).group(1)
setup(
name="cfscrape",
packages=["cfscrape"],
version=VERSION,
description='A simple Python module to bypass Cloudflare\'s anti-bot page. See https... | readme_md = os.path.join(base_path, "README.md")
with open(readme_md) as f:
return f.read() | identifier_body |
setup.py | import os
import re
from setuptools import setup
base_path = os.path.dirname(__file__)
def | ():
readme_md = os.path.join(base_path, "README.md")
with open(readme_md) as f:
return f.read()
with open(os.path.join(base_path, "cfscrape", "__init__.py")) as f:
VERSION = re.compile(r'.*__version__ = "(.*?)"', re.S).match(f.read()).group(1)
setup(
name="cfscrape",
packages=["cfscrape"]... | get_long_description | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.