file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
39k
suffix
large_stringlengths
0
36.1k
middle
large_stringlengths
0
29.4k
fim_type
large_stringclasses
4 values
tuples.rs
use AsMutLua; use AsLua; use Push; use PushGuard; use LuaRead; macro_rules! tuple_impl { ($ty:ident) => ( impl<LU, $ty> Push<LU> for ($ty,) where LU: AsMutLua, $ty: Push<LU> { fn push_to_lua(self, lua: LU) -> PushGuard<LU> { self.0.push_to_lua(lua) } } ...
fn lua_read_at_position(mut lua: LU, index: i32) -> Result<($first, $($other),+), LU> { let mut i = index; let $first: $first = match LuaRead::lua_read_at_position(&mut lua, i) { Ok(v) => v, Err(_) => return Err(lua) };...
LuaRead<LU> for ($first, $($other),+) where LU: AsLua {
random_line_split
irc.js
var _ = require('lodash'); var socket = require('./socket'); var selectedTabStore = require('./stores/selectedTab'); var channelActions = require('./actions/channel'); var messageActions = require('./actions/message'); var serverActions = require('./actions/server'); var routeActions = require('./actions/route'); var ...
(message, reason) { return message + (reason ? ' (' + reason + ')' : ''); } socket.on('join', function(data) { channelActions.addUser(data.user, data.server, data.channels[0]); messageActions.inform(data.user + ' joined the channel', data.server, data.channels[0]); }); socket.on('part', function(data) { channelAc...
withReason
identifier_name
irc.js
var _ = require('lodash'); var socket = require('./socket'); var selectedTabStore = require('./stores/selectedTab'); var channelActions = require('./actions/channel'); var messageActions = require('./actions/message'); var serverActions = require('./actions/server'); var routeActions = require('./actions/route'); var ...
server: data.server, to: data.server, message: line }; })); }); socket.on('users', function(data) { channelActions.setUsers(data.users, data.server, data.channel); }); socket.on('topic', function(data) { channelActions.setTopic(data.topic, data.server, data.channel); }); socket.on('mode', function(data...
}); socket.on('motd', function(data) { messageActions.addAll(_.map(data.content, line => { return {
random_line_split
irc.js
var _ = require('lodash'); var socket = require('./socket'); var selectedTabStore = require('./stores/selectedTab'); var channelActions = require('./actions/channel'); var messageActions = require('./actions/message'); var serverActions = require('./actions/server'); var routeActions = require('./actions/route'); var ...
socket.on('join', function(data) { channelActions.addUser(data.user, data.server, data.channels[0]); messageActions.inform(data.user + ' joined the channel', data.server, data.channels[0]); }); socket.on('part', function(data) { channelActions.removeUser(data.user, data.server, data.channels[0]); messageActions....
{ return message + (reason ? ' (' + reason + ')' : ''); }
identifier_body
irc.js
var _ = require('lodash'); var socket = require('./socket'); var selectedTabStore = require('./stores/selectedTab'); var channelActions = require('./actions/channel'); var messageActions = require('./actions/message'); var serverActions = require('./actions/server'); var routeActions = require('./actions/route'); var ...
serverActions.load(data); }); socket.on('channels', function(data) { channelActions.load(data); }); socket.on('search', function(data) { searchActions.searchDone(data.results); }); serverActions.connect.listen(function(server) { messageActions.inform('Connecting...', server); });
{ routeActions.navigate('connect', true); }
conditional_block
ice-3969.rs
// https://github.com/rust-lang/rust-clippy/issues/3969 // used to crash: error: internal compiler error: // src/librustc_traits/normalize_erasing_regions.rs:43: could not fully normalize `<i32 as // std::iter::Iterator>::Item test from rustc ./ui/trivial-bounds/trivial-bounds-inconsistent.rs // Check that tautalogica...
where str: Sized; fn unsized_local() where for<'a> Dst<dyn A + 'a>: Sized, { let x: Dst<dyn A> = *(Box::new(Dst { x: 1 }) as Box<Dst<dyn A>>); } fn return_str() -> str where str: Sized, { *"Sized".to_string().into_boxed_str() } fn use_op(s: String) -> String where String: ::std::ops::Neg<Outp...
} struct TwoStrs(str, str)
random_line_split
ice-3969.rs
// https://github.com/rust-lang/rust-clippy/issues/3969 // used to crash: error: internal compiler error: // src/librustc_traits/normalize_erasing_regions.rs:43: could not fully normalize `<i32 as // std::iter::Iterator>::Item test from rustc ./ui/trivial-bounds/trivial-bounds-inconsistent.rs // Check that tautalogica...
() {}
main
identifier_name
ice-3969.rs
// https://github.com/rust-lang/rust-clippy/issues/3969 // used to crash: error: internal compiler error: // src/librustc_traits/normalize_erasing_regions.rs:43: could not fully normalize `<i32 as // std::iter::Iterator>::Item test from rustc ./ui/trivial-bounds/trivial-bounds-inconsistent.rs // Check that tautalogica...
fn return_str() -> str where str: Sized, { *"Sized".to_string().into_boxed_str() } fn use_op(s: String) -> String where String: ::std::ops::Neg<Output = String>, { -s } fn use_for() where i32: Iterator, { for _ in 2i32 {} } fn main() {}
{ let x: Dst<dyn A> = *(Box::new(Dst { x: 1 }) as Box<Dst<dyn A>>); }
identifier_body
ItRequestsWebPart.ts
import { Version } from '@microsoft/sp-core-library'; import { BaseClientSideWebPart, IPropertyPaneConfiguration, PropertyPaneTextField } from '@microsoft/sp-webpart-base'; import { escape } from '@microsoft/sp-lodash-subset'; import styles from './ItRequests.module.scss'; import * as strings from 'itRequestsStr...
(): Version { return Version.parse('1.0'); } protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration { return { pages: [ { header: { description: strings.PropertyPaneDescription }, groups: [ { groupName: strings....
dataVersion
identifier_name
ItRequestsWebPart.ts
import { Version } from '@microsoft/sp-core-library'; import { BaseClientSideWebPart, IPropertyPaneConfiguration, PropertyPaneTextField } from '@microsoft/sp-webpart-base'; import { escape } from '@microsoft/sp-lodash-subset'; import styles from './ItRequests.module.scss'; import * as strings from 'itRequestsStr...
item.Category, item.Status, new Date(item.DueDate), item.AssignedTo.Title ]; }); } }, columnDefs: [{ targets: 4, render: ($.fn.DataTable as any).render.moment('YYYY/MM/DD') }] }); } protected...
item.BusinessUnit,
random_line_split
ItRequestsWebPart.ts
import { Version } from '@microsoft/sp-core-library'; import { BaseClientSideWebPart, IPropertyPaneConfiguration, PropertyPaneTextField } from '@microsoft/sp-webpart-base'; import { escape } from '@microsoft/sp-lodash-subset'; import styles from './ItRequests.module.scss'; import * as strings from 'itRequestsStr...
protected get disableReactivePropertyChanges(): boolean { return true; } }
{ return { pages: [ { header: { description: strings.PropertyPaneDescription }, groups: [ { groupName: strings.BasicGroupName, groupFields: [ PropertyPaneTextField('listName', { label: s...
identifier_body
read_pixels.py
#!/usr/bin/python3 -i import serial # if you have not already done so from time import sleep import matplotlib.pyplot as plt import re import datetime import numpy import pickle class DataExtruder: def __init__(self,port='/dev/ttyACM0',baudrate=115200): self.pattern_pixels=re.compile(r'data=(?P<pixels>[\w ]*)...
test=DataExtruder(port='/dev/ttyACM0',baudrate=115200) test.acquire()
conditional_block
read_pixels.py
#!/usr/bin/python3 -i import serial # if you have not already done so from time import sleep import matplotlib.pyplot as plt import re import datetime import numpy import pickle class DataExtruder: def __init__(self,port='/dev/ttyACM0',baudrate=115200): self.pattern_pixels=re.compile(r'data=(?P<pixels>[\w ]*)...
(self): plt.cla() self.figure_axe.set_position([0.05,0.1,0.94,0.8]) if len(self.data['pixels'])==0: return last_reading=self.data['pixels'][len(self.data['pixels'])-1] if len(last_reading)!=3648: return x=range(1,3649) self.plt_pixels,=plt.plot(x,last_reading,'b-') self.figur...
plot_pixels
identifier_name
read_pixels.py
#!/usr/bin/python3 -i import serial # if you have not already done so from time import sleep import matplotlib.pyplot as plt import re import datetime import numpy import pickle class DataExtruder: def __init__(self,port='/dev/ttyACM0',baudrate=115200): self.pattern_pixels=re.compile(r'data=(?P<pixels>[\w ]*)...
else: print('ERROR reading pixel') break else: pixel=255-int(pixels_ascii[i:i+2],16) pixels_num.append(pixel) i=i+2 npixel=npixel+1 self.data['pixels'].append(pixels_num) self.data['nerror...
if pixels_ascii[i]==' ': if pixels_ascii[i+1]==' ': pixels_num.append(-1) i=i+2
random_line_split
read_pixels.py
#!/usr/bin/python3 -i import serial # if you have not already done so from time import sleep import matplotlib.pyplot as plt import re import datetime import numpy import pickle class DataExtruder: def __init__(self,port='/dev/ttyACM0',baudrate=115200): self.pattern_pixels=re.compile(r'data=(?P<pixels>[\w ]*)...
if __name__ == '__main__': test=DataExtruder(port='/dev/ttyACM0',baudrate=115200) test.acquire()
plt.cla() self.figure_axe.set_position([0.05,0.1,0.94,0.8]) if len(self.data['pixels'])==0: return last_reading=self.data['pixels'][len(self.data['pixels'])-1] if len(last_reading)!=3648: return x=range(1,3649) self.plt_pixels,=plt.plot(x,last_reading,'b-') self.figure_axe.set_yl...
identifier_body
responsive-carousel.dynamic-containers.js
/* * responsive-carousel dynamic containers extension * https://github.com/filamentgroup/responsive-carousel * * Copyright (c) 2012 Filament Group, Inc. * Licensed under the MIT, GPL licenses. */ (function($) { var pluginName = "carousel", initSelector = "." + pluginName, itemClass = pluginName + "-item",...
else{ $kids.appendTo( $self ); $rows.remove(); } $kids .removeClass( itemClass + " " + activeClass ) .each(function(){ var prev = $( this ).prev(); if( !prev.length || $( this ).offset().top !== prev.offset().top ){ sets.push([]); } sets...
{ $kids = $( this ).find( "." + itemClass ); }
conditional_block
responsive-carousel.dynamic-containers.js
/* * responsive-carousel dynamic containers extension * https://github.com/filamentgroup/responsive-carousel * * Copyright (c) 2012 Filament Group, Inc. * Licensed under the MIT, GPL licenses. */ (function($) { var pluginName = "carousel", initSelector = "." + pluginName, itemClass = pluginName + "-item",...
// on init $self[ pluginName ]( "_assessContainers" ); // and on resize $win.on( "resize", function( e ){ // IE wants to constantly run resize for some reason // Let’s make sure it is actually a resize event var win_w_new = $win.width(), win_h_new = $win.height(); ...
win_h = $win.height(), timeout;
random_line_split
fields.py
#! /usr/bin/env python """ couchbasekit.fields ~~~~~~~~~~~~~~~~~~~ :website: http://github.com/kirpit/couchbasekit :copyright: Copyright 2013, Roy Enjoy <kirpit *at* gmail.com>, see AUTHORS.txt. :license: MIT, see LICENSE.txt for details. * :class:`couchbasekit.fields.CustomField` * :class:`couchbasekit.fields.Choice...
return self._value @value.setter def value(self, value): """Propery setter that should be used to assign final (calculated) value. """ self._value = value class ChoiceField(CustomField): """The custom field to be used for multi choice options such as gender, s...
raise ValueError("%s's 'value' is not set." % type(self).__name__)
conditional_block
fields.py
#! /usr/bin/env python """ couchbasekit.fields ~~~~~~~~~~~~~~~~~~~ :website: http://github.com/kirpit/couchbasekit :copyright: Copyright 2013, Roy Enjoy <kirpit *at* gmail.com>, see AUTHORS.txt. :license: MIT, see LICENSE.txt for details. * :class:`couchbasekit.fields.CustomField` * :class:`couchbasekit.fields.Choice...
# stolen from django email validator: EMAIL_RE = re.compile( r"(^[-!#$%&'*+/=?^_`{}|~0-9A-Z]+(\.[-!#$%&'*+/=?^_`{}|~0-9A-Z]+)*" # dot-atom # quoted-string, see also http://tools.ietf.org/html/rfc2822#section-3.2.5 r'|^"([\001-\010\013\014\016-\037!#-\[\]-\177]|\\[\001-\011\013\014\016-\177])*"' r')@...
return self.CHOICES.iteritems()
identifier_body
fields.py
#! /usr/bin/env python """ couchbasekit.fields ~~~~~~~~~~~~~~~~~~~ :website: http://github.com/kirpit/couchbasekit :copyright: Copyright 2013, Roy Enjoy <kirpit *at* gmail.com>, see AUTHORS.txt. :license: MIT, see LICENSE.txt for details. * :class:`couchbasekit.fields.CustomField` * :class:`couchbasekit.fields.Choice...
_value = None def __init__(self): raise NotImplementedError() def __repr__(self): return repr(self.value) def __eq__(self, other): if type(other) is type(self) and other.value==self.value: return True return False def __ne__(self, other): return...
""" __metaclass__ = ABCMeta
random_line_split
fields.py
#! /usr/bin/env python """ couchbasekit.fields ~~~~~~~~~~~~~~~~~~~ :website: http://github.com/kirpit/couchbasekit :copyright: Copyright 2013, Roy Enjoy <kirpit *at* gmail.com>, see AUTHORS.txt. :license: MIT, see LICENSE.txt for details. * :class:`couchbasekit.fields.CustomField` * :class:`couchbasekit.fields.Choice...
(CustomField): """The custom field to be used for email addresses and intended to validate them as well. :param email: Email address to be saved. :type email: basestring """ def __init__(self, email): if not self.is_valid(email): raise ValueError("Email address is invalid.")...
EmailField
identifier_name
NetworkSizesApi.js
/** * Vericred API * Vericred's API allows you to search for Health Plans that a specific doctor accepts. ## Getting Started Visit our [Developer Portal](https://developers.vericred.com) to create an account. Once you have created an account, you can create one Application for Production and another for our Sandbo...
code: 'NY' }] } ``` ## Benefits summary format Benefit cost-share strings are formatted to capture: * Network tiers * Compound or conditional cost-share * Limits on the cost-share * Benefit-specific maximum out-of-pocket costs **Example #1** As an example, we would represent [this Summary of Benefits &amp; ...
id: 1, name: 'New York',
random_line_split
tok.rs
use std::str::FromStr; #[derive(Debug)] pub enum Tok { Num(i32), LParen, RParen, Minus, Plus, Times, Div, Comma, } // simplest and stupidest possible tokenizer pub fn tokenize(s: &str) -> Vec<(usize, Tok, usize)> { let mut tokens = vec![]; let mut chars = s.chars(); let mut...
<C,F>(c0: char, chars: &mut C, f: F) -> (String, Option<char>) where C: Iterator<Item=char>, F: Fn(char) -> bool { let mut buf = String::new(); buf.push(c0); while let Some(c) = chars.next() { if !f(c) { return (buf, Some(c)); } buf.push(c); } return (buf,...
take_while
identifier_name
tok.rs
use std::str::FromStr; #[derive(Debug)] pub enum Tok { Num(i32), LParen, RParen, Minus, Plus, Times, Div, Comma, } // simplest and stupidest possible tokenizer pub fn tokenize(s: &str) -> Vec<(usize, Tok, usize)> { let mut tokens = vec![]; let mut chars = s.chars(); let mut...
buf.push(c); } return (buf, None); }
if !f(c) { return (buf, Some(c)); }
random_line_split
scraper.js
var gplay = require('google-play-scraper'); var fs = require('fs'); var appSet = new Set(); var lineReader = require('readline').createInterface({ input: fs.createReadStream('teste') }); var wStream = fs.createWriteStream("handledApps.csv", { flags : 'w' }); lineReader.on('line', function (line){ if(line.inde...
}); lineReader.on('close', function(){ console.log("Total of apps: " + appSet.size); appSet.forEach(function(collectedApp){ gplay.app({appId: collectedApp}) .then(function(app){ wStream.write(collectedApp + " " + app.genreId + "\n"); //console.log(collectedApp +...
{ var vals = line.split(":"); var pattern = /[\"\\\[\]]/g; var apps = vals[1].replace(pattern, "").split(","); console.log("********************"); console.log(vals[1]); console.log(vals[1].replace(pattern, "")); console.log(apps); apps.forEach(function(collectedApp){ appSet...
conditional_block
scraper.js
var gplay = require('google-play-scraper'); var fs = require('fs'); var appSet = new Set(); var lineReader = require('readline').createInterface({ input: fs.createReadStream('teste') }); var wStream = fs.createWriteStream("handledApps.csv", { flags : 'w' }); lineReader.on('line', function (line){ if(line.inde...
var pattern = /[\"\\\[\]]/g; var apps = vals[1].replace(pattern, "").split(","); console.log("********************"); console.log(vals[1]); console.log(vals[1].replace(pattern, "")); console.log(apps); apps.forEach(function(collectedApp){ appSet.add(collectedApp); }); } ...
random_line_split
fs.ts
import * as vscode from 'vscode'; import { promisify } from 'util'; import * as util from 'util'; import * as fs from 'fs'; export const constants = { UV_FS_SYMLINK_DIR: 1, UV_FS_SYMLINK_JUNCTION: 2, O_RDONLY: 0, O_WRONLY: 1, O_RDWR: 2, UV_DIRENT_UNKNOWN: 0, UV_DIRENT_FILE: 1, UV_DIRENT_DIR: 2, UV_DI...
{ fs.unlinkSync(path); }
identifier_body
fs.ts
import * as vscode from 'vscode'; import { promisify } from 'util'; import * as util from 'util'; import * as fs from 'fs'; export const constants = { UV_FS_SYMLINK_DIR: 1, UV_FS_SYMLINK_JUNCTION: 2, O_RDONLY: 0, O_WRONLY: 1, O_RDWR: 2, UV_DIRENT_UNKNOWN: 0, UV_DIRENT_FILE: 1, UV_DIRENT_DIR: 2, UV_DI...
return promisify(fs.access)(path, mode); } export async function chmodAsync(path: string, mode: string | number) { return promisify(fs.chmod)(path, mode); } export async function getMode(path: string): Promise<number> { const pathMode = await fs.promises .stat(path) .then((stat) => stat.mode) .catch...
random_line_split
fs.ts
import * as vscode from 'vscode'; import { promisify } from 'util'; import * as util from 'util'; import * as fs from 'fs'; export const constants = { UV_FS_SYMLINK_DIR: 1, UV_FS_SYMLINK_JUNCTION: 2, O_RDONLY: 0, O_WRONLY: 1, O_RDWR: 2, UV_DIRENT_UNKNOWN: 0, UV_DIRENT_FILE: 1, UV_DIRENT_DIR: 2, UV_DI...
else { // fallback to local fs const fsExists = util.promisify(fs.exists); return fsExists(fileUri.fsPath); } } export async function existsAsync(path: string): Promise<boolean> { try { await vscode.workspace.fs.stat(vscode.Uri.file(path)); return true; } catch (_e) { return false; } }...
{ try { await vscode.workspace.fs.stat(fileUri); return true; } catch { return false; } }
conditional_block
fs.ts
import * as vscode from 'vscode'; import { promisify } from 'util'; import * as util from 'util'; import * as fs from 'fs'; export const constants = { UV_FS_SYMLINK_DIR: 1, UV_FS_SYMLINK_JUNCTION: 2, O_RDONLY: 0, O_WRONLY: 1, O_RDWR: 2, UV_DIRENT_UNKNOWN: 0, UV_DIRENT_FILE: 1, UV_DIRENT_DIR: 2, UV_DI...
(path: string, encoding: BufferEncoding): Promise<string> { return promisify(fs.readFile)(path, encoding); } export async function mkdirAsync(path: string, options: any): Promise<void> { await promisify(fs.mkdir)(path, options); } export async function writeFileAsync( path: string, content: string, encoding...
readFileAsync
identifier_name
base.py
# -*- coding: utf-8 -*- # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
service_account.Credentials, "with_always_use_jwt_access" ) ): credentials = credentials.with_always_use_jwt_access(True) # Save the credentials. self._credentials = credentials def _prep_wrapped_messages(self, client_info): # Precompute the ...
# If the credentials are service account credentials, then always try to use self signed JWT. if ( always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(
random_line_split
base.py
# -*- coding: utf-8 -*- # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
@property def mutate_remarketing_actions( self, ) -> Callable[ [remarketing_action_service.MutateRemarketingActionsRequest], Union[ remarketing_action_service.MutateRemarketingActionsResponse, Awaitable[ remarketing_action_service.MutateRemar...
"""Closes resources associated with the transport. .. warning:: Only call this method if the transport is NOT shared with other clients - this may cause errors in other clients! """ raise NotImplementedError()
identifier_body
base.py
# -*- coding: utf-8 -*- # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( credentials_file, **scopes_kwargs, quota_project_id=quota_project_id, ) elif credentials is None: credentials, _ = google.auth.d...
raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" )
conditional_block
base.py
# -*- coding: utf-8 -*- # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
(self): """Closes resources associated with the transport. .. warning:: Only call this method if the transport is NOT shared with other clients - this may cause errors in other clients! """ raise NotImplementedError() @property def mutate_remarketing_acti...
close
identifier_name
15.2.3.3-4-165.js
/// Copyright (c) 2012 Ecma International. All rights reserved. /// Ecma International makes this code available under the terms and conditions set /// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the /// "Use Terms"). Any redistribution of this code must retain the above /// copyright an...
() { var desc = Object.getOwnPropertyDescriptor(RegExp.prototype, "exec"); if (desc.value === RegExp.prototype.exec && desc.writable === true && desc.enumerable === false && desc.configurable === true) { return true; } } runTestCase(testcase);
testcase
identifier_name
15.2.3.3-4-165.js
/// Copyright (c) 2012 Ecma International. All rights reserved. /// Ecma International makes this code available under the terms and conditions set /// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the /// "Use Terms"). Any redistribution of this code must retain the above /// copyright an...
runTestCase(testcase);
random_line_split
15.2.3.3-4-165.js
/// Copyright (c) 2012 Ecma International. All rights reserved. /// Ecma International makes this code available under the terms and conditions set /// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the /// "Use Terms"). Any redistribution of this code must retain the above /// copyright an...
} runTestCase(testcase);
{ return true; }
conditional_block
15.2.3.3-4-165.js
/// Copyright (c) 2012 Ecma International. All rights reserved. /// Ecma International makes this code available under the terms and conditions set /// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the /// "Use Terms"). Any redistribution of this code must retain the above /// copyright an...
runTestCase(testcase);
{ var desc = Object.getOwnPropertyDescriptor(RegExp.prototype, "exec"); if (desc.value === RegExp.prototype.exec && desc.writable === true && desc.enumerable === false && desc.configurable === true) { return true; } }
identifier_body
application.js
import { ZoneId, ZonedDateTime, Duration, LocalTime } from 'js-joda'; import { Map as ImmutableMap } from 'immutable'; import { handle } from 'redux-pack'; import * as Actions from 'app/store/action/application'; import { LOAD as LOAD_CALENDARS } from 'app/store/action/calendars'; const INITIAL_STATE = new ImmutableM...
(prev_state) { return state.set('time_zone', ZoneId.of(action.payload.time_zone)); } }); } case Actions.SET_TOUCH_CAPABILITY: { return state.set('touch_capable', action.payload); } case Actions.LAST_ACTIVITY: { ret...
success
identifier_name
application.js
import { ZoneId, ZonedDateTime, Duration, LocalTime } from 'js-joda'; import { Map as ImmutableMap } from 'immutable'; import { handle } from 'redux-pack'; import * as Actions from 'app/store/action/application'; import { LOAD as LOAD_CALENDARS } from 'app/store/action/calendars'; const INITIAL_STATE = new ImmutableM...
} }
random_line_split
application.js
import { ZoneId, ZonedDateTime, Duration, LocalTime } from 'js-joda'; import { Map as ImmutableMap } from 'immutable'; import { handle } from 'redux-pack'; import * as Actions from 'app/store/action/application'; import { LOAD as LOAD_CALENDARS } from 'app/store/action/calendars'; const INITIAL_STATE = new ImmutableM...
}); } case Actions.SET_TOUCH_CAPABILITY: { return state.set('touch_capable', action.payload); } case Actions.LAST_ACTIVITY: { return state.set('last_activity', state.get('time')); } case Actions.SET_IDLE: { return state....
{ return state.set('time_zone', ZoneId.of(action.payload.time_zone)); }
identifier_body
header.py
import bpy # ----------------------------------------------------------------------------- # Draw UI, use an function to be append into 3D View Header # ----------------------------------------------------------------------------- def ui_3D(self, context): layout = self.layout row = layout.row(align=True) ...
(): bpy.types.VIEW3D_HT_header.append(ui_3D) bpy.types.IMAGE_HT_header.append(ui_UV) def unregister(): bpy.types.VIEW3D_HT_header.remove(ui_3D) bpy.types.IMAGE_HT_header.remove(ui_UV)
register
identifier_name
header.py
import bpy # ----------------------------------------------------------------------------- # Draw UI, use an function to be append into 3D View Header # ----------------------------------------------------------------------------- def ui_3D(self, context): layout = self.layout row = layout.row(align=True) ...
bpy.types.VIEW3D_HT_header.remove(ui_3D) bpy.types.IMAGE_HT_header.remove(ui_UV)
random_line_split
header.py
import bpy # ----------------------------------------------------------------------------- # Draw UI, use an function to be append into 3D View Header # ----------------------------------------------------------------------------- def ui_3D(self, context):
# ----------------------------------------------------------------------------- # Draw UI, use an function to be append into UV/Image Editor View Header # ----------------------------------------------------------------------------- def ui_UV(self, context): layout = self.layout row = layout.row(align=True) ...
layout = self.layout row = layout.row(align=True) row.operator("view.grid_control", text='', icon='GRID') icon = 'CURSOR' row.operator("object.center_pivot_mesh_obj", text='', icon=icon) icon = 'SMOOTH' row.operator("object.smooth_shading", text='', icon=icon) row = layout.row(align=True) ...
identifier_body
mpsc_queue.rs
// Copyright (c) 2010-2011 Dmitry Vyukov. All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of con...
() { let q: Queue<Box<_>> = Queue::new(); q.push(box 1); q.push(box 2); } #[test] fn test() { let nthreads = 8; let nmsgs = 1000; let q = Queue::new(); match q.pop() { Empty => {} Inconsistent | Data(..) => panic!(), } ...
test_full
identifier_name
mpsc_queue.rs
// Copyright (c) 2010-2011 Dmitry Vyukov. All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of con...
Empty, /// The queue is in an inconsistent state. Popping data should succeed, but /// some pushers have yet to make enough progress in order allow a pop to /// succeed. It is recommended that a pop() occur "in the near future" in /// order to see if the sender has made progress or not Inconsist...
Data(T), /// The queue is empty
random_line_split
mod.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
reason = "module just underwent fairly large reorganization and the dust \ still needs to settle")] pub use self::c_str::CString; pub use self::c_str::c_str_to_bytes; pub use self::c_str::c_str_to_bytes_with_nul; pub use self::os_str::OsString; pub use self::os_str::OsStr; mod c_str...
//! Utilities related to FFI bindings. #![unstable(feature = "std_misc",
random_line_split
dstr-meth-ary-ptrn-elem-obj-val-undef.js
// This file was procedurally generated from the following sources: // - src/dstr-binding/ary-ptrn-elem-obj-val-undef.case // - src/dstr-binding/error/cls-expr-meth.template /*--- description: Nested object destructuring with a value of `undefined` (class expression method) esid: sec-class-definitions-runtime-semantics...
([{ x }]) {} }; var c = new C(); assert.throws(TypeError, function() { c.method([]); });
method
identifier_name
dstr-meth-ary-ptrn-elem-obj-val-undef.js
// This file was procedurally generated from the following sources: // - src/dstr-binding/ary-ptrn-elem-obj-val-undef.case // - src/dstr-binding/error/cls-expr-meth.template /*--- description: Nested object destructuring with a value of `undefined` (class expression method) esid: sec-class-definitions-runtime-semantics...
}; var c = new C(); assert.throws(TypeError, function() { c.method([]); });
{}
identifier_body
dstr-meth-ary-ptrn-elem-obj-val-undef.js
// This file was procedurally generated from the following sources: // - src/dstr-binding/ary-ptrn-elem-obj-val-undef.case // - src/dstr-binding/error/cls-expr-meth.template /*--- description: Nested object destructuring with a value of `undefined` (class expression method) esid: sec-class-definitions-runtime-semantics...
1. Let valid be RequireObjectCoercible(value). 2. ReturnIfAbrupt(valid). ---*/ var C = class { method([{ x }]) {} }; var c = new C(); assert.throws(TypeError, function() { c.method([]); });
BindingPattern : ObjectBindingPattern
random_line_split
views.py
import datetime from django.contrib.auth.decorators import user_passes_test from django.core import urlresolvers from django.http import Http404 from django.shortcuts import get_object_or_404, render_to_response from satchmo.payment.config import credit_choices from satchmo.product.models import Product, Category from ...
url = shop_config.base_url + urlresolvers.reverse(view, None, params) payment_choices = [c[1] for c in credit_choices(None, True)] return render_to_response(template, { 'products' : products, 'category' : cat, 'url' : url, 'shop' : shop_config, 'payments' : ...
if category: params['category'] = category view = 'satchmo_atom_category_feed'
random_line_split
views.py
import datetime from django.contrib.auth.decorators import user_passes_test from django.core import urlresolvers from django.http import Http404 from django.shortcuts import get_object_or_404, render_to_response from satchmo.payment.config import credit_choices from satchmo.product.models import Product, Category from ...
url = shop_config.base_url + urlresolvers.reverse(view, None, params) payment_choices = [c[1] for c in credit_choices(None, True)] return render_to_response(template, { 'products' : products, 'category' : cat, 'url' : url, 'shop' : shop_config, 'paymen...
params['category'] = category view = 'satchmo_atom_category_feed'
conditional_block
views.py
import datetime from django.contrib.auth.decorators import user_passes_test from django.core import urlresolvers from django.http import Http404 from django.shortcuts import get_object_or_404, render_to_response from satchmo.payment.config import credit_choices from satchmo.product.models import Product, Category from ...
"""Build a feed of all active products. """ shop_config = Config.objects.get_current() if category: try: cat = Category.objects.get(slug=category) products = cat.active_products() except Category.DoesNotExist: raise Http404, _("Bad Category: %s" % categor...
identifier_body
views.py
import datetime from django.contrib.auth.decorators import user_passes_test from django.core import urlresolvers from django.http import Http404 from django.shortcuts import get_object_or_404, render_to_response from satchmo.payment.config import credit_choices from satchmo.product.models import Product, Category from ...
(request, category=None, template="feeds/product_feed.csv", mimetype="text/csv"): """Admin authenticated feed - same as product feed but for different types of feeds. """ return product_feed(request, category=category, template=template, mimetype=mimetype) def product_feed(request, category=None, template=...
admin_product_feed
identifier_name
BasicSamples.BasicSamplesService.ts
namespace Enterprise.BasicSamples { export namespace BasicSamplesService { export const baseUrl = 'BasicSamples/BasicSamples'; export declare function OrdersByShipper(request: OrdersByShipperRequest, onSuccess?: (response: OrdersByShipperResponse) => void, opt?: Q.ServiceOptions<any>): JQueryXHR; ...
}
}
random_line_split
main.py
# # Author: Daniel Dittenhafer # # Created: Sept 27, 2016 # # Description: Main entry point for emotional faces data set creator. # __author__ = 'Daniel Dittenhafer' import os import operator import csv import time import numpy as np import matplotlib.pyplot as plt import matplotlib.cm as cm from scipy import misc...
# throttle so Msft doesn't get mad at us... time.sleep(waitSecs) def transformFaces(srcPath, destPath): start = 5924 end = start + 1 #1500 theFiles = list_files(srcPath, True) print(len(theFiles)) for f in theFiles[start:end]: img = misc.imread(f) ...
# Save the results print(fileName + ": " + emo) emoCsv.writerow([i, fileName, emo]) i += 1
random_line_split
main.py
# # Author: Daniel Dittenhafer # # Created: Sept 27, 2016 # # Description: Main entry point for emotional faces data set creator. # __author__ = 'Daniel Dittenhafer' import os import operator import csv import time import numpy as np import matplotlib.pyplot as plt import matplotlib.cm as cm from scipy import misc...
(): """Function to iterate through a directory of images (faces) and call Microsoft Emotion API to determine the label for the face.""" path = "C:\Code\Python\emotional-faces\data\Resize" emoFile = 'facialEmos.csv' theFiles = list_files(path, True) print(len(theFiles)) # Load the existing...
labelFaces
identifier_name
main.py
# # Author: Daniel Dittenhafer # # Created: Sept 27, 2016 # # Description: Main entry point for emotional faces data set creator. # __author__ = 'Daniel Dittenhafer' import os import operator import csv import time import numpy as np import matplotlib.pyplot as plt import matplotlib.cm as cm from scipy import misc...
# This is the main of the program. if __name__ == "__main__": main()
"""Our main function.""" destPath = "C:\Code\Python\emotional-faces\data\\transformed" srcPath = "C:\Code\Python\emotional-faces\data\Resize" #labelFaces() #print "OpenCV version: " + cv2.__version__ #transformFaces(srcPath, destPath) #compareFolders() #compareLegendAndFiles() dataF...
identifier_body
main.py
# # Author: Daniel Dittenhafer # # Created: Sept 27, 2016 # # Description: Main entry point for emotional faces data set creator. # __author__ = 'Daniel Dittenhafer' import os import operator import csv import time import numpy as np import matplotlib.pyplot as plt import matplotlib.cm as cm from scipy import misc...
def transformFaces(srcPath, destPath): start = 5924 end = start + 1 #1500 theFiles = list_files(srcPath, True) print(len(theFiles)) for f in theFiles[start:end]: img = misc.imread(f) # 1. Reflect Y imgReflectY = dwdii_transforms.reflectY(img) dwdii_transforms.s...
fileName = os.path.basename(f) if not fileName in emoDict: rj = ms_emotionapi.detectFacesFromDiskFile(f, _key) if 0 < len(rj): scores = rj[0]["scores"] emo = max(scores.iteritems(), key=operator.itemgetter(1))[0] # ...
conditional_block
octree.rs
use shapes::bbox::BBox; use na::{Vector3}; use sceneobject::SceneObject; use std::sync::Arc; use std::fmt; use ray::Ray; use intersection::{RawIntersection, Intersection}; use ordered_float::OrderedFloat; use shapes::geometry::Geometry; #[derive(Clone)] pub struct Octree<T: Geometry>{ root: OctreeNode, items: ...
fn closest_intersection(&self, r: &Ray, max:f64, min:f64) -> Option<(usize, RawIntersection)> { return match self.root.naive_intersection(r, max, min) { Some(opts) => self.items_intersection(r,max, min, opts), None => None } } // Iterate through potential items. Sh...
{ match self.closest_intersection(r, max, min) { Some(tupl) => { return Some((self.items[tupl.0].clone(), tupl.1)) }, None => None } }
identifier_body
octree.rs
use shapes::bbox::BBox; use na::{Vector3}; use sceneobject::SceneObject; use std::sync::Arc; use std::fmt; use ray::Ray; use intersection::{RawIntersection, Intersection}; use ordered_float::OrderedFloat; use shapes::geometry::Geometry; #[derive(Clone)] pub struct Octree<T: Geometry>{ root: OctreeNode, items: ...
if rd0 < 0. { ro0 = self.bounds.size()[0] - ro0; rd0 = - rd0; a |= 4 ; //bitwise OR (latest bits are XYZ) } if rd1 < 0. { ro1 = self.bounds.size()[1] - ro1; rd1 = - rd1; a |= 2 ; } if rd2 < 0. { ...
// fixes for rays with negative direction
random_line_split
octree.rs
use shapes::bbox::BBox; use na::{Vector3}; use sceneobject::SceneObject; use std::sync::Arc; use std::fmt; use ray::Ray; use intersection::{RawIntersection, Intersection}; use ordered_float::OrderedFloat; use shapes::geometry::Geometry; #[derive(Clone)] pub struct Octree<T: Geometry>{ root: OctreeNode, items: ...
(&self, r: &Ray, max:f64, min:f64) -> Option<RawIntersection> { return match self.closest_intersection(r, max, min) { Some(tupl) => Some(tupl.1), None => None } } pub fn intersection(&self, r: &Ray, max:f64, min:f64) -> Option<(Arc<T>, RawIntersection)> { match ...
raw_intersection
identifier_name
block-arg.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
; assert!(w); }
{ false }
conditional_block
block-arg.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
() { let v = ~[-1f, 0f, 1f, 2f, 3f]; // Statement form does not require parentheses: for v.iter().advance |i| { info!("%?", *i); } // Usable at all: let mut any_negative = do v.iter().any_ |e| { e.is_negative() }; assert!(any_negative); // Higher precedence than assignments: ...
main
identifier_name
block-arg.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
for v.iter().advance |i| { info!("%?", *i); } // Usable at all: let mut any_negative = do v.iter().any_ |e| { e.is_negative() }; assert!(any_negative); // Higher precedence than assignments: any_negative = do v.iter().any_ |e| { e.is_negative() }; assert!(any_negative); //...
// Statement form does not require parentheses:
random_line_split
block-arg.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
// Usable at all: let mut any_negative = do v.iter().any_ |e| { e.is_negative() }; assert!(any_negative); // Higher precedence than assignments: any_negative = do v.iter().any_ |e| { e.is_negative() }; assert!(any_negative); // Higher precedence than unary operations: let abs_v = do ...
{ let v = ~[-1f, 0f, 1f, 2f, 3f]; // Statement form does not require parentheses: for v.iter().advance |i| { info!("%?", *i); }
identifier_body
__SharedActionCreators.js
"use strict"; import assert from "assert"; import sinon from "sinon"; import testPlease from "../helpers/testPlease"; import { genericDouble } from "../helpers/doubles"; import * as JobsActionCreators from "../../../src/js/actions/JobsActionCreators"; import * as JobItemsActionCreators from "../../../src/js/actions/Job...
type: "SORT_ONE", give: ["doctor"], want: "doctor", desc: "a sort string" }, { fn: "setCurrentY", type: "SET_CURRENT_Y", give: [158], want: 158, desc: "a new y position" }, { fn: "setTableHeight", type: "SET_TABLE_HEIGHT", give: [450], want: 450, desc: "a new table height" } ]; descr...
}, { fn: "sortBy",
random_line_split
__SharedActionCreators.js
"use strict"; import assert from "assert"; import sinon from "sinon"; import testPlease from "../helpers/testPlease"; import { genericDouble } from "../helpers/doubles"; import * as JobsActionCreators from "../../../src/js/actions/JobsActionCreators"; import * as JobItemsActionCreators from "../../../src/js/actions/Job...
(thing) { return thing; } }); assert.deepEqual(result.deleteSingleItem, "item_id"); }); }); testPlease(toTest, SharedActionCreators); });
get
identifier_name
__SharedActionCreators.js
"use strict"; import assert from "assert"; import sinon from "sinon"; import testPlease from "../helpers/testPlease"; import { genericDouble } from "../helpers/doubles"; import * as JobsActionCreators from "../../../src/js/actions/JobsActionCreators"; import * as JobItemsActionCreators from "../../../src/js/actions/Job...
}); assert.deepEqual(result.deleteSingleItem, "item_id"); }); }); testPlease(toTest, SharedActionCreators); });
{ return thing; }
identifier_body
parser_cc_block.py
# # Copyright 2013, 2018 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio 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, or (at your option) # any later versio...
def _typestr_to_vlen(typestr): """ From a type identifier, returns the vector length of the block's input/out. E.g., for 'sizeof(int) * 10', it returns 10. For 'sizeof(int)', it returns '1'. For 'sizeof(int) * vlen', it returns the string vlen. """ # ...
""" Convert a type string (e.g. sizeof(int) * vlen) to the type (e.g. 'int'). """ type_match = re.search(r'sizeof\s*\(([^)]*)\)', typestr) if type_match is None: return self.type_trans('char') return self.type_trans(type_match.group(1))
identifier_body
parser_cc_block.py
# # Copyright 2013, 2018 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio 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, or (at your option) # any later versio...
this_defv += c[i] i += 1 continue return param_list # Go, go, go! if self.version in ('37', '38'): make_regex = r'static\s+sptr\s+make\s*' else: make_regex = r'(?<=_API)\s+\w+_sptr\s+\w+_make_\w+\...
this_defv = '' else:
random_line_split
parser_cc_block.py
# # Copyright 2013, 2018 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio 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, or (at your option) # any later versio...
(start_idx): """ Go through a parameter list and return a tuple each: (type, name, default_value). Python's re just doesn't cut it for C++ code :( """ i = start_idx c = self.code_h if c[i] != '(': raise ValueError ...
_scan_param_list
identifier_name
parser_cc_block.py
# # Copyright 2013, 2018 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio 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, or (at your option) # any later versio...
elif c[i] == '=': if parens_count != 0: raise ValueError( 'While parsing argument {} ({}): name finished but no closing parentheses.'.format \ (len(param_list)+1, this_type + ...
i += 1
conditional_block
tracksHelper.ts
import Raphael from 'webpack-raphael'; import $ from 'jquery'; import _ from 'lodash'; import { Mutation } from 'cbioportal-ts-api-client'; import { default as chromosomeSizes } from './chromosomeSizes.json'; import { IIconData } from './GenomicOverviewUtils.js'; import { GENOME_ID_TO_GENOME_BUILD } from 'shared/lib/re...
line.attr('stroke', cl); line.attr('stroke-width', width); line.attr('opacity', 0.5); line.translate(0.5, 0.5); return line; } function loc2string(loc: any, chmInfo: any) { return 'chr' + chmInfo.chmName(loc[0]) + ':' + addCommas(loc[1]); } function addCommas(x: any) { var strX = x.toStrin...
cl: any, width: any ) { var path = 'M' + x1 + ' ' + y1 + ' L' + x2 + ' ' + y2; var line = p.path(path);
random_line_split
tracksHelper.ts
import Raphael from 'webpack-raphael'; import $ from 'jquery'; import _ from 'lodash'; import { Mutation } from 'cbioportal-ts-api-client'; import { default as chromosomeSizes } from './chromosomeSizes.json'; import { IIconData } from './GenomicOverviewUtils.js'; import { GENOME_ID_TO_GENOME_BUILD } from 'shared/lib/re...
function addToolTip( node: any, tip: any, showDelay: any, position: any, genePanel?: string, tooltipContentEl?: any, setGenePanelInTooltip?: (genePanelId: string) => void ) { var param = { content: { text: () => { return tooltipContentEl || tip; ...
{ var numMut = 0; var mutObjs = _.filter(mutations, function(_mutObj: Mutation) { return _mutObj.sampleId === caseId; }); let pixelMap: Array<Array<string>> = []; for (var i = 0; i < mutObjs.length; i++) { var mutObj: Mutation = mutObjs[i]; if (typeof mutObj.chr !== 'undefin...
identifier_body
tracksHelper.ts
import Raphael from 'webpack-raphael'; import $ from 'jquery'; import _ from 'lodash'; import { Mutation } from 'cbioportal-ts-api-client'; import { default as chromosomeSizes } from './chromosomeSizes.json'; import { IIconData } from './GenomicOverviewUtils.js'; import { GENOME_ID_TO_GENOME_BUILD } from 'shared/lib/re...
}, hide: () => { if (setGenePanelInTooltip) { setGenePanelInTooltip(''); } }, }, }; const TOOLTIP_CLASSNAME = 'genover-tooltip'; $(node).hover( () => { try { const offset = ...
{ setGenePanelInTooltip(genePanel); }
conditional_block
tracksHelper.ts
import Raphael from 'webpack-raphael'; import $ from 'jquery'; import _ from 'lodash'; import { Mutation } from 'cbioportal-ts-api-client'; import { default as chromosomeSizes } from './chromosomeSizes.json'; import { IIconData } from './GenomicOverviewUtils.js'; import { GENOME_ID_TO_GENOME_BUILD } from 'shared/lib/re...
(textElement: any, p: any) { var textBBox = textElement.getBBox(); return p.path( 'M' + textBBox.x + ' ' + (textBBox.y + textBBox.height) + 'L' + (textBBox.x + textBBox.width) + ' ' + (textBBox.y + textBBox.height) )...
underlineText
identifier_name
middleware.py
# -*- coding: utf-8 -*- # Copyright (C) 2012 Rodrigo Alves Lima # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version...
request.url_name = resolve(request.path).url_name return None
identifier_body
middleware.py
# -*- coding: utf-8 -*- # Copyright (C) 2012 Rodrigo Alves Lima # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version...
: def process_view(self, request, *args): request.url_name = resolve(request.path).url_name return None
URLNameMiddleware
identifier_name
middleware.py
# -*- coding: utf-8 -*- # Copyright (C) 2012 Rodrigo Alves Lima # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version...
class URLNameMiddleware: def process_view(self, request, *args): request.url_name = resolve(request.path).url_name return None
random_line_split
const-big-enum.rs
// run-pass enum Foo { Bar(u32), Baz, Quux(u64, u16) } static X: Foo = Foo::Baz; pub fn main() { match X {
Foo::Bar(s) => assert_eq!(s, 2654435769), _ => panic!() } match Z { Foo::Quux(d,h) => { assert_eq!(d, 0x123456789abcdef0); assert_eq!(h, 0x1234); } _ => panic!() } } static Y: Foo = Foo::Bar(2654435769); static Z: Foo = Foo::Quux(0x123456789ab...
Foo::Baz => {} _ => panic!() } match Y {
random_line_split
const-big-enum.rs
// run-pass enum
{ Bar(u32), Baz, Quux(u64, u16) } static X: Foo = Foo::Baz; pub fn main() { match X { Foo::Baz => {} _ => panic!() } match Y { Foo::Bar(s) => assert_eq!(s, 2654435769), _ => panic!() } match Z { Foo::Quux(d,h) => { assert_eq!(d, 0x12...
Foo
identifier_name
es6setvemap.js
document.write("-----------------------Sets-----------------------<br />"); var randSet = new Set(); randSet.add(10); randSet.add("Word"); document.write(`Set Size : ${randSet.size}<br />`); for (let val of randSet) document.write(`Set Val : ${val}<br />`); document.write("-----------------------MAPS -----------------...
document.write(`key2 : ${randMap.get("key2")}<br />`); // değerlerim boyuru document.write(`Map Boyutu : ${randMap.size}<br />`); randMap.forEach(function(value, key){ document.write(`${key} : ${value}<br />`); });
randMap.set("key2", 10); // Değerleri Getir document.write(`key1 : ${randMap.get("key1")}<br />`);
random_line_split
__init__.py
import datetime from xml.etree import ElementTree try: from urllib.parse import urlparse, parse_qs except ImportError: # Python 2 from urlparse import urlparse, parse_qs import html5lib import requests from .models import ( Category, SearchSortKey, SearchOrderKey, SearchResultPage, TorrentPage, To...
return content_div def view_torrent(self, torrent_id): """Retrieves and parses the torrent page for a given `torrent_id`. :param torrent_id: the ID of the torrent to view :raises TorrentNotFoundError: if the torrent does not exist :returns: a :class:`TorrentPage` with a sn...
return None
conditional_block
__init__.py
import datetime from xml.etree import ElementTree try: from urllib.parse import urlparse, parse_qs except ImportError: # Python 2 from urlparse import urlparse, parse_qs import html5lib import requests from .models import ( Category, SearchSortKey, SearchOrderKey, SearchResultPage, TorrentPage, To...
(self, terms, category=Category.all_categories, page=1, sort_key=SearchSortKey.date, order_key=SearchOrderKey.descending): """Get a list of torrents that match the given search term :param terms: the `str` needle :param category: the desired :class:`Category` of th...
search
identifier_name
__init__.py
import datetime from xml.etree import ElementTree try: from urllib.parse import urlparse, parse_qs except ImportError: # Python 2 from urlparse import urlparse, parse_qs import html5lib import requests from .models import ( Category, SearchSortKey, SearchOrderKey, SearchResultPage, TorrentPage, To...
class NyaaClient(object): """The Nyaa client. Provides configuration and methods to access Nyaa. """ def __init__(self, url='http://www.nyaa.se'): """Initialize the :class:`NyaaClient`. :param url: the base URL of the Nyaa or Nyaa-like torrent tracker """ self.base_...
pass
identifier_body
__init__.py
import datetime from xml.etree import ElementTree try: from urllib.parse import urlparse, parse_qs except ImportError: # Python 2 from urlparse import urlparse, parse_qs import html5lib import requests from .models import ( Category, SearchSortKey, SearchOrderKey, SearchResultPage, TorrentPage, To...
# original contents of the description div description = ElementTree.tostring( content.findall(".//div[@class='viewdescription']")[0], encoding='utf8', method='html') return TorrentPage( torrent_id, name, submitter, category, tracker, date_created, ...
# note that the tree returned by html5lib might not exactly match the
random_line_split
run_tests.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """Script to run the tests.""" from __future__ import print_function import sys import unittest # Change PYTHONPATH to include dependencies. sys.path.insert(0, '.') import utils.dependencies # pylint: disable=wrong-import-position if __name__ == '__main__': print('...
sys.exit(1)
conditional_block
run_tests.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """Script to run the tests.""" from __future__ import print_function import sys import unittest # Change PYTHONPATH to include dependencies. sys.path.insert(0, '.') import utils.dependencies # pylint: disable=wrong-import-position
print('Using Python version {0!s}'.format(sys.version)) fail_unless_has_test_file = '--fail-unless-has-test-file' in sys.argv setattr(unittest, 'fail_unless_has_test_file', fail_unless_has_test_file) if fail_unless_has_test_file: # Remove --fail-unless-has-test-file otherwise it will conflict with # th...
if __name__ == '__main__':
random_line_split
Datatypes.py
# Copyright (c) 2016 Iotic Labs Ltd. 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 # # https://github.com/Iotic-Labs/py-IoticAgent/blob/master/LICENSE # # Unless re...
''' DATETIME = 'dateTime' ''' Represents a specific instant of time. It has the form YYYY-MM-DDThh:mm:ss followed by an optional time-zone suffix. `YYYY` is the year, `MM` is the month number, `DD` is the day number, `hh` the hour in 24-hour format, `mm` the minute, and `ss` the second (a decimal and fraction are allo...
UNSIGNED_BYTE = 'unsignedByte' '''An unsigned 8-bit integer in the range [0, 255]. Derived from the unsignedShort datatype.''' DATE = 'date' '''Represents a specific date. The syntax is the same as that for the date part of dateTime, with an optional time zone indicator. Example: "1889-09-24".
random_line_split
trait-coercion-generic-bad.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
() { // FIXME (#22405): Replace `Box::new` with `box` here when/if possible. let s: Box<Trait<isize>> = Box::new(Struct { person: "Fred" }); //~^ ERROR the trait `Trait<isize>` is not implemented for the type `Struct` s.f(1); }
main
identifier_name
trait-coercion-generic-bad.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
struct Struct { person: &'static str } trait Trait<T> { fn f(&self, x: T); } impl Trait<&'static str> for Struct { fn f(&self, x: &'static str) { println!("Hello, {}!", x); } } fn main() { // FIXME (#22405): Replace `Box::new` with `box` here when/if possible. let s: Box<Trait<isize>>...
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms.
random_line_split
settings.rs
use crate::render::object::BodyColor; use std::fs::File; use std::path::PathBuf; #[derive(Deserialize)] pub struct Car { pub id: String, pub color: BodyColor, pub slots: Vec<String>, pub pos: Option<(i32, i32)>, } #[derive(Copy, Clone, Deserialize)] pub enum View { Flat, Perspective, } #[der...
File::open(path) .unwrap_or_else(|e| panic!("Unable to open the settings file: {:?}.\nPlease copy '{}' to '{}' and adjust 'data_path'", e, TEMPLATE, PATH)) .read_to_string(&mut string) .unwrap(); let set: Settings = match ron::de::from_str(&string) { ...
use std::io::Read; const TEMPLATE: &str = "config/settings.template.ron"; const PATH: &str = "config/settings.ron"; let mut string = String::new();
random_line_split
settings.rs
use crate::render::object::BodyColor; use std::fs::File; use std::path::PathBuf; #[derive(Deserialize)] pub struct Car { pub id: String, pub color: BodyColor, pub slots: Vec<String>, pub pos: Option<(i32, i32)>, } #[derive(Copy, Clone, Deserialize)] pub enum View { Flat, Perspective, } #[der...
{ pub color: [f32; 4], pub depth: f32, } #[derive(Clone, Deserialize)] pub struct Render { pub wgpu_trace_path: String, pub light: Light, pub terrain: Terrain, pub water: Water, pub fog: Fog, pub debug: DebugRender, } #[derive(Deserialize)] pub struct Settings { pub data_path: Pat...
Fog
identifier_name
crunchtime.js
$.ajax({ async: false, url: "http://api.visalus.com/ITReporting/SalesAnalytics/GetDataBySP/?SPName=usp_PROMO_ViCrunch3FF_JSON&?", type: 'GET', dataType: 'jsonp', success: function (data) { var result = JSON.stringify(data); ...
error: function (e) { alert('fail'); } });
document.getElementById("crunchtime").innerHTML = output; },
random_line_split
rule-must-exist.guard.spec.ts
/* * Squidex Headless CMS * * @license * Copyright (c) Squidex UG (haftungsbeschränkt). All rights reserved. */ import { Router } from '@angular/router'; import { firstValueFrom, of } from 'rxjs'; import { IMock, It, Mock, Times } from 'typemoq'; import { RuleDto, RulesState } from '@app/shared/internal'; import ...
expect(result).toBeTruthy(); rulesState.verify(x => x.select(null), Times.once()); }); });
const result = await firstValueFrom(ruleGuard.canActivate(route));
random_line_split
commonLwm2m.js
/* * Copyright 2014 Telefonica Investigación y Desarrollo, S.A.U * * This file is part of lightweightM2M-iotagent * * lightweightM2M-iotagent is free software: you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, eithe...
name: name, type: type, value: value } ]; logger.debug(context, 'Handling data from device [%s]', registeredDevice.id); iotAgentLib.update( registeredDevice.name, registeredDevice.type, '', attributes, registeredDevice, ...
* @param {String} value New value for the attribute. */ function activeDataHandler(registeredDevice, name, type, value) { var attributes = [ {
random_line_split
commonLwm2m.js
/* * Copyright 2014 Telefonica Investigación y Desarrollo, S.A.U * * This file is part of lightweightM2M-iotagent * * lightweightM2M-iotagent is free software: you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, eithe...
else { callback('Couldn\'t find any way to map the active attribute: ' + activeAttributes[i].name); return; } if (lwm2mMapping) { var mappedUri = '/' + lwm2mMapping.objectType + '/' + lwm2mMapping.objectInstance; for (var j = 0; j < objects.length; j++) ...
lwm2mMapping = omaInverseRegistry[activeAttributes[i].name]; if (!lwm2mMapping.objectInstance) { lwm2mMapping.objectInstance = 0; } }
conditional_block
commonLwm2m.js
/* * Copyright 2014 Telefonica Investigación y Desarrollo, S.A.U * * This file is part of lightweightM2M-iotagent * * lightweightM2M-iotagent is free software: you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, eithe...
payload, registeredDevice, callback) { var objects = lwm2mUtils.parseObjectUriList(payload), activeAttributes = [], observationList = []; if (registeredDevice.active) { activeAttributes = registeredDevice.active; } else if (commons.getConfig().ngsi.types[registeredDevice.type]) { ...
bserveActiveAttributes(
identifier_name
commonLwm2m.js
/* * Copyright 2014 Telefonica Investigación y Desarrollo, S.A.U * * This file is part of lightweightM2M-iotagent * * lightweightM2M-iotagent is free software: you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, eithe...
/** * Given a registered device and a text payload indicating a list of the OMA Objects supported by a client, creates an * observer for each active resource associated with that kind of device. * * @param {String} payload Text representation of the list of objects supported by the client. * @param {...
var attributes = [ { name: name, type: type, value: value } ]; logger.debug(context, 'Handling data from device [%s]', registeredDevice.id); iotAgentLib.update( registeredDevice.name, registeredDevice.type, '', attrib...
identifier_body