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
group_dao.py
# Copyright 2017 Google Inc. # # 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 writing, s...
(self, resource_name, group_id, timestamp): """Get the members of a group. Args: resource_name: String of the resource name. group_id: String of the group id. timestamp: The timestamp of the snapshot. Returns: A tuple of group members in dict fo...
get_group_members
identifier_name
group_dao.py
# Copyright 2017 Google Inc. # # 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 writing, s...
return all_members
queue.put(member.get('member_id'))
conditional_block
group_dao.py
# Copyright 2017 Google Inc. # # 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 writing, s...
timestamp: The timestamp of the snapshot. Returns: A tuple of the groups as dict. """ sql = select_data.GROUPS.format(timestamp) return self.execute_sql_with_fetch(resource_name, sql, None) def get_group_id(self, resource_name, group_email, timestamp): ...
resource_name: String of the resource name.
random_line_split
group_dao.py
# Copyright 2017 Google Inc. # # 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 writing, s...
group_email: String of the group email. timestamp: The timestamp of the snapshot. Returns: String of the group id. """ sql = select_data.GROUP_ID.format(timestamp) result = self.execute_sql_with_fetch(resource_name, sql, (group_email,)) retur...
"""Data access object (DAO) for Groups.""" def get_all_groups(self, resource_name, timestamp): """Get all the groups. Args: resource_name: String of the resource name. timestamp: The timestamp of the snapshot. Returns: A tuple of the groups as dict. ...
identifier_body
core.py
# Copyright 2017 Erik Tollerud # # 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 ...
else: # leave just the alpha to control the fading cdata = np.ones(data.shape) imarr = np.transpose([cdata*ci[0], cdata*ci[1], cdata*ci[2], data*ci[3]], (1, 2, 0)) im.set_data(imarr) ims.append(im) for im in ims: ...
cdata = 1-data
conditional_block
core.py
# Copyright 2017 Erik Tollerud # # 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 n_cats(): return len(_CAT_DATA) def catter(x, y, s=40, c=None, cat='random', alpha=1, ax=None, cmap=None, aspects='auto'): """ A catter plot (scatter plot with cats). Most arguments are interpreted the same as the matplotlib `scatter` function, except that ``s`` is the ...
return _CAT_DATA[i]
identifier_body
core.py
# Copyright 2017 Erik Tollerud # # 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 ...
import numpy as np from matplotlib import image, cm from matplotlib import pyplot as plt __all__ = ['get_cat_num', 'n_cats', 'catter'] # N_cats x 72 x 72, 0 is transparent, 1 is full-cat _CAT_DATA = np.load(io.BytesIO(pkgutil.get_data('catterplot', 'data/cats.npy'))) def get_cat_num(i): return...
random_line_split
core.py
# Copyright 2017 Erik Tollerud # # 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 ...
(x, y, s=40, c=None, cat='random', alpha=1, ax=None, cmap=None, aspects='auto'): """ A catter plot (scatter plot with cats). Most arguments are interpreted the same as the matplotlib `scatter` function, except that ``s`` is the *data* size of the symbol (not pixel). Additional kwargs i...
catter
identifier_name
DayPicker.js
import React from 'react'; import { storiesOf } from '@kadira/storybook'; import DayPicker from '../src/components/DayPicker'; import moment from 'moment-jalaali' import { VERTICAL_ORIENTATION, VERTICAL_SCROLLABLE, } from '../constants'; const TestPrevIcon = props => ( <span style={{ border: '1px solid #d...
/> )) .addWithInfo('with custom details', () => ( <DayPicker renderDay={day => (day.day() % 6 === 5 ? '😻' : day.format('D'))} /> )) .addWithInfo('vertical with fixed-width container', () => ( <div style={{ width: '400px' }}> <DayPicker numberOfMonths={2} orientation=...
navNext={<TestNextIcon />}
random_line_split
AlertMessageView_spec.js
define( [ 'views/AlertMessageView', 'lib/Mediator' ], function (AlertMessageView, Mediator) {
beforeEach(function () { resultsCollection = new Backbone.Collection(); mediator = new Mediator(); }); it('should initially be hidden', function () { view = new AlertMessageView().render(); expect(view.$el.find('.alert')).toHaveClass('hidden'); }); it('sh...
describe('AlertMessageView', function () { var resultsCollection, view, mediator;
random_line_split
zipping_list.py
import sys import random from linked_list_prototype import ListNode from reverse_linked_list_iterative import reverse_linked_list # @include def zipping_linked_list(L): if not L or not L.next: return L # Finds the second half of L. slow = fast = L while fast and fast.next: slow, fast ...
curr = zipping_linked_list(head) idx = 0 while curr: if len(sys.argv) <= 2: if idx & 1: assert pre + curr.data == n idx += 1 print(curr.data) pre = curr.data curr = curr.next if __name__ == '__main__': main()
n = int(sys.argv[1]) if len(sys.argv) == 2 else random.randint(1, 1000) for i in reversed(range(n + 1)): curr = ListNode(i, head) head = curr
conditional_block
zipping_list.py
import sys import random from linked_list_prototype import ListNode from reverse_linked_list_iterative import reverse_linked_list # @include def zipping_linked_list(L): if not L or not L.next: return L # Finds the second half of L. slow = fast = L while fast and fast.next: slow, fast ...
if len(sys.argv) <= 2: if idx & 1: assert pre + curr.data == n idx += 1 print(curr.data) pre = curr.data curr = curr.next if __name__ == '__main__': main()
while curr:
random_line_split
zipping_list.py
import sys import random from linked_list_prototype import ListNode from reverse_linked_list_iterative import reverse_linked_list # @include def zipping_linked_list(L): if not L or not L.next: return L # Finds the second half of L. slow = fast = L while fast and fast.next: slow, fast ...
(): head = None if len(sys.argv) > 2: for i in sys.argv[1:]: curr = ListNode(int(i), head) head = curr else: n = int(sys.argv[1]) if len(sys.argv) == 2 else random.randint(1, 1000) for i in reversed(range(n + 1)): curr = ListNode(i, head) ...
main
identifier_name
zipping_list.py
import sys import random from linked_list_prototype import ListNode from reverse_linked_list_iterative import reverse_linked_list # @include def zipping_linked_list(L): if not L or not L.next: return L # Finds the second half of L. slow = fast = L while fast and fast.next: slow, fast ...
if __name__ == '__main__': main()
head = None if len(sys.argv) > 2: for i in sys.argv[1:]: curr = ListNode(int(i), head) head = curr else: n = int(sys.argv[1]) if len(sys.argv) == 2 else random.randint(1, 1000) for i in reversed(range(n + 1)): curr = ListNode(i, head) head ...
identifier_body
input.rs
self.mouse_scroll = 0.0; self.type_buffer.clear(); for state in self.mouse_keys.iter_mut() { if *state == KeyState::Released { *state = KeyState::Up; } if *state == KeyState::Pressed { *state = KeyState::Down; } assert!(*state != KeyState::PressedRepeat); ...
Escape = 0x1, // Grave = 0x31,
random_line_split
input.rs
_KEYS], /// Cleared each frame. Contains typed characters in the order they where typed pub type_buffer: String, pub window_has_keyboard_focus: bool, pub received_events_this_frame: bool, #[cfg(feature = "gamepad")] pub gamepads: [Gamepad; 4], } impl Input { pub fn new() -> Input { ...
else { gamepad.buttons = [KeyState::Up; GAMEPAD_BUTTON_COUNT]; gamepad.left = Vec2::ZERO; gamepad.right = Vec2::ZERO; gamepad.left_trigger = 0.0; gamepad.right_trigger = 0.0; } } self.received_events_this_...
{ for state in gamepad.buttons.iter_mut() { if *state == KeyState::Released { *state = KeyState::Up; } if *state == KeyState::Pressed { *state = KeyState::Down; } assert!(*state != KeyState::PressedRepeat); } }
conditional_block
input.rs
_KEYS], /// Cleared each frame. Contains typed characters in the order they where typed pub type_buffer: String, pub window_has_keyboard_focus: bool, pub received_events_this_frame: bool, #[cfg(feature = "gamepad")] pub gamepads: [Gamepad; 4], } impl Input { pub fn new() -> Input { ...
(self) -> bool { !self.down() } /// Returns true if the button is being held down, but was not held down in the last /// frame (`Pressed`) pub fn pressed(self) -> bool { self == KeyState::Pressed } /// Returns true either if this button is being held down and was not held down in the ///...
up
identifier_name
insert.rs
use redox::*; use super::*;
pub enum InsertMode { Append, Insert, Replace, } #[derive(Clone, PartialEq, Copy)] /// The insert options pub struct InsertOptions { /// The mode type pub mode: InsertMode, } impl Editor { /// Insert text pub fn insert(&mut self, c: Key) { let x = self.x(); let y = self.y()...
use core::iter::FromIterator; #[derive(Clone, PartialEq, Copy)] /// The type of the insert mode
random_line_split
insert.rs
use redox::*; use super::*; use core::iter::FromIterator; #[derive(Clone, PartialEq, Copy)] /// The type of the insert mode pub enum InsertMode { Append, Insert, Replace, } #[derive(Clone, PartialEq, Copy)] /// The insert options pub struct
{ /// The mode type pub mode: InsertMode, } impl Editor { /// Insert text pub fn insert(&mut self, c: Key) { let x = self.x(); let y = self.y(); match c { Key::Char('\n') => { let ln = self.text[y].clone(); let (slice, _) = ln.as_slic...
InsertOptions
identifier_name
insert.rs
use redox::*; use super::*; use core::iter::FromIterator; #[derive(Clone, PartialEq, Copy)] /// The type of the insert mode pub enum InsertMode { Append, Insert, Replace, } #[derive(Clone, PartialEq, Copy)] /// The insert options pub struct InsertOptions { /// The mode type pub mode: InsertMode, }...
_ => {}, } } }
{ self.text[y].insert(x, ch); self.next(); }
conditional_block
discovery_utils.ts
which have been bootstrapped by Angular. * * @param elementOrDir DOM element, component or directive instance * for which to retrieve the root components. * @returns Root components associated with the target object. * * @publicApi * @globalApi ng */ export function getRootComponents(elementOrDir: Element |...
{ return obj.type !== undefined && obj.template !== undefined && obj.declaredInputs !== undefined; }
identifier_body
discovery_utils.ts
getComponent<T>(element: Element): T|null { assertDomElement(element); const context = loadLContext(element, false); if (context === null) return null; if (context.component === undefined) { context.component = getComponentAtNodeIndex(context.nodeIndex, context.lView); } return context.component as T...
(component: any): string { const hostElement = getHostElement(component); return hostElement.textContent || ''; } export function loadLContextFromNode(node: Node): LContext { if (!(node instanceof Node)) throw new Error('Expecting instance of DOM Element'); return loadLContext(node) !; } /** * Event listener...
getRenderedText
identifier_name
discovery_utils.ts
getComponent<T>(element: Element): T|null { assertDomElement(element); const context = loadLContext(element, false); if (context === null) return null; if (context.component === undefined) { context.component = getComponentAtNodeIndex(context.nodeIndex, context.lView); } return context.component as T...
return providerTokens; } /** * Retrieves directive instances associated with a given DOM element. Does not include * component instances. * * @usageNotes * Given the following DOM structure: * ``` * <my-app> * <button my-button></button> * <my-comp></my-comp> * </my-app> * ``` * Calling `getDirectiv...
{ let value = tView.data[i]; if (isDirectiveDefHack(value)) { // The fact that we sometimes store Type and sometimes DirectiveDef in this location is a // design flaw. We should always store same type so that we can be monomorphic. The issue // is that for Components/Directives we store the d...
conditional_block
discovery_utils.ts
getComponent<T>(element: Element): T|null { assertDomElement(element); const context = loadLContext(element, false); if (context === null) return null; if (context.component === undefined) { context.component = getComponentAtNodeIndex(context.nodeIndex, context.lView); } return context.component as T...
* @publicApi * @globalApi ng */ export function getInjector(elementOrDir: Element | {}): Injector { const context = loadLContext(elementOrDir, false); if (context === null) return Injector.NULL; const tNode = context.lView[TVIEW].data[context.nodeIndex] as TElementNode; return new NodeInjector(tNode, contex...
* * @param elementOrDir DOM element, component or directive instance for which to * retrieve the injector. * @returns Injector associated with the element, component or directive instance. *
random_line_split
workbench.service.ts
* 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 writing, software * distributed...
el`, params); // params => query / webSocketId } public checkConnectionStatus(queryEditorId: string, socketId: string) { const param = { webSocketId: socketId }; return this.post(this.API_URL + `queryeditors/${queryEditorId}/status`, param); } // 쿼리 결과 조회 (페이징 사용) public runQueryResult(edi...
Id}/query/canc
identifier_name
workbench.service.ts
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 writing, software * distributed u...
n.sid; connInfo.table = table; connInfo.url = connection.url; // properties 속성이 존재 할경우 if (!CommonUtil.isNullOrUndefined(connection.properties)) { connInfo.properties = connection.properties; } params.connection = connInfo; params.database = connection.database; params.type = 'TA...
nInfo.type = connection.type; connInfo.catalog = connection.catalog; connInfo.sid = connectio
conditional_block
workbench.service.ts
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 writing, software * distributed u...
g, params: any) { return this.postBinary(this.API_URL + `queryeditors/${queryEditorId}/query/download`, params); } // 쿼리 취소 public setQueryRunCancel(queryEditorId: string, params: any) { return this.post(this.API_URL + `queryeditors/${queryEditorId}/query/cancel`, params); // params => query / webSocketI...
} return this.post(this.API_URL + `queryeditors/${id}/query/run`, param); // params => query 값만 사용. } // 쿼리 실행 => websocket public runSingleQueryWithInvalidQueryEditorId(params: QueryEditor) { const id = params.editorId; return this.post(this.API_URL + `queryeditors/${id}/query/run`, params); ...
identifier_body
workbench.service.ts
/* * 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 writing, software * distribu...
import {CommonUtil} from '@common/util/common.util'; import {AbstractService} from '@common/service/abstract.service'; import {QueryEditor, Workbench} from '@domain/workbench/workbench'; import {Page} from '@domain/common/page'; @Injectable() export class WorkbenchService extends AbstractService { /*-=-=-=-=-=-=-=-...
* limitations under the License. */ import {Injectable, Injector} from '@angular/core';
random_line_split
cpqScsiPhyDrv.py
################################################################################ # # This program is part of the HPMon Zenpack for Zenoss. # Copyright (C) 2008, 2009, 2010, 2011 Egor Puzanov. # # This program can be used under the GNU General Public License version 2 # You can find full information here: http://www.zen...
$Id: cpqScsiPhyDrv.py,v 1.2 2011/01/04 23:27:26 egor Exp $""" __version__ = "$Revision: 1.2 $"[11:-2] from HPHardDisk import HPHardDisk from HPComponent import * class cpqScsiPhyDrv(HPHardDisk): """cpqScsiPhyDrv object """ statusmap ={1: (DOT_GREY, SEV_WARNING, 'other'), 2: (DOT_GREEN, S...
random_line_split
cpqScsiPhyDrv.py
################################################################################ # # This program is part of the HPMon Zenpack for Zenoss. # Copyright (C) 2008, 2009, 2010, 2011 Egor Puzanov. # # This program can be used under the GNU General Public License version 2 # You can find full information here: http://www.zen...
InitializeClass(cpqScsiPhyDrv)
"""cpqScsiPhyDrv object """ statusmap ={1: (DOT_GREY, SEV_WARNING, 'other'), 2: (DOT_GREEN, SEV_CLEAN, 'Ok'), 3: (DOT_RED, SEV_CRITICAL, 'Failed'), 4: (DOT_YELLOW, SEV_WARNING, 'Not Configured'), 5: (DOT_ORANGE, SEV_ERROR, 'Bad Cable'), ...
identifier_body
cpqScsiPhyDrv.py
################################################################################ # # This program is part of the HPMon Zenpack for Zenoss. # Copyright (C) 2008, 2009, 2010, 2011 Egor Puzanov. # # This program can be used under the GNU General Public License version 2 # You can find full information here: http://www.zen...
(HPHardDisk): """cpqScsiPhyDrv object """ statusmap ={1: (DOT_GREY, SEV_WARNING, 'other'), 2: (DOT_GREEN, SEV_CLEAN, 'Ok'), 3: (DOT_RED, SEV_CRITICAL, 'Failed'), 4: (DOT_YELLOW, SEV_WARNING, 'Not Configured'), 5: (DOT_ORANGE, SEV_ERROR, 'Bad C...
cpqScsiPhyDrv
identifier_name
build.py
import os from os.path import join, getctime, dirname import glob import subprocess import argparse def newest_file(root): path = join(root, "*tar.bz2") newest = max(glob.iglob(path), key=getctime) return newest def upload(pkg, user): cmd = ["binstar", "upload", "--force","-u", user, pkg] subproce...
if __name__ == "__main__": p = argparse.ArgumentParser() p.add_argument("build_dir") p.add_argument("--py", action="append", default=[]) p.add_argument("--plat", action="append", default=[]) p.add_argument("-u", "--binstar-user", help="binstar user") args = p.parse_args() build_dir = p.add...
print (recipe, pythons, platforms) for p in pythons: cmd = ["conda", "build", recipe, "--python", p] subprocess.check_call(cmd) pkg = newest_file(build_path) if binstar_user: upload(pkg, binstar_user) for plat in platforms: cmd = ["conda", "convert", "...
identifier_body
build.py
import os from os.path import join, getctime, dirname import glob import subprocess import argparse def newest_file(root): path = join(root, "*tar.bz2") newest = max(glob.iglob(path), key=getctime) return newest def upload(pkg, user): cmd = ["binstar", "upload", "--force","-u", user, pkg] subproce...
(recipe, build_path, pythons=[], platforms=[], binstar_user=None): print (recipe, pythons, platforms) for p in pythons: cmd = ["conda", "build", recipe, "--python", p] subprocess.check_call(cmd) pkg = newest_file(build_path) if binstar_user: upload(pkg, binstar_user) ...
build
identifier_name
build.py
import os from os.path import join, getctime, dirname import glob import subprocess import argparse def newest_file(root): path = join(root, "*tar.bz2") newest = max(glob.iglob(path), key=getctime) return newest def upload(pkg, user): cmd = ["binstar", "upload", "--force","-u", user, pkg] subproce...
if __name__ == "__main__": p = argparse.ArgumentParser() p.add_argument("build_dir") p.add_argument("--py", action="append", default=[]) p.add_argument("--plat", action="append", default=[]) p.add_argument("-u", "--binstar-user", help="binstar user") args = p.parse_args() build_dir = p.add...
cmd = ["conda", "convert", "-p", plat, pkg] subprocess.check_call(cmd) if binstar_user: to_upload = newest_file(plat) upload(to_upload, binstar_user)
conditional_block
build.py
import os from os.path import join, getctime, dirname import glob import subprocess import argparse def newest_file(root): path = join(root, "*tar.bz2") newest = max(glob.iglob(path), key=getctime) return newest def upload(pkg, user): cmd = ["binstar", "upload", "--force","-u", user, pkg] subproce...
""" python build.py /opt/anaconda/conda-bld/linux-64 --py 27 --py 34 --plat osx-64 --plat win-64 -u hugo """
random_line_split
gen_lines.rs
// Copyright (c) Carl-Erwin Griffith // // Permission is hereby granted, free of charge, to any // person obtaining a copy of this software and associated // documentation files (the "Software"), to deal in the // Software without restriction, including without // limitation the rights to use, copy, modify, merge, // p...
let mut string = String::new(); let table = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']; for x in 0..linewidth { string.push(ta...
buff.write_fmt(format_args!("{:012} {}", x, string)).unwrap(); } } fn gen_line(linewidth: u64) -> String {
random_line_split
gen_lines.rs
// Copyright (c) Carl-Erwin Griffith // // Permission is hereby granted, free of charge, to any // person obtaining a copy of this software and associated // documentation files (the "Software"), to deal in the // Software without restriction, including without // limitation the rights to use, copy, modify, merge, // p...
let start_num = args[1].trim_end().parse::<u64>().unwrap_or(0); let stop_num = args[2].trim_end().parse::<u64>().unwrap_or(0); let width_num = args[3].trim_end().parse::<u64>().unwrap_or(0); gen_lines(start_num, stop_num, width_num); } fn gen_lines(start: u64, stop: u64, linewidth: u64) -> () { ...
{ println!("usage : {} start numline width", args[0]); return; }
conditional_block
gen_lines.rs
// Copyright (c) Carl-Erwin Griffith // // Permission is hereby granted, free of charge, to any // person obtaining a copy of this software and associated // documentation files (the "Software"), to deal in the // Software without restriction, including without // limitation the rights to use, copy, modify, merge, // p...
fn gen_line(linewidth: u64) -> String { let mut string = String::new(); let table = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']; for ...
{ let string = gen_line(linewidth); let stdout = io::stdout(); let mut buff = BufWriter::new(stdout); for x in start..start + stop + 1 { buff.write_fmt(format_args!("{:012} {}", x, string)).unwrap(); } }
identifier_body
gen_lines.rs
// Copyright (c) Carl-Erwin Griffith // // Permission is hereby granted, free of charge, to any // person obtaining a copy of this software and associated // documentation files (the "Software"), to deal in the // Software without restriction, including without // limitation the rights to use, copy, modify, merge, // p...
(linewidth: u64) -> String { let mut string = String::new(); let table = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']; for x in 0..linew...
gen_line
identifier_name
message.rs
use std::net::SocketAddr; use std::sync::mpsc::Sender; #[derive(Debug, Clone)] pub struct Member { pub name: String, pub addr: SocketAddr } pub struct Request { pub addr: SocketAddr, pub body: RequestBody } pub enum RequestBody { Join { tx: Sender<Notify> }, Leave, List, Rename { name...
{ Join { name: String }, Leave, List(Vec<(Member)>), Rename(bool), Submit(bool), Message(String) } #[derive(Debug, Clone)] pub enum BroadcastNotify { Join { name: String, addr: SocketAddr }, Leave { name: String, addr: SocketAddr }, Rename { old_name: String, new_name: String, addr...
UnicastNotify
identifier_name
message.rs
use std::net::SocketAddr; use std::sync::mpsc::Sender; #[derive(Debug, Clone)] pub struct Member { pub name: String, pub addr: SocketAddr } pub struct Request { pub addr: SocketAddr, pub body: RequestBody } pub enum RequestBody { Join { tx: Sender<Notify> }, Leave, List, Rename { name...
pub enum BroadcastNotify { Join { name: String, addr: SocketAddr }, Leave { name: String, addr: SocketAddr }, Rename { old_name: String, new_name: String, addr: SocketAddr }, Submit { name: String, addr: SocketAddr, message: String }, }
#[derive(Debug, Clone)]
random_line_split
views.py
from django.shortcuts import render, redirect from django.contrib.auth.decorators import login_required from django.contrib import messages from .models import Profile from .forms import ProfileForm @login_required def
(request): next = request.GET.get("next") profile, created = Profile.objects.get_or_create( user=request.user, defaults={ "first_name": request.user.first_name, "last_name": request.user.last_name, } ) if request.method == "POST": form = ...
profile_edit
identifier_name
views.py
from django.shortcuts import render, redirect from django.contrib.auth.decorators import login_required from django.contrib import messages from .models import Profile from .forms import ProfileForm @login_required def profile_edit(request):
else: form = ProfileForm(instance=profile) return render(request, "profiles/edit.html", { "form": form, "next": next, })
next = request.GET.get("next") profile, created = Profile.objects.get_or_create( user=request.user, defaults={ "first_name": request.user.first_name, "last_name": request.user.last_name, } ) if request.method == "POST": form = ProfileForm(request....
identifier_body
views.py
from django.shortcuts import render, redirect from django.contrib.auth.decorators import login_required from django.contrib import messages from .models import Profile from .forms import ProfileForm @login_required def profile_edit(request): next = request.GET.get("next") profile, created = Profile.obj...
else: form = ProfileForm(instance=profile) return render(request, "profiles/edit.html", { "form": form, "next": next, })
profile = form.save() request.user.first_name = form.cleaned_data["first_name"] request.user.last_name = form.cleaned_data["last_name"] messages.add_message(request, messages.SUCCESS, "Successfully updated profile." ) if next: r...
conditional_block
views.py
from django.shortcuts import render, redirect from django.contrib.auth.decorators import login_required from django.contrib import messages from .models import Profile from .forms import ProfileForm @login_required def profile_edit(request): next = request.GET.get("next") profile, created = Profile.obj...
profile = form.save() request.user.first_name = form.cleaned_data["first_name"] request.user.last_name = form.cleaned_data["last_name"] messages.add_message(request, messages.SUCCESS, "Successfully updated profile." ) if next: ...
form = ProfileForm(request.POST, instance=profile) if form.is_valid():
random_line_split
__init__.py
self.device.execute('mkdir -p {}'.format(self.tmpfs_mount_point), as_root=True) self.device.execute(self.mount_command.format(self.tmpfs_size, self.tmpfs_mount_point), as_root=True) def setup(self, context): before_dirs = [ _d(os.path.join(co...
bchunks = bline.strip().split() while True: achunks = aline.strip().split()
random_line_split
__init__.py
_PATH = 3 parameters = [ Parameter('paths', kind=list_of_strings, mandatory=True, description="""A list of paths to be pulled from the device. These could be directories as well as files.""", global_alias='sysfs_extract_dirs'), Par...
(self, context):
stop
identifier_name
__init__.py
_PATH = 3 parameters = [ Parameter('paths', kind=list_of_strings, mandatory=True, description="""A list of paths to be pulled from the device. These could be directories as well as files.""", global_alias='sysfs_extract_dirs'), Par...
def slow_start(self, context): if self.use_tmpfs: for d in self.paths: dest_dir = self.device.path.join(self.on_device_before, as_relative(d)) if '*' in dest_dir: dest_dir = self.device.path.dirname(dest_dir) self.device.execu...
for d in self.paths: before_dir = self.device.path.join(self.on_device_before, self.device.path.dirname(as_relative(d))) after_dir = self.device.path.join(self.on_device_after, self.devic...
conditional_block
__init__.py
# pylint: disable=access-member-before-definition raise ConfigError('use_tempfs must be False for an unrooted device.') elif self.use_tmpfs is None: # pylint: disable=access-member-before-definition self.use_tmpfs = self.device.is_rooted if self.use_tmpfs: self.on...
name = 'cpufreq' description = """ Collects dynamic frequency (DVFS) settings before and after workload execution. """ tarname = 'cpufreq.tar' parameters = [ Parameter('paths', mandatory=False, override=True), ] def setup(self, context): self.paths = ['/sys/devices/system...
identifier_body
preferences_default.py
"""User preferences for KlustaViewa.""" # ----------------------------------------------------------------------------- # Imports # ----------------------------------------------------------------------------- import logging import numpy as np # --------------------------------------------------------------...
# Level of the logging file. DEBUG, INFO or WARNING, or just None to disable. loglevel_file = logging.INFO # ----------------------------------------------------------------------------- # Main window # ----------------------------------------------------------------------------- # Should the software ask th...
# Console logging level, can be DEBUG, INFO or WARNING. loglevel = logging.INFO
random_line_split
component_fixture.ts
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {ChangeDetectorRef, ComponentRef, DebugElement, ElementRef, getDebugNode, NgZone, RendererFactory2} from '@ang...
} }); }); } } private _tick(checkNoChanges: boolean) { this.changeDetectorRef.detectChanges(); if (checkNoChanges) { this.checkNoChanges(); } } /** * Trigger a change detection cycle for the component. */ detectChanges(checkNoChanges: boolean = true): void...
}); this._onErrorSubscription = ngZone.onError.subscribe({ next: (error: any) => { throw error;
random_line_split
component_fixture.ts
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {ChangeDetectorRef, ComponentRef, DebugElement, ElementRef, getDebugNode, NgZone, RendererFactory2} from '@ang...
this._isDestroyed = true; } } } function scheduleMicroTask(fn: Function) { Zone.current.scheduleMicroTask('scheduleMicrotask', fn); }
{ this._onErrorSubscription.unsubscribe(); this._onErrorSubscription = null; }
conditional_block
component_fixture.ts
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {ChangeDetectorRef, ComponentRef, DebugElement, ElementRef, getDebugNode, NgZone, RendererFactory2} from '@ang...
<T> { /** * The DebugElement associated with the root element of this component. */ debugElement: DebugElement; /** * The instance of the root component class. */ componentInstance: T; /** * The native element at the root of the component. */ nativeElement: any; /** * The ElementRe...
ComponentFixture
identifier_name
local_output_manager_test.py
#! /usr/bin/env vpython3 # Copyright 2017 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # pylint: disable=protected-access import tempfile import shutil import unittest from pylib.base import output_manager from pylib....
(self): self.assertUsableTempFile( self._output_manager._CreateArchivedFile( 'test_file', 'test_subdir', output_manager.Datatype.TEXT)) def tearDown(self): shutil.rmtree(self._output_dir) if __name__ == '__main__': unittest.main()
testUsableTempFile
identifier_name
local_output_manager_test.py
#! /usr/bin/env vpython3 # Copyright 2017 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # pylint: disable=protected-access import tempfile import shutil import unittest from pylib.base import output_manager from pylib....
def setUp(self): self._output_dir = tempfile.mkdtemp() self._output_manager = local_output_manager.LocalOutputManager( self._output_dir) def testUsableTempFile(self): self.assertUsableTempFile( self._output_manager._CreateArchivedFile( 'test_file', 'test_subdir', output_man...
class LocalOutputManagerTest(output_manager_test_case.OutputManagerTestCase):
random_line_split
local_output_manager_test.py
#! /usr/bin/env vpython3 # Copyright 2017 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # pylint: disable=protected-access import tempfile import shutil import unittest from pylib.base import output_manager from pylib....
unittest.main()
conditional_block
local_output_manager_test.py
#! /usr/bin/env vpython3 # Copyright 2017 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # pylint: disable=protected-access import tempfile import shutil import unittest from pylib.base import output_manager from pylib....
def tearDown(self): shutil.rmtree(self._output_dir) if __name__ == '__main__': unittest.main()
self.assertUsableTempFile( self._output_manager._CreateArchivedFile( 'test_file', 'test_subdir', output_manager.Datatype.TEXT))
identifier_body
tastypie.js
/** * Backbone-tastypie.js 0.1 * (c) 2011 Paul Uithol * * Backbone-tastypie may be freely distributed under the MIT license. * Add or override Backbone.js functionality, for compatibility with django-tastypie. */ (function( undefined ) { "use strict"; // Backbone.noConflict support. Save local copy of Ba...
url = url || this.collection && ( _.isFunction( this.collection.url ) ? this.collection.url() : this.collection.url ); if ( url && this.has( 'id' ) ) { url = addSlash( url ) + this.get( 'id' ); } } url = url && addSlash( url ); return url ||...
// If there's no idAttribute, use the 'urlRoot'. Fallback to try to have the collection construct a url. // Explicitly add the 'id' attribute if the model has one. if ( !url ) { url = this.urlRoot;
random_line_split
tastypie.js
/** * Backbone-tastypie.js 0.1 * (c) 2011 Paul Uithol * * Backbone-tastypie may be freely distributed under the MIT license. * Add or override Backbone.js functionality, for compatibility with django-tastypie. */ (function( undefined ) { "use strict"; // Backbone.noConflict support. Save local copy of Ba...
}; // Set up 'error' handling dfd.fail( options.error ); options.error = function( xhr, status, resp ) { dfd.rejectWith( options.context || options, [ xhr, status, resp ] ); }; // Make the request, make it accessibly by assigning...
{ return dfd.resolveWith( options.context || options, [ resp, status, xhr ] ); }
conditional_block
Teams.d.ts
declare class
{ create(obj: any): Promise<Team.OnfleetTeam>; deleteOne(id: string): Promise<void>; get(): Promise<Team.OnfleetTeam[]>; get(id: string): Promise<Team.OnfleetTeam>; insertTask(id: string, obj: { tasks: string[] }): Promise<Team.OnfleetTeam>; update(id: string, obj: Team.UpdateTeamProps): Promise<Team.Onfle...
Team
identifier_name
Teams.d.ts
declare class Team { create(obj: any): Promise<Team.OnfleetTeam>; deleteOne(id: string): Promise<void>; get(): Promise<Team.OnfleetTeam[]>; get(id: string): Promise<Team.OnfleetTeam>; insertTask(id: string, obj: { tasks: string[] }): Promise<Team.OnfleetTeam>; update(id: string, obj: Team.UpdateTeamProps): ...
interface CreateTeamProps { managers: string[]; name: string; workers: string[]; hub?: string; } interface UpdateTeamProps { managers?: string[]; name?: string; workers?: string[]; hub?: string; } } export = Team;
* @prop hub - Optional. The ID of the team's hub. */
random_line_split
commands.py
see the # AUTHORS and LICENSE files distributed with this source code, or # at https://www.sourcefabric.org/superdesk/license import superdesk import urllib3 import urllib import xml.etree.ElementTree as etree from superdesk.io.iptc import subject_codes from datetime import datetime from superdesk.metadata.item impor...
(self, start_id, user, password, url, query, limit): print('Starting text archive import at {}'.format(start_id)) self._user = user self._password = password self._id = int(start_id) self._url_root = url self._query = urllib.parse.quote(query) if limit is not None...
run
identifier_name
commands.py
please see the # AUTHORS and LICENSE files distributed with this source code, or # at https://www.sourcefabric.org/superdesk/license import superdesk import urllib3 import urllib import xml.etree.ElementTree as etree from superdesk.io.iptc import subject_codes from datetime import datetime from superdesk.metadata.ite...
def _addkeywords(self, key, doc, item): code = self._get_head_value(doc, key) if code: if 'keywords' not in item: item['keywords'] = [] item['keywords'].append(code) def _process_bunch(self, x): # x.findall('dc_rest_docs/dc_r...
el = doc.find('dcdossier/document/head/' + field) if el is not None: return el.text return None
identifier_body
commands.py
see the # AUTHORS and LICENSE files distributed with this source code, or # at https://www.sourcefabric.org/superdesk/license import superdesk import urllib3 import urllib import xml.etree.ElementTree as etree from superdesk.io.iptc import subject_codes from datetime import datetime from superdesk.metadata.item impor...
item = {} item['guid'] = doc.find('dcdossier').get('guid') # if the item has been modified in the archive then it is due to a kill # there is an argument that this item should not be imported at all if doc.find('dcdossier').get('created') != doc.find('dcdoss...
self._id = int(id)
conditional_block
commands.py
see the # AUTHORS and LICENSE files distributed with this source code, or # at https://www.sourcefabric.org/superdesk/license import superdesk import urllib3 import urllib import xml.etree.ElementTree as etree from superdesk.io.iptc import subject_codes from datetime import datetime from superdesk.metadata.item impor...
retries -= 1 return None def _get_head_value(self, doc, field): el = doc.find('dcdossier/document/head/' + field) if el is not None: return el.text return None def _addkeywords(self, key, doc, item): code = self._get_head_value(doc, key) ...
if count > 0: print('count : {}'.format(count)) return e else: self._api_login()
random_line_split
strainreview-component.ts
import {Component, OnInit, ViewChild} from "@angular/core"; import {StrainReviewService} from "../services/strainreview-service"; import {StrainService} from "../services/strain-service"; import {StrainReview} from "../classes/strainReview"; import {Strain} from "../classes/strain"; import {Router} from "@angular/route...
() : void { this.strainReviewService.getAllStrainReviews() .subscribe(strainReviews => { this.strainReviews = strainReviews; this.strainService.getStrainByStrainId(this.strainReview.strainReviewId) .subscribe(strains => this.strains=strains); }); } } //Written by Nathan Sanchez @nsanchez121@cnm.e...
reloadStrainReviews
identifier_name
strainreview-component.ts
import {Component, OnInit, ViewChild} from "@angular/core"; import {StrainReviewService} from "../services/strainreview-service"; import {StrainService} from "../services/strain-service"; import {StrainReview} from "../classes/strainReview"; import {Strain} from "../classes/strain"; import {Router} from "@angular/route...
} //Written by Nathan Sanchez @nsanchez121@cnm.edu
{ this.strainReviewService.getAllStrainReviews() .subscribe(strainReviews => { this.strainReviews = strainReviews; this.strainService.getStrainByStrainId(this.strainReview.strainReviewId) .subscribe(strains => this.strains=strains); }); }
identifier_body
strainreview-component.ts
import {Component, OnInit, ViewChild} from "@angular/core"; import {StrainReviewService} from "../services/strainreview-service"; import {StrainService} from "../services/strain-service"; import {StrainReview} from "../classes/strainReview"; import {Strain} from "../classes/strain"; import {Router} from "@angular/route...
}); } } //Written by Nathan Sanchez @nsanchez121@cnm.edu
this.strainReviewService.getAllStrainReviews() .subscribe(strainReviews => { this.strainReviews = strainReviews; this.strainService.getStrainByStrainId(this.strainReview.strainReviewId) .subscribe(strains => this.strains=strains);
random_line_split
mod-ent-install.js
var log = new Log(); var mod = require('store'); var user = mod.user; var server = require('store').server; var currentUser = server.current(session); var SUBSCRIPTIONS_PATH = '/subscriptions/mobileapp/'; var mobileGeneric = new Packages.org.wso2.carbon.appmgt.mobile.store.Generic(); var m...
useragent = request.getHeader("User-Agent"); if(useragent.match(/iPad/i) || useragent.match(/iPhone/i) || useragent.match(/Android/i)) { if(mdmConfig.AppDownloadURLHost == "%http%"){ var serverAddress = carbon.server.address('http'); }else i...
if(isDirectDownloadEnabled){
random_line_split
mod-ent-install.js
var log = new Log(); var mod = require('store'); var user = mod.user; var server = require('store').server; var currentUser = server.current(session); var SUBSCRIPTIONS_PATH = '/subscriptions/mobileapp/'; var mobileGeneric = new Packages.org.wso2.carbon.appmgt.mobile.store.Generic(); v...
function setVisibility(appId, username, opType){ asset = store.asset('mobileapp', appId); var path = "/_system/governance/mobileapps/" + asset.attributes.overview_provider + "/" + asset.attributes.overview_platform + "/" + asset.attributes.overview_name + "/" + asset.attributes.overvi...
{ if (registry.exists(path)) { registry.remove(path); setVisibility(appId, username, 'DENY'); } }
identifier_body
mod-ent-install.js
var log = new Log(); var mod = require('store'); var user = mod.user; var server = require('store').server; var currentUser = server.current(session); var SUBSCRIPTIONS_PATH = '/subscriptions/mobileapp/'; var mobileGeneric = new Packages.org.wso2.carbon.appmgt.mobile.store.Generic(); v...
(appId, username, opType){ asset = store.asset('mobileapp', appId); var path = "/_system/governance/mobileapps/" + asset.attributes.overview_provider + "/" + asset.attributes.overview_platform + "/" + asset.attributes.overview_name + "/" + asset.attributes.overview_version; mobileGen...
setVisibility
identifier_name
rcvr-borrowed-to-region.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 x = box(GC) 6; let y = x.get(); assert_eq!(y, 6); let x = box(GC) 6; let y = x.get(); println!("y={}", y); assert_eq!(y, 6); let x = box 6; let y = x.get(); println!("y={}", y); assert_eq!(y, 6); let x = &6; let y = x.get(); println!("y={}", y); asser...
identifier_body
rcvr-borrowed-to-region.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 x = box(GC) 6; let y = x.get(); assert_eq!(y, 6); let x = box(GC) 6; let y = x.get(); println!("y={}", y); assert_eq!(y, 6); let x = box 6; let y = x.get(); println!("y={}", y); assert_eq!(y, 6); let x = &6; let y = x.get(); println!("y={}", y); as...
main
identifier_name
rcvr-borrowed-to-region.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 http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![feature(managed_...
random_line_split
368-disused-railway-stations.py
# -*- encoding: utf-8 -*- from shapely.wkt import loads as wkt_loads import dsl from . import FixtureTest class DisusedRailwayStations(FixtureTest):
def test_old_south_ferry(self): # Old South Ferry (1) (disused=yes) self.generate_fixtures(dsl.way(2086974744, wkt_loads('POINT (-74.01325716895789 40.701283821753)'), {u'name': u'Old South Ferry (1)', u'wheelchair': u'no', u'source': u'openstreetmap.org', u'railway': u'station', u'disused': u'yes', u'n...
identifier_body
368-disused-railway-stations.py
# -*- encoding: utf-8 -*- from shapely.wkt import loads as wkt_loads import dsl from . import FixtureTest class DisusedRailwayStations(FixtureTest): def test_old_south_ferry(self): # Old South Ferry (1) (disused=yes) self.generate_fixtures(dsl.way(2086974744, wkt_loads('POINT (-74.01325716895789 ...
(self): # Valle, AZ (disused=station) self.generate_fixtures(dsl.way(366220389, wkt_loads('POINT (-112.200039193448 35.65261688375637)'), {u'name': u'Valle', u'gnis:reviewed': u'no', u'addr:state': u'AZ', u'ele': u'1794', u'source': u'openstreetmap.org', u'gnis:feature_id': u'21103', u'disused': u'stati...
test_valle_az
identifier_name
368-disused-railway-stations.py
# -*- encoding: utf-8 -*- from shapely.wkt import loads as wkt_loads import dsl from . import FixtureTest class DisusedRailwayStations(FixtureTest): def test_old_south_ferry(self):
# Old South Ferry (1) (disused=yes) self.generate_fixtures(dsl.way(2086974744, wkt_loads('POINT (-74.01325716895789 40.701283821753)'), {u'name': u'Old South Ferry (1)', u'wheelchair': u'no', u'source': u'openstreetmap.org', u'railway': u'station', u'disused': u'yes', u'network': u'New York City Subway'...
random_line_split
MacroScreenView.js
// Copyright 2013-2021, University of Colorado Boulder /** * View for the 'Macro' screen. * * @author Chris Malley (PixelZoom, Inc.) */ import Property from '../../../../axon/js/Property.js'; import ScreenView from '../../../../joist/js/ScreenView.js'; import merge from '../../../../phet-core/js/merge.js'; import...
extends ScreenView { /** * @param {MacroModel} model * @param {ModelViewTransform2} modelViewTransform * @param {Tandem} tandem */ constructor( model, modelViewTransform, tandem ) { assert && assert( tandem instanceof Tandem, 'invalid tandem' ); assert && assert( modelViewTransform instanceof ...
MacroScreenView
identifier_name
MacroScreenView.js
// Copyright 2013-2021, University of Colorado Boulder /** * View for the 'Macro' screen. * * @author Chris Malley (PixelZoom, Inc.) */ import Property from '../../../../axon/js/Property.js'; import ScreenView from '../../../../joist/js/ScreenView.js'; import merge from '../../../../phet-core/js/merge.js'; import...
// Neutral indicator that appears in the bottom of the beaker. const neutralIndicatorNode = new NeutralIndicatorNode( model.solution, { tandem: tandem.createTandem( 'neutralIndicatorNode' ) } ); // dropper const DROPPER_SCALE = 0.85; const dropperNode = new PHDropperNode( model.dropper, ...
{ assert && assert( tandem instanceof Tandem, 'invalid tandem' ); assert && assert( modelViewTransform instanceof ModelViewTransform2, 'invalid modelViewTransform' ); super( merge( {}, PHScaleConstants.SCREEN_VIEW_OPTIONS, { tandem: tandem } ) ); // beaker const beakerNode = new BeakerNo...
identifier_body
MacroScreenView.js
// Copyright 2013-2021, University of Colorado Boulder /** * View for the 'Macro' screen. * * @author Chris Malley (PixelZoom, Inc.) */ import Property from '../../../../axon/js/Property.js'; import ScreenView from '../../../../joist/js/ScreenView.js'; import merge from '../../../../phet-core/js/merge.js'; import...
const dropperNode = new PHDropperNode( model.dropper, modelViewTransform, { visibleProperty: model.dropper.visibleProperty, tandem: tandem.createTandem( 'dropperNode' ) } ); dropperNode.setScaleMagnitude( DROPPER_SCALE ); const dropperFluidNode = new DropperFluidNode( model.dropper, model.be...
tandem: tandem.createTandem( 'neutralIndicatorNode' ) } ); // dropper const DROPPER_SCALE = 0.85;
random_line_split
views.py
import asjson from flask.views import MethodView from functools import wraps from flask.ext.mongoengine.wtf import model_form from flask import request, render_template, Blueprint, redirect, abort, session, make_response from .models import User, SessionStorage from mongoengine import DoesNotExist auth = Blueprint('au...
response = make_response(redirect('/panel_control')) if 'session' in request.cookies: session_id = request.cookies['session'] else: session_id = session['csrf_token'] # Setting user-cooki...
# prepare response/redirect
random_line_split
views.py
import asjson from flask.views import MethodView from functools import wraps from flask.ext.mongoengine.wtf import model_form from flask import request, render_template, Blueprint, redirect, abort, session, make_response from .models import User, SessionStorage from mongoengine import DoesNotExist auth = Blueprint('au...
record.remove_old_session(username) record.user = username record.session_key = session_id record.save() # And redirect to admin-panel return response else: raise ...
if request.form: try: username = request.form['name'] password = request.form['password'] user = User.objects.get(name=username) if user and user.password == password: # prepare response/redirect response...
identifier_body
views.py
import asjson from flask.views import MethodView from functools import wraps from flask.ext.mongoengine.wtf import model_form from flask import request, render_template, Blueprint, redirect, abort, session, make_response from .models import User, SessionStorage from mongoengine import DoesNotExist auth = Blueprint('au...
ot UserAuth.is_admin(): return redirect('auth') return f(*args, **kwargs) return decorated auth.add_url_rule('/auth/', view_func=UserAuth.as_view('auth'))
: return False def requires_auth(f): @wraps(f) def decorated(*args, **kwargs): if n
conditional_block
views.py
import asjson from flask.views import MethodView from functools import wraps from flask.ext.mongoengine.wtf import model_form from flask import request, render_template, Blueprint, redirect, abort, session, make_response from .models import User, SessionStorage from mongoengine import DoesNotExist auth = Blueprint('au...
(): # Выуживаем куки из различных мест,т.к. отправлять могут в виде атрибута заголовков cookies = request.cookies if not cookies: # Ничего не нашли на первой иттерации.Попробуем вытащить из заголовка try: cookies = asjson.loads(request.headers['Set-Cookie']) ...
is_admin
identifier_name
diepempmsk.rs
#[doc = "Register `DIEPEMPMSK` reader"] pub struct R(crate::R<DIEPEMPMSK_SPEC>); impl core::ops::Deref for R { type Target = crate::R<DIEPEMPMSK_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl From<crate::R<DIEPEMPMSK_SPEC>> for R { #[inline(always)] fn from(...
pub struct INEPTXFEMPMSK_R(crate::FieldReader<u16, u16>); impl INEPTXFEMPMSK_R { pub(crate) fn new(bits: u16) -> Self { INEPTXFEMPMSK_R(crate::FieldReader::new(bits)) } } impl core::ops::Deref for INEPTXFEMPMSK_R { type Target = crate::FieldReader<u16, u16>; #[inline(always)] fn deref(&self)...
} } #[doc = "Field `InEpTxfEmpMsk` reader - IN EP Tx FIFO Empty Interrupt Mask Bits"]
random_line_split
diepempmsk.rs
#[doc = "Register `DIEPEMPMSK` reader"] pub struct R(crate::R<DIEPEMPMSK_SPEC>); impl core::ops::Deref for R { type Target = crate::R<DIEPEMPMSK_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl From<crate::R<DIEPEMPMSK_SPEC>> for R { #[inline(always)] fn from(...
(&mut self) -> &mut Self::Target { &mut self.0 } } impl From<crate::W<DIEPEMPMSK_SPEC>> for W { #[inline(always)] fn from(writer: crate::W<DIEPEMPMSK_SPEC>) -> Self { W(writer) } } #[doc = "Field `InEpTxfEmpMsk` reader - IN EP Tx FIFO Empty Interrupt Mask Bits"] pub struct INEPTXFEMPMSK_...
deref_mut
identifier_name
diepempmsk.rs
#[doc = "Register `DIEPEMPMSK` reader"] pub struct R(crate::R<DIEPEMPMSK_SPEC>); impl core::ops::Deref for R { type Target = crate::R<DIEPEMPMSK_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl From<crate::R<DIEPEMPMSK_SPEC>> for R { #[inline(always)] fn from(...
} #[doc = "Field `InEpTxfEmpMsk` writer - IN EP Tx FIFO Empty Interrupt Mask Bits"] pub struct INEPTXFEMPMSK_W<'a> { w: &'a mut W, } impl<'a> INEPTXFEMPMSK_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u16) -> &'a mut W { self.w.bits = (self....
{ &self.0 }
identifier_body
test_apis_tags.py
# -*- coding: utf-8 -*- # Copyright 2017-TODAY LasLabs Inc. # License MIT (https://opensource.org/licenses/MIT). from .api_common import ApiCommon, recorder class TestApisTags(ApiCommon): """Tests the Tags API endpoint.""" def setUp(self): super(TestApisTags, self).setUp() self.__endpoint__ ...
self.__endpoint__.search([], None)
random_line_split
test_apis_tags.py
# -*- coding: utf-8 -*- # Copyright 2017-TODAY LasLabs Inc. # License MIT (https://opensource.org/licenses/MIT). from .api_common import ApiCommon, recorder class TestApisTags(ApiCommon): """Tests the Tags API endpoint.""" def setUp(self): super(TestApisTags, self).setUp() self.__endpoint__ ...
(self): """It should not be implemented.""" with self.assertRaises(NotImplementedError): self.__endpoint__.update(None) @recorder.use_cassette() def test_apis_tags_create(self): """It should not be implemented.""" with self.assertRaises(NotImplementedError): ...
test_apis_tags_update
identifier_name
test_apis_tags.py
# -*- coding: utf-8 -*- # Copyright 2017-TODAY LasLabs Inc. # License MIT (https://opensource.org/licenses/MIT). from .api_common import ApiCommon, recorder class TestApisTags(ApiCommon): """Tests the Tags API endpoint.""" def setUp(self): super(TestApisTags, self).setUp() self.__endpoint__ ...
@recorder.use_cassette() def test_apis_tags_search(self): """It should not be implemented.""" with self.assertRaises(NotImplementedError): self.__endpoint__.search([], None)
"""It should list the tags in the tag.""" self._test_list()
identifier_body
version.py
imedia/%s/!svn/vcc/default' % tag request = http.fetch(uri=uri, method='PROPFIND', body="<?xml version='1.0' encoding='utf-8'?>" "<propfind xmlns=\"DAV:\"><allprop/></propfind>", headers={'label': str(rev), ...
random_line_split
version.py
dT%H:%M:%S') rev = entries.readline()[:-1] return tag, rev, date # We haven't found the information in entries file. # Use sqlite table for new entries format from sqlite3 import dbapi2 as sqlite con = sqlite.connect(os.path.join(_program_dir, ".svn/wc.db")) cur = co...
getfileversion
identifier_name
version.py
may be a nightly. if getversion_package in exceptions: warn('Unable to detect version; exceptions raised:\n%r' % exceptions, UserWarning) elif exceptions: pywikibot.debug('version algorithm exceptions:\n%r' % exceptions, _logger) if isinstance(date, bas...
# Try 'origin' and then 'gerrit' as remote name; bail if can't find either. remote_pos = tag.find('[remote "origin"]') if remote_pos == -1: remote_pos = tag.find('[remote "gerrit"]') if remote_pos == -1: tag = '?' else: s = tag.find('url = ', remote_pos) e = tag.find(...
"""Get version info for a Git clone. @param path: directory of the Git checkout @return: - tag (name for the repository), - rev (current revision identifier), - date (date of current revision), - hash (git hash for the current revision) @rtype: C{tuple} of three C{str} and a...
identifier_body
version.py
github_svn_rev2hash(tag, rev): """Convert a Subversion revision to a Git hash using Github. @param tag: name of the Subversion repo on Github @param rev: Subversion revision identifier @return: the git hash @rtype: str """ from pywikibot.comms import http uri = 'https://github.com/wik...
if line.find('__version__') == 0: try: exec(line) except: pass break
conditional_block
Themer.tsx
import * as PropTypes from 'prop-types'; import * as React from 'react'; export interface ThemerProps { readonly theme?: string; } const DEFAULT_THEME: string = 'Day'; const bodyClassList: DOMTokenList = document.body.classList; /** * Impure component that changes the theme on the `body` tag */ export default c...
({ theme }: ThemerProps) { this.removeTheme({ theme }); this.addTheme({ theme: this.props.theme }); } componentWillUnmount() { this.removeTheme({ theme: this.props.theme }); } addTheme({ theme }: ThemerProps) { if (theme) { bodyClassList.add(theme); } } removeTheme({ theme }: T...
componentDidUpdate
identifier_name
Themer.tsx
import * as PropTypes from 'prop-types'; import * as React from 'react'; export interface ThemerProps { readonly theme?: string; } const DEFAULT_THEME: string = 'Day'; const bodyClassList: DOMTokenList = document.body.classList; /** * Impure component that changes the theme on the `body` tag */ export default c...
} render() { return ( <div data-testid="Themer"> {this.props.children} </div> ); } }
{ bodyClassList.remove(theme); }
conditional_block
Themer.tsx
import * as PropTypes from 'prop-types'; import * as React from 'react'; export interface ThemerProps { readonly theme?: string; } const DEFAULT_THEME: string = 'Day'; const bodyClassList: DOMTokenList = document.body.classList; /** * Impure component that changes the theme on the `body` tag */ export default c...
componentWillUnmount() { this.removeTheme({ theme: this.props.theme }); } addTheme({ theme }: ThemerProps) { if (theme) { bodyClassList.add(theme); } } removeTheme({ theme }: ThemerProps) { if (theme) { bodyClassList.remove(theme); } } render() { return ( <di...
{ this.removeTheme({ theme }); this.addTheme({ theme: this.props.theme }); }
identifier_body
Themer.tsx
import * as PropTypes from 'prop-types'; import * as React from 'react'; export interface ThemerProps { readonly theme?: string; } const DEFAULT_THEME: string = 'Day'; const bodyClassList: DOMTokenList = document.body.classList; /** * Impure component that changes the theme on the `body` tag */ export default c...
addTheme({ theme }: ThemerProps) { if (theme) { bodyClassList.add(theme); } } removeTheme({ theme }: ThemerProps) { if (theme) { bodyClassList.remove(theme); } } render() { return ( <div data-testid="Themer"> {this.props.children} </div> ); } }
this.removeTheme({ theme: this.props.theme }); }
random_line_split
GlobalSearch.js
import React, { Component, PropTypes } from 'react' import { Search, Grid } from 'semantic-ui-react' import { browserHistory } from 'react-router' import Tag from './Tag' import { search, setQuery, clearSearch } from '../actions/entities' import { MIN_CHARACTERS, DONE_TYPING_INTERVAL } from '../constants/search' cons...
extends Component { state = { typingTimer: null } handleSearchChange = (e, value) => { clearTimeout(this.state.typingTimer) this.setState({ typingTimer: setTimeout( () => this.handleDoneTyping(value.trim()), DONE_TYPING_INTERVAL ) }) const { dispatch } = this.prop...
GlobalSearch
identifier_name
GlobalSearch.js
import React, { Component, PropTypes } from 'react'
import { Search, Grid } from 'semantic-ui-react' import { browserHistory } from 'react-router' import Tag from './Tag' import { search, setQuery, clearSearch } from '../actions/entities' import { MIN_CHARACTERS, DONE_TYPING_INTERVAL } from '../constants/search' const propTypes = { dispatch: PropTypes.func.isRequire...
random_line_split