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 |
|---|---|---|---|---|
time_log_batch.js | // Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
// License: GNU General Public License v3. See license.txt
cur_frm.add_fetch("time_log", "activity_type", "activity_type");
cur_frm.add_fetch("time_log", "billing_amount", "billing_amount");
cur_frm.add_fetch("time_log", "hours", "hours");
cur_frm.... |
},
make_invoice: function() {
frappe.model.open_mapped_doc({
method: "erpnext.projects.doctype.time_log_batch.time_log_batch.make_sales_invoice",
frm: cur_frm
});
}
});
frappe.ui.form.on("Time Log Batch Detail", "time_log", function(frm, cdt, cdn) {
var tl = frm.doc.time_logs || [];
total_hr = 0;
tota... | {
cur_frm.add_custom_button(__("Make Sales Invoice"), function() { cur_frm.cscript.make_invoice() },
"icon-file-alt");
} | conditional_block |
pyunit_parquet_parser_simple.py | from __future__ import print_function
import sys
sys.path.insert(1,"../../")
import h2o
from tests import pyunit_utils
def parquet_parse_simple():
"""
Tests Parquet parser by comparing the summary of the original csv frame with the h2o parsed Parquet frame.
Basic use case of importing files with auto-dete... | parquet_parse_simple() | conditional_block | |
pyunit_parquet_parser_simple.py | from __future__ import print_function
import sys
sys.path.insert(1,"../../")
import h2o
from tests import pyunit_utils
def parquet_parse_simple():
|
if __name__ == "__main__":
pyunit_utils.standalone_test(parquet_parse_simple)
else:
parquet_parse_simple() | """
Tests Parquet parser by comparing the summary of the original csv frame with the h2o parsed Parquet frame.
Basic use case of importing files with auto-detection of column types.
:return: None if passed. Otherwise, an exception will be thrown.
"""
csv = h2o.import_file(path=pyunit_utils.locate("... | identifier_body |
pyunit_parquet_parser_simple.py | from __future__ import print_function
import sys
sys.path.insert(1,"../../")
import h2o
from tests import pyunit_utils
| :return: None if passed. Otherwise, an exception will be thrown.
"""
csv = h2o.import_file(path=pyunit_utils.locate("smalldata/airlines/AirlinesTrain.csv.zip"))
parquet = h2o.import_file(path=pyunit_utils.locate("smalldata/parser/parquet/airlines-simple.snappy.parquet"))
csv.summary()
csv_summ... |
def parquet_parse_simple():
"""
Tests Parquet parser by comparing the summary of the original csv frame with the h2o parsed Parquet frame.
Basic use case of importing files with auto-detection of column types. | random_line_split |
pyunit_parquet_parser_simple.py | from __future__ import print_function
import sys
sys.path.insert(1,"../../")
import h2o
from tests import pyunit_utils
def | ():
"""
Tests Parquet parser by comparing the summary of the original csv frame with the h2o parsed Parquet frame.
Basic use case of importing files with auto-detection of column types.
:return: None if passed. Otherwise, an exception will be thrown.
"""
csv = h2o.import_file(path=pyunit_utils.... | parquet_parse_simple | identifier_name |
scroll-register.spec.ts | import * as Models from '../../src/models';
import { Observable } from 'rxjs';
import * as ScrollRegister from '../../src/services/scroll-register';
import * as ScrollResolver from '../../src/services/scroll-resolver';
import { ElementRef } from '@angular/core';
describe('Scroll Regsiter', () => {
let mockedElement:... | const expected = 3;
expect(Object.keys(actual).length).toEqual(expected);
});
describe('toInfiniteScrollAction', () => {
let response;
beforeEach(() => {
response = {
stats: {
scrolled: 100
}
} as Models.IScrollParams;
});
[
{
it: 'shoul... | shouldFireScrollEvent: true
};
spyOn(ScrollResolver, 'getScrollStats').and.returnValue(scrollStats);
const actual = ScrollRegister.toInfiniteScrollParams(lastScrollPosition, positionStats, distance); | random_line_split |
thread_comm.rs | extern crate alloc;
use core::ptr::{self};
use std::sync::{Arc,RwLock};
//use std::sync::{Barrier};
use std::sync::atomic::{AtomicPtr,AtomicUsize,AtomicBool,Ordering};
pub struct ThreadComm<T> {
n_threads: usize,
//Slot has a MatrixBuffer, to be broadcast
slot: AtomicPtr<T>,
//Slot_reads represents t... |
pub fn split(&self, n_way: usize) -> ThreadInfo<T> {
let subcomm = self.comm.split(self.thread_id, n_way);
let subcomm_id = self.thread_id % (self.comm.n_threads / n_way);
ThreadInfo{ thread_id: subcomm_id, comm: subcomm }
}
}
| { self.thread_id } | identifier_body |
thread_comm.rs | extern crate alloc;
use core::ptr::{self};
use std::sync::{Arc,RwLock};
//use std::sync::{Barrier};
use std::sync::atomic::{AtomicPtr,AtomicUsize,AtomicBool,Ordering};
pub struct ThreadComm<T> {
n_threads: usize,
//Slot has a MatrixBuffer, to be broadcast
slot: AtomicPtr<T>,
//Slot_reads represents t... |
//self.barrier.wait();
}
fn broadcast(&self, info: &ThreadInfo<T>, to_send: *mut T) -> *mut T {
if info.thread_id == 0 {
//Spin while waiting for the thread communicator to be ready to broadcast
while self.slot_reads.load(Ordering::Relaxed) != self.n_threads ... | {
while self.barrier_sense.load(Ordering::Relaxed) == my_sense { }
} | conditional_block |
thread_comm.rs | extern crate alloc;
use core::ptr::{self};
use std::sync::{Arc,RwLock};
//use std::sync::{Barrier};
use std::sync::atomic::{AtomicPtr,AtomicUsize,AtomicBool,Ordering};
pub struct ThreadComm<T> {
n_threads: usize,
//Slot has a MatrixBuffer, to be broadcast
slot: AtomicPtr<T>,
//Slot_reads represents t... | (&self, info: &ThreadInfo<T>, to_send: *mut T) -> *mut T {
if info.thread_id == 0 {
//Spin while waiting for the thread communicator to be ready to broadcast
while self.slot_reads.load(Ordering::Relaxed) != self.n_threads {
}
self.slot.store(to_send, Orde... | broadcast | identifier_name |
thread_comm.rs | extern crate alloc;
use core::ptr::{self};
use std::sync::{Arc,RwLock};
//use std::sync::{Barrier};
use std::sync::atomic::{AtomicPtr,AtomicUsize,AtomicBool,Ordering};
pub struct ThreadComm<T> {
n_threads: usize,
//Slot has a MatrixBuffer, to be broadcast
slot: AtomicPtr<T>,
//Slot_reads represents t... | //If slot_reads < n_threads, it is ready to be read.
//Each thread is only allowed to read from the slot one time.
//It is incremented every time slot is read,
//And it is an integer modulo n_threads
slot_reads: AtomicUsize,
//barrier: Barrier,
//Stuff for barriers
barrier_sense: Atomi... | //If slot_reads == n_threads, then it is ready to be written to. | random_line_split |
gui.MlExtension.js | /**
* -----------------------------------------------------------------------------
*
* @review isipka
*
* -----------------------------------------------------------------------------
*/
/**
* Basic ML extensions class. Extensions purpose is rendering of observer value,
* implementation of input methods, etc.... |
return obj;
}
/**
* Returns new instance of chosen <b>sctype</b> extension type.
* @static
* @public
* @function
* @param {FM.AppObject} app Current application.
* @param {object} attrs Extension attributes.
* @param {node} node Extension node.
* @param {String} type Extension subclass type.
*... | {
obj = list['GLOBAL'][name];
} | conditional_block |
gui.MlExtension.js | /**
* -----------------------------------------------------------------------------
*
* @review isipka
*
* -----------------------------------------------------------------------------
*/
/**
* Basic ML extensions class. Extensions purpose is rendering of observer value,
* implementation of input methods, etc.... | FM.MlExtension.prototype.update = function(obs) {
}
/**
* Returns observer this extension belongs to.
*
* @public
* @function
* @returns {FM.MlObserver}
*/
FM.MlExtension.prototype.getObserver = function() {
return this.observer ? this.observer : null;
}
/**
* Returns host this extension belongs to.
* ... | * @function
* @param {FM.MlObserver} obs Observer extension belongs to.
*/ | random_line_split |
GeometricObject.ts | /// <reference path="Vector.ts" />
/// <reference path="SceneObject.ts" />
module RT {
export var EPSILON = 0.000001;
export class Ray {
constructor(public origin: Vector, public direction: Vector) { }
inchForward() {
this.origin.add(this.direction.scaledBy(EPSILON));
}
... | }
export class RayIntersection extends BasicRayIntersection {
point: Vector;
normal: Vector;
incident: Vector;
object: SceneObject = null;
}
export abstract class GeometricObject {
findNormal(intersection: RayIntersection): Vector {
var normal = this... | geometricData: number; | random_line_split |
GeometricObject.ts | /// <reference path="Vector.ts" />
/// <reference path="SceneObject.ts" />
module RT {
export var EPSILON = 0.000001;
export class Ra |
constructor(public origin: Vector, public direction: Vector) { }
inchForward() {
this.origin.add(this.direction.scaledBy(EPSILON));
}
}
export class BasicRayIntersection {
t: number;
u: number;
v: number;
geometricData: number;
}
ex... | y { | identifier_name |
app.module.ts | import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { AppComponent } from './app.component';
import { BoardComponent } from './games/board/board.component';
import { MovesCo... | { }
| AppModule | identifier_name |
app.module.ts | import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { AppComponent } from './app.component';
import { BoardComponent } from './games/board/board.component';
import { MovesCo... | WelcomeComponent,
HeaderComponent,
LoginComponent,
RegisterComponent,
TypeListComponent,
GameListComponent,
GameComponent,
WrapperComponent,
CellComponent
],
imports: [
BrowserModule,
FormsModule,
HttpModule,
... | AppComponent,
BoardComponent,
MovesComponent, | random_line_split |
keys.py | name):
"""Returns a boolean indicating whether key ``name`` exists"""
return await self.execute_command('EXISTS', name)
async def expire(self, name, time):
"""
Set an expire flag on key ``name`` for ``time`` seconds. ``time``
can be represented by an integer or a Python tim... | count += await self.execute_command('DEL', arg) | conditional_block | |
keys.py | in ('idletime', 'refcount'):
return int_or_none(response)
return response
def parse_scan(response, **options):
cursor, r = response
return int(cursor), r
class KeysCommandMixin:
RESPONSE_CALLBACKS = dict_merge(
string_keys_to_dict(
'EXISTS EXPIRE EXPIREAT '
... | rename | identifier_name | |
keys.py | in range(n)]))
def parse_object(response, infotype):
"""Parse the results of an OBJECT command"""
if infotype in ('idletime', 'refcount'):
return int_or_none(response)
return response
def parse_scan(response, **options):
cursor, r = response
return int(cursor), r
class KeysCommandMixi... |
async def keys(self, pattern='*'):
"""Returns a list of keys matching ``pattern``"""
return await self.execute_command('KEYS', pattern)
async def move(self, name, db):
"""Moves the key ``name`` to a different Redis database ``db``"""
return await self.execute_command('MOVE', n... | """
Set an expire flag on key ``name``. ``when`` can be represented
as an integer indicating unix time or a Python datetime object.
"""
if isinstance(when, datetime.datetime):
when = int(mod_time.mktime(when.timetuple()))
return await self.execute_command('EXPIREAT', ... | identifier_body |
keys.py | in range(n)]))
def parse_object(response, infotype):
"""Parse the results of an OBJECT command"""
if infotype in ('idletime', 'refcount'):
return int_or_none(response)
return response
def parse_scan(response, **options):
cursor, r = response
return int(cursor), r
class KeysCommandMixi... | return await self.execute_command('DUMP', name)
async def exists(self, name):
"""Returns a boolean indicating whether key ``name`` exists"""
return await self.execute_command('EXISTS', name)
async def expire(self, name, time):
"""
Set an expire flag on key ``name`` for ... | """ | random_line_split |
trait-inheritance-subst2.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 ... |
pub fn main() {
let (x, y) = (mi(3), mi(5));
let z = f(x, y);
assert_eq!(z.val, 13);
}
| { MyInt { val: v } } | identifier_body |
trait-inheritance-subst2.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 ... | fn add(&self, other: &MyInt) -> MyInt { self.chomp(other) }
}
impl MyNum for MyInt {}
fn f<T:MyNum>(x: T, y: T) -> T {
return x.add(&y).chomp(&y);
}
fn mi(v: isize) -> MyInt { MyInt { val: v } }
pub fn main() {
let (x, y) = (mi(3), mi(5));
let z = f(x, y);
assert_eq!(z.val, 13);
} | }
impl Add<MyInt, MyInt> for MyInt { | random_line_split |
trait-inheritance-subst2.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 ... | (&self, other: &MyInt) -> MyInt { self.chomp(other) }
}
impl MyNum for MyInt {}
fn f<T:MyNum>(x: T, y: T) -> T {
return x.add(&y).chomp(&y);
}
fn mi(v: isize) -> MyInt { MyInt { val: v } }
pub fn main() {
let (x, y) = (mi(3), mi(5));
let z = f(x, y);
assert_eq!(z.val, 13);
}
| add | identifier_name |
http-server.rs | extern crate mioco;
extern crate env_logger;
extern crate httparse;
use std::net::SocketAddr;
use std::str::FromStr;
use std::io::{self, Write, Read};
use mioco::net::TcpListener;
const DEFAULT_LISTEN_ADDR: &'static str = "127.0.0.1:5555";
fn listend_addr() -> SocketAddr {
FromStr::from_str(DEFAULT_LISTEN_ADDR).... |
}
});
}
})
})
.collect();
joins.drain(..).map(|join| join.join().unwrap()).count();
})
.join()
.unwrap();
}
| {
let req_len = res.unwrap();
match req.path {
Some(ref _path) => {
let _ = conn.write_all(&RESPONSE.as_bytes())?;
if re... | conditional_block |
http-server.rs | extern crate mioco;
extern crate env_logger;
extern crate httparse;
use std::net::SocketAddr;
use std::str::FromStr;
use std::io::{self, Write, Read};
use mioco::net::TcpListener;
const DEFAULT_LISTEN_ADDR: &'static str = "127.0.0.1:5555";
fn listend_addr() -> SocketAddr {
FromStr::from_str(DEFAULT_LISTEN_ADDR).... | loop {
let mut headers = [httparse::EMPTY_HEADER; 16];
let len = conn.read(&mut buf[buf_i..])?;
if len == 0 {
return Ok(());
}
... | {
env_logger::init();
let addr = listend_addr();
let listener = TcpListener::bind(&addr).unwrap();
println!("Starting mioco http server on {:?}",
listener.local_addr().unwrap());
mioco::spawn(move || {
let mut joins: Vec<_> = (0..mioco::thread_num())
.map(|_| {
... | identifier_body |
http-server.rs | extern crate mioco;
extern crate env_logger;
extern crate httparse;
use std::net::SocketAddr;
use std::str::FromStr;
use std::io::{self, Write, Read};
use mioco::net::TcpListener;
const DEFAULT_LISTEN_ADDR: &'static str = "127.0.0.1:5555";
fn listend_addr() -> SocketAddr {
FromStr::from_str(DEFAULT_LISTEN_ADDR).... | () {
env_logger::init();
let addr = listend_addr();
let listener = TcpListener::bind(&addr).unwrap();
println!("Starting mioco http server on {:?}",
listener.local_addr().unwrap());
mioco::spawn(move || {
let mut joins: Vec<_> = (0..mioco::thread_num())
.map(|_| {... | main | identifier_name |
http-server.rs | extern crate mioco;
extern crate env_logger;
extern crate httparse;
use std::net::SocketAddr;
use std::str::FromStr;
use std::io::{self, Write, Read};
use mioco::net::TcpListener;
const DEFAULT_LISTEN_ADDR: &'static str = "127.0.0.1:5555";
fn listend_addr() -> SocketAddr {
FromStr::from_str(DEFAULT_LISTEN_ADDR).... | }
});
}
})
})
.collect();
joins.drain(..).map(|join| join.join().unwrap()).count();
})
.join()
.unwrap();
} | } | random_line_split |
helpers.rs | use handlebars::*;
use serde_json::value::Value;
use serde_json::Map;
#[derive(PartialEq)]
enum Kind {
Object,
Array,
String,
Number,
Boolean,
Null,
}
struct IsKind {
kind: Kind,
}
impl HelperDef for IsKind {
fn call(&self, h: &Helper, r: &Handlebars, rc: &mut RenderContext) -> Result... | else {
h.inverse()
} {
Some(ref t) => t.render(r, rc),
None => Ok(()),
}
}
}
fn include_helper(h: &Helper, r: &Handlebars, rc: &mut RenderContext) -> Result<(), RenderError> {
let param = h.param(0)
.ok_or(RenderError::new("Param expected... | {
h.template()
} | conditional_block |
helpers.rs | use handlebars::*;
use serde_json::value::Value;
use serde_json::Map;
#[derive(PartialEq)]
enum Kind {
Object,
Array,
String,
Number,
Boolean,
Null,
}
struct IsKind {
kind: Kind,
}
impl HelperDef for IsKind {
fn call(&self, h: &Helper, r: &Handlebars, rc: &mut RenderContext) -> Result... | hb.register_decorator("annotate", Box::new(annotate_decorator));
} | hb.register_helper("if_null", Box::new(IsKind { kind: Kind::Null }));
hb.register_helper("include", Box::new(include_helper)); | random_line_split |
helpers.rs | use handlebars::*;
use serde_json::value::Value;
use serde_json::Map;
#[derive(PartialEq)]
enum | {
Object,
Array,
String,
Number,
Boolean,
Null,
}
struct IsKind {
kind: Kind,
}
impl HelperDef for IsKind {
fn call(&self, h: &Helper, r: &Handlebars, rc: &mut RenderContext) -> Result<(), RenderError> {
let param = h.param(0)
.ok_or(RenderError::new("Param expecte... | Kind | identifier_name |
helpers.rs | use handlebars::*;
use serde_json::value::Value;
use serde_json::Map;
#[derive(PartialEq)]
enum Kind {
Object,
Array,
String,
Number,
Boolean,
Null,
}
struct IsKind {
kind: Kind,
}
impl HelperDef for IsKind {
fn call(&self, h: &Helper, r: &Handlebars, rc: &mut RenderContext) -> Result... |
fn annotate_decorator(_: &Decorator,
_: &Handlebars,
rc: &mut RenderContext)
-> Result<(), RenderError> {
fn annotate_map(map: &mut Map<String, Value>) {
for (k, v) in map {
if let Some(ref mut m) = v.as_object_mut().as_mut() {
... | {
let param = h.param(0)
.ok_or(RenderError::new("Param expected for helper"))?;
match param.value().as_str() {
Some(s) => {
match r.get_template(s) {
Some(t) => t.render(r, rc),
None => Err(RenderError::new("Template not found")),
}
... | identifier_body |
fr.js | /*
*
* Date.addLocale(<code>) adds this locale to Sugar.
* To set the locale globally, simply call:
*
* Date.setLocale('fr');
*
* var locale = Date.getLocale(<code>) will return this object, which
* can be tweaked to change the behavior of parsing/formatting in the locales.
*
* locale.addFormat adds a date fo... | *
* Additionally in the months, weekdays, units, and numbers array these will be added at indexes that are multiples
* of the relevant number for retrieval. For example having "sunday:|s" in the units array will result in:
*
* units: ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 's... | * all entries in the modifiers array follow a special format indicated by a colon:
*
* minute:|s = minute|minutes
* thicke:n|r = thicken|thicker | random_line_split |
views.py | + str(coords[2]) + ',' + str(coords[3])
url = url + "&tags=%s&per_page=%s&has_geo=1&bbox=%s&format=json&extras=geo,url_q&accuracy=1&nojsoncallback=1" % (query,maxResults,newbbox)
feed_response = urllib.urlopen(url).read()
return HttpResponse(feed_response, mimetype="text/xml")
def hglpoints (request):
... | youtube | identifier_name | |
views.py | # ows exceptions
if "<ows:ExceptionReport" in responseContent:
return responseContent
if responseContent[0] == "<":
try:
from defusedxml.ElementTree import fromstring
et = fromstring(responseContent)
if re.match(_valid_tags, et.tag):
return r... |
def tweetTrendProxy (request):
tweetUrl = "http://" + settings.AWS_INSTANCE_IP + "/?agg=trend&bounds=" + request.POST["bounds"] + "&dateStart=" + request.POST["dateStart"] + "&dateEnd=" + request.POST["dateEnd"];
resultJSON =""
# resultJSON = urllib.urlopen(tweetUrl).read()
# import datetime
#
#
# ... | if (not request.user.is_authenticated() or not request.user.get_profile().is_org_member):
return HttpResponse(status=403)
proxy_url = urlsplit(request.get_full_path())
download_url = "http://" + settings.GEOPS_IP + "?" + proxy_url.query + settings.GEOPS_DOWNLOAD
http = httplib2.Http()
respon... | identifier_body |
views.py | # ows exceptions
if "<ows:ExceptionReport" in responseContent:
return responseContent
if responseContent[0] == "<":
try:
from defusedxml.ElementTree import fromstring
et = fromstring(responseContent)
if re.match(_valid_tags, et.tag):
return r... |
step1 = urllib.urlopen(tweet_url)
step2 = step1.read()
if 'content-type' in step1.info().dict:
response = HttpResponse(step2, mimetype= step1.info().dict['content-type'])
else:
response = HttpResponse(step2)
try :
cookie = step1.info().dict['set-cookie'].split(";")[0].split... | if re.search("%20limit%2010&", tweet_url)is None:
return HttpResponse(status=403) | conditional_block |
views.py | feed_response = urllib.urlopen(url).read()
return HttpResponse(feed_response, mimetype="text/xml")
def hglpoints (request):
from xml.dom import minidom
import re
url = HGL_URL + "/HGLGeoRSS?GeometryType=point"
bbox = ["-180","-90","180","90"]
max_results = request.GET['max-results'] if reques... | query = request.GET['q'] if request.method == 'GET' else request.POST['q'] | random_line_split | |
outlineViewState.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... |
restore(storageService: IStorageService): void {
let raw = storageService.get('outline/state', StorageScope.WORKSPACE);
if (!raw) {
return;
}
let data: any;
try {
data = JSON.parse(raw);
} catch (e) {
return;
}
this.followCursor = data.followCursor;
this.sortBy = data.sortBy ?? OutlineSort... | {
storageService.store('outline/state', JSON.stringify({
followCursor: this.followCursor,
sortBy: this.sortBy,
filterOnType: this.filterOnType,
}), StorageScope.WORKSPACE, StorageTarget.USER);
} | identifier_body |
outlineViewState.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... |
}
get followCursor(): boolean {
return this._followCursor;
}
get filterOnType() {
return this._filterOnType;
}
set filterOnType(value) {
if (value !== this._filterOnType) {
this._filterOnType = value;
this._onDidChange.fire({ filterOnType: true });
}
}
set sortBy(value: OutlineSortOrder) {
... | {
this._followCursor = value;
this._onDidChange.fire({ followCursor: true });
} | conditional_block |
outlineViewState.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | this._sortBy = value;
this._onDidChange.fire({ sortBy: true });
}
}
get sortBy(): OutlineSortOrder {
return this._sortBy;
}
persist(storageService: IStorageService): void {
storageService.store('outline/state', JSON.stringify({
followCursor: this.followCursor,
sortBy: this.sortBy,
filterOnTyp... |
set sortBy(value: OutlineSortOrder) {
if (value !== this._sortBy) { | random_line_split |
outlineViewState.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | (value: boolean) {
if (value !== this._followCursor) {
this._followCursor = value;
this._onDidChange.fire({ followCursor: true });
}
}
get followCursor(): boolean {
return this._followCursor;
}
get filterOnType() {
return this._filterOnType;
}
set filterOnType(value) {
if (value !== this._filte... | followCursor | identifier_name |
session-card.component.ts | import { Component, OnInit, OnDestroy, Input} from '@angular/core';
import { Router } from '@angular/router';
import { FirebaseAuthState } from 'angularfire2';
import { UUID } from 'angular2-uuid';
import { AuthService } from '../shared/security/auth.service';
import { Session } from '../shared/model/session';
import ... | () {
return this.type === 'pending' && this.user && this.user.$key !== this.authInfo.uid;
}
get sessionStatus() {
if (this.isPending) {
return 'pending';
} else if (this.inSession) {
return 'inSession';
}
return 'notInSession';
}
get inSession() {
return this.isTutor || this.isTutee;
}
constr... | displayPendingUserPic | identifier_name |
session-card.component.ts | import { Component, OnInit, OnDestroy, Input} from '@angular/core';
import { Router } from '@angular/router';
import { FirebaseAuthState } from 'angularfire2';
import { UUID } from 'angular2-uuid';
import { AuthService } from '../shared/security/auth.service';
import { Session } from '../shared/model/session';
import ... |
get role() {
if (this.isTutor) {
return 'tutor';
} else if (this.isTutee) {
return 'tutee';
}
return null;
}
get isTutor() {
if (!this.authInfo) {
return false;
}
return this.session.tutor.$key === this.authInfo.uid;
}
get isTutee() {
if (!this.authInfo) {
return false;
}
return... | {
return this.session.end.format('h:mm');
} | identifier_body |
session-card.component.ts | import { Component, OnInit, OnDestroy, Input} from '@angular/core';
import { Router } from '@angular/router';
import { FirebaseAuthState } from 'angularfire2';
import { UUID } from 'angular2-uuid';
import { AuthService } from '../shared/security/auth.service';
import { Session } from '../shared/model/session';
import ... |
return this.session.tutor.$key === this.authInfo.uid;
}
get isTutee() {
if (!this.authInfo) {
return false;
}
return this.session.tutees.some(user => user.$key === this.authInfo.uid);
}
get isPending() {
if (!this.authInfo) {
return false;
}
return this.session.pending.includes(this.authInfo.... | {
return false;
} | conditional_block |
session-card.component.ts | import { Component, OnInit, OnDestroy, Input} from '@angular/core';
import { Router } from '@angular/router';
import { FirebaseAuthState } from 'angularfire2';
import { UUID } from 'angular2-uuid';
import { AuthService } from '../shared/security/auth.service';
import { Session } from '../shared/model/session';
import ... | }
get isPending() {
if (!this.authInfo) {
return false;
}
return this.session.pending.includes(this.authInfo.uid);
}
get displayPendingUserPic() {
return this.type === 'pending' && this.user && this.user.$key !== this.authInfo.uid;
}
get sessionStatus() {
if (this.isPending) {
return 'pending';... | }
return this.session.tutees.some(user => user.$key === this.authInfo.uid); | random_line_split |
test_auth_basic.py | """Test code for iiif.auth_basic.
See http://flask.pocoo.org/docs/0.10/testing/ for Flask notes.
"""
from flask import Flask, request, make_response, redirect
from werkzeug.datastructures import Headers
import base64
import json
import re
import unittest
from iiif.auth_basic import IIIFAuthBasic
dummy_app = Flask('d... | def test02_logout_service_description(self):
"""Test logout_service_description."""
auth = IIIFAuthBasic()
auth.logout_uri = 'xyz'
lsd = auth.logout_service_description()
self.assertEqual(lsd['profile'], 'http://iiif.io/api/auth/1/logout')
self.assertEqual(lsd['@id'],... | self.assertEqual(auth.cookie_prefix, 'abc')
| random_line_split |
test_auth_basic.py | """Test code for iiif.auth_basic.
See http://flask.pocoo.org/docs/0.10/testing/ for Flask notes.
"""
from flask import Flask, request, make_response, redirect
from werkzeug.datastructures import Headers
import base64
import json
import re
import unittest
from iiif.auth_basic import IIIFAuthBasic
dummy_app = Flask('d... |
def test02_logout_service_description(self):
"""Test logout_service_description."""
auth = IIIFAuthBasic()
auth.logout_uri = 'xyz'
lsd = auth.logout_service_description()
self.assertEqual(lsd['profile'], 'http://iiif.io/api/auth/1/logout')
self.assertEqual(lsd['@id'... | """Test inialization."""
auth = IIIFAuthBasic()
self.assertTrue(re.match(r'\d+_', auth.cookie_prefix))
auth = IIIFAuthBasic(cookie_prefix='abc')
self.assertEqual(auth.cookie_prefix, 'abc') | identifier_body |
test_auth_basic.py | """Test code for iiif.auth_basic.
See http://flask.pocoo.org/docs/0.10/testing/ for Flask notes.
"""
from flask import Flask, request, make_response, redirect
from werkzeug.datastructures import Headers
import base64
import json
import re
import unittest
from iiif.auth_basic import IIIFAuthBasic
dummy_app = Flask('d... | (self):
"""Test logout_service_description."""
auth = IIIFAuthBasic()
auth.logout_uri = 'xyz'
lsd = auth.logout_service_description()
self.assertEqual(lsd['profile'], 'http://iiif.io/api/auth/1/logout')
self.assertEqual(lsd['@id'], 'xyz')
self.assertEqual(lsd['lab... | test02_logout_service_description | identifier_name |
files.contribution.ts | arts/editor/baseEditor';
import { FILE_EDITOR_INPUT_ID, VIEWLET_ID } from 'vs/workbench/parts/files/common/files';
import { FileEditorTracker } from 'vs/workbench/parts/files/common/editors/fileEditorTracker';
import { SaveErrorHandler } from 'vs/workbench/parts/files/browser/saveErrorHandler';
import { FileEditorInput... |
public serialize(editorInput: EditorInput): string {
const fileEditorInput = <FileEditorInput>editorInput;
const fileInput: ISerializedFileInput = {
resource: fileEditorInput.getResource().toString()
};
return JSON.stringify(fileInput);
}
public deserialize(instantiationService: IInstantiationService,... | { } | identifier_body |
files.contribution.ts | import { Registry } from 'vs/platform/platform';
import { IConfigurationRegistry, Extensions as ConfigurationExtensions } from 'vs/platform/configuration/common/configurationRegistry';
import { IWorkbenchActionRegistry, Extensions as ActionExtensions } from 'vs/workbench/common/actionRegistry';
import { IWorkbenchContr... | import URI from 'vs/base/common/uri';
import { ViewletRegistry, Extensions as ViewletExtensions, ViewletDescriptor, ToggleViewletAction } from 'vs/workbench/browser/viewlet';
import nls = require('vs/nls');
import { SyncActionDescriptor } from 'vs/platform/actions/common/actions'; | random_line_split | |
files.contribution.ts | arts/editor/baseEditor';
import { FILE_EDITOR_INPUT_ID, VIEWLET_ID } from 'vs/workbench/parts/files/common/files';
import { FileEditorTracker } from 'vs/workbench/parts/files/common/editors/fileEditorTracker';
import { SaveErrorHandler } from 'vs/workbench/parts/files/browser/saveErrorHandler';
import { FileEditorInput... | () { }
public serialize(editorInput: EditorInput): string {
const fileEditorInput = <FileEditorInput>editorInput;
const fileInput: ISerializedFileInput = {
resource: fileEditorInput.getResource().toString()
};
return JSON.stringify(fileInput);
}
public deserialize(instantiationService: IInstantiationSe... | constructor | identifier_name |
pytest_makevers.py | import os
import shutil
import pytest
from ..pyautoupdate.launcher import Launcher
@pytest.fixture(scope='function')
def | (request):
"""Fixture that creates and tears down version.txt and log files"""
def create_update_dir(version="0.0.1"):
def teardown():
if os.path.isfile(Launcher.version_check_log):
os.remove(Launcher.version_check_log)
if os.path.isfile(Launcher.version_doc):
... | fixture_update_dir | identifier_name |
pytest_makevers.py | import os
import shutil
import pytest
from ..pyautoupdate.launcher import Launcher
@pytest.fixture(scope='function')
def fixture_update_dir(request):
"""Fixture that creates and tears down version.txt and log files"""
def create_update_dir(version="0.0.1"):
def teardown():
if os.path.isfil... |
if os.path.isfile(Launcher.version_doc):
os.remove(Launcher.version_doc)
request.addfinalizer(teardown)
with open(Launcher.version_doc, mode='w') as version_file:
version_file.write(version)
return fixture_update_dir
return create_update_dir
@pytest.... | os.remove(Launcher.version_check_log) | conditional_block |
pytest_makevers.py | import os
import shutil
import pytest
from ..pyautoupdate.launcher import Launcher |
@pytest.fixture(scope='function')
def fixture_update_dir(request):
"""Fixture that creates and tears down version.txt and log files"""
def create_update_dir(version="0.0.1"):
def teardown():
if os.path.isfile(Launcher.version_check_log):
os.remove(Launcher.version_check_log)... | random_line_split | |
pytest_makevers.py | import os
import shutil
import pytest
from ..pyautoupdate.launcher import Launcher
@pytest.fixture(scope='function')
def fixture_update_dir(request):
"""Fixture that creates and tears down version.txt and log files"""
def create_update_dir(version="0.0.1"):
def teardown():
|
request.addfinalizer(teardown)
with open(Launcher.version_doc, mode='w') as version_file:
version_file.write(version)
return fixture_update_dir
return create_update_dir
@pytest.fixture(scope='function')
def create_update_dir(request):
"""Fixture that tears down downloads di... | if os.path.isfile(Launcher.version_check_log):
os.remove(Launcher.version_check_log)
if os.path.isfile(Launcher.version_doc):
os.remove(Launcher.version_doc) | identifier_body |
change_detection_util.js | /**
* @license
* Copyright Google Inc. 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 { areIterablesEqual, isListLikeIterable } from '../facade/collection';
import { isPrimitive, looseIdentical } ... | * }
* ```
* @stable
*/
export var WrappedValue = (function () {
function WrappedValue(wrapped) {
this.wrapped = wrapped;
}
WrappedValue.wrap = function (value) { return new WrappedValue(value); };
return WrappedValue;
}());
/**
* Helper class for unwrapping WrappedValue s
*/
export var Va... | * } else {
* this._latestReturnedValue = this._latestValue;
* return WrappedValue.wrap(this._latestValue); // this will force update | random_line_split |
change_detection_util.js | /**
* @license
* Copyright Google Inc. 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 { areIterablesEqual, isListLikeIterable } from '../facade/collection';
import { isPrimitive, looseIdentical } ... | (a, b) {
if (isListLikeIterable(a) && isListLikeIterable(b)) {
return areIterablesEqual(a, b, devModeEqual);
}
else if (!isListLikeIterable(a) && !isPrimitive(a) && !isListLikeIterable(b) && !isPrimitive(b)) {
return true;
}
else {
return looseIdentical(a, b);
}
}
/**
* ... | devModeEqual | identifier_name |
change_detection_util.js | /**
* @license
* Copyright Google Inc. 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 { areIterablesEqual, isListLikeIterable } from '../facade/collection';
import { isPrimitive, looseIdentical } ... |
}
/**
* Indicates that the result of a {@link PipeMetadata} transformation has changed even though the
* reference
* has not changed.
*
* The wrapped value will be unwrapped by change detection, and the unwrapped value will be stored.
*
* Example:
*
* ```
* if (this._latestValue === this._latestReturnedValue... | {
return looseIdentical(a, b);
} | conditional_block |
change_detection_util.js | /**
* @license
* Copyright Google Inc. 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 { areIterablesEqual, isListLikeIterable } from '../facade/collection';
import { isPrimitive, looseIdentical } ... |
WrappedValue.wrap = function (value) { return new WrappedValue(value); };
return WrappedValue;
}());
/**
* Helper class for unwrapping WrappedValue s
*/
export var ValueUnwrapper = (function () {
function ValueUnwrapper() {
this.hasWrappedValue = false;
}
ValueUnwrapper.prototype.unwrap =... | {
this.wrapped = wrapped;
} | identifier_body |
gpdma0_ch2.rs | #[doc = r"Register block"]
#[repr(C)]
pub struct RegisterBlock {
#[doc = "0x00 - Source Address Register"]
pub sar: crate::Reg<sar::SAR_SPEC>,
_reserved1: [u8; 0x04],
#[doc = "0x08 - Destination Address Register"]
pub dar: crate::Reg<dar::DAR_SPEC>,
_reserved2: [u8; 0x0c],
#[doc = "0x18 - Co... | pub mod dar;
#[doc = "CTLL register accessor: an alias for `Reg<CTLL_SPEC>`"]
pub type CTLL = crate::Reg<ctll::CTLL_SPEC>;
#[doc = "Control Register Low"]
pub mod ctll;
#[doc = "CTLH register accessor: an alias for `Reg<CTLH_SPEC>`"]
pub type CTLH = crate::Reg<ctlh::CTLH_SPEC>;
#[doc = "Control Register High"]
pub mod ... | #[doc = "Destination Address Register"] | random_line_split |
gpdma0_ch2.rs | #[doc = r"Register block"]
#[repr(C)]
pub struct | {
#[doc = "0x00 - Source Address Register"]
pub sar: crate::Reg<sar::SAR_SPEC>,
_reserved1: [u8; 0x04],
#[doc = "0x08 - Destination Address Register"]
pub dar: crate::Reg<dar::DAR_SPEC>,
_reserved2: [u8; 0x0c],
#[doc = "0x18 - Control Register Low"]
pub ctll: crate::Reg<ctll::CTLL_SPEC>... | RegisterBlock | identifier_name |
buffer.d.ts | import { Observable } from '../Observable';
import { OperatorFunction } from '../types'; | * that array only when another Observable emits.</span>
*
* 
*
* Buffers the incoming Observable values until the given `closingNotifier`
* Observable emits a value, at which point it emits the buffer on the output
* Observable and starts a new buffer internally, awaiting the next time... | /**
* Buffers the source Observable values until `closingNotifier` emits.
*
* <span class="informal">Collects values from the past as an array, and emits | random_line_split |
agp2camsa_points.py | .dirname(os.path.dirname(os.path.abspath(__file__))))))
import camsa
import camsa.core.io as camsa_io
from camsa.core.data_structures import AssemblyPoint
class Component(object):
def __init__(self, object_id, object_beg, object_end, part_number, component_type):
self.object_id = object_id
self.o... |
if __name__ == "__main__":
full_description = camsa.full_description_template.format(
names=camsa.CAMSA_AUTHORS,
affiliations=camsa.AFFILIATIONS,
dummy=" ",
tool="Converting AGPv2.0 formatted scaffolding results for further CAMSA processing.",
information="For more informa... | result = []
components = object_as_components
f_non_gap_element = get_index_of_first_non_gap_element(component_sequence=components)
current_element = components[f_non_gap_element]
current_index = f_non_gap_element
next_index, next_element = get_next_non_gap_element(components=components, current_ind... | identifier_body |
agp2camsa_points.py | .dirname(os.path.dirname(os.path.abspath(__file__))))))
import camsa
import camsa.core.io as camsa_io
from camsa.core.data_structures import AssemblyPoint
class Component(object):
def __init__(self, object_id, object_beg, object_end, part_number, component_type):
self.object_id = object_id
self.o... | help="Format string for python logger.")
parser.add_argument("agp", type=configargparse.FileType("rt"), nargs="+", default=sys.stdin,
help="Input stream of AGPv2 formatted scaffold assemblies\nDEFAULT: stdin")
parser.add_argument("--origin", type=str, default=Non... | parser.add_argument("--version", action="version", version=camsa.VERSION)
parser.add_argument("--c-logging-level", type=int,
choices=[logging.NOTSET, logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR, logging.CRITICAL],
help="Logging level for the conver... | random_line_split |
agp2camsa_points.py | (os.path.dirname(os.path.abspath(__file__))))))
import camsa
import camsa.core.io as camsa_io
from camsa.core.data_structures import AssemblyPoint
class Component(object):
def __init__(self, object_id, object_beg, object_end, part_number, component_type):
self.object_id = object_id
self.object_be... | (component_type):
return component_type not in ["U", "N"]
class ScaffoldComponent(Component):
def __init__(self, object_id, object_beg, object_end, part_number, component_type, component_id, component_beg, component_end, orientation):
super(ScaffoldComponent, self).__init__(object_id=object_id, ob... | is_scaffold_component | identifier_name |
agp2camsa_points.py | .dirname(os.path.dirname(os.path.abspath(__file__))))))
import camsa
import camsa.core.io as camsa_io
from camsa.core.data_structures import AssemblyPoint
class Component(object):
def __init__(self, object_id, object_beg, object_end, part_number, component_type):
self.object_id = object_id
self.o... |
gap_components = components[current_index+1:next_index]
result = 0
for component in gap_components:
assert component.is_gap_component
if component.component_type == "U":
return "?"
result += component.gap_length
return result
def camsa_orientation_from_agp(agp_or):... | return 1 | conditional_block |
nvd3-test-discreteBarChart.ts |
namespace nvd3_test_discreteBarChart {
var historicalBarChart = [
{
key: "Cumulative Return",
values: [
{
"label": "A",
"value": 29.765957771107
},
{
"label": "B",
... | .x(function (d) { return d.label })
.y(function (d) { return d.value })
.staggerLabels(true)
//.staggerLabels(historicalBarChart[0].values.length > 8)
.showValues(true)
.duration(250)
;
d3.select('#chart1 svg')
.dat... | var chart = nv.models.discreteBarChart() | random_line_split |
test_streamfile.py | import pytest
from mitmproxy.test import taddons
from mitmproxy.test import tflow
from mitmproxy import io
from mitmproxy import exceptions
from mitmproxy import options
from mitmproxy.addons import streamfile
def test_configure(tmpdir):
sa = streamfile.StreamFile()
with taddons.context(options=options.Opti... |
def test_tcp(tmpdir):
sa = streamfile.StreamFile()
with taddons.context() as tctx:
p = str(tmpdir.join("foo"))
tctx.configure(sa, streamfile=p)
tt = tflow.ttcpflow()
sa.tcp_start(tt)
sa.tcp_end(tt)
tctx.configure(sa, streamfile=None)
assert rd(p)
def t... | x = io.FlowReader(open(p, "rb"))
return list(x.stream())
| random_line_split |
test_streamfile.py | import pytest
from mitmproxy.test import taddons
from mitmproxy.test import tflow
from mitmproxy import io
from mitmproxy import exceptions
from mitmproxy import options
from mitmproxy.addons import streamfile
def test_configure(tmpdir):
sa = streamfile.StreamFile()
with taddons.context(options=options.Opti... |
def test_tcp(tmpdir):
sa = streamfile.StreamFile()
with taddons.context() as tctx:
p = str(tmpdir.join("foo"))
tctx.configure(sa, streamfile=p)
tt = tflow.ttcpflow()
sa.tcp_start(tt)
sa.tcp_end(tt)
tctx.configure(sa, streamfile=None)
assert rd(p)
def... | x = io.FlowReader(open(p, "rb"))
return list(x.stream()) | identifier_body |
test_streamfile.py | import pytest
from mitmproxy.test import taddons
from mitmproxy.test import tflow
from mitmproxy import io
from mitmproxy import exceptions
from mitmproxy import options
from mitmproxy.addons import streamfile
def test_configure(tmpdir):
sa = streamfile.StreamFile()
with taddons.context(options=options.Opti... | (p):
x = io.FlowReader(open(p, "rb"))
return list(x.stream())
def test_tcp(tmpdir):
sa = streamfile.StreamFile()
with taddons.context() as tctx:
p = str(tmpdir.join("foo"))
tctx.configure(sa, streamfile=p)
tt = tflow.ttcpflow()
sa.tcp_start(tt)
sa.tcp_end(tt)
... | rd | identifier_name |
ion-router-outlet.ts | ) {
this.nativeEl = elementRef.nativeElement;
this.name = name || PRIMARY_OUTLET;
this.tabsPrefix = tabs === 'true' ? getUrl(router, activatedRoute) : undefined;
this.stackCtrl = new StackController(this.tabsPrefix, this.nativeEl, router, navCtrl, zone, commonLocation);
parentContexts.onChildOutle... | {
return this.route;
} | conditional_block | |
ion-router-outlet.ts | IonRouterOutlet implements OnDestroy, OnInit {
nativeEl: HTMLIonRouterOutletElement;
private activated: ComponentRef<any> | null = null;
activatedView: RouteView | null = null;
private _activatedRoute: ActivatedRoute | null = null;
private _swipeGesture?: boolean;
private name: string;
private stackCtr... | (animation: AnimationBuilder) {
this.nativeEl.animation = animation;
}
set animated(animated: boolean) {
this.nativeEl.animated = animated;
}
set swipeGesture(swipe: boolean) {
this._swipeGesture = swipe;
this.nativeEl.swipeHandler = swipe ? {
canStart: () => this.stackCtrl.canGoBack(1)... | animation | identifier_name |
ion-router-outlet.ts | IonRouterOutlet implements OnDestroy, OnInit {
nativeEl: HTMLIonRouterOutletElement;
private activated: ComponentRef<any> | null = null;
activatedView: RouteView | null = null;
private _activatedRoute: ActivatedRoute | null = null;
private _swipeGesture?: boolean;
private name: string;
private stackCtr... | get activatedRouteData(): any {
if (this._activatedRoute) {
return this._activatedRoute.snapshot.data;
}
return {};
}
/**
* Called when the `RouteReuseStrategy` instructs to detach the subtree
*/
detach(): ComponentRef<any> {
throw new Error('incompatible reuse strategy');
}
/*... | }
| random_line_split |
enums.rs | use parking_lot::RwLock;
use std::collections::hash_map::HashMap;
use std::convert::TryInto;
use std::ops::Index;
use std::sync::Arc;
use dora_parser::ast;
use dora_parser::interner::Name;
use dora_parser::lexer::position::Position;
use crate::language::ty::{SourceType, SourceTypeArray};
use crate::utils::GrowableVe... | };
if let Some(&method_id) = table.get(&name) {
candidates.push(Candidate {
object_type: object_type.clone(),
container_type_params: bindings.clone(),
fct_id: method_id,
});
}
}
}... | &ximpl.static_names
} else {
&ximpl.instance_names | random_line_split |
enums.rs | use parking_lot::RwLock;
use std::collections::hash_map::HashMap;
use std::convert::TryInto;
use std::ops::Index;
use std::sync::Arc;
use dora_parser::ast;
use dora_parser::interner::Name;
use dora_parser::lexer::position::Position;
use crate::language::ty::{SourceType, SourceTypeArray};
use crate::utils::GrowableVe... |
}
}
candidates
}
| {
candidates.push(Candidate {
object_type: object_type.clone(),
container_type_params: bindings.clone(),
fct_id: method_id,
});
} | conditional_block |
enums.rs | use parking_lot::RwLock;
use std::collections::hash_map::HashMap;
use std::convert::TryInto;
use std::ops::Index;
use std::sync::Arc;
use dora_parser::ast;
use dora_parser::interner::Name;
use dora_parser::lexer::position::Position;
use crate::language::ty::{SourceType, SourceTypeArray};
use crate::utils::GrowableVe... | (data: usize) -> EnumInstanceId {
EnumInstanceId(data as u32)
}
}
impl GrowableVec<EnumInstance> {
pub fn idx(&self, index: EnumInstanceId) -> Arc<EnumInstance> {
self.idx_usize(index.0 as usize)
}
}
#[derive(Debug)]
pub struct EnumInstance {
pub id: EnumInstanceId,
pub enum_id: En... | from | identifier_name |
sudoku_solver_level_3_1.py | # https://www.codewars.com/kata/sudoku-solver/train/python
def sudoku(puzzle):
import collections
print('=== in sudoku ===')
# Print arguments
print_board(puzzle)
# Count the numbers that are currently populated on the sudoku board
number_count = collections.Counter(number for row in puzzle for number in row)... |
def print_dict(my_dict):
for key in sorted(my_dict):
print('{}: {}'.format(key, my_dict[key])) | print('-- print_board --')
for row in board:
print row | identifier_body |
sudoku_solver_level_3_1.py | # https://www.codewars.com/kata/sudoku-solver/train/python
def sudoku(puzzle):
import collections
print('=== in sudoku ===')
# Print arguments
print_board(puzzle)
# Count the numbers that are currently populated on the sudoku board
number_count = collections.Counter(number for row in puzzle for number in row)... | (my_dict):
for key in sorted(my_dict):
print('{}: {}'.format(key, my_dict[key])) | print_dict | identifier_name |
sudoku_solver_level_3_1.py | # https://www.codewars.com/kata/sudoku-solver/train/python
def sudoku(puzzle):
import collections
print('=== in sudoku ===')
# Print arguments
print_board(puzzle)
# Count the numbers that are currently populated on the sudoku board
number_count = collections.Counter(number for row in puzzle for number in row)... | # print_board(columns_missing_numbers)
# Validate all the inner 3x3 boards
grid_missing_numbers = []
# Step 1: Split the rows into 3 columns
# Break up the 9x9 board into 3 9x3 boards (i.e. split up all the rows into 3 parts)
split_board = [] # Contains original board with all rows split into 3 pa... | print('-- columns_missing_numbers --') | random_line_split |
sudoku_solver_level_3_1.py | # https://www.codewars.com/kata/sudoku-solver/train/python
def sudoku(puzzle):
import collections
print('=== in sudoku ===')
# Print arguments
print_board(puzzle)
# Count the numbers that are currently populated on the sudoku board
number_count = collections.Counter(number for row in puzzle for number in row)... |
print('-- grid_missing_numbers --')
# print_board(grid_missing_numbers)
# Loop through the puzzle board, until we find a '0'
# Count of zeros
print('-- Looking for a 0 --')
board = replace_zero(puzzle, rows_missing_numbers, columns_missing_numbers, grid_missing_numbers)
print('-- (replaced) board --... | inner_board = row[s_index:s_index+3] # Every 3 1x3 sub-rows in this row define the inner 3x3 matrix
single_row = [[digit for row_3x3 in inner_board for digit in row_3x3]] # Convert the 3x3 matrix into a single nested list [[1, ..., 9]], so we can check it
# Break it down:
# for row_3x3 in inner_boa... | conditional_block |
registration.py | # -*- coding: utf-8 -*-
#
# Copyright (C) 2006 Edgewall Software
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at http://trac.edgewall.com/license.html.
#
# This software consists of vo... | try:
if check.__class__.__name__ != 'RegistrationFilterAdapter':
self.log.debug("Add registration check data %s", check)
fragment, f_data = \
check.render_registration_fields(req, data)
... | """Spam filter strategy that calls account manager checks for
account registration.
"""
implements(IFilterStrategy)
karma_points = IntOption('spam-filter', 'account_karma', '0',
"""By how many points a failed registration check impacts
the overall score.""", doc_domain='tracspamfilter')... | identifier_body |
registration.py | # -*- coding: utf-8 -*-
#
# Copyright (C) 2006 Edgewall Software
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at http://trac.edgewall.com/license.html.
#
# This software consists of vo... |
except Exception, e:
self.log.exception("Adding registration fields failed: %s",
e)
return fragments, data
# IFilterStrategy methods
def is_external(self):
return False
def test(self, req, author, content, ip):
... | self.log.debug("Add registration check data %s", check)
fragment, f_data = \
check.render_registration_fields(req, data)
try:
fragments['optional'] = \
tag(fragments.get('optional', ''... | conditional_block |
registration.py | # -*- coding: utf-8 -*-
#
# Copyright (C) 2006 Edgewall Software
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at http://trac.edgewall.com/license.html.
#
# This software consists of vo... | (self, req, author, content, ip):
if req.path_info == '/register':
karma = 0
checks = []
for check in self.listeners:
try:
if check.__class__.__name__ != 'RegistrationFilterAdapter':
self.log.debug("Try registration ... | test | identifier_name |
registration.py | # -*- coding: utf-8 -*-
#
# Copyright (C) 2006 Edgewall Software
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at http://trac.edgewall.com/license.html.
#
# This software consists of vo... | def train(self, req, author, content, ip, spam=True):
return 0 | random_line_split | |
urls.py | from django.conf.urls.defaults import *
from django.views.generic import DetailView, ListView
from archive.models import Catalogue, Document
urlpatterns = patterns('archive.views',
url(r'^$',
ListView.as_view(
context_object_name="catalogues",
queryset=Catalogu... | template_name='archive/document.html'), name='document-detail'),
) | random_line_split | |
Values.tsx | import * as React from 'react';
import Box from '@material-ui/core/Box';
| return (
<Box sx={{ width: '100%' }}>
<Box sx={{ width: 1 / 4, bgcolor: 'grey.300', p: 1, my: 0.5 }}>Width 1/4</Box>
<Box sx={{ width: 300, bgcolor: 'grey.300', p: 1, my: 0.5 }}>Width 300</Box>
<Box sx={{ width: '75%', bgcolor: 'grey.300', p: 1, my: 0.5 }}>Width 75%</Box>
<Box sx={{ width:... | export default function Values() { | random_line_split |
et.js | URL",
"Browse": "sirvida",
"Drop image": "Aseta pilt",
"or click": "v\u00f5i kliki",
"Manage Images": "Halda pilte",
"Loading": "Laadimine",
"Deleting": "Kustutamine",
"Tags": "Sildid",
"Are you sure? Image will be deleted.": "Oled sa kindel? Pilt kustutatakse.",
"Replace": "Asendam... |
// Line breaker
"Break": "Murdma",
| random_line_split | |
test_shell_interactive.py | .0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.... | (self):
"""Regression test for IMPALA-1317
The shell does not call close() for alter, use and drop queries, leaving them in
flight. This test issues those queries in interactive mode, and checks the debug
webpage to confirm that they've been closed.
TODO: Add every statement type.
"""
TMP_... | test_ddl_queries_are_closed | identifier_name |
test_shell_interactive.py | .0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.... |
@pytest.mark.execute_serially
def test_escaped_quotes(self):
"""Test escaping quotes"""
# test escaped quotes outside of quotes
result = run_impala_shell_interactive("select \\'bc';")
assert "could not match input" in result.stderr
result = run_impala_shell_interactive("select \\\"bc\";")
... | if os.path.exists(TMP_HISTORY_FILE): shutil.move(TMP_HISTORY_FILE, SHELL_HISTORY_FILE) | identifier_body |
test_shell_interactive.py | .0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.... |
child_proc.expect(prompt_regex)
child_proc.sendline('quit;')
p = self._start_new_shell_process()
self._send_cmd_to | child_proc.expect(prompt_regex)
child_proc.sendline(query) | conditional_block |
test_shell_interactive.py | .0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.... | assert "could not match input" in result.stderr
# test escaped quotes within quotes
result = run_impala_shell_interactive("select 'ab\\'c';")
assert "Fetched 1 row(s)" in result.stderr
result = run_impala_shell_interactive("select \"ab\\\"c\";")
assert "Fetched 1 row(s)" in result.stderr
@pyt... | result = run_impala_shell_interactive("select \\\"bc\";") | random_line_split |
users-routing.module.ts | /*
* Copyright (c) 2015-2018 IPT-Intellectual Products & Technologies (IPT).
* All rights reserved.
*
* This software provided by IPT-Intellectual Products & Technologies (IPT) is for
* non-commercial illustartive and evaluation purposes only.
* It is NOT SUITABLE FOR PRODUCTION purposes because it is not finishe... | export class UsersRoutingModule { } | random_line_split | |
users-routing.module.ts | /*
* Copyright (c) 2015-2018 IPT-Intellectual Products & Technologies (IPT).
* All rights reserved.
*
* This software provided by IPT-Intellectual Products & Technologies (IPT) is for
* non-commercial illustartive and evaluation purposes only.
* It is NOT SUITABLE FOR PRODUCTION purposes because it is not finishe... | { }
| sersRoutingModule | identifier_name |
filters.py | # -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from django.conf import settings
from django... | (link):
"""Converts `link` into an internal link.
Any active static pages defined for a site can be linked by pointing
to its virtual path by starting the anchors with the `#/` sequence
(e.g. `#/the/virtual/path`).
Links pointing to non-existent pages will return `#`.
Links not starting with `... | rewrite_internal_link | identifier_name |
filters.py | # -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from django.conf import settings
from django... |
def apply_markup_filter(text):
"""Applies a text-to-HTML conversion function to a piece of text and
returns the generated HTML.
The function to use is derived from the value of the setting
``POOTLE_MARKUP_FILTER``, which should be a 2-tuple:
* The first element should be the name of a marku... | """Returns the configured filter as a tuple with name and args.
If there is any problem it returns (None, '').
"""
try:
markup_filter, markup_kwargs = settings.POOTLE_MARKUP_FILTER
if markup_filter is None:
return (None, "unset")
elif markup_filter == 'textile':
... | identifier_body |
filters.py | # -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from django.conf import settings
from django... |
elif markup_filter == 'markdown':
import markdown # noqa
elif markup_filter == 'restructuredtext':
import docutils # noqa
else:
return (None, '')
except Exception:
return (None, '')
return (markup_filter, markup_kwargs)
def apply_markup_f... | import textile # noqa | conditional_block |
filters.py | # -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from django.conf import settings |
__all__ = (
'get_markup_filter_name', 'get_markup_filter_display_name',
'get_markup_filter', 'apply_markup_filter',
)
def rewrite_internal_link(link):
"""Converts `link` into an internal link.
Any active static pages defined for a site can be linked by pointing
to its virtual path by starting th... | from django.core.exceptions import ObjectDoesNotExist
from ..utils.html import rewrite_links
| random_line_split |
__init__.py | # -*- coding: utf-8 -*-
# Copyright 2022 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | # Compile a registry of transports.
_transport_registry = OrderedDict() # type: Dict[str, Type[ForwardingRulesTransport]]
_transport_registry["rest"] = ForwardingRulesRestTransport
__all__ = (
"ForwardingRulesTransport",
"ForwardingRulesRestTransport",
"ForwardingRulesRestInterceptor",
) | random_line_split | |
pushNotificationService.js | var firebase = require("unirest");
var logger = require("../log/logger");
var config = require("config");
var async = require("async");
function buildMessage (message, deviceFirebaseId) {
return {
data: message,
to: deviceFirebaseId
};
}
module.exports = {
findActiveFirabseIds (user) {
if (!user || ... |
firebase.post("https://fcm.googleapis.com/fcm/send")
.headers({
Authorization: "key=" + config.app.firebase.key,
"Content-Type": "application/json"
})
.send(buildMessage(message, deviceFirebaseId))
.end(function (response) {
logger.trace("[firebase] response body:", response.body... | {
logger.warn("[firebase.sendMessageToSingleDevice]", "Cannot send message because Message or deviceFirebaseId is empty");
return callback(new Error("Message or deviceFirebaseId is empty"));
} | conditional_block |
pushNotificationService.js | var firebase = require("unirest");
var logger = require("../log/logger");
var config = require("config");
var async = require("async");
function buildMessage (message, deviceFirebaseId) {
return {
data: message,
to: deviceFirebaseId
};
}
module.exports = {
findActiveFirabseIds (user) {
if (!user || ... | (message, user, callback) {
var activeDFireBaseIds = this.findActiveFirabseIds(user);
this.sendMessageToDevices(message, activeDFireBaseIds, callback);
}
};
| sendMessageToAllActiveUserDevices | identifier_name |
pushNotificationService.js | var firebase = require("unirest"); | var config = require("config");
var async = require("async");
function buildMessage (message, deviceFirebaseId) {
return {
data: message,
to: deviceFirebaseId
};
}
module.exports = {
findActiveFirabseIds (user) {
if (!user || !user.firebaseInstanceIds) {
logger.warn("[firebaseService.findActiv... | var logger = require("../log/logger"); | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.