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
auth.service.ts
import { Injectable } from '@angular/core'; import { Router, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router'; import 'rxjs/add/operator/filter'; import * as auth0 from 'auth0-js'; import { BehaviorSubject } from 'rxjs/Rx'; import { LoggerService } from 'app/core/services/logger.service'; import { e...
} } @Injectable() export class AuthGuard { constructor( private authService: AuthService, private storage: StorageService, private logger: LoggerService, private router: Router) { } canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean { const url: string = state.ur...
random_line_split
auth.service.ts
import { Injectable } from '@angular/core'; import { Router, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router'; import 'rxjs/add/operator/filter'; import * as auth0 from 'auth0-js'; import { BehaviorSubject } from 'rxjs/Rx'; import { LoggerService } from 'app/core/services/logger.service'; import { e...
checkLogin(url: string): boolean { if (!this.authService.isAuthenticated()) { console.info('AuthGuard redirecting to login page..'); this.authService.goToLogin(url); return false; } if (!this.storage.get('member_id')) { console.info('AuthGuard redirecting to under-review page..')...
{ const url: string = state.url; return this.checkLogin(url); }
identifier_body
auth.service.ts
import { Injectable } from '@angular/core'; import { Router, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router'; import 'rxjs/add/operator/filter'; import * as auth0 from 'auth0-js'; import { BehaviorSubject } from 'rxjs/Rx'; import { LoggerService } from 'app/core/services/logger.service'; import { e...
(redirectUrl?: string): void { // Store the attempted URL for redirecting this.redirectUrl = redirectUrl; // Navigate to the starting page // TODO: if user logged in before, go straight to login page this.router.navigate(['start']); } public login(): void { this.auth0.authorize(); } p...
goToLogin
identifier_name
auth.service.ts
import { Injectable } from '@angular/core'; import { Router, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router'; import 'rxjs/add/operator/filter'; import * as auth0 from 'auth0-js'; import { BehaviorSubject } from 'rxjs/Rx'; import { LoggerService } from 'app/core/services/logger.service'; import { e...
} else if (err) { this.router.navigate(['/home']); console.log(err); } }); } private setSession(authResult): void { // Set the time that the access token will expire at const expiresAt = JSON.stringify((authResult.expiresIn * 1000) + new Date().getTime()); const memberI...
{ this.router.navigate(['/home']); }
conditional_block
main.rs
use std::io; use std::io::Read; use std::collections::HashMap; use std::str::FromStr; type DynamicInfo<'a> = HashMap<&'a str, u8>; #[derive(Debug)] struct Aunt<'a> { number: u16, info: DynamicInfo<'a> } fn parse_aunt(line: &str) -> Aunt { let tokens: Vec<_> = line .split(|c: char| !c.is_alphanume...
.into_iter() .all(|(attribute, value)| { match specification.get(attribute) { Some(x) if x == value => true, _ => false } }) } fn matches_adjusted(aunt: &Aunt, specification: &DynamicInfo) -> bool { let ref info = aunt.info; info ...
} fn matches(aunt: &Aunt, specification: &DynamicInfo) -> bool { let ref info = aunt.info; info
random_line_split
main.rs
use std::io; use std::io::Read; use std::collections::HashMap; use std::str::FromStr; type DynamicInfo<'a> = HashMap<&'a str, u8>; #[derive(Debug)] struct Aunt<'a> { number: u16, info: DynamicInfo<'a> } fn parse_aunt(line: &str) -> Aunt { let tokens: Vec<_> = line .split(|c: char| !c.is_alphanume...
(aunt: &Aunt, specification: &DynamicInfo) -> bool { let ref info = aunt.info; info .into_iter() .all(|(attribute, value)| { match (*attribute, specification.get(attribute)) { ("cats", Some(x)) | ("trees", Some(x)) => x < value, ("pomeranians", Some(x)...
matches_adjusted
identifier_name
numberList.component.spec.ts
import { mock } from 'angular'; import { NUMBER_LIST_COMPONENT, INumberListConstraints } from './numberList.component'; describe('Component: numberList', () => { let $compile: ng.ICompileService, model: number[], stringModel: string, $scope: ng.IScope, elem: any, constraints: INumberListConstrain...
const dom = `<number-list model="data.model" constraints="data.constraints" on-change="data.onChange()"></number-list>`; elem = $compile(dom)($scope); $scope.$digest(); }; describe('initialization', () => { it('initializes with an empty number input on an empty list, but does not add empty entry ...
{ $scope['data'].model = stringModel; }
conditional_block
numberList.component.spec.ts
import { mock } from 'angular'; import { NUMBER_LIST_COMPONENT, INumberListConstraints } from './numberList.component'; describe('Component: numberList', () => { let $compile: ng.ICompileService, model: number[], stringModel: string, $scope: ng.IScope, elem: any, constraints: INumberListConstrain...
describe('initialization', () => { it('initializes with an empty number input on an empty list, but does not add empty entry to model', () => { initialize([]); expect(elem.find('input[type="number"]').length).toBe(1); expect(model.length).toBe(0); }); it('initializes with existing numb...
$scope.$digest(); };
random_line_split
main.py
''' Created on Apr 19, 2015 @author: bcopy ''' import os import cherrypy import sys import subprocess import random import time import threading import Queue import tempfile class ScriptMonitor(object): ''' Monitors the script execution and updates result statuses ''' def __init__(self): ...
assert callable(fd.readline) threading.Thread.__init__(self) self._fd = fd self._queue = queue def run(self): '''The body of the thread: read lines and put them on the queue.''' for line in iter(self._fd.readline, ''): self._queue.put(line) def eof...
random_line_split
main.py
''' Created on Apr 19, 2015 @author: bcopy ''' import os import cherrypy import sys import subprocess import random import time import threading import Queue import tempfile class ScriptMonitor(object): ''' Monitors the script execution and updates result statuses ''' def __init__(self): ...
(self): print "Starting raspbuggy script process output polling..." if(self.m_processInitialized and self.m_process.poll() == None): self.m_process.terminate() self.m_processInitialized = False def isRunning(self): return (self.m_processInitialized and self.m_process.po...
abort
identifier_name
main.py
''' Created on Apr 19, 2015 @author: bcopy ''' import os import cherrypy import sys import subprocess import random import time import threading import Queue import tempfile class ScriptMonitor(object): ''' Monitors the script execution and updates result statuses ''' def __init__(self): ...
@cherrypy.expose @cherrypy.tools.json_in() @cherrypy.tools.json_out() def execute(self): scriptData = cherrypy.request.json if(self.m_scriptMonitor == None): self.m_scriptMonitor = ScriptMonitor() if(scriptData["scriptText"] == None): return...
if(self.m_scriptMonitor != None): running = self.m_scriptMonitor.isRunning() retCode = self.m_scriptMonitor.m_process.poll() if(retCode == None): retCode = -1 return {"running":running,"exitCode":retCode} else: return {"running":False,"...
identifier_body
main.py
''' Created on Apr 19, 2015 @author: bcopy ''' import os import cherrypy import sys import subprocess import random import time import threading import Queue import tempfile class ScriptMonitor(object): ''' Monitors the script execution and updates result statuses ''' def __init__(self): ...
else: print "Raspbuggy script process startup failed." def abort(self): print "Starting raspbuggy script process output polling..." if(self.m_processInitialized and self.m_process.poll() == None): self.m_process.terminate() self...
print "Starting raspbuggy script process output polling..." self.m_stdoutQueue = Queue.Queue() self.m_stderrQueue = Queue.Queue() self.m_stdoutReader = AsynchronousFileReader(self.m_process.stdout, self.m_stdoutQueue) self.m_stdoutReader.start()
conditional_block
main.rs
#[macro_use] extern crate error_chain; extern crate calamine; mod errors; use std::path::{PathBuf, Path}; use std::fs; use std::io::{BufWriter, Write}; use errors::Result; use calamine::{Sheets, Range, CellType}; fn main() { let mut args = ::std::env::args(); let file = args.by_ref() .skip(1) ...
<P, T>(path: P, range: Range<T>) -> Result<()> where P: AsRef<Path>, T: CellType + ::std::fmt::Display { if range.is_empty() { return Ok(()); } let mut f = BufWriter::new(fs::File::create(path.as_ref())?); let ((srow, scol), (_, ecol)) = (range.start(), range.end()); write!(f...
write_range
identifier_name
main.rs
#[macro_use] extern crate error_chain; extern crate calamine; mod errors; use std::path::{PathBuf, Path}; use std::fs; use std::io::{BufWriter, Write}; use errors::Result; use calamine::{Sheets, Range, CellType}; fn main() { let mut args = ::std::env::args(); let file = args.by_ref() .skip(1) ...
let vba = root.join("vba"); if !vba.exists() { fs::create_dir(&vba)?; } let formula = root.join("formula"); if !formula.exists() { fs::create_dir(&formula)?; } Ok(XlPaths { orig: orig, data: data, ...
{ fs::create_dir(&data)?; }
conditional_block
main.rs
#[macro_use] extern crate error_chain; extern crate calamine; mod errors; use std::path::{PathBuf, Path}; use std::fs; use std::io::{BufWriter, Write}; use errors::Result; use calamine::{Sheets, Range, CellType}; fn main() { let mut args = ::std::env::args(); let file = args.by_ref() .skip(1) ...
buf.extend(rev.chars().rev()); } buf }
let c = col % 26; rev.push((b'A' + c as u8) as char); col -= c; col /= 26; }
random_line_split
scouts.js
scouts = new Meteor.Collection('scouts', { schema: new SimpleSchema({ userId: { type: String, index: 1, unique: true }, scoutId: { type: String, optional: true }, scoutStatusCode: { type: String, optional: true
scoutLand: { type: String, optional: true }, scoutName: { type: String, optional: true }, scoutBudget: { type: Number, optional: true }, scoutSpent: { type: Number, optional: true } }) }); // Collection2 already does...
},
random_line_split
special_case_tutorial.py
""" Create quiz TimeSpecialCase for all students in a particular lab/tutorial section. Usage will be like: ./manage.py special_case_tutorial 2020su-cmpt-120-d1 q1 D101 '2021-10-07T09:30' '2021-10-07T10:30' """ import datetime
from coredata.models import CourseOffering, Member from quizzes.models import Quiz, TimeSpecialCase def parse_datetime(s: str) -> datetime.datetime: return iso8601.parse_date(s).replace(tzinfo=None) class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument('offering_slug', typ...
from django.core.management.base import BaseCommand from django.db import transaction from iso8601 import iso8601
random_line_split
special_case_tutorial.py
""" Create quiz TimeSpecialCase for all students in a particular lab/tutorial section. Usage will be like: ./manage.py special_case_tutorial 2020su-cmpt-120-d1 q1 D101 '2021-10-07T09:30' '2021-10-07T10:30' """ import datetime from django.core.management.base import BaseCommand from django.db import transaction from ...
class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument('offering_slug', type=str, help='CourseOffering slug') parser.add_argument('activity_slug', type=str, help='the slug of the Activity with the quiz') parser.add_argument('section', type=str, help='lab/tutorial...
return iso8601.parse_date(s).replace(tzinfo=None)
identifier_body
special_case_tutorial.py
""" Create quiz TimeSpecialCase for all students in a particular lab/tutorial section. Usage will be like: ./manage.py special_case_tutorial 2020su-cmpt-120-d1 q1 D101 '2021-10-07T09:30' '2021-10-07T10:30' """ import datetime from django.core.management.base import BaseCommand from django.db import transaction from ...
(self, parser): parser.add_argument('offering_slug', type=str, help='CourseOffering slug') parser.add_argument('activity_slug', type=str, help='the slug of the Activity with the quiz') parser.add_argument('section', type=str, help='lab/tutorial section to modify') parser.add_argument('st...
add_arguments
identifier_name
special_case_tutorial.py
""" Create quiz TimeSpecialCase for all students in a particular lab/tutorial section. Usage will be like: ./manage.py special_case_tutorial 2020su-cmpt-120-d1 q1 D101 '2021-10-07T09:30' '2021-10-07T10:30' """ import datetime from django.core.management.base import BaseCommand from django.db import transaction from ...
TimeSpecialCase.objects.update_or_create( quiz=quiz, student=m, defaults={'start': start_time, 'end': end_time} )
conditional_block
themeService.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
return color ? color.toString() : null; } }
{ color = modify(color, this.theme); }
conditional_block
themeService.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
(type: ThemeType): string { switch (type) { case DARK: return 'vs-dark'; case HIGH_CONTRAST: return 'hc-black'; default: return 'vs'; } } export interface ITokenStyle { readonly foreground?: number; readonly bold?: boolean; readonly underline?: boolean; readonly italic?: boolean; } export interface IColor...
getThemeTypeSelector
identifier_name
themeService.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
}
{ let color = this.theme.getColor(id); if (color && modify) { color = modify(color, this.theme); } return color ? color.toString() : null; }
identifier_body
themeService.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
return this.onThemingParticipantAddedEmitter.event; } public getThemingParticipants(): IThemingParticipant[] { return this.themingParticipants; } } let themingRegistry = new ThemingRegistry(); platform.Registry.add(Extensions.ThemingContribution, themingRegistry); export function registerThemingParticipant(pa...
this.themingParticipants.splice(idx, 1); }); } public get onThemingParticipantAdded(): Event<IThemingParticipant> {
random_line_split
lib.rs
mask2); ptr::write_volatile(self.intc_reg.offset(SECR2_REG), mask2); // Enable host interrupts. for h in &interrupts.host_enable { ptr::write_volatile(self.intc_reg.offset(HIEISR_REG), *h as u32); } ptr::write_volatile(self.intc_reg.offset(GE...
{ assert!(position >= self.from && position <= self.to); (MemSegment { base: self.base, from: self.from, to: position, _memory_marker: PhantomData, }, MemSegment { base: self.base, from: position, to: se...
identifier_body
lib.rs
+ DRAM2_SIZE); let hostram = MemSegment::new(hostmap.base, 0, hostmem_size); // Voila. Ok(Pruss { _prumap: prumap, _hostmap: hostmap, intc: intc, pru0: pru0, pru1: pru1, dram0: dram0, dram1: dram1, ...
/// Clears a system event. pub fn clear_sysevt(&self, sysevt: Sysevt) { unsafe { ptr::write_volatile(self.intc_reg.offset(SICR_REG), sysevt as u32); } } /// Enables a system event. pub fn enable_sysevt(&self, sysevt: Sysevt) { unsafe { ptr::write_vol...
}
random_line_split
lib.rs
ecessary initialization if the PRU is anyway going to initialize /// memory before it will be read by the host. In some cases, it can also be used to avoid /// trashing the stack with a large temporary initialization object if for some reason the /// compiler cannot inline the call to `alloc`. /// /...
EvtoutIrq
identifier_name
reactReadonlyPropsAndStateRule.ts
/** * react-readonly-props-and-state * * This custom tslint rule is highly specific to GitHub Desktop and attempts * to prevent props and state interfaces from being declared with mutable * members. * * While it's technically possible to modify this.props there's never a good * reason to do so and marking our i...
}
{ const modifiers = propertySignature.modifiers if (!modifiers) { return false } if (modifiers.find(m => m.kind === ts.SyntaxKind.ReadonlyKeyword)) { return true } return false }
identifier_body
reactReadonlyPropsAndStateRule.ts
/** * react-readonly-props-and-state * * This custom tslint rule is highly specific to GitHub Desktop and attempts * to prevent props and state interfaces from being declared with mutable * members. * * While it's technically possible to modify this.props there's never a good * reason to do so and marking our i...
super.visitInterfaceDeclaration(node) } private ensureReadOnly(members: ts.NodeArray<ts.TypeElement>) { members.forEach(member => { if (member.kind !== ts.SyntaxKind.PropertySignature) { return } const propertySignature = member as ts.PropertySignature if (!this.isReadOnly(propertyS...
{ this.ensureReadOnly(node.members) }
conditional_block
reactReadonlyPropsAndStateRule.ts
/** * react-readonly-props-and-state * * This custom tslint rule is highly specific to GitHub Desktop and attempts * to prevent props and state interfaces from being declared with mutable * members. * * While it's technically possible to modify this.props there's never a good * reason to do so and marking our i...
(propertySignature: ts.PropertySignature): boolean { const modifiers = propertySignature.modifiers if (!modifiers) { return false } if (modifiers.find(m => m.kind === ts.SyntaxKind.ReadonlyKeyword)) { return true } return false } }
isReadOnly
identifier_name
reactReadonlyPropsAndStateRule.ts
/** * react-readonly-props-and-state * * This custom tslint rule is highly specific to GitHub Desktop and attempts * to prevent props and state interfaces from being declared with mutable * members. * * While it's technically possible to modify this.props there's never a good * reason to do so and marking our i...
private isReadOnly(propertySignature: ts.PropertySignature): boolean { const modifiers = propertySignature.modifiers if (!modifiers) { return false } if (modifiers.find(m => m.kind === ts.SyntaxKind.ReadonlyKeyword)) { return true } return false } }
this.addFailure(this.createFailure(start, width, error)) } }) }
random_line_split
db_sample.js
/** * @author Trilogis Srl * @author Gustavo German Soria * * Database Module */
* PostgreSQL client for node.js module import. * @type {exports} */ var pg = require('pg'); /** * Username for the database connection * @type {string} */ var username = "<username>"; /** * Password for the database connection * @type {string} */ var password = "<password>"; /** * Name of the database * @...
/**
random_line_split
db_sample.js
/** * @author Trilogis Srl * @author Gustavo German Soria * * Database Module */ /** * PostgreSQL client for node.js module import. * @type {exports} */ var pg = require('pg'); /** * Username for the database connection * @type {string} */ var username = "<username>"; /** * Password for the database conn...
} }); }); } module.exports.execute = executeQuery; module.exports.conString = connString;
{ var _next = callback.list.pop(); if (_next) { callback.rows = result.rows; _next(callback); } }
conditional_block
womble.py
# Author: Nic Wolfe <nic@wolfeden.ca> # URL: http://code.google.com/p/sickbeard/ # # This file is part of SickRage. # # SickRage is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License,...
(self, provider): tvcache.TVCache.__init__(self, provider) # only poll Womble's Index every 15 minutes max self.minTime = 15 def updateCache(self): # check if we should update if not self.shouldUpdate(): return # clear cache self._clearCache() ...
__init__
identifier_name
womble.py
# Author: Nic Wolfe <nic@wolfeden.ca> # URL: http://code.google.com/p/sickbeard/ # # This file is part of SickRage. # # SickRage is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License,...
def updateCache(self): # check if we should update if not self.shouldUpdate(): return # clear cache self._clearCache() # set updated self.setLastUpdate() cl = [] for url in [self.provider.url + 'rss/?sec=tv-sd&fr=false', self.provider....
tvcache.TVCache.__init__(self, provider) # only poll Womble's Index every 15 minutes max self.minTime = 15
identifier_body
womble.py
# Author: Nic Wolfe <nic@wolfeden.ca>
# SickRage is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # SickRage is distributed in the hope that it will be useful, # but WITHOU...
# URL: http://code.google.com/p/sickbeard/ # # This file is part of SickRage. #
random_line_split
womble.py
# Author: Nic Wolfe <nic@wolfeden.ca> # URL: http://code.google.com/p/sickbeard/ # # This file is part of SickRage. # # SickRage is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License,...
# clear cache self._clearCache() # set updated self.setLastUpdate() cl = [] for url in [self.provider.url + 'rss/?sec=tv-sd&fr=false', self.provider.url + 'rss/?sec=tv-hd&fr=false']: logger.log(u"Womble's Index cache update URL: " + url, logger.DEBUG) ...
return
conditional_block
main.py
""" bjson/main.py Copyright (c) 2010 David Martinez Marti All rights reserved. Licensed under 3-clause BSD License. See LICENSE.txt for the full license text. """ import socket import bjsonrpc.server import bjsonrpc.connection import bjsonrpc.handlers __all__ = [ "createserver", "...
**host** Address (IP or Host Name) to connect to. **port** Port number to connect to. **handler_factory** Class to instantiate to publish remote functions to the server. By default this is *NullHandler* which means that no functions ...
Creates a *bjson.connection.Connection* object linked to a connected socket. Parameters:
random_line_split
main.py
""" bjson/main.py Copyright (c) 2010 David Martinez Marti All rights reserved. Licensed under 3-clause BSD License. See LICENSE.txt for the full license text. """ import socket import bjsonrpc.server import bjsonrpc.connection import bjsonrpc.handlers __all__ = [ "createserver", "...
Servers are usually created this way:: import bjsonrpc server = bjsonrpc.createserver("0.0.0.0") server.serve() Check :ref:`bjsonrpc.server` documentation """ if sock is None: sock = socket.socket(socket.AF_INET, sock...
""" Creates a *bjson.server.Server* object linked to a listening socket. Parameters: **host** Address (IP or Host Name) to listen to as in *socket.bind*. Use "0.0.0.0" to listen to all address. By default this points to 127.0.0.1 to avoid security...
identifier_body
main.py
""" bjson/main.py Copyright (c) 2010 David Martinez Marti All rights reserved. Licensed under 3-clause BSD License. See LICENSE.txt for the full license text. """ import socket import bjsonrpc.server import bjsonrpc.connection import bjsonrpc.handlers __all__ = [ "createserver", "...
sock.connect((host, port)) return bjsonrpc.connection.Connection(sock, handler_factory=handler_factory)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
conditional_block
main.py
""" bjson/main.py Copyright (c) 2010 David Martinez Marti All rights reserved. Licensed under 3-clause BSD License. See LICENSE.txt for the full license text. """ import socket import bjsonrpc.server import bjsonrpc.connection import bjsonrpc.handlers __all__ = [ "createserver", "...
(host="127.0.0.1", port=10123, sock=None, handler_factory=bjsonrpc.handlers.NullHandler): """ Creates a *bjson.connection.Connection* object linked to a connected socket. Parameters: **host** Address (IP or Host Name) to connect to. ...
connect
identifier_name
menu.py
import sys from core import loop from util import jsonmanager, debug def make_console_menu(name): menu_data_file_path = '_Resources/Data/MenuData/' path = menu_data_file_path + name + '.json' data = jsonmanager.get_data(path) title = data['Title'] item_data = data['Items'] args = [] for...
return ConsoleMenu(title, args) class ConsoleMenuItem: def __init__(self, text, action): self.text = text self.action = action def invoke(self): try: getattr(sys.modules[__name__], self.action)() except AttributeError as error: debug.log('Somethin...
args.append((item_datum['Text'], item_datum['Action']))
conditional_block
menu.py
import sys from core import loop from util import jsonmanager, debug def make_console_menu(name): menu_data_file_path = '_Resources/Data/MenuData/' path = menu_data_file_path + name + '.json' data = jsonmanager.get_data(path) title = data['Title'] item_data = data['Items'] args = [] for...
class ConsoleMenu: def __init__(self, title, args): self.title = title self.menu_items = [] for argument in args: self.add_menu_item(argument[0], argument[1]) def add_menu_item(self, text, action): self.menu_items.append(ConsoleMenuItem(text, action)) def get_m...
raise error
random_line_split
menu.py
import sys from core import loop from util import jsonmanager, debug def make_console_menu(name): menu_data_file_path = '_Resources/Data/MenuData/' path = menu_data_file_path + name + '.json' data = jsonmanager.get_data(path) title = data['Title'] item_data = data['Items'] args = [] for...
def run_game(): run_loop(loop.DefaultGameLoop())
run_loop(loop.EditorLoop())
identifier_body
menu.py
import sys from core import loop from util import jsonmanager, debug def make_console_menu(name): menu_data_file_path = '_Resources/Data/MenuData/' path = menu_data_file_path + name + '.json' data = jsonmanager.get_data(path) title = data['Title'] item_data = data['Items'] args = [] for...
(self, text, action): self.menu_items.append(ConsoleMenuItem(text, action)) def get_menu_item(self, index): return self.menu_items[index] def display_menu_item(self, index): menu_item = self.get_menu_item(index) print('[' + str(index) + '] - ' + menu_item.text) def run(sel...
add_menu_item
identifier_name
login.ts
import { Component} from '@angular/core'; import { AlertService } from '../../services/alert.service'; import { SharedService } from '../../services/sharedService.service'; import {FormGroup, FormBuilder, FormControl, Validators} from "@angular/forms"; import { NavController,ViewController } from 'ionic-angular'; impor...
} else{ this.alertService.alertPrompt("Oops!","This email is not registered with us."); } }); } rememberMe() { console.log('Cucumbers new state:'); } }
{ if(this.userInfo.password == val.password){ this.sharedService.setUserName(this.userInfo.email); this.navCtrl.pop(); }else{ this.alertService.alertPrompt("Oops!","incorrect password"); } }
conditional_block
login.ts
import { Component} from '@angular/core'; import { AlertService } from '../../services/alert.service'; import { SharedService } from '../../services/sharedService.service'; import {FormGroup, FormBuilder, FormControl, Validators} from "@angular/forms"; import { NavController,ViewController } from 'ionic-angular'; impor...
() { console.log('Cucumbers new state:'); } }
rememberMe
identifier_name
login.ts
import { Component} from '@angular/core'; import { AlertService } from '../../services/alert.service'; import { SharedService } from '../../services/sharedService.service'; import {FormGroup, FormBuilder, FormControl, Validators} from "@angular/forms"; import { NavController,ViewController } from 'ionic-angular'; impor...
} ngOnInit(): any { this.myForm = this.formBuilder.group({ 'email': ['', [Validators.required, this.emailValidator.bind(this)]], 'password': ['', [Validators.required, this.passwordValidator.bind(this)]], 'rememberMe': ['', []] }); } isValid(field: string) { l...
this.sharedService=sharedService;
random_line_split
login.ts
import { Component} from '@angular/core'; import { AlertService } from '../../services/alert.service'; import { SharedService } from '../../services/sharedService.service'; import {FormGroup, FormBuilder, FormControl, Validators} from "@angular/forms"; import { NavController,ViewController } from 'ionic-angular'; impor...
goBack(){ this.navCtrl.setRoot(TabsPage); } login (){ this.storage.get(this.userInfo.email).then((val) => { console.log('data', val); if( val!=null && val.email!= null){ if(this.userInfo.email == val.email){ if(this.userInfo.password == val.password){ this....
{ if (control.value!==''){ if(!control.value.match('^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#\$%\^&\*])(?=.{8,})')){ return {'invalidPassword': true}; } } }
identifier_body
atfExt.py
import pylab as pl import scipy as sp from serpentine import * from elements import * import visualize class AtfExt : def __init__(self) : print 'AtfExt:__init__' # set twiss parameters mytwiss = Twiss() mytwiss.betax = 6.85338806855804 mytwiss.alphax = 1.11230788371885 ...
def correctorCalibration(self, corr, bpms) : pass def bba(self, mag, bpm) : pass def magMoverCalibration(self, mag, bpm) : pass def setMagnet(self,name, value) : ei = self.atfExt.beamline.FindEleByName(name) print ei e = self.atfExt.beamline[ei[0]...
def moverCalibration(self, mag, bpms) : pass
random_line_split
atfExt.py
import pylab as pl import scipy as sp from serpentine import * from elements import * import visualize class AtfExt : def __init__(self) :
self.atfExt = Serpentine(line=beamline.Line(self.atfFull.beamline[947:]),twiss=mytwiss) # zero zero cors self.atfExt.beamline.ZeroCors() # Track self.atfExt.Track() readings = self.atfExt.GetBPMReadings() # Visualisation self.v = visualize.Vi...
print 'AtfExt:__init__' # set twiss parameters mytwiss = Twiss() mytwiss.betax = 6.85338806855804 mytwiss.alphax = 1.11230788371885 mytwiss.etax = 3.89188697330735e-012 mytwiss.etaxp = 63.1945125619190e-015 mytwiss.betay = 2.94129410712918 mytwiss.al...
identifier_body
atfExt.py
import pylab as pl import scipy as sp from serpentine import * from elements import * import visualize class AtfExt : def __init__(self) : print 'AtfExt:__init__' # set twiss parameters mytwiss = Twiss() mytwiss.betax = 6.85338806855804 mytwiss.alphax = 1.11230788371885 ...
(self) : self.v.PlotBPMReadings(self.atfExt) def plotTwiss(self) : self.v.PlotTwiss(self.atfExt) def run(self) : self.atfExt.Track() def jitterBeam(self) : r = 1+sp.random.standard_normal() # self.s.beam_in.x[5,:] = (1+r/3e4)*self.nominalE # print r,...
plotOrbit
identifier_name
direct_style_player.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 {NoopAnimationPlayer} from '@angular/animations'; import {hypenatePropsObject} from '../shared'; export class ...
else { this.element.style.removeProperty(prop); } }); this._startingStyles = null; super.destroy(); } }
{ this.element.style.setProperty(prop, value); }
conditional_block
direct_style_player.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 {NoopAnimationPlayer} from '@angular/animations'; import {hypenatePropsObject} from '../shared'; export class ...
init() { if (this.__initialized || !this._startingStyles) return; this.__initialized = true; Object.keys(this._styles).forEach(prop => { this._startingStyles![prop] = this.element.style[prop]; }); super.init(); } play() { if (!this._startingStyles) return; this.init(); Obj...
{ super(); this._styles = hypenatePropsObject(styles); }
identifier_body
direct_style_player.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 {NoopAnimationPlayer} from '@angular/animations'; import {hypenatePropsObject} from '../shared'; export class ...
() { if (!this._startingStyles) return; Object.keys(this._startingStyles).forEach(prop => { const value = this._startingStyles![prop]; if (value) { this.element.style.setProperty(prop, value); } else { this.element.style.removeProperty(prop); } }); this._startingS...
destroy
identifier_name
direct_style_player.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 {NoopAnimationPlayer} from '@angular/animations'; import {hypenatePropsObject} from '../shared'; export class ...
.forEach(prop => this.element.style.setProperty(prop, this._styles[prop])); super.play(); } destroy() { if (!this._startingStyles) return; Object.keys(this._startingStyles).forEach(prop => { const value = this._startingStyles![prop]; if (value) { this.element.style.setProper...
this.init(); Object.keys(this._styles)
random_line_split
index.tsx
import React from 'react' import styled from 'styled-components' import Box from 'v2/components/UI/Box' import Text from 'v2/components/UI/Text' import FeedObjectLink from 'v2/components/FeedGroups/components/FeedGroupSentence/components/FeedObjectLink/index' import BorderedLock from 'v2/components/UI/BorderedLock' i...
group, }) => { const { owner, action, item, connector, target, created_at, item_phrase, is_private, } = group return ( <Container my={3} pr={6}> <Sentence> <FeedObjectLink obj={owner} {...owner} /> {action === 'commented' && item.__typename === 'Commen...
interface FeedGroupSentenceProps { group: FeedGroupSentenceType } export const FeedGroupSentence: React.FC<FeedGroupSentenceProps> = ({
random_line_split
autocopyleft.py
#-*- coding: utf-8 -*- import sys, fileinput, os # Configuration path_src = "../src/" fextension = [".py"] date_copyright = "2011" authors = "see AUTHORS" project_name = "ProfileExtractor" header_file = "license_header.txt" def pre_append(line, file_name): fobj = fileinput.FileInput(file_name, inplace=1) fir...
if __name__ == '__main__': f = open(header_file, 'r') licence_head = f.readlines() f.close() files = listdirectory(path_src, fextension) for f in files: name = os.path.basename(f) str_lhead = "" for l in licence_head: l = l.replace("DATE", date_copyright) ...
all_files = [] for root, dirs, files in os.walk(path): for i in files: if os.path.splitext(i)[1] in extension: all_files.append(os.path.join(root, i)) return all_files
identifier_body
autocopyleft.py
#-*- coding: utf-8 -*- import sys, fileinput, os # Configuration path_src = "../src/" fextension = [".py"] date_copyright = "2011" authors = "see AUTHORS" project_name = "ProfileExtractor" header_file = "license_header.txt" def pre_append(line, file_name): fobj = fileinput.FileInput(file_name, inplace=1) fir...
name = os.path.basename(f) str_lhead = "" for l in licence_head: l = l.replace("DATE", date_copyright) l = l.replace("AUTHORS", authors) l = l.replace("PROJECT_NAME", project_name) l = l.replace("FILENAME", name) str_lhead += l pre...
conditional_block
autocopyleft.py
#-*- coding: utf-8 -*- import sys, fileinput, os # Configuration path_src = "../src/" fextension = [".py"] date_copyright = "2011" authors = "see AUTHORS" project_name = "ProfileExtractor" header_file = "license_header.txt" def
(line, file_name): fobj = fileinput.FileInput(file_name, inplace=1) first_line = fobj.readline() sys.stdout.write("%s\n%s" % (line, first_line)) for line in fobj: sys.stdout.write("%s" % line) fobj.close() def listdirectory(path, extension): all_files = [] for root, dirs, files in...
pre_append
identifier_name
autocopyleft.py
#-*- coding: utf-8 -*-
path_src = "../src/" fextension = [".py"] date_copyright = "2011" authors = "see AUTHORS" project_name = "ProfileExtractor" header_file = "license_header.txt" def pre_append(line, file_name): fobj = fileinput.FileInput(file_name, inplace=1) first_line = fobj.readline() sys.stdout.write("%s\n%s" % (line, fi...
import sys, fileinput, os # Configuration
random_line_split
decoder.py
""" maxminddb.decoder ~~~~~~~~~~~~~~~~~ This package contains code for decoding the MaxMind DB data section. """ from __future__ import unicode_literals import struct from maxminddb.compat import byte_from_int, int_from_bytes from maxminddb.errors import InvalidDatabaseError class Decoder(object): # pylint: disa...
elif size > 30: size = struct.unpack( b'!I', size_bytes.rjust(4, b'\x00'))[0] + 65821 return size, new_offset
size = 285 + struct.unpack(b'!H', size_bytes)[0]
conditional_block
decoder.py
""" maxminddb.decoder ~~~~~~~~~~~~~~~~~ This package contains code for decoding the MaxMind DB data section. """ from __future__ import unicode_literals import struct from maxminddb.compat import byte_from_int, int_from_bytes from maxminddb.errors import InvalidDatabaseError class Decoder(object): # pylint: disa...
def _decode_bytes(self, size, offset): new_offset = offset + size return self._buffer[offset:new_offset], new_offset # pylint: disable=no-self-argument # |-> I am open to better ways of doing this as long as it doesn't involve # lots of code duplication. def _decode_packed_typ...
return size != 0, offset
identifier_body
decoder.py
"""
""" from __future__ import unicode_literals import struct from maxminddb.compat import byte_from_int, int_from_bytes from maxminddb.errors import InvalidDatabaseError class Decoder(object): # pylint: disable=too-few-public-methods """Decoder for the data section of the MaxMind DB""" def __init__(self, da...
maxminddb.decoder ~~~~~~~~~~~~~~~~~ This package contains code for decoding the MaxMind DB data section.
random_line_split
decoder.py
""" maxminddb.decoder ~~~~~~~~~~~~~~~~~ This package contains code for decoding the MaxMind DB data section. """ from __future__ import unicode_literals import struct from maxminddb.compat import byte_from_int, int_from_bytes from maxminddb.errors import InvalidDatabaseError class Decoder(object): # pylint: disa...
(self, size, offset): container = {} for _ in range(size): (key, offset) = self.decode(offset) (value, offset) = self.decode(offset) container[key] = value return container, offset _pointer_value_offset = { 1: 0, 2: 2048, 3: 526336...
_decode_map
identifier_name
category.js
var _ = require('underscore'); var AutoStyler = require('./auto-styler'); module.exports = AutoStyler.extend({ updateStyle: function (style) { this.styles = style.auto_style; this.colors.updateColors(style.auto_style); this.colors.updateData(_.pluck(this.dataviewModel.get('data'), 'name')); }, _getR...
} } else if (i === categories.length - 1) { catListValues = catListValues.substring(0, catListValues.length - 2); } } return ramp + '(' + catListColors + '), (' + catListValues + '), \'=\')'; } });
if (!cat.agg) { if (typeof cat.name !== 'string') { catListValues += cat.name + next; } else { catListValues += '"' + String(cat.name).replace(/"/g, '\\"') + '"' + next;
random_line_split
category.js
var _ = require('underscore'); var AutoStyler = require('./auto-styler'); module.exports = AutoStyler.extend({ updateStyle: function (style) { this.styles = style.auto_style; this.colors.updateColors(style.auto_style); this.colors.updateData(_.pluck(this.dataviewModel.get('data'), 'name')); }, _getR...
return ramp + '(' + catListColors + '), (' + catListValues + '), \'=\')'; } });
{ var cat = categories[i]; var next = i !== categories.length - 1 ? ', ' : ''; catListColors += '"' + this.colors.getColorByCategory(cat.name) + '"' + next; if (!cat.agg) { if (typeof cat.name !== 'string') { catListValues += cat.name + next; } else { catList...
conditional_block
dellos6.py
# # (c) 2016 Red Hat Inc. # # (c) 2017 Dell EMC. # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later ve...
if prompt.strip().endswith(b')#'): self._exec_cli_command(b'end') self._exec_cli_command(b'disable') elif prompt.endswith(b'#'): self._exec_cli_command(b'disable')
return
conditional_block
dellos6.py
# # (c) 2016 Red Hat Inc. # # (c) 2017 Dell EMC. # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later ve...
def on_unbecome(self): prompt = self._get_prompt() if prompt is None: # if prompt is None most likely the terminal is hung up at a prompt return if prompt.strip().endswith(b')#'): self._exec_cli_command(b'end') self._exec_cli_command(b'disab...
if self._get_prompt().endswith(b'#'): return cmd = {u'command': u'enable'} if passwd: cmd[u'prompt'] = to_text(r"[\r\n]?password:$", errors='surrogate_or_strict') cmd[u'answer'] = passwd try: self._exec_cli_command(to_bytes(json.dumps(cmd), errors...
identifier_body
dellos6.py
# # (c) 2016 Red Hat Inc. # # (c) 2017 Dell EMC. # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later ve...
except AnsibleConnectionFailure: raise AnsibleConnectionFailure('unable to set terminal parameters') def on_become(self, passwd=None): if self._get_prompt().endswith(b'#'): return cmd = {u'command': u'enable'} if passwd: cmd[u'prompt'] = to_text(...
self._exec_cli_command(b'terminal length 0')
random_line_split
dellos6.py
# # (c) 2016 Red Hat Inc. # # (c) 2017 Dell EMC. # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later ve...
(TerminalBase): terminal_stdout_re = [ re.compile(br"[\r\n]?[\w+\-\.:\/\[\]]+(?:\([^\)]+\)){,3}(?:>|#) ?$"), re.compile(br"\[\w+\@[\w\-\.]+(?: [^\]])\] ?[>#\$] ?$") ] terminal_stderr_re = [ re.compile(br"% ?Bad secret"), re.compile(br"(\bInterface is part of a port-channel\...
TerminalModule
identifier_name
handleQuickReply.js
const weekly = require('./'), botMessages = require('../messages/bot-msgs'), sendMessage = require('../tools/sendMessage') ; module.exports = function (datastore, userObject, quick_reply) { let day = quick_reply.payload.split('_')[1].toLowerCase(); weekly(datastore, userObject, day).then(postsElem...
}); };
random_line_split
nf.rs
use e2d2::headers::*; use e2d2::operators::*; #[inline] fn lat() { unsafe { asm!("nop" : : : : "volatile"); } } #[inline] fn delay_loop(delay: u64) { let mut d = 0; while d < delay { lat(); d += 1; }
pub fn delay<T: 'static + Batch<Header = NullHeader>>( parent: T, delay: u64, ) -> MapBatch<NullHeader, ResetParsingBatch<TransformBatch<MacHeader, ParsedBatch<MacHeader, T>>>> { parent .parse::<MacHeader>() .transform(box move |pkt| { assert!(pkt.refcnt() == 1); let ...
}
random_line_split
nf.rs
use e2d2::headers::*; use e2d2::operators::*; #[inline] fn
() { unsafe { asm!("nop" : : : : "volatile"); } } #[inline] fn delay_loop(delay: u64) { let mut d = 0; while d < delay { lat(); d += 1; } } pub fn delay<T: 'static + Batch<Header = NullHeader>>( parent: T, delay: u...
lat
identifier_name
nf.rs
use e2d2::headers::*; use e2d2::operators::*; #[inline] fn lat()
#[inline] fn delay_loop(delay: u64) { let mut d = 0; while d < delay { lat(); d += 1; } } pub fn delay<T: 'static + Batch<Header = NullHeader>>( parent: T, delay: u64, ) -> MapBatch<NullHeader, ResetParsingBatch<TransformBatch<MacHeader, ParsedBatch<MacHeader, T>>>> { parent ...
{ unsafe { asm!("nop" : : : : "volatile"); } }
identifier_body
exceptions.py
# Copyright 2014 Alcatel-Lucent USA 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 l...
(n_exc.InvalidConfigurationOption): message = _("Nuage Plugin does not support this operation: %(msg)s") class NuageBadRequest(n_exc.BadRequest): message = _("Bad request: %(msg)s")
OperationNotSupported
identifier_name
exceptions.py
# Copyright 2014 Alcatel-Lucent USA 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 l...
class NuageBadRequest(n_exc.BadRequest): message = _("Bad request: %(msg)s")
message = _("Nuage Plugin does not support this operation: %(msg)s")
identifier_body
exceptions.py
# Copyright 2014 Alcatel-Lucent USA 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 l...
class NuageBadRequest(n_exc.BadRequest): message = _("Bad request: %(msg)s")
random_line_split
15.2.3.6-3-37.js
/// Copyright (c) 2009 Microsoft Corporation /// /// Redistribution and use in source and binary forms, with or without modification, are permitted provided /// that the following conditions are met:
/// endorse or promote products derived from this software without specific prior written permission. /// /// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR /// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS ...
/// * Redistributions of source code must retain the above copyright notice, this list of conditions and /// the following disclaimer. /// * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and /// the following disclaimer in the documentation and/or ot...
random_line_split
15.2.3.6-3-37.js
/// Copyright (c) 2009 Microsoft Corporation /// /// Redistribution and use in source and binary forms, with or without modification, are permitted provided /// that the following conditions are met: /// * Redistributions of source code must retain the above copyright notice, this list of conditions and /// ...
} return accessed; }, precondition: function prereq() { return fnExists(Object.defineProperty); } });
{ accessed = true; }
conditional_block
base.py
Extend this on the implementing protocol. If it should error out, return the output of the 'self.faults.fault_name' response. Otherwise, it MUST return a TUPLE of TUPLE. Each entry tuple must have the following structure: ('method_name', params) ...where params is a list...
return x+y
random_line_split
base.py
config = Config() class BaseRPCParser(object): """ This class is responsible for managing the request, dispatch, and response formatting of the system. It is tied into the _RPC_ attribute of the BaseRPCHandler (or subclasses) and populated as necessary throughout the request. Use the .faults ...
verbose = True short_errors = True
identifier_body
base.py
""" content_type = 'text/plain' def __init__(self, library, encode=None, decode=None): # Attaches the RPC library and encode / decode functions. self.library = library if not encode: encode = getattr(library, 'dumps') if not decode: decode = getattr(libr...
handler._RPC_finished = True responses = tuple(handler._results) response_text = self.parse_responses(responses) if type(response_text) not in types.StringTypes: # Likely a fault, or something messed up response_text = self.encode(response_text) # Calling...
raise Exception("Error trying to send response twice.")
conditional_block
base.py
Minimum number of lines to see what happened # Plus title and separators print '\n'.join(err_lines[0:4]+err_lines[-3:]) else: print '\n'.join(err_lines) # Log here return def parse_request(self, request_body): """ Extend t...
power
identifier_name
index.js
// // partial2js // Copyright (c) 2014 Dennis Sänger // Licensed under the MIT // http://opensource.org/licenses/MIT // "use strict"; var glob = require('glob-all'); var fs = require('fs'); var path = require('path'); var stream = require('stream'); var htmlmin = require('html-minifier').minify; var escape...
patterns, entry ) { var res = patterns.length + 100; patterns.every(function( pattern, index ) { if ( entry.indexOf( pattern ) > -1 ) { res = index; return false; } return true; }); return res; } var unique = (function() { if ( typeof this.uniqueFn === 'funct...
atchInPattern(
identifier_name
index.js
// // partial2js // Copyright (c) 2014 Dennis Sänger // Licensed under the MIT // http://opensource.org/licenses/MIT // "use strict"; var glob = require('glob-all'); var fs = require('fs'); var path = require('path'); var stream = require('stream'); var htmlmin = require('html-minifier').minify; var escape...
}).bind( this ); var find = (function() { this.files = glob.sync( this.patterns.slice( 0 )) || []; }).bind( this ); function cleanPatterns( patterns ) { return patterns.map(function( entry ) { return entry.replace(/\/\*+/g, ''); }); } function compare( patterns, a, b ) { return matc...
console.log.apply( console, arguments ); }
conditional_block
index.js
// // partial2js // Copyright (c) 2014 Dennis Sänger // Licensed under the MIT // http://opensource.org/licenses/MIT // "use strict"; var glob = require('glob-all'); var fs = require('fs'); var path = require('path'); var stream = require('stream'); var htmlmin = require('html-minifier').minify; var escape...
function compare( patterns, a, b ) { return matchInPattern( patterns, a ) - matchInPattern( patterns, b ); } var sort = (function() { var clean = cleanPatterns( this.patterns ); this.files.sort(function( a, b ) { return compare( clean, a, b ); }); }).bind( this ); // // this functio...
return patterns.map(function( entry ) { return entry.replace(/\/\*+/g, ''); }); }
identifier_body
index.js
// // partial2js // Copyright (c) 2014 Dennis Sänger // Licensed under the MIT // http://opensource.org/licenses/MIT // "use strict"; var glob = require('glob-all'); var fs = require('fs'); var path = require('path'); var stream = require('stream'); var htmlmin = require('html-minifier').minify; var escape...
var key = self.uniqueFn( file ); if ( !obj[key] ) { obj[key] = file; } }); this.files = obj; } }).bind( this ); var asString = (function( moduleName ) { var buffer = ''; buffer += '(function(window,document){' + eol; buffer += '"use strict";' + eol; ...
this.files.forEach(function( file ) {
random_line_split
delete.rs
use nom::character::complete::multispace1; use std::{fmt, str}; use common::{statement_terminator, schema_table_reference}; use condition::ConditionExpression; use keywords::escape_if_keyword; use nom::bytes::complete::tag_no_case; use nom::combinator::opt; use nom::sequence::{delimited, tuple}; use nom::IResult; use ...
(i: &[u8]) -> IResult<&[u8], DeleteStatement> { let (remaining_input, (_, _, table, where_clause, _)) = tuple(( tag_no_case("delete"), delimited(multispace1, tag_no_case("from"), multispace1), schema_table_reference, opt(where_clause), statement_terminator, ))(i)?; O...
deletion
identifier_name
delete.rs
use nom::character::complete::multispace1; use std::{fmt, str}; use common::{statement_terminator, schema_table_reference}; use condition::ConditionExpression; use keywords::escape_if_keyword; use nom::bytes::complete::tag_no_case; use nom::combinator::opt; use nom::sequence::{delimited, tuple}; use nom::IResult; use ...
Ok(()) } } pub fn deletion(i: &[u8]) -> IResult<&[u8], DeleteStatement> { let (remaining_input, (_, _, table, where_clause, _)) = tuple(( tag_no_case("delete"), delimited(multispace1, tag_no_case("from"), multispace1), schema_table_reference, opt(where_clause), ...
{ write!(f, " WHERE ")?; write!(f, "{}", where_clause)?; }
conditional_block
delete.rs
use nom::character::complete::multispace1; use std::{fmt, str}; use common::{statement_terminator, schema_table_reference}; use condition::ConditionExpression; use keywords::escape_if_keyword; use nom::bytes::complete::tag_no_case; use nom::combinator::opt; use nom::sequence::{delimited, tuple}; use nom::IResult; use ...
operator: Operator::Equal, })); assert_eq!( res.unwrap().1, DeleteStatement { table: Table::from("users"), where_clause: expected_where_cond, ..Default::default() } ); } #[test] fn format...
let expected_left = Base(Field(Column::from("id"))); let expected_where_cond = Some(ComparisonOp(ConditionTree { left: Box::new(expected_left), right: Box::new(Base(Literal(Literal::Integer(1)))),
random_line_split
delete.rs
use nom::character::complete::multispace1; use std::{fmt, str}; use common::{statement_terminator, schema_table_reference}; use condition::ConditionExpression; use keywords::escape_if_keyword; use nom::bytes::complete::tag_no_case; use nom::combinator::opt; use nom::sequence::{delimited, tuple}; use nom::IResult; use ...
} pub fn deletion(i: &[u8]) -> IResult<&[u8], DeleteStatement> { let (remaining_input, (_, _, table, where_clause, _)) = tuple(( tag_no_case("delete"), delimited(multispace1, tag_no_case("from"), multispace1), schema_table_reference, opt(where_clause), statement_terminator,...
{ write!(f, "DELETE FROM ")?; write!(f, "{}", escape_if_keyword(&self.table.name))?; if let Some(ref where_clause) = self.where_clause { write!(f, " WHERE ")?; write!(f, "{}", where_clause)?; } Ok(()) }
identifier_body
messages.py
'''Module for the messages pageset''' from murmeli.pages.base import PageSet from murmeli.pagetemplate import PageTemplate from murmeli import dbutils from murmeli.contactmgr import ContactManager from murmeli.messageutils import MessageTree from murmeli import inbox class MessagesPageSet(PageSet): '''Messages p...
def serve_page(self, view, url, params): '''Serve a page to the given view''' print("Messages serving page", url, "params:", params) self.require_resources(['button-compose.png', 'default.css', 'avatar-none.jpg']) database = self.system.get_component(self.system.COMPNAME_DATABASE) ...
PageSet.__init__(self, system, "messages") self.messages_template = PageTemplate('messages')
identifier_body
messages.py
'''Module for the messages pageset''' from murmeli.pages.base import PageSet from murmeli.pagetemplate import PageTemplate from murmeli import dbutils from murmeli.contactmgr import ContactManager from murmeli.messageutils import MessageTree from murmeli import inbox class MessagesPageSet(PageSet): '''Messages p...
(self, url, params): '''Process a command given by the url and params''' database = self.system.get_component(self.system.COMPNAME_DATABASE) if url == 'send': if params.get('messageType') == "contactresponse": if params.get('accept') == "1": crypto...
_process_command
identifier_name
messages.py
'''Module for the messages pageset''' from murmeli.pages.base import PageSet from murmeli.pagetemplate import PageTemplate from murmeli import dbutils from murmeli.contactmgr import ContactManager from murmeli.messageutils import MessageTree from murmeli import inbox class MessagesPageSet(PageSet): '''Messages p...
mails = mail_tree.build() num_msgs = len(conreqs) + len(conresps) + len(mails) bodytext = self.messages_template.get_html(self.get_all_i18n(), {"contactrequests":conreqs, "contactresponses":c...
recpts = msg.get(inbox.FN_RECIPIENTS) if recpts: reply_all = recpts.split(",") recpt_name_list = [contact_names.get(i, unknown_recpt) for i in reply_all] msg[inbox.FN_RECIPIENT_NAMES] = ", ".join(recpt_name_list) reply_all.a...
conditional_block
messages.py
'''Module for the messages pageset''' from murmeli.pages.base import PageSet from murmeli.pagetemplate import PageTemplate from murmeli import dbutils from murmeli.contactmgr import ContactManager from murmeli.messageutils import MessageTree from murmeli import inbox class MessagesPageSet(PageSet): '''Messages p...
message_list = database.get_inbox() if database else [] conreqs = [] conresps = [] mail_tree = MessageTree() for msg in message_list: if not msg or msg.get(inbox.FN_DELETED): continue timestamp = msg.get(inbox.FN_TIMESTAMP) msg[...
unknown_sender = self.i18n("messages.sender.unknown") unknown_recpt = self.i18n("messages.recpt.unknown")
random_line_split
observer.js
import { watch, unwatch } from './watching'; import { addListener, removeListener } from './events'; /** @module @ember/object */ const AFTER_OBSERVERS = ':change'; export function changeEvent(keyName) { return keyName + AFTER_OBSERVERS; } /** @method addObserver @static @for @ember/object/observers ...
/** @method removeObserver @static @for @ember/object/observers @param obj @param {String} path @param {Object|Function} target @param {Function|String} [method] @public */ export function removeObserver(obj, path, target, method) { unwatch(obj, path); removeListener(obj, changeEvent(path), target...
{ addListener(obj, changeEvent(path), target, method); watch(obj, path); }
identifier_body
observer.js
import { watch, unwatch } from './watching'; import { addListener, removeListener } from './events'; /** @module @ember/object */ const AFTER_OBSERVERS = ':change'; export function changeEvent(keyName) { return keyName + AFTER_OBSERVERS; } /** @method addObserver
@static @for @ember/object/observers @param obj @param {String} path @param {Object|Function} target @param {Function|String} [method] @public */ export function addObserver(obj, path, target, method) { addListener(obj, changeEvent(path), target, method); watch(obj, path); } /** @method removeObser...
random_line_split
observer.js
import { watch, unwatch } from './watching'; import { addListener, removeListener } from './events'; /** @module @ember/object */ const AFTER_OBSERVERS = ':change'; export function changeEvent(keyName) { return keyName + AFTER_OBSERVERS; } /** @method addObserver @static @for @ember/object/observers ...
(obj, path, target, method) { addListener(obj, changeEvent(path), target, method); watch(obj, path); } /** @method removeObserver @static @for @ember/object/observers @param obj @param {String} path @param {Object|Function} target @param {Function|String} [method] @public */ export function removeO...
addObserver
identifier_name
mainTelemetryService.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
(eventName: string, data?: any): void { if (this.hardIdleMonitor && this.hardIdleMonitor.getStatus() === UserStatus.Idle) { return; } // don't send telemetry when channel is not enabled if (!this.config.enableTelemetry) { return; } // don't send events when the user is optout unless the event is fla...
handleEvent
identifier_name