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 |
|---|---|---|---|---|
test_url_middleware.py | # Copyright 2012 OpenStack Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in... |
def start_fake_response(self, status, headers):
self.response_status = int(status.split(' ', 1)[0])
self.response_headers = dict(headers)
def test_trailing_slash_normalization(self):
"""Tests /v2.0/tokens and /v2.0/tokens/ normalized URLs match."""
req1 = webob.Request.blank('... | self.middleware = middleware.NormalizingFilter(FakeApp())
self.response_status = None
self.response_headers = None
super(UrlMiddlewareTest, self).setUp() | identifier_body |
test_url_middleware.py | # Copyright 2012 OpenStack Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in... | (object):
"""Fakes a WSGI app URL normalized."""
def __call__(self, env, start_response):
resp = webob.Response()
resp.body = 'SUCCESS'
return resp(env, start_response)
class UrlMiddlewareTest(tests.TestCase):
def setUp(self):
self.middleware = middleware.NormalizingFilter(... | FakeApp | identifier_name |
trikRun_fr.ts | <?xml version="1.0" encoding="utf-8"?> | <location filename="../../trikRun/trikRunMain.cpp" line="+64"/>
<source>File with script to execute</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>(optional of -js or -py option is specified)</source>
<tra... | <!DOCTYPE TS>
<TS version="2.1" language="fr_FR">
<context>
<name>QObject</name>
<message> | random_line_split |
ckms_u32.rs | #![no_main]
#[macro_use] extern crate libfuzzer_sys;
extern crate quantiles;
extern crate byteorder;
use std::io::Cursor;
use byteorder::{BigEndian, ReadBytesExt};
#[derive(Debug, Clone, Copy)]
pub struct Xorshift {
seed: u64,
}
impl Xorshift {
pub fn new(seed: u64) -> Xorshift {
Xorshift { seed: see... | (&mut self) -> u32 {
// implementation inspired by
// https://github.com/astocko/xorshift/blob/master/src/splitmix64.rs
use std::num::Wrapping as w;
let mut z = w(self.seed) + w(0x9E37_79B9_7F4A_7C15_u64);
let nxt_seed = z.0;
z = (z ^ (z >> 30)) * w(0xBF58_476D_1CE4_E5B9... | next_val | identifier_name |
ckms_u32.rs | #![no_main]
#[macro_use] extern crate libfuzzer_sys;
extern crate quantiles;
extern crate byteorder;
use std::io::Cursor;
use byteorder::{BigEndian, ReadBytesExt};
#[derive(Debug, Clone, Copy)]
pub struct Xorshift {
seed: u64,
}
impl Xorshift {
pub fn new(seed: u64) -> Xorshift {
Xorshift { seed: see... | z = (z ^ (z >> 27)) * w(0x94D0_49BB_1331_11EB_u64);
self.seed = nxt_seed;
u32::from((z ^ (z >> 31)).0 as u16)
}
}
fuzz_target!(|data: &[u8]| {
let mut cursor = Cursor::new(data);
// unbounded, CKMS will adjust to within bounds
let error: f64 = if let Ok(res) = cursor.read_f64:... | random_line_split | |
ckms_u32.rs | #![no_main]
#[macro_use] extern crate libfuzzer_sys;
extern crate quantiles;
extern crate byteorder;
use std::io::Cursor;
use byteorder::{BigEndian, ReadBytesExt};
#[derive(Debug, Clone, Copy)]
pub struct Xorshift {
seed: u64,
}
impl Xorshift {
pub fn new(seed: u64) -> Xorshift |
pub fn next_val(&mut self) -> u32 {
// implementation inspired by
// https://github.com/astocko/xorshift/blob/master/src/splitmix64.rs
use std::num::Wrapping as w;
let mut z = w(self.seed) + w(0x9E37_79B9_7F4A_7C15_u64);
let nxt_seed = z.0;
z = (z ^ (z >> 30)) * w(... | {
Xorshift { seed: seed }
} | identifier_body |
imports.rs | // Imports.
// Long import.
use syntax::ast::{ItemForeignMod, ItemImpl, ItemMac, ItemMod, ItemStatic, ItemDefaultImpl};
use exceedingly::looooooooooooooooooooooooooooooooooooooooooooooooooooooooooong::import::path::{ItemA,
... | () {
use Baz::*;
use Qux;
}
// Simple imports
use foo::bar::baz;
use bar::quux as kaas;
use foo;
// With aliases.
use foo::{self as bar, baz};
use foo as bar;
use foo::qux as bar;
use foo::{baz, qux as bar};
// With absolute paths
use ::foo;
use ::foo::Bar;
use ::foo::{Bar, Baz};
use ::Foo;
use ::{Bar, Baz};... | test | identifier_name |
imports.rs | // Imports.
// Long import.
use syntax::ast::{ItemForeignMod, ItemImpl, ItemMac, ItemMod, ItemStatic, ItemDefaultImpl};
use exceedingly::looooooooooooooooooooooooooooooooooooooooooooooooooooooooooong::import::path::{ItemA,
... |
// Simple imports
use foo::bar::baz;
use bar::quux as kaas;
use foo;
// With aliases.
use foo::{self as bar, baz};
use foo as bar;
use foo::qux as bar;
use foo::{baz, qux as bar};
// With absolute paths
use ::foo;
use ::foo::Bar;
use ::foo::{Bar, Baz};
use ::Foo;
use ::{Bar, Baz};
| {
use Baz::*;
use Qux;
} | identifier_body |
imports.rs | // Imports.
// Long import.
use syntax::ast::{ItemForeignMod, ItemImpl, ItemMac, ItemMod, ItemStatic, ItemDefaultImpl};
use exceedingly::looooooooooooooooooooooooooooooooooooooooooooooooooooooooooong::import::path::{ItemA,
... | use Foo::{Bar, Baz};
pub use syntax::ast::{Expr_, Expr, ExprAssign, ExprCall, ExprMethodCall, ExprPath};
mod Foo {
pub use syntax::ast::{ItemForeignMod, ItemImpl, ItemMac, ItemMod, ItemStatic, ItemDefaultImpl};
mod Foo2 {
pub use syntax::ast::{self, ItemForeignMod, ItemImpl, ItemMac, ItemMod, ItemStat... | use syntax;
use {/* Pre-comment! */ Foo, Bar /* comment */}; | random_line_split |
data_label_tool.py | """ Defines the DataLabelTool class.
"""
# Major library imports
from numpy import array, asarray, argmin, sqrt
# Enthought library imports
from traits.api import Any, Bool, Enum
from enable.tools.drag_tool import DragTool
class DataLabelTool(DragTool):
""" A tool for dragging a data label.
Attach this tool... |
else:
return False
def drag_start(self, event):
""" Called when the drag operation starts.
Implements DragTool.
"""
if self.component:
label = self.component
pointx, pointy = label.component.map_screen(label.data_point)
self... | label = self.component
return (x >= label.x and x <= label.x2 and \
y >= label.y and y <= label.y2) | conditional_block |
data_label_tool.py | """ Defines the DataLabelTool class.
"""
# Major library imports
from numpy import array, asarray, argmin, sqrt
# Enthought library imports
from traits.api import Any, Bool, Enum
from enable.tools.drag_tool import DragTool
class DataLabelTool(DragTool):
""" A tool for dragging a data label.
Attach this tool... |
def dragging(self, event):
""" This method is called for every mouse_move event that the tool
receives while the user is dragging the mouse.
Implements DragTool. Moves and redraws the label.
"""
if self.component:
label = self.component
dx = int(even... | random_line_split | |
data_label_tool.py | """ Defines the DataLabelTool class.
"""
# Major library imports
from numpy import array, asarray, argmin, sqrt
# Enthought library imports
from traits.api import Any, Bool, Enum
from enable.tools.drag_tool import DragTool
class DataLabelTool(DragTool):
""" A tool for dragging a data label.
Attach this tool... |
def drag_start(self, event):
""" Called when the drag operation starts.
Implements DragTool.
"""
if self.component:
label = self.component
pointx, pointy = label.component.map_screen(label.data_point)
self._original_offset = (label.x - pointx, ... | """ Returns whether the (x,y) position is in a region that is OK to
drag.
Overrides DragTool.
"""
if self.component:
label = self.component
return (x >= label.x and x <= label.x2 and \
y >= label.y and y <= label.y2)
else:
... | identifier_body |
data_label_tool.py | """ Defines the DataLabelTool class.
"""
# Major library imports
from numpy import array, asarray, argmin, sqrt
# Enthought library imports
from traits.api import Any, Bool, Enum
from enable.tools.drag_tool import DragTool
class DataLabelTool(DragTool):
""" A tool for dragging a data label.
Attach this tool... | (self, x, y):
""" Returns whether the (x,y) position is in a region that is OK to
drag.
Overrides DragTool.
"""
if self.component:
label = self.component
return (x >= label.x and x <= label.x2 and \
y >= label.y and y <= label.y2)
... | is_draggable | identifier_name |
Image.tsx | import { css } from 'glamor'
import React, { Component, ImgHTMLAttributes } from 'react'
import { ResourceProviderContext } from '../ResourceProvider'
import View, { IViewProps } from '../View'
interface IImage {
/** Alternative image to use */
alt?: string
/** The URL of the image */
src: string
/** The URL... | *
* ```example
* <Image
* style={{width: 225, height: 225}}
* src="https://placeimg.com/nothing"
* />
* ```
*/
export default class ImageElement extends Component<
IImageProps,
Record<string, boolean>
> {
state = {
useFallback: false,
}
componentDidMount() {
this.loadImage(this.props.src)... | * size="cover"
* src="https://placeimg.com/225/225/people"
* />
* ``` | random_line_split |
Image.tsx | import { css } from 'glamor'
import React, { Component, ImgHTMLAttributes } from 'react'
import { ResourceProviderContext } from '../ResourceProvider'
import View, { IViewProps } from '../View'
interface IImage {
/** Alternative image to use */
alt?: string
/** The URL of the image */
src: string
/** The URL... |
}
loadImage = (src: string) => {
const image = new window.Image()
image.onerror = this.onError
image.src = src
}
getFallbackUrl = (resourcePath?: string) => {
const baseUrl =
typeof resourcePath === 'undefined'
? 'https://static.allthings.me/app/prod/'
: resourcePath
... | {
this.setState({ useFallback: false })
this.loadImage(this.props.src)
} | conditional_block |
Image.tsx | import { css } from 'glamor'
import React, { Component, ImgHTMLAttributes } from 'react'
import { ResourceProviderContext } from '../ResourceProvider'
import View, { IViewProps } from '../View'
interface IImage {
/** Alternative image to use */
alt?: string
/** The URL of the image */
src: string
/** The URL... | extends Component<
IImageProps,
Record<string, boolean>
> {
state = {
useFallback: false,
}
componentDidMount() {
this.loadImage(this.props.src)
}
componentDidUpdate(prevProps: IImageProps) {
if (this.props.src !== prevProps.src) {
this.setState({ useFallback: false })
this.load... | ImageElement | identifier_name |
Image.tsx | import { css } from 'glamor'
import React, { Component, ImgHTMLAttributes } from 'react'
import { ResourceProviderContext } from '../ResourceProvider'
import View, { IViewProps } from '../View'
interface IImage {
/** Alternative image to use */
alt?: string
/** The URL of the image */
src: string
/** The URL... |
loadImage = (src: string) => {
const image = new window.Image()
image.onerror = this.onError
image.src = src
}
getFallbackUrl = (resourcePath?: string) => {
const baseUrl =
typeof resourcePath === 'undefined'
? 'https://static.allthings.me/app/prod/'
: resourcePath
re... | {
if (this.props.src !== prevProps.src) {
this.setState({ useFallback: false })
this.loadImage(this.props.src)
}
} | identifier_body |
global.d.ts | this file to you under the MIT License (MIT), the "License"; you may not use this
// file except in compliance with the License. You may obtain a copy of the License at:
//
// http://opensource.org/licenses/MIT
//
// Unless agreed to in writing, the subject software distributed under the License is distributed ... |
interface State<T> {
Status: SPCTools.Status,
Data: T[],
Error: null | string,
SortField: keyof T,
Ascending: boolean,
Filters?: Filter.IFilter<T>[]
}
interface OptionState<T> {
Status: SPCTools.Status,
Data: T[],
Error: null | strin... | AlarmGroupView: State<SPCTools.IAlarmGroupView>,
WizardAffectedChannel: State<openXDA.IChannel>,
Severity: State<SPCTools.ISeverity>,
SetPointParse: DynamicWizzard.ISetPointParseState,
} | random_line_split |
TestPathTool.py | # -*- coding: utf-8 -*-
# ***************************************************************************
# * Copyright (c) 2017 sliptonic <shopinthewoods@gmail.com> *
# * *
# * This program is free software; you can redistribute it a... | from PathTests.PathTestUtils import PathTestBase
class TestPathTool(PathTestBase):
def test00(self):
'''Verify templateAttrs'''
name = 'tool 1'
mat = 'Carbide'
typ = 'EndMill'
dia = 1.7
flat = 7.2
offset = 3.2
corner = 4
height = 45.3... | # ***************************************************************************
import Path
| random_line_split |
TestPathTool.py | # -*- coding: utf-8 -*-
# ***************************************************************************
# * Copyright (c) 2017 sliptonic <shopinthewoods@gmail.com> *
# * *
# * This program is free software; you can redistribute it a... |
def test02(self):
'''Verify template dictionary construction'''
t0 = self.test00()
t1 = Path.Tool(t0.templateAttrs())
self.assertEqual(t0.Name, t1.Name)
self.assertEqual(t0.ToolType, t1.ToolType)
self.assertEqual(t0.Material, t1.Material)
self.assertEqual(... | '''Verify template roundtrip'''
t0 = self.test00()
t1 = Path.Tool()
t1.setFromTemplate(t0.templateAttrs())
self.assertEqual(t0.Name, t1.Name)
self.assertEqual(t0.ToolType, t1.ToolType)
self.assertEqual(t0.Material, t1.Material)
self.assertEqual(t0.Diameter, t1.D... | identifier_body |
TestPathTool.py | # -*- coding: utf-8 -*-
# ***************************************************************************
# * Copyright (c) 2017 sliptonic <shopinthewoods@gmail.com> *
# * *
# * This program is free software; you can redistribute it a... | (self):
'''Verify template dictionary construction'''
t0 = self.test00()
t1 = Path.Tool(t0.templateAttrs())
self.assertEqual(t0.Name, t1.Name)
self.assertEqual(t0.ToolType, t1.ToolType)
self.assertEqual(t0.Material, t1.Material)
self.assertEqual(t0.Diameter, t1.... | test02 | identifier_name |
marathon.py | import contextlib
import pytest
import logging
from distutils.version import LooseVersion
from .service import service_available_predicate
from ..clients import marathon
from ..matcher import assert_that, eventually, has_len
logger = logging.getLogger(__name__)
marathon_1_3 = pytest.mark.skipif('marathon_version_l... | (service_id=None, deployment_id=None):
deployments = marathon.create_client().get_deployments()
if deployment_id:
filtered = [
deployment for deployment in deployments
if deployment_id == deployment["id"]
]
return filtered
elif service_id:
filtered = [... | deployments_for | identifier_name |
marathon.py | import contextlib
import pytest
import logging
from distutils.version import LooseVersion
from .service import service_available_predicate
from ..clients import marathon
from ..matcher import assert_that, eventually, has_len
logger = logging.getLogger(__name__)
marathon_1_3 = pytest.mark.skipif('marathon_version_l... | def mom_version_less_than(version, name='marathon-user'):
""" Returns True if MoM with the given {name} exists and has a version less
than {version}. Note that if MoM does not exist False is returned.
:param version: required version
:type: string
:param name: MoM name, default is '... | # or raise an exception.
logger.warning('{} MoM not found. Version is None'.format(name))
return None
| random_line_split |
marathon.py | import contextlib
import pytest
import logging
from distutils.version import LooseVersion
from .service import service_available_predicate
from ..clients import marathon
from ..matcher import assert_that, eventually, has_len
logger = logging.getLogger(__name__)
marathon_1_3 = pytest.mark.skipif('marathon_version_l... |
def deployment_wait(service_id=None, deployment_id=None, wait_fixed=2000, max_attempts=60):
""" Wait for a specific app/pod to deploy successfully. If no app/pod Id passed, wait for all
current deployments to succeed. This inner matcher will retry fetching deployments
after `wait_fixed` milliseco... | deployments = marathon.create_client().get_deployments()
if deployment_id:
filtered = [
deployment for deployment in deployments
if deployment_id == deployment["id"]
]
return filtered
elif service_id:
filtered = [
deployment for deployment in d... | identifier_body |
marathon.py | import contextlib
import pytest
import logging
from distutils.version import LooseVersion
from .service import service_available_predicate
from ..clients import marathon
from ..matcher import assert_that, eventually, has_len
logger = logging.getLogger(__name__)
marathon_1_3 = pytest.mark.skipif('marathon_version_l... |
assert_that(lambda: deployments_for(service_id, deployment_id),
eventually(has_len(0), wait_fixed=wait_fixed, max_attempts=max_attempts))
| logger.info('Waiting for all current deployments to finish') | conditional_block |
encoderRun.py | from __future__ import division
import encoder
import socket_class as socket
import threading
import time
import sys
rightC,leftC = (0,0)
s = None
IP = "10.42.0.1"
host = 50679
class sendData(threading.Thread): | self.waitTime = waitTime
threading.Thread.__init__(self)
def run(self):
#send info every waitTime
global s
global rightC,leftC
conf = "OK"
while True:
if(conf == "OK"):
s.send(str(rightC)+","+str(leftC))
conf = s.re... | def __init__(self,waitTime): | random_line_split |
encoderRun.py | from __future__ import division
import encoder
import socket_class as socket
import threading
import time
import sys
rightC,leftC = (0,0)
s = None
IP = "10.42.0.1"
host = 50679
class sendData(threading.Thread):
def __init__(self,waitTime):
self.waitTime = waitTime
threading.Thread.__init__(self)
... |
def checkArgs():
global IP,host
if(len(sys.argv)!=1):
IP = sys.argv[1]
host = sys.argv[2]
if __name__ == "__main__":
"""if 2 arguments are passed in overwrite IP and port number to those values else use IP = 10.42.0.1 and 50679"""
encoder.encoderSetup()
if len(sys.argv) in (1,3):
... | global leftC
leftC += 1
print "right: ",rightC,"\t","left :",leftC | identifier_body |
encoderRun.py | from __future__ import division
import encoder
import socket_class as socket
import threading
import time
import sys
rightC,leftC = (0,0)
s = None
IP = "10.42.0.1"
host = 50679
class sendData(threading.Thread):
def __init__(self,waitTime):
self.waitTime = waitTime
threading.Thread.__init__(self)
... | encoder.getEncoder(right,left)
| """if 2 arguments are passed in overwrite IP and port number to those values else use IP = 10.42.0.1 and 50679"""
encoder.encoderSetup()
if len(sys.argv) in (1,3):
checkArgs()
s = socket.initSocket()
while True:
try:
socket.connect(s,IP,host)
b... | conditional_block |
encoderRun.py | from __future__ import division
import encoder
import socket_class as socket
import threading
import time
import sys
rightC,leftC = (0,0)
s = None
IP = "10.42.0.1"
host = 50679
class sendData(threading.Thread):
def | (self,waitTime):
self.waitTime = waitTime
threading.Thread.__init__(self)
def run(self):
#send info every waitTime
global s
global rightC,leftC
conf = "OK"
while True:
if(conf == "OK"):
s.send(str(rightC)+","+str(leftC))
... | __init__ | identifier_name |
static.rs | // Compiler:
//
// Run-time:
// status: 0
// stdout: 10
// 14
// 1
// 12
// 12
// 1
#![feature(auto_traits, lang_items, no_core, start, intrinsics)]
#![no_std]
#![no_core]
/*
* Core
*/
// Because we don't have core yet.
#[lang = "sized"]
pub trait Sized {}
#[lang = "copy"]
trait Copy... | }
struct WithRef {
refe: &'static Test,
}
static mut CONSTANT: isize = 10;
static mut TEST: Test = Test {
field: 12,
};
static mut TEST2: Test = Test {
field: 14,
};
static mut WITH_REF: WithRef = WithRef {
refe: unsafe { &TEST },
};
#[start]
fn main(mut argc: isize, _argv: *const *const u8) -> is... | field: isize, | random_line_split |
static.rs | // Compiler:
//
// Run-time:
// status: 0
// stdout: 10
// 14
// 1
// 12
// 12
// 1
#![feature(auto_traits, lang_items, no_core, start, intrinsics)]
#![no_std]
#![no_core]
/*
* Core
*/
// Because we don't have core yet.
#[lang = "sized"]
pub trait Sized {}
#[lang = "copy"]
trait Copy... | {
unsafe {
libc::printf(b"%ld\n\0" as *const u8 as *const i8, CONSTANT);
libc::printf(b"%ld\n\0" as *const u8 as *const i8, TEST2.field);
TEST2.field = argc;
libc::printf(b"%ld\n\0" as *const u8 as *const i8, TEST2.field);
libc::printf(b"%ld\n\0" as *const u8 as *const i8, WI... | identifier_body | |
static.rs | // Compiler:
//
// Run-time:
// status: 0
// stdout: 10
// 14
// 1
// 12
// 12
// 1
#![feature(auto_traits, lang_items, no_core, start, intrinsics)]
#![no_std]
#![no_core]
/*
* Core
*/
// Because we don't have core yet.
#[lang = "sized"]
pub trait Sized {}
#[lang = "copy"]
trait Copy... | {
refe: &'static Test,
}
static mut CONSTANT: isize = 10;
static mut TEST: Test = Test {
field: 12,
};
static mut TEST2: Test = Test {
field: 14,
};
static mut WITH_REF: WithRef = WithRef {
refe: unsafe { &TEST },
};
#[start]
fn main(mut argc: isize, _argv: *const *const u8) -> isize {
unsafe ... | WithRef | identifier_name |
app.component.ts |
import { Component, ViewChild } from '@angular/core';
import { jqxChartComponent } from '../../../../../jqwidgets-ts/angular_jqxChart';
import { jqxSliderComponent } from '../../../../../jqwidgets-ts/angular_jqxslider';
import { jqxDropDownListComponent } from '../../../../../jqwidgets-ts/angular_jqxdropdownlist';
... |
source: any =
{
datatype: "tab",
datafields: [
{ name: 'Year' },
{ name: 'HPI' },
{ name: 'BuildCost' },
{ name: 'Population' },
{ name: 'Rate' }
],
url: '../sampledata/homeprices.txt'
};
dataAdapter: any = ne... | {
let args = event.args;
if (args)
{
let value = args.item.value;
this.seriesGroups[0].type = value;
this.myChart.refresh();
}
} | identifier_body |
app.component.ts |
import { Component, ViewChild } from '@angular/core';
import { jqxChartComponent } from '../../../../../jqwidgets-ts/angular_jqxChart';
import { jqxSliderComponent } from '../../../../../jqwidgets-ts/angular_jqxslider';
import { jqxDropDownListComponent } from '../../../../../jqwidgets-ts/angular_jqxdropdownlist';
... |
}
source: any =
{
datatype: "tab",
datafields: [
{ name: 'Year' },
{ name: 'HPI' },
{ name: 'BuildCost' },
{ name: 'Population' },
{ name: 'Rate' }
],
url: '../sampledata/homeprices.txt'
};
dataAdapter: an... | {
let value = args.item.value;
this.seriesGroups[0].type = value;
this.myChart.refresh();
} | conditional_block |
app.component.ts | import { Component, ViewChild } from '@angular/core';
import { jqxChartComponent } from '../../../../../jqwidgets-ts/angular_jqxChart';
import { jqxSliderComponent } from '../../../../../jqwidgets-ts/angular_jqxslider';
import { jqxDropDownListComponent } from '../../../../../jqwidgets-ts/angular_jqxdropdownlist';
@C... | this.seriesGroups[0].endAngle = value + 360;
this.myChart.refresh();
}
sliderRadiusOnChange(event: any): void
{
let value = event.args.value;
this.seriesGroups[0].radius = value;
this.myChart.refresh();
}
dropDownListColorsOnChange(event: any): void
{
... | {
let value = event.args.value;
this.seriesGroups[0].startAngle = value; | random_line_split |
app.component.ts |
import { Component, ViewChild } from '@angular/core';
import { jqxChartComponent } from '../../../../../jqwidgets-ts/angular_jqxChart';
import { jqxSliderComponent } from '../../../../../jqwidgets-ts/angular_jqxslider';
import { jqxDropDownListComponent } from '../../../../../jqwidgets-ts/angular_jqxdropdownlist';
... | (event: any): void
{
let value = event.args.value;
this.seriesGroups[0].startAngle = value;
this.seriesGroups[0].endAngle = value + 360;
this.myChart.refresh();
}
sliderRadiusOnChange(event: any): void
{
let value = event.args.value;
this.seriesGroups[0].r... | sliderStartAngleOnChange | identifier_name |
renderer.py | # encoding=utf8
import sublime
def get_message_from_ftype(ftype, argpos):
msg = ftype["name"] + "("
i = 0
for name, type in ftype["args"]:
if i > 0: msg += ", "
if i == argpos: msg += "*"
msg += name + ("" if type == "?" else ": " + type)
i += 1
msg += ")"
if ftype["retval"] is not None:
... | elf, pfile, view):
pfile.showing_arguments = False
class StatusArghintsRenderer(object):
def render(self, pfile, view, ftype, argpos):
msg = get_message_from_ftype(ftype, argpos)
sublime.status_message(msg)
pfile.showing_arguments = True
def clean(self, pfile, view):
if pfile.showing_argument... | ean(s | identifier_name |
renderer.py | # encoding=utf8
import sublime
def get_message_from_ftype(ftype, argpos):
msg = ftype["name"] + "("
i = 0
for name, type in ftype["args"]:
if i > 0: msg += ", "
if i == argpos: msg += "*"
msg += name + ("" if type == "?" else ": " + type)
i += 1
msg += ")"
if ftype["retval"] is not None:
... | }
</style>
'''
func_signature = '<span class="func-name">{func_name}</span>('.format(func_name=ftype["name"])
i = 0
for name, type in ftype["args"]:
if i > 0: func_signature += ", "
if i == argpos:
func_signature += '<span class="arg-name current-arg">{name}</span>'.format(name=name)
... | }
.type {
color: #07c; | random_line_split |
renderer.py | # encoding=utf8
import sublime
def get_message_from_ftype(ftype, argpos):
msg = ftype["name"] + "("
i = 0
for name, type in ftype["args"]:
if i > 0: msg += ", "
if i == argpos: msg += "*"
msg += name + ("" if type == "?" else ": " + type)
i += 1
msg += ")"
if ftype["retval"] is not None:
... | class TooltipArghintsRenderer(object):
def render(self, pfile, view, ftype, argpos):
view.show_popup(get_html_message_from_ftype(ftype, argpos), sublime.COOPERATE_WITH_AUTO_COMPLETE, max_width=600, on_navigate=go_to_url)
pfile.showing_arguments = True
def clean(self, pfile, view):
pfile.showing_argumen... | port webbrowser
webbrowser.open(url)
| conditional_block |
renderer.py | # encoding=utf8
import sublime
def get_message_from_ftype(ftype, argpos):
msg = ftype["name"] + "("
i = 0
for name, type in ftype["args"]:
if i > 0: msg += ", "
if i == argpos: msg += "*"
msg += name + ("" if type == "?" else ": " + type)
i += 1
msg += ")"
if ftype["retval"] is not None:
... | return maybe_fn
@maybe
def link(url):
return '<a href={url}>{url}</a>'.format(url=url)
@maybe
def hint_line(txt):
return '<div class="hint-line-content">{txt}</div>'.format(txt=txt)
def go_to_url(url=None):
if url:
import webbrowser
webbrowser.open(url)
class TooltipArghintsRenderer(object):
def re... | turn fn(arg) if arg else ''
| identifier_body |
example.js | var auth = require('./lib/index.js');
var config = require('config');
const USERNAME = (process.env.USERNAME) ?
process.env.USERNAME :
config.get('icarus.username');
const PASSWORD = (process.env.PASSWORD) ?
(process.env.PASSWORD) :
config.get('icarus.password');
if (!(USERNAME && PASSWORD)) {
thr... | })
}); | console.log(value); | random_line_split |
example.js | var auth = require('./lib/index.js');
var config = require('config');
const USERNAME = (process.env.USERNAME) ?
process.env.USERNAME :
config.get('icarus.username');
const PASSWORD = (process.env.PASSWORD) ?
(process.env.PASSWORD) :
config.get('icarus.password');
if (!(USERNAME && PASSWORD)) {
thr... |
var formData = [];
for (var i in value) {
if (value.hasOwnProperty(i)) {
formData.push(value[i].id);
}
}
console.log(value)
// call postCurriculumToDeclare(formData, (err, value) {....}) to post them
});
parser.postCurriculumTo... | {
console.log('error:', err.message); // Print the error if one occurred
} | conditional_block |
RemoveTileAtWorldXY.js | /**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2018 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
var RemoveTileAt = require('./RemoveTileAt');
var WorldToTileX = require('./WorldToTileX');
var WorldToTileY = require... | *
* @param {number} worldX - [description]
* @param {number} worldY - [description]
* @param {boolean} [replaceWithNull=true] - If true, this will replace the tile at the specified
* location with null instead of a Tile with an index of -1.
* @param {boolean} [recalculateFaces=true] - [description]
* @param {Pha... | * @function Phaser.Tilemaps.Components.RemoveTileAtWorldXY
* @private
* @since 3.0.0 | random_line_split |
_createOpNode.js | import assert from "assert";
import createNode from "../../../src/scapi/utils/createNode";
import createRef from "../../../src/scapi/utils/createRef";
import isSCNode from "../../../src/scapi/utils/isSCNode";
import isSCRef from "../../../src/scapi/utils/isSCRef";
import createOpNode from "../../../src/scapi/operators/... | assert.throws(() => {
max(1, "2");
});
});
}); | it("should throw TypeError when given invalid type value", () => { | random_line_split |
main.js | (function() {
Smart.ui.createApplicationMainWin = function() {
var navWindow;
var mainWindow = Titanium.UI.createWindow(style.Window);
var lblTitle = Titanium.UI.createLabel(Smart.combine(style.titleBar, {
text : 'SmartSell'
}));
mainWindow.setTitleControl(lblTitle);
//Eerste scherm
navWindow = Ti... | alert('Link bestaat al.');
}else{
if(response.add === true) {
Ti.App.fireEvent('app:reloadLinks', {
action : 'Reload links'
});
Titanium.App.prodId = response.productId;
Titanium.App.linkId=response.linkId;
Titanium.App.linkNaam=response.linkNaam;
... | {
var createReq = Titanium.Network.createHTTPClient();
if(Ti.App.localonline==="local"){
createReq.open("POST", "http://localhost/smartsell/post_addlink.php");
}else{
createReq.open("POST", "http://sofiehendrickx.eu/smartsell/post_addlink.php");
}
var params = {
linkProduct1 : Ti.App.pro... | identifier_body |
main.js | (function() {
Smart.ui.createApplicationMainWin = function() {
var navWindow;
var mainWindow = Titanium.UI.createWindow(style.Window);
var lblTitle = Titanium.UI.createLabel(Smart.combine(style.titleBar, {
text : 'SmartSell'
}));
mainWindow.setTitleControl(lblTitle);
//Eerste scherm
navWindow = Ti... |
Smart.navGroup.open(Smart.ui.createDetailWindow(), {
animated : false
});
});
//Delete row
listLinks.addEventListener('delete', function(e) {
Ti.API.info('DELETE FROM tblLink WHERE linkId=' + links[e.index].linkId);
var deleteReq = Titanium.Network.createH... | //Open detail van window
listLinks.addEventListener('click', function(e) {
Titanium.App.selectedIndex = links[e.index].linkId;
Titanium.App.selectedNaam = links[e.index].linkNaam; | random_line_split |
main.js | (function() {
Smart.ui.createApplicationMainWin = function() {
var navWindow;
var mainWindow = Titanium.UI.createWindow(style.Window);
var lblTitle = Titanium.UI.createLabel(Smart.combine(style.titleBar, {
text : 'SmartSell'
}));
mainWindow.setTitleControl(lblTitle);
//Eerste scherm
navWindow = Ti... | () {
var createReq = Titanium.Network.createHTTPClient();
if(Ti.App.localonline==="local"){
createReq.open("POST", "http://localhost/smartsell/post_addlink.php");
}else{
createReq.open("POST", "http://sofiehendrickx.eu/smartsell/post_addlink.php");
}
var params = {
linkProduct1 : Ti.App.... | addLink | identifier_name |
main.js | (function() {
Smart.ui.createApplicationMainWin = function() {
var navWindow;
var mainWindow = Titanium.UI.createWindow(style.Window);
var lblTitle = Titanium.UI.createLabel(Smart.combine(style.titleBar, {
text : 'SmartSell'
}));
mainWindow.setTitleControl(lblTitle);
//Eerste scherm
navWindow = Ti... | ;
var listLinks = Titanium.UI.createTableView(Smart.combine(style.tableView, {
data : data,
search : searchbar
}));
mainWindow.add(listLinks);
//Open detail van window
listLinks.addEventListener('click', function(e) {
Titanium.App.selectedIndex = links[e.index].linkI... | {
var linkid = links[i].linkId;
var linknaam = links[i].linkNaam;
var row = Ti.UI.createTableViewRow(style.row);
row.filter = links[i].linkNaam;
var name = Ti.UI.createLabel(Smart.combine(style.textNormal, {
text : linknaam,
left : 15,
width : 250
}));... | conditional_block |
_app.constants.js | <%#
Copyright 2013-2017 the original author or authors.
This file is part of the JHipster project, see https://jhipster.github.io/
for more information.
| http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permiss... | 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
| random_line_split |
htmlbodyelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use cssparser::RGBA;
use dom::attr::Attr;
use dom::bindings::codegen::Bindings::EventHandlerBinding::{EventHandler... |
impl HTMLBodyElement {
fn new_inherited(localName: Atom, prefix: Option<DOMString>, document: &Document)
-> HTMLBodyElement {
HTMLBodyElement {
htmlelement: HTMLElement::new_inherited(localName, prefix, document),
}
}
#[allow(unrooted_must_root)]
pub fn... | pub struct HTMLBodyElement {
htmlelement: HTMLElement,
} | random_line_split |
htmlbodyelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use cssparser::RGBA;
use dom::attr::Attr;
use dom::bindings::codegen::Bindings::EventHandlerBinding::{EventHandler... | }
_ => true, // HTMLElement::attribute_mutated will take care of this.
}
},
_ => true,
};
if do_super_mutate {
self.super_type().unwrap().attribute_mutated(attr, mutation);
}
}
}
| {
let do_super_mutate = match (attr.local_name(), mutation) {
(name, AttributeMutation::Set(_)) if name.starts_with("on") => {
let window = window_from_node(self);
// https://html.spec.whatwg.org/multipage/
// #event-handlers-on-elements,-document-obje... | identifier_body |
htmlbodyelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use cssparser::RGBA;
use dom::attr::Attr;
use dom::bindings::codegen::Bindings::EventHandlerBinding::{EventHandler... | (localName: Atom, prefix: Option<DOMString>, document: &Document)
-> HTMLBodyElement {
HTMLBodyElement {
htmlelement: HTMLElement::new_inherited(localName, prefix, document),
}
}
#[allow(unrooted_must_root)]
pub fn new(localName: Atom, prefix: Option<DOMStri... | new_inherited | identifier_name |
html_outputer.py | #!/usr/bin/env python -t
# -*- coding: UTF-8 -*-
import codecs
import urllib
class | (object):
def __init__(self):
self.datas = []
def collect_data(self,data):
if data is None:
return
self.datas.append(data)
def output_html(self):
fout = open('output.html','w')
"""
for data in self.datas:
print data['url'].encode("utf... | HtmlOutputer | identifier_name |
html_outputer.py | #!/usr/bin/env python -t
# -*- coding: UTF-8 -*-
import codecs
import urllib
class HtmlOutputer(object):
def __init__(self):
self.datas = []
def collect_data(self,data):
if data is None:
return
self.datas.append(data)
def output_html(self):
fout = open('output.... | fout.write("</table>")
fout.write("</body>")
fout.write("</html>")
fout.close()
| te("<tr>")
fout.write("<td>%s</td>" % urllib.unquote(data['url'].encode('utf-8')))
fout.write("<td>%s</td>" % data['title'].encode('utf-8'))
fout.write("<td>%s</td>" % data['summary'].encode('utf-8'))
fout.write("</tr>")
| conditional_block |
html_outputer.py | #!/usr/bin/env python -t
# -*- coding: UTF-8 -*-
import codecs
import urllib
class HtmlOutputer(object):
def __init__(self):
self.datas = []
def collect_data(self,data):
if data is None:
return
self.datas.append(data)
def output_html(self):
fout = open('output.... | fout.write("<td>%s</td>" % data['summary'].encode('utf-8'))
fout.write("</tr>")
fout.write("</table>")
fout.write("</body>")
fout.write("</html>")
fout.close() | random_line_split | |
html_outputer.py | #!/usr/bin/env python -t
# -*- coding: UTF-8 -*-
import codecs
import urllib
class HtmlOutputer(object):
| fout.write("<head>")
fout.write("<meta charset='UTF-8'>")
fout.write("</head>")
fout.write("<body>")
fout.write("<table>")
# 默认编码ascii
for data in self.datas:
fout.write("<tr>")
fout.write("<td>%s</td>" % urllib.unquote(da... | def __init__(self):
self.datas = []
def collect_data(self,data):
if data is None:
return
self.datas.append(data)
def output_html(self):
fout = open('output.html','w')
"""
for data in self.datas:
print data['url'].encode("utf-8"), type(da... | identifier_body |
xc.rs | pub struct Something { pub x: isize }
pub trait A {
fn f(&self) -> isize;
fn g(&self) -> isize { 10 }
fn h(&self) -> isize { 11 }
fn lurr(x: &Self, y: &Self) -> isize { x.g() + y.h() }
}
impl A for isize {
fn f(&self) -> isize { 10 }
}
impl A for Something {
fn f(&self) -> isize { 10 }
}
pu... | } | impl TestEquality for isize {
fn test_eq(&self, rhs: &isize) -> bool {
*self == *rhs
} | random_line_split |
xc.rs | pub struct Something { pub x: isize }
pub trait A {
fn f(&self) -> isize;
fn g(&self) -> isize { 10 }
fn | (&self) -> isize { 11 }
fn lurr(x: &Self, y: &Self) -> isize { x.g() + y.h() }
}
impl A for isize {
fn f(&self) -> isize { 10 }
}
impl A for Something {
fn f(&self) -> isize { 10 }
}
pub trait B<T> {
fn thing<U>(&self, x: T, y: U) -> (T, U) { (x, y) }
fn staticthing<U>(_z: &Self, x: T, y: U) -> ... | h | identifier_name |
xc.rs | pub struct Something { pub x: isize }
pub trait A {
fn f(&self) -> isize;
fn g(&self) -> isize { 10 }
fn h(&self) -> isize { 11 }
fn lurr(x: &Self, y: &Self) -> isize { x.g() + y.h() }
}
impl A for isize {
fn f(&self) -> isize { 10 }
}
impl A for Something {
fn f(&self) -> isize |
}
pub trait B<T> {
fn thing<U>(&self, x: T, y: U) -> (T, U) { (x, y) }
fn staticthing<U>(_z: &Self, x: T, y: U) -> (T, U) { (x, y) }
}
impl<T> B<T> for isize { }
impl B<f64> for bool { }
pub trait TestEquality {
fn test_eq(&self, rhs: &Self) -> bool;
fn test_neq(&self, rhs: &Self) -> bool {
... | { 10 } | identifier_body |
worker.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::compartments::enter_realm;
use crate::dom::abstractworker::SimpleWorkerErrorHandler;
use crate::dom::a... | },
));
Ok(())
}
}
impl WorkerMethods for Worker {
/// https://html.spec.whatwg.org/multipage/#dom-worker-postmessage
fn PostMessage(
&self,
cx: JSContext,
message: HandleValue,
transfer: CustomAutoRooterGuard<Vec<*mut JSObject>>,
) -> ErrorRes... | random_line_split | |
worker.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::compartments::enter_realm;
use crate::dom::abstractworker::SimpleWorkerErrorHandler;
use crate::dom::a... | let worker_id = WorkerId(Uuid::new_v4());
if let Some(ref chan) = global.devtools_chan() {
let pipeline_id = global.pipeline_id();
let title = format!("Worker for {}", worker_url);
let page_info = DevtoolsPageInfo {
title: title,
url: w... | {
// Step 2-4.
let worker_url = match global.api_base_url().join(&script_url) {
Ok(url) => url,
Err(_) => return Err(Error::Syntax),
};
let (sender, receiver) = unbounded();
let closing = Arc::new(AtomicBool::new(false));
let worker = Worker::new(... | identifier_body |
worker.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::compartments::enter_realm;
use crate::dom::abstractworker::SimpleWorkerErrorHandler;
use crate::dom::a... | (
&self,
cx: JSContext,
message: HandleValue,
transfer: CustomAutoRooterGuard<Vec<*mut JSObject>>,
) -> ErrorResult {
self.post_message_impl(cx, message, transfer)
}
/// https://html.spec.whatwg.org/multipage/#dom-worker-postmessage
fn PostMessage_(
&self... | PostMessage | identifier_name |
worker.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::compartments::enter_realm;
use crate::dom::abstractworker::SimpleWorkerErrorHandler;
use crate::dom::a... |
let global = worker.global();
let target = worker.upcast();
let _ac = enter_realm(target);
rooted!(in(*global.get_cx()) let mut message = UndefinedValue());
if let Ok(ports) = structuredclone::read(&global, data, message.handle_mut()) {
MessageEvent::dispatch_jsval(... | {
return;
} | conditional_block |
views.py | from urllib.parse import urlparse
from allauth.socialaccount.providers.google.views import GoogleOAuth2Adapter
from allauth.socialaccount.providers.oauth2.views import (
OAuth2CallbackView,
OAuth2LoginView,
)
from kuma.core.decorators import redirect_in_maintenance_mode
from kuma.core.ga_tracking import ACTIO... |
oauth2_login = redirect_in_maintenance_mode(
KumaOAuth2LoginView.adapter_view(GoogleOAuth2Adapter)
)
oauth2_callback = redirect_in_maintenance_mode(
OAuth2CallbackView.adapter_view(GoogleOAuth2Adapter)
)
| http_referer = request.META.get("HTTP_REFERER")
if http_referer:
if urlparse(http_referer).netloc == request.get_host():
track_event(CATEGORY_SIGNUP_FLOW, ACTION_AUTH_STARTED, "google")
return super().dispatch(request) | identifier_body |
views.py | from urllib.parse import urlparse
from allauth.socialaccount.providers.google.views import GoogleOAuth2Adapter
from allauth.socialaccount.providers.oauth2.views import (
OAuth2CallbackView,
OAuth2LoginView,
)
from kuma.core.decorators import redirect_in_maintenance_mode
from kuma.core.ga_tracking import ACTIO... |
return super().dispatch(request)
oauth2_login = redirect_in_maintenance_mode(
KumaOAuth2LoginView.adapter_view(GoogleOAuth2Adapter)
)
oauth2_callback = redirect_in_maintenance_mode(
OAuth2CallbackView.adapter_view(GoogleOAuth2Adapter)
)
| track_event(CATEGORY_SIGNUP_FLOW, ACTION_AUTH_STARTED, "google") | conditional_block |
views.py | from urllib.parse import urlparse
from allauth.socialaccount.providers.google.views import GoogleOAuth2Adapter
from allauth.socialaccount.providers.oauth2.views import (
OAuth2CallbackView,
OAuth2LoginView,
)
from kuma.core.decorators import redirect_in_maintenance_mode
from kuma.core.ga_tracking import ACTIO... | (OAuth2LoginView):
def dispatch(self, request):
# TODO: Figure out a way to NOT trigger the "ACTION_AUTH_STARTED" when
# simply following the link. We've seen far too many submissions when
# curl or some browser extensions follow the link but not actually being
# users who proceed "e... | KumaOAuth2LoginView | identifier_name |
views.py | from urllib.parse import urlparse
from allauth.socialaccount.providers.google.views import GoogleOAuth2Adapter
from allauth.socialaccount.providers.oauth2.views import (
OAuth2CallbackView,
OAuth2LoginView,
)
from kuma.core.decorators import redirect_in_maintenance_mode
from kuma.core.ga_tracking import ACTIO... | )
oauth2_callback = redirect_in_maintenance_mode(
OAuth2CallbackView.adapter_view(GoogleOAuth2Adapter)
) | random_line_split | |
karma.conf.js | // Karma configuration
// Generated on Tue Sep 09 2014 13:58:24 GMT-0700 (PDT)
'use strict';
var browsers = ['Chrome', 'PhantomJS'];
if ( /^win/.test(process.platform) ) {
browsers = ['IE'];
}
if (process.env.TRAVIS ) |
module.exports = function(config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['browserify', 'mocha'],
browserify: {
... | {
browsers = ['PhantomJS'];
} | conditional_block |
karma.conf.js | // Karma configuration
// Generated on Tue Sep 09 2014 13:58:24 GMT-0700 (PDT)
'use strict';
var browsers = ['Chrome', 'PhantomJS'];
if ( /^win/.test(process.platform) ) {
browsers = ['IE'];
}
if (process.env.TRAVIS ) {
browsers = ['PhantomJS'];
}
module.exports = function(config) {
config.set({
// base pa... | transform: ['6to5ify']
},
// list of files / patterns to load in the browser
files: [
'node_modules/chai/chai.js',
'test/front-end/phantomjs-bind-polyfill.js',
'test/front-end/*-spec.js'
],
// list of files to exclude
exclude: [
'**/*.swp'
],
// preproces... |
browserify: {
debug: true, | random_line_split |
models.py | from webapp2_extras.appengine.auth.models import User
from google.appengine.ext import ndb
class User(User):
"""
Universal user model. Can be used with App Engine's default users API,
own auth or third party authentication methods (OpenID, OAuth etc).
based on https://gist.github.com/kylefinley
""... |
class LogVisit(ndb.Model):
user = ndb.KeyProperty(kind=User)
uastring = ndb.StringProperty()
ip = ndb.StringProperty()
timestamp = ndb.StringProperty()
class LogEmail(ndb.Model):
sender = ndb.StringProperty(
required=True)
to = ndb.StringProperty(
required=True)
subject ... | providers = self.get_social_providers_names()
result = {'used': [], 'unused': []}
for k,v in SocialUser.PROVIDERS_INFO.items():
if k in providers:
result['used'].append(v)
else:
result['unused'].append(v)
return result | identifier_body |
models.py | from webapp2_extras.appengine.auth.models import User
from google.appengine.ext import ndb
class User(User):
"""
Universal user model. Can be used with App Engine's default users API,
own auth or third party authentication methods (OpenID, OAuth etc).
based on https://gist.github.com/kylefinley
""... | (cls, user_id, token):
return cls.validate_token(user_id, 'resend-activation-mail', token)
@classmethod
def delete_resend_token(cls, user_id, token):
cls.token_model.get_key(user_id, 'resend-activation-mail', token).delete()
def get_social_providers_names(self):
social_user_objects... | validate_resend_token | identifier_name |
models.py | from webapp2_extras.appengine.auth.models import User
from google.appengine.ext import ndb
class User(User):
"""
Universal user model. Can be used with App Engine's default users API,
own auth or third party authentication methods (OpenID, OAuth etc).
based on https://gist.github.com/kylefinley
""... |
else:
result['unused'].append(v)
return result
class LogVisit(ndb.Model):
user = ndb.KeyProperty(kind=User)
uastring = ndb.StringProperty()
ip = ndb.StringProperty()
timestamp = ndb.StringProperty()
class LogEmail(ndb.Model):
sender = ndb.StringProperty(
... | result['used'].append(v) | conditional_block |
models.py | from webapp2_extras.appengine.auth.models import User
from google.appengine.ext import ndb
class User(User):
"""
Universal user model. Can be used with App Engine's default users API,
own auth or third party authentication methods (OpenID, OAuth etc).
based on https://gist.github.com/kylefinley
""... | return cls.validate_token(user_id, 'resend-activation-mail', token)
@classmethod
def delete_resend_token(cls, user_id, token):
cls.token_model.get_key(user_id, 'resend-activation-mail', token).delete()
def get_social_providers_names(self):
social_user_objects = SocialUser.get_by_us... | random_line_split | |
views.py | PermanentRedirect
from django.shortcuts import get_object_or_404
from django.template import loader, RequestContext
from django.views.decorators.vary import vary_on_headers
from parliament.activity.models import Activity
from parliament.activity import utils as activity
from parliament.core.api import ModelListView, M... | (self, request, pol_id=None, pol_slug=None):
pol = self.get_object(request, pol_id, pol_slug)
if pol.slug and not pol_slug:
return HttpResponsePermanentRedirect(pol.get_absolute_url())
show_statements = bool('page' in request.GET or
(pol.latest_member and not po... | get_html | identifier_name |
views.py | PermanentRedirect
from django.shortcuts import get_object_or_404
from django.template import loader, RequestContext
from django.views.decorators.vary import vary_on_headers
from parliament.activity.models import Activity
from parliament.activity import utils as activity
from parliament.core.api import ModelListView, M... | if pol.slug and not pol_slug:
return HttpResponsePermanentRedirect(pol.get_absolute_url())
show_statements = bool('page' in request.GET or
(pol.latest_member and not pol.latest_member.current))
if show_statements:
STATEMENTS_PER_PAGE = 10
... | resource_name = 'Politician'
def get_object(self, request, pol_id=None, pol_slug=None):
if pol_slug:
return get_object_or_404(Politician, slug=pol_slug)
else:
return get_object_or_404(Politician, pk=pol_id)
def get_related_resources(self, request, obj, result):
... | identifier_body |
views.py | 'name': APIFilters.dbfield(help='e.g. Stephen Harper'),
'family_name': APIFilters.dbfield('name_family', help='e.g. Harper'),
'given_name': APIFilters.dbfield('name_given', help='e.g. Stephen'),
'include': APIFilters.noop(help="'former' to show former MPs (since 94), 'all' for current an... | def item_description(self, activity):
payload = r_excerpt.sub('<br><span style="display: block; border-left: 1px dotted #AAAAAA; margin-left: 2em; padding-left: 1em; font-style: italic; margin-top: 5px;">', activity.payload_wrapped()) | random_line_split | |
views.py | PermanentRedirect
from django.shortcuts import get_object_or_404
from django.template import loader, RequestContext
from django.views.decorators.vary import vary_on_headers
from parliament.activity.models import Activity
from parliament.activity import utils as activity
from parliament.core.api import ModelListView, M... |
if not pol.current_member:
raise Http404
c = RequestContext(request, {
'pol': pol,
'info': pol.info(),
'title': u'Contact %s' % pol.name
})
t = loader.get_template("politicians/contact.html")
return HttpResponse(t.render(c))
def hide_activity(request):
if ... | pol = get_object_or_404(Politician, pk=pol_id) | conditional_block |
test_extended_status.py | # Copyright 2011 OpenStack Foundation
# All Rights Reserved.
#
# 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 requ... |
class ExtendedStatusTest(test.TestCase):
content_type = 'application/json'
prefix = 'os-extended-status:'
def setUp(self):
super(ExtendedStatusTest, self).setUp()
fakes.stub_out_nw_api(self.stubs)
self.stubs.Set(compute.api.API, 'get', fake_compute_get)
self.stubs.Set(com... | db_list = [
fakes.stub_instance(1, uuid=UUID1, task_state="task-1",
vm_state="vm-1", power_state=1, locked_by=None),
fakes.stub_instance(2, uuid=UUID2, task_state="task-2",
vm_state="vm-2", power_state=2, locked_by='admin'),
]
fields = instance_obj.INSTANCE_DEFAUL... | identifier_body |
test_extended_status.py | # Copyright 2011 OpenStack Foundation
# All Rights Reserved.
#
# 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 requ... | (self):
super(ExtendedStatusTest, self).setUp()
fakes.stub_out_nw_api(self.stubs)
self.stubs.Set(compute.api.API, 'get', fake_compute_get)
self.stubs.Set(compute.api.API, 'get_all', fake_compute_get_all)
return_server = fakes.fake_instance_get()
self.stubs.Set(db, 'instan... | setUp | identifier_name |
test_extended_status.py | # Copyright 2011 OpenStack Foundation
# All Rights Reserved.
#
# 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 requ... |
def test_no_instance_passthrough_404(self):
def fake_compute_get(*args, **kwargs):
raise exception.InstanceNotFound(instance_id='fake')
self.stubs.Set(compute.api.API, 'get', fake_compute_get)
url = '/v3/servers/70f6db34-de8d-4fbd-aafb-4065bdfa6115'
res = self._make_r... | self.assertServerStates(server,
vm_state='vm-%s' % (i + 1),
power_state=(i + 1),
task_state='task-%s' % (i + 1),
locked_by=['None', 'admin'][i]) | conditional_block |
test_extended_status.py | # Copyright 2011 OpenStack Foundation
# All Rights Reserved.
#
# 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 requ... | super(ExtendedStatusTest, self).setUp()
fakes.stub_out_nw_api(self.stubs)
self.stubs.Set(compute.api.API, 'get', fake_compute_get)
self.stubs.Set(compute.api.API, 'get_all', fake_compute_get_all)
return_server = fakes.fake_instance_get()
self.stubs.Set(db, 'instance_get_b... | prefix = 'os-extended-status:'
def setUp(self): | random_line_split |
reducer.js | /*
*
* HomePage reducer
*
*/
import { fromJS, List, Map } from 'immutable';
import {
CANCEL_CHANGES,
DELETE_DATA,
DELETE_DATA_SUCCEEDED,
FETCH_DATA,
FETCH_DATA_SUCCEEDED,
ON_CHANGE,
RESET_PROPS,
SET_DATA_TO_EDIT,
SET_FORM,
SET_FORM_ERRORS,
SUBMIT_SUCCEEDED,
UNSET_DATA_TO_EDIT,
} from './co... | case SUBMIT_SUCCEEDED:
return state
.set('formErrors', List([]))
.update('dataToEdit', () => '')
.update('initialData', () => state.get('modifiedData'));
case UNSET_DATA_TO_EDIT:
return state
.set('formErrors', List([]))
.update('dataToEdit', () => '')
... | case SET_FORM_ERRORS:
return state
.update('didCheckErrors', (v) => v = !v)
.set('formErrors', List(action.formErrors)); | random_line_split |
reducer.js | /*
*
* HomePage reducer
*
*/
import { fromJS, List, Map } from 'immutable';
import {
CANCEL_CHANGES,
DELETE_DATA,
DELETE_DATA_SUCCEEDED,
FETCH_DATA,
FETCH_DATA_SUCCEEDED,
ON_CHANGE,
RESET_PROPS,
SET_DATA_TO_EDIT,
SET_FORM,
SET_FORM_ERRORS,
SUBMIT_SUCCEEDED,
UNSET_DATA_TO_EDIT,
} from './co... | case FETCH_DATA_SUCCEEDED:
return state
.updateIn(['data', state.get('endPoint')], () => List(action.data))
.updateIn(['initialData', state.get('endPoint')], () => action.modifiedData)
.update('isLoading', () => false)
.updateIn(['modifiedData', state.get('endPoint')], () => ac... | {
switch (action.type) {
case CANCEL_CHANGES:
return state
.set('formErrors', List([]))
.update('modifiedData', () => state.get('initialData'));
case DELETE_DATA:
return state
.set('dataToDelete', Map(action.dataToDelete))
.set('deleteEndPoint', action.deleteEndPoin... | identifier_body |
reducer.js | /*
*
* HomePage reducer
*
*/
import { fromJS, List, Map } from 'immutable';
import {
CANCEL_CHANGES,
DELETE_DATA,
DELETE_DATA_SUCCEEDED,
FETCH_DATA,
FETCH_DATA_SUCCEEDED,
ON_CHANGE,
RESET_PROPS,
SET_DATA_TO_EDIT,
SET_FORM,
SET_FORM_ERRORS,
SUBMIT_SUCCEEDED,
UNSET_DATA_TO_EDIT,
} from './co... | (state = initialState, action) {
switch (action.type) {
case CANCEL_CHANGES:
return state
.set('formErrors', List([]))
.update('modifiedData', () => state.get('initialData'));
case DELETE_DATA:
return state
.set('dataToDelete', Map(action.dataToDelete))
.set('delete... | homePageReducer | identifier_name |
index.d.ts | // Type definitions for koa-bodyparser v3.x
// Project: https://github.com/koajs/bodyparser
// Definitions by: Jerry Chin <https://github.com/hellopao/>
// Definitions: https://github.com/hellopao/DefinitelyTyped
/* =================== USAGE ===================
import bodyParser = require("koa-bodyparser");
v... |
declare namespace bodyParser { }
export = bodyParser; | /**
* support custom error handle
*/
onerror?: (err: Error, ctx: Koa.Context) => void;
}): Koa.Middleware; | random_line_split |
terminal.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals, division
import os
import shlex
import struct
import platform
import subprocess
def get_terminal_size():
""" get_terminal_size()
- get width and height of console
- works on linux,os x,windows,cygwin(windows)
original... |
return int(cr[1]), int(cr[0])
| cr = (env.get('LINES', 25), env.get('COLUMNS', 80)) | conditional_block |
terminal.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals, division
import os
import shlex
import struct
import platform
import subprocess
def get_terminal_size():
""" get_terminal_size()
- get width and height of console
- works on linux,os x,windows,cygwin(windows)
original... | ():
# get terminal width
# src: http://stackoverflow.com/questions/263890/
# how-do-i-find-the-width-height-of-a-terminal-window
try:
cols = int(subprocess.check_call(shlex.split('tput cols')))
rows = int(subprocess.check_call(shlex.split('tput lines')))
return (cols, rows)
... | _get_terminal_size_tput | identifier_name |
terminal.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals, division
import os
import shlex
import struct
import platform
import subprocess
def get_terminal_size():
""" get_terminal_size()
- get width and height of console
- works on linux,os x,windows,cygwin(windows)
original... | if not cr:
try:
fd = os.open(os.ctermid(), os.O_RDONLY)
cr = ioctl_GWINSZ(fd)
os.close(fd)
except:
pass
if not cr:
cr = (env.get('LINES', 25), env.get('COLUMNS', 80))
return int(cr[1]), int(cr[0]) | return
return cr
cr = ioctl_GWINSZ(0) or ioctl_GWINSZ(1) or ioctl_GWINSZ(2) | random_line_split |
terminal.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals, division
import os
import shlex
import struct
import platform
import subprocess
def get_terminal_size():
""" get_terminal_size()
- get width and height of console
- works on linux,os x,windows,cygwin(windows)
original... |
def _get_terminal_size_linux():
import os
env = os.environ
def ioctl_GWINSZ(fd):
try:
import fcntl, termios, struct, os
cr = struct.unpack(b'hh', fcntl.ioctl(fd, termios.TIOCGWINSZ,
b'1234'))
except:
ret... | try:
cols = int(subprocess.check_call(shlex.split('tput cols')))
rows = int(subprocess.check_call(shlex.split('tput lines')))
return (cols, rows)
except:
pass | identifier_body |
testcase_getatr.py | #! /usr/bin/env python
"""Unit tests for SCardConnect/SCardStatus/SCardDisconnect
This test case can be executed individually, or with all other test cases
thru testsuite_scard.py.
__author__ = "http://www.gemalto.com"
Copyright 2001-2012 gemalto
Author: Jean-Daniel Aussel, mailto:jean-daniel.aussel@gemalto.com
Thi... | (self):
testcase_getATR._getATR(self, 3)
def suite():
suite1 = unittest.makeSuite(testcase_getATR)
return unittest.TestSuite((suite1))
if __name__ == '__main__':
unittest.main()
| test_getATR3 | identifier_name |
testcase_getatr.py | #! /usr/bin/env python
"""Unit tests for SCardConnect/SCardStatus/SCardDisconnect
This test case can be executed individually, or with all other test cases
thru testsuite_scard.py.
__author__ = "http://www.gemalto.com"
Copyright 2001-2012 gemalto
Author: Jean-Daniel Aussel, mailto:jean-daniel.aussel@gemalto.com
Thi... |
if __name__ == '__main__':
unittest.main()
| suite1 = unittest.makeSuite(testcase_getATR)
return unittest.TestSuite((suite1)) | identifier_body |
testcase_getatr.py | #! /usr/bin/env python
"""Unit tests for SCardConnect/SCardStatus/SCardDisconnect
This test case can be executed individually, or with all other test cases
thru testsuite_scard.py.
__author__ = "http://www.gemalto.com"
Copyright 2001-2012 gemalto
Author: Jean-Daniel Aussel, mailto:jean-daniel.aussel@gemalto.com
Thi... | self.assertEquals(hresult, 0)
def _getATR(self, r):
if r < len(expectedATRs) and [] != expectedATRs[r]:
hresult, hcard, dwActiveProtocol = SCardConnect(
self.hcontext,
self.readers[r],
SCARD_SHARE_SHARED,
SCARD_PROTOCOL_T0 ... |
def tearDown(self):
hresult = SCardReleaseContext(self.hcontext) | random_line_split |
testcase_getatr.py | #! /usr/bin/env python
"""Unit tests for SCardConnect/SCardStatus/SCardDisconnect
This test case can be executed individually, or with all other test cases
thru testsuite_scard.py.
__author__ = "http://www.gemalto.com"
Copyright 2001-2012 gemalto
Author: Jean-Daniel Aussel, mailto:jean-daniel.aussel@gemalto.com
Thi... |
def test_getATR0(self):
testcase_getATR._getATR(self, 0)
def test_getATR1(self):
testcase_getATR._getATR(self, 1)
def test_getATR2(self):
testcase_getATR._getATR(self, 2)
def test_getATR3(self):
testcase_getATR._getATR(self, 3)
def suite():
suite1 = unittest.ma... | hresult, hcard, dwActiveProtocol = SCardConnect(
self.hcontext,
self.readers[r],
SCARD_SHARE_SHARED,
SCARD_PROTOCOL_T0 | SCARD_PROTOCOL_T1)
self.assertEquals(hresult, 0)
try:
hresult, reader, state, protocol, atr = ... | conditional_block |
ex_7.rs | /*
Copyright © 2013 Free Software Foundation, Inc
See licensing in LICENSE file
File: examples/ex_7.rs
Author: Jesse 'Jeaye' Wilkerson
Description:
Basic input and attribute example, using the Unicode-aware get_wch functions.
*/
extern crate ncurses;
use std::char;
use ncurses::*;
fn main(... | keypad(stdscr(), true);
noecho();
/* Prompt for a character. */
printw("Enter a character within 2 seconds: ");
/* Wait for input. */
let ch = wget_wch(stdscr());
match ch {
Some(WchResult::KeyCode(KEY_MOUSE)) => {
/* Enable attributes and output message. */
attron(A_BOLD() | A_BLINK());... | /* Enable mouse events. */
mousemask(ALL_MOUSE_EVENTS as mmask_t, None);
/* Allow for extended keyboard (like F1). */ | random_line_split |
ex_7.rs | /*
Copyright © 2013 Free Software Foundation, Inc
See licensing in LICENSE file
File: examples/ex_7.rs
Author: Jesse 'Jeaye' Wilkerson
Description:
Basic input and attribute example, using the Unicode-aware get_wch functions.
*/
extern crate ncurses;
use std::char;
use ncurses::*;
fn main(... | /* Wait for input. */
let ch = wget_wch(stdscr());
match ch {
Some(WchResult::KeyCode(KEY_MOUSE)) => {
/* Enable attributes and output message. */
attron(A_BOLD() | A_BLINK());
printw("\nMouse");
attroff(A_BOLD() | A_BLINK());
printw(" pressed");
}
Some(WchResult::KeyCod... |
let locale_conf = LcCategory::all;
setlocale(locale_conf, "en_US.UTF-8");
/* Setup ncurses. */
initscr();
raw();
/* Require input within 2 seconds. */
halfdelay(20);
/* Enable mouse events. */
mousemask(ALL_MOUSE_EVENTS as mmask_t, None);
/* Allow for extended keyboard (like F1). */
keypad(std... | identifier_body |
ex_7.rs | /*
Copyright © 2013 Free Software Foundation, Inc
See licensing in LICENSE file
File: examples/ex_7.rs
Author: Jesse 'Jeaye' Wilkerson
Description:
Basic input and attribute example, using the Unicode-aware get_wch functions.
*/
extern crate ncurses;
use std::char;
use ncurses::*;
fn m | )
{
let locale_conf = LcCategory::all;
setlocale(locale_conf, "en_US.UTF-8");
/* Setup ncurses. */
initscr();
raw();
/* Require input within 2 seconds. */
halfdelay(20);
/* Enable mouse events. */
mousemask(ALL_MOUSE_EVENTS as mmask_t, None);
/* Allow for extended keyboard (like F1). */
keypad(... | ain( | identifier_name |
ex_7.rs | /*
Copyright © 2013 Free Software Foundation, Inc
See licensing in LICENSE file
File: examples/ex_7.rs
Author: Jesse 'Jeaye' Wilkerson
Description:
Basic input and attribute example, using the Unicode-aware get_wch functions.
*/
extern crate ncurses;
use std::char;
use ncurses::*;
fn main(... |
None => {
printw("\nYou didn't enter a character in time!");
}
}
/* Refresh, showing the previous message. */
refresh();
/* Wait for one more character before exiting. Disable the input timeout. */
nocbreak();
getch();
endwin();
}
|
/* Enable attributes and output message. */
printw("\nKey pressed: ");
attron(A_BOLD() | A_BLINK());
printw(format!("{}\n", char::from_u32(c as u32).expect("Invalid char")).as_ref());
attroff(A_BOLD() | A_BLINK());
}
| conditional_block |
SelectedListItem.js | import React from 'react';
import { makeStyles } from '@material-ui/core/styles';
import List from '@material-ui/core/List';
import ListItem from '@material-ui/core/ListItem';
import ListItemIcon from '@material-ui/core/ListItemIcon';
import ListItemText from '@material-ui/core/ListItemText';
import Divider from '@mate... | </ListItem>
<ListItem
button
selected={selectedIndex === 1}
onClick={(event) => handleListItemClick(event, 1)}
>
<ListItemIcon>
<DraftsIcon />
</ListItemIcon>
<ListItemText primary="Drafts" />
</ListItem>
</Lis... | {
const classes = useStyles();
const [selectedIndex, setSelectedIndex] = React.useState(1);
const handleListItemClick = (event, index) => {
setSelectedIndex(index);
};
return (
<div className={classes.root}>
<List component="nav" aria-label="main mailbox folders">
<ListItem
b... | identifier_body |
SelectedListItem.js | import React from 'react';
import { makeStyles } from '@material-ui/core/styles';
import List from '@material-ui/core/List';
import ListItem from '@material-ui/core/ListItem';
import ListItemIcon from '@material-ui/core/ListItemIcon';
import ListItemText from '@material-ui/core/ListItemText';
import Divider from '@mate... | const handleListItemClick = (event, index) => {
setSelectedIndex(index);
};
return (
<div className={classes.root}>
<List component="nav" aria-label="main mailbox folders">
<ListItem
button
selected={selectedIndex === 0}
onClick={(event) => handleListItemClick(... | random_line_split | |
SelectedListItem.js | import React from 'react';
import { makeStyles } from '@material-ui/core/styles';
import List from '@material-ui/core/List';
import ListItem from '@material-ui/core/ListItem';
import ListItemIcon from '@material-ui/core/ListItemIcon';
import ListItemText from '@material-ui/core/ListItemText';
import Divider from '@mate... | () {
const classes = useStyles();
const [selectedIndex, setSelectedIndex] = React.useState(1);
const handleListItemClick = (event, index) => {
setSelectedIndex(index);
};
return (
<div className={classes.root}>
<List component="nav" aria-label="main mailbox folders">
<ListItem
... | SelectedListItem | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.