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 |
|---|---|---|---|---|
jquery_006.js | SPACE: 8,
CAPS_LOCK: 20,
COMMA: 188,
COMMAND: 91,
COMMAND_LEFT: 91, // COMMAND
COMMAND_RIGHT: 93,
CONTROL: 17,
DELETE: 46,
DOWN: 40,
END: 35,
ENTER: 13,
ESCAPE: 27,
HOME: 36,
INSERT: 45,
LEFT: 37,
MENU: 93, // COMMAND_RIGHT
NUMPAD_ADD: 107,
NUMPAD_DECIMAL: 110,
NUMP... |
$.extend( $.expr[ ":" ], {
data: function( elem, i, match ) {
return !!$.data( elem, match[ 3 ] );
},
focusable: function( element ) {
var nodeName = element.nodeName.toLowerCase(),
tabIndex = $.attr( element, "tabindex" );
if ( "area" === nodeName ) {
var map = element.parentNode,
map... | {
return !$( element ).parents().andSelf().filter(function() {
return $.curCSS( this, "visibility" ) === "hidden" ||
$.expr.filters.hidden( this );
}).length;
} | identifier_body |
jquery_006.js | SPACE: 8,
CAPS_LOCK: 20,
COMMA: 188,
COMMAND: 91,
COMMAND_LEFT: 91, // COMMAND
COMMAND_RIGHT: 93,
CONTROL: 17,
DELETE: 46,
DOWN: 40,
END: 35,
ENTER: 13,
ESCAPE: 27,
HOME: 36,
INSERT: 45,
LEFT: 37,
MENU: 93, // COMMAND_RIGHT
NUMPAD_ADD: 107,
NUMPAD_DECIMAL: 110,
NUMP... | PAGE_UP: 33,
PERIOD: 190,
RIGHT: 39,
SHIFT: 16,
SPACE: 32,
TAB: 9,
UP: 38,
WINDOWS: 91 // COMMAND
}
});
// plugins
$.fn.extend({
_focus: $.fn.focus,
focus: function( delay, fn ) {
return typeof delay === "number" ?
this.each(function() {
var elem = this;
setTimeout(fun... | NUMPAD_SUBTRACT: 109,
PAGE_DOWN: 34,
| random_line_split |
jquery_006.js | SPACE: 8,
CAPS_LOCK: 20,
COMMA: 188,
COMMAND: 91,
COMMAND_LEFT: 91, // COMMAND
COMMAND_RIGHT: 93,
CONTROL: 17,
DELETE: 46,
DOWN: 40,
END: 35,
ENTER: 13,
ESCAPE: 27,
HOME: 36,
INSERT: 45,
LEFT: 37,
MENU: 93, // COMMAND_RIGHT
NUMPAD_ADD: 107,
NUMPAD_DECIMAL: 110,
NUMP... | ( element ) {
return !$( element ).parents().andSelf().filter(function() {
return $.curCSS( this, "visibility" ) === "hidden" ||
$.expr.filters.hidden( this );
}).length;
}
$.extend( $.expr[ ":" ], {
data: function( elem, i, match ) {
return !!$.data( elem, match[ 3 ] );
},
focusable: function... | visible | identifier_name |
jquery_006.js | SPACE: 8,
CAPS_LOCK: 20,
COMMA: 188,
COMMAND: 91,
COMMAND_LEFT: 91, // COMMAND
COMMAND_RIGHT: 93,
CONTROL: 17,
DELETE: 46,
DOWN: 40,
END: 35,
ENTER: 13,
ESCAPE: 27,
HOME: 36,
INSERT: 45,
LEFT: 37,
MENU: 93, // COMMAND_RIGHT
NUMPAD_ADD: 107,
NUMPAD_DECIMAL: 110,
NUMP... |
return (/fixed/).test(this.css('position')) || !scrollParent.length ? $(document) : scrollParent;
},
zIndex: function( zIndex ) {
if ( zIndex !== undefined ) {
return this.css( "zIndex", zIndex );
}
if ( this.length ) {
var elem = $( this[ 0 ] ), position, value;
while ( elem.length &... | {
scrollParent = this.parents().filter(function() {
return (/(auto|scroll)/).test($.curCSS(this,'overflow',1)+$.curCSS(this,'overflow-y',1)+$.curCSS(this,'overflow-x',1));
}).eq(0);
} | conditional_block |
tweet.component.ts | /**
* Created by puneet on 30/4/17.
*/
import {Component} from 'angular2/core'
import {TweetServices} from './tweet.service'
import {HeartComponent} from './heart.component'
import {PipeSummary} from './summary.pipe'
@Component({
selector: 'tweet',
template: `
<div *ngFor="#tweet of tweetInfo">
... | (tweetServies: TweetServices){
this.tweetInfo = tweetServies.getTweetInfo();
}
onLikeChange($event, tweet){
if($event.heart) {
tweet.totalLikes += 1;
}
else {
tweet.totalLikes -= 1;
}
}
} | constructor | identifier_name |
tweet.component.ts | /**
* Created by puneet on 30/4/17.
*/
import {Component} from 'angular2/core'
import {TweetServices} from './tweet.service'
import {HeartComponent} from './heart.component'
import {PipeSummary} from './summary.pipe'
@Component({
selector: 'tweet',
template: `
<div *ngFor="#tweet of tweetInfo">
... |
} | {
if($event.heart) {
tweet.totalLikes += 1;
}
else {
tweet.totalLikes -= 1;
}
} | identifier_body |
tweet.component.ts | /**
* Created by puneet on 30/4/17.
*/
import {Component} from 'angular2/core'
import {TweetServices} from './tweet.service'
import {HeartComponent} from './heart.component'
import {PipeSummary} from './summary.pipe'
@Component({
selector: 'tweet',
template: `
<div *ngFor="#tweet of tweetInfo">
... |
else {
tweet.totalLikes -= 1;
}
}
} | {
tweet.totalLikes += 1;
} | conditional_block |
tweet.component.ts | /**
* Created by puneet on 30/4/17.
*/
import {Component} from 'angular2/core'
import {TweetServices} from './tweet.service'
import {HeartComponent} from './heart.component'
import {PipeSummary} from './summary.pipe'
@Component({
selector: 'tweet',
template: `
<div *ngFor="#tweet of tweetInfo">
... | </div>
<br/>
`,
providers: [TweetServices],
directives: [HeartComponent],
pipes:[PipeSummary]
})
export class TweetComponent{
tweetInfo;
constructor(tweetServies: TweetServices){
this.tweetInfo = tweetServies.getTweetInfo();
}
onLikeChange($event, tweet){
... | random_line_split | |
owned.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 ... |
}
/// Extension methods for an owning `Any+Send` trait object
pub trait AnySendOwnExt {
/// Returns the boxed value if it is of type `T`, or
/// `Err(Self)` if it isn't.
fn move_send<T: 'static>(self) -> Result<Box<T>, Self>;
}
impl AnySendOwnExt for Box<Any+Send> {
#[inline]
fn move_send<T: 'sta... | {
if self.is::<T>() {
unsafe {
// Get the raw representation of the trait object
let to: TraitObject =
*mem::transmute::<&Box<Any>, &TraitObject>(&self);
// Prevent destructor on self being run
intrinsics::forget(se... | identifier_body |
owned.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 ... | }
}
impl fmt::Show for Box<Any> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.pad("Box<Any>")
}
}
#[cfg(test)]
mod test {
#[test]
fn test_owned_clone() {
let a = box 5i;
let b: Box<int> = a.clone();
assert!(a == b);
}
#[test]
fn any_move() ... | impl<T: fmt::Show> fmt::Show for Box<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
(**self).fmt(f) | random_line_split |
owned.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: &Box<T>) -> bool { *(*self) > *(*other) }
}
impl<T: Ord> Ord for Box<T> {
#[inline]
fn cmp(&self, other: &Box<T>) -> Ordering { (**self).cmp(*other) }
}
impl<T: Eq> Eq for Box<T> {}
/// Extension methods for an owning `Any` trait object
pub trait AnyOwnExt {
/// Returns the boxed value if it... | gt | identifier_name |
owned.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 ... | else {
Err(self)
}
}
}
/// Extension methods for an owning `Any+Send` trait object
pub trait AnySendOwnExt {
/// Returns the boxed value if it is of type `T`, or
/// `Err(Self)` if it isn't.
fn move_send<T: 'static>(self) -> Result<Box<T>, Self>;
}
impl AnySendOwnExt for Box<Any+S... | {
unsafe {
// Get the raw representation of the trait object
let to: TraitObject =
*mem::transmute::<&Box<Any>, &TraitObject>(&self);
// Prevent destructor on self being run
intrinsics::forget(self);
// Ext... | conditional_block |
utils.py | # General utility functions can go here.
import os
import random
import string
from django.utils import functional
from django.utils.http import urlencode
def rand_string(numOfChars):
"""
Generates a string of lowercase letters and numbers.
That makes 36^10 = 3 x 10^15 possibilities.
If we generate f... |
else:
return False
| return True | conditional_block |
utils.py | # General utility functions can go here.
import os
import random
import string
from django.utils import functional
from django.utils.http import urlencode
def rand_string(numOfChars):
"""
Generates a string of lowercase letters and numbers.
That makes 36^10 = 3 x 10^15 possibilities.
If we generate f... | return os.path.join(directory, filenameBase + extension)
def url_with_querystring(path, **kwargs):
"""
Takes a base URL (path) and GET query arguments (kwargs).
Returns the complete GET URL.
NOTE:
Any kwargs with special characters like '/' and ' ' will be
escaped with %2f, %20, etc.
... | # to make filename collisions far more likely.
extension = os.path.splitext(originalFilename)[1]
filenameBase = rand_string(numOfChars) | random_line_split |
utils.py | # General utility functions can go here.
import os
import random
import string
from django.utils import functional
from django.utils.http import urlencode
def rand_string(numOfChars):
"""
Generates a string of lowercase letters and numbers.
That makes 36^10 = 3 x 10^15 possibilities.
If we generate f... | """
Checks that the argument is either:
(a) an instance of basestring, or
(b) a Django lazy-translation string.
:param s: Object to check the type of.
:return: True if s is a Django string, False otherwise.
"""
if isinstance(s, basestring):
return True
elif isinstance(s, functio... | identifier_body | |
utils.py | # General utility functions can go here.
import os
import random
import string
from django.utils import functional
from django.utils.http import urlencode
def | (numOfChars):
"""
Generates a string of lowercase letters and numbers.
That makes 36^10 = 3 x 10^15 possibilities.
If we generate filenames randomly, it's harder for people to guess filenames
and type in their URLs directly to bypass permissions.
"""
return ''.join(random.choice(string.asci... | rand_string | identifier_name |
main.rs | pub mod release;
use std::env::args;
use std::process::exit;
use crate::release::*;
use compat::getpid;
use config::Config;
use logger::{Level, Logger};
use networking::Server;
fn main() {
let mut config = Config::new(Logger::new(Level::Notice));
if let Some(f) = args().nth(1) |
let (port, daemonize) = (config.port, config.daemonize);
let mut server = Server::new(config);
{
let mut db = server.get_mut_db();
db.git_sha1 = GIT_SHA1;
db.git_dirty = GIT_DIRTY;
db.version = env!("CARGO_PKG_VERSION");
db.rustc_version = RUSTC_VERSION;
}
... | {
if config.parsefile(f).is_err() {
exit(1);
}
} | conditional_block |
main.rs | pub mod release;
use std::env::args;
use std::process::exit;
use crate::release::*;
use compat::getpid;
use config::Config;
use logger::{Level, Logger};
use networking::Server;
fn main() | println!("PID: {}", getpid());
}
server.run();
}
| {
let mut config = Config::new(Logger::new(Level::Notice));
if let Some(f) = args().nth(1) {
if config.parsefile(f).is_err() {
exit(1);
}
}
let (port, daemonize) = (config.port, config.daemonize);
let mut server = Server::new(config);
{
let mut db = server.ge... | identifier_body |
main.rs | pub mod release;
use std::env::args;
use std::process::exit;
use crate::release::*;
use compat::getpid;
use config::Config;
use logger::{Level, Logger};
use networking::Server;
fn main() {
let mut config = Config::new(Logger::new(Level::Notice));
if let Some(f) = args().nth(1) {
if config.parsefile(f... | let mut db = server.get_mut_db();
db.git_sha1 = GIT_SHA1;
db.git_dirty = GIT_DIRTY;
db.version = env!("CARGO_PKG_VERSION");
db.rustc_version = RUSTC_VERSION;
}
if !daemonize {
println!("Port: {}", port);
println!("PID: {}", getpid());
}
server.run... | random_line_split | |
main.rs | pub mod release;
use std::env::args;
use std::process::exit;
use crate::release::*;
use compat::getpid;
use config::Config;
use logger::{Level, Logger};
use networking::Server;
fn | () {
let mut config = Config::new(Logger::new(Level::Notice));
if let Some(f) = args().nth(1) {
if config.parsefile(f).is_err() {
exit(1);
}
}
let (port, daemonize) = (config.port, config.daemonize);
let mut server = Server::new(config);
{
let mut db = server... | main | identifier_name |
portal.rs | // Copyright 2013-2014 Jeffery Olson
//
// Licensed under the 3-Clause BSD License, see LICENSE.txt
// at the top-level of this repository.
// This file may not be copied, modified, or distributed
// except according to those terms.
use uuid::Uuid;
use world::TraversalDirection;
use world::TraversalDirection::*;
#[d... | b_zid: Uuid, bx: TraversalDirection) -> Portal {
if ae == North && bx != South { panic!("bad portal dirs a:{} b:{}", ae, bx); }
if ae == South && bx != North { panic!("bad portal dirs a:{} b:{}", ae, bx); }
if ae == West && bx != East { panic!("bad portal dirs a:{} b:{}", ae, bx);... | pub fn new(id: Uuid, a_zid: Uuid, ae: TraversalDirection, | random_line_split |
portal.rs | // Copyright 2013-2014 Jeffery Olson
//
// Licensed under the 3-Clause BSD License, see LICENSE.txt
// at the top-level of this repository.
// This file may not be copied, modified, or distributed
// except according to those terms.
use uuid::Uuid;
use world::TraversalDirection;
use world::TraversalDirection::*;
#[d... |
pub fn info_from(&self, zid: Uuid) -> (Uuid, TraversalDirection) {
if self.a_zid == zid { (self.b_zid, self.a_exit) }
else if self.b_zid == zid { (self.a_zid, self.b_exit) }
else { panic!("zid:{} isn't in this portal!", zid) }
}
}
| {
if ae == North && bx != South { panic!("bad portal dirs a:{} b:{}", ae, bx); }
if ae == South && bx != North { panic!("bad portal dirs a:{} b:{}", ae, bx); }
if ae == West && bx != East { panic!("bad portal dirs a:{} b:{}", ae, bx); }
if ae == East && bx != West { panic!("bad portal di... | identifier_body |
portal.rs | // Copyright 2013-2014 Jeffery Olson
//
// Licensed under the 3-Clause BSD License, see LICENSE.txt
// at the top-level of this repository.
// This file may not be copied, modified, or distributed
// except according to those terms.
use uuid::Uuid;
use world::TraversalDirection;
use world::TraversalDirection::*;
#[d... |
if ae == South && bx != North { panic!("bad portal dirs a:{} b:{}", ae, bx); }
if ae == West && bx != East { panic!("bad portal dirs a:{} b:{}", ae, bx); }
if ae == East && bx != West { panic!("bad portal dirs a:{} b:{}", ae, bx); }
Portal { id: id, a_zid: a_zid, a_exit: ae, b_zid: b_zi... | { panic!("bad portal dirs a:{} b:{}", ae, bx); } | conditional_block |
portal.rs | // Copyright 2013-2014 Jeffery Olson
//
// Licensed under the 3-Clause BSD License, see LICENSE.txt
// at the top-level of this repository.
// This file may not be copied, modified, or distributed
// except according to those terms.
use uuid::Uuid;
use world::TraversalDirection;
use world::TraversalDirection::*;
#[d... | (id: Uuid, a_zid: Uuid, ae: TraversalDirection,
b_zid: Uuid, bx: TraversalDirection) -> Portal {
if ae == North && bx != South { panic!("bad portal dirs a:{} b:{}", ae, bx); }
if ae == South && bx != North { panic!("bad portal dirs a:{} b:{}", ae, bx); }
if ae == West && bx != Eas... | new | identifier_name |
index.js | import React from 'react';
import { TextField } from 'material-ui';
import { AdministrativeButton } from './../../components';
import { auth } from './../../services';
class | extends React.Component {
state = {
name: '',
level: 0
};
handleNameChange = (e, newValue) => this.setState({ name: newValue });
handleLevelChange = (e, newValue) => this.setState({ level: newValue });
handleCancel = () => this.props.history.push('matches');
async handleSave(event) {
event.p... | NewRole | identifier_name |
index.js | import React from 'react';
import { TextField } from 'material-ui';
import { AdministrativeButton } from './../../components';
import { auth } from './../../services';
class NewRole extends React.Component {
state = {
name: '',
level: 0
};
handleNameChange = (e, newValue) => this.setState({ name: new... |
}
export default NewRole; | {
return (
<div className='new-team page'>
<div className='new-team--content'>
<h2>NEW ROLE</h2>
<div>
<form>
<TextField name='name' floatingLabelText='Name' onChange={this.handleNameChange} value={this.state.name} />
<TextField name='level' ... | identifier_body |
index.js | import React from 'react';
import { TextField } from 'material-ui';
import { AdministrativeButton } from './../../components';
import { auth } from './../../services';
class NewRole extends React.Component {
state = {
name: '',
level: 0
};
handleNameChange = (e, newValue) => this.setState({ name: new... |
async handleSave(event) {
event.preventDefault();
const requestBody = {
name: this.state.name,
level: this.state.level
};
try {
await auth.saveRole(requestBody);
this.props.history.push('matches');
} catch (e) {
alert(`Error: ${JSON.stringify(e)}`);
}
}
r... | handleCancel = () => this.props.history.push('matches'); | random_line_split |
game-character-sheet.component.ts | import { AfterViewInit, Component, Input, OnDestroy, OnInit } from '@angular/core';
import { EventSystem, Network } from '@udonarium/core/system';
import { DataElement } from '@udonarium/data-element';
import { PresetSound, SoundEffect } from '@udonarium/sound-effect';
import { TabletopObject } from '@udonarium/tablet... | dal(name: string = '', isAllowedEmpty: boolean = false) {
this.modalService.open<string>(FileSelecterComponent, { isAllowedEmpty: isAllowedEmpty }).then(value => {
if (!this.tabletopObject || !this.tabletopObject.imageDataElement || !value) return;
let element = this.tabletopObject.imageDataElement.getF... | .tabletopObject.setLocation(locationName);
}
openMo | identifier_body |
game-character-sheet.component.ts | import { AfterViewInit, Component, Input, OnDestroy, OnInit } from '@angular/core';
import { EventSystem, Network } from '@udonarium/core/system';
import { DataElement } from '@udonarium/data-element';
import { PresetSound, SoundEffect } from '@udonarium/sound-effect';
import { TabletopObject } from '@udonarium/tablet... |
});
}
ngAfterViewInit() {
}
ngOnDestroy() {
EventSystem.unregister(this);
}
toggleEditMode() {
this.isEdit = this.isEdit ? false : true;
}
addDataElement() {
if (this.tabletopObject.detailDataElement) {
let title = DataElement.create('見出し', '', {});
let tag = DataEleme... | {
this.panelService.close();
} | conditional_block |
game-character-sheet.component.ts | import { AfterViewInit, Component, Input, OnDestroy, OnInit } from '@angular/core';
import { EventSystem, Network } from '@udonarium/core/system';
import { DataElement } from '@udonarium/data-element';
import { PresetSound, SoundEffect } from '@udonarium/sound-effect';
import { TabletopObject } from '@udonarium/tablet... | ame: string) {
this.tabletopObject.setLocation(locationName);
}
openModal(name: string = '', isAllowedEmpty: boolean = false) {
this.modalService.open<string>(FileSelecterComponent, { isAllowedEmpty: isAllowedEmpty }).then(value => {
if (!this.tabletopObject || !this.tabletopObject.imageDataElement |... | n(locationN | identifier_name |
game-character-sheet.component.ts | import { AfterViewInit, Component, Input, OnDestroy, OnInit } from '@angular/core';
import { EventSystem, Network } from '@udonarium/core/system';
import { DataElement } from '@udonarium/data-element';
import { PresetSound, SoundEffect } from '@udonarium/sound-effect';
import { TabletopObject } from '@udonarium/tablet... | templateUrl: './game-character-sheet.component.html',
styleUrls: ['./game-character-sheet.component.css']
})
export class GameCharacterSheetComponent implements OnInit, OnDestroy, AfterViewInit {
@Input() tabletopObject: TabletopObject = null;
isEdit: boolean = false;
networkService = Network;
isSaveing:... |
@Component({
selector: 'game-character-sheet', | random_line_split |
component_resolver.ts | import {Injectable} from 'angular2/src/core/di';
import {Type, isBlank, stringify} from 'angular2/src/facade/lang';
import {BaseException} from 'angular2/src/facade/exceptions';
import {PromiseWrapper} from 'angular2/src/facade/async';
import {reflector} from 'angular2/src/core/reflection/reflection';
import {Component... | }
return PromiseWrapper.resolve(componentFactory);
}
clearCache() {}
} | if (isBlank(componentFactory)) {
throw new BaseException(`No precompiled component ${stringify(componentType)} found`); | random_line_split |
component_resolver.ts | import {Injectable} from 'angular2/src/core/di';
import {Type, isBlank, stringify} from 'angular2/src/facade/lang';
import {BaseException} from 'angular2/src/facade/exceptions';
import {PromiseWrapper} from 'angular2/src/facade/async';
import {reflector} from 'angular2/src/core/reflection/reflection';
import {Component... |
return PromiseWrapper.resolve(componentFactory);
}
clearCache() {}
}
| {
throw new BaseException(`No precompiled component ${stringify(componentType)} found`);
} | conditional_block |
component_resolver.ts | import {Injectable} from 'angular2/src/core/di';
import {Type, isBlank, stringify} from 'angular2/src/facade/lang';
import {BaseException} from 'angular2/src/facade/exceptions';
import {PromiseWrapper} from 'angular2/src/facade/async';
import {reflector} from 'angular2/src/core/reflection/reflection';
import {Component... | () {}
}
| clearCache | identifier_name |
component_resolver.ts | import {Injectable} from 'angular2/src/core/di';
import {Type, isBlank, stringify} from 'angular2/src/facade/lang';
import {BaseException} from 'angular2/src/facade/exceptions';
import {PromiseWrapper} from 'angular2/src/facade/async';
import {reflector} from 'angular2/src/core/reflection/reflection';
import {Component... |
@Injectable()
export class ReflectorComponentResolver extends ComponentResolver {
resolveComponent(componentType: Type): Promise<ComponentFactory> {
var metadatas = reflector.annotations(componentType);
var componentFactory = metadatas.find(_isComponentFactory);
if (isBlank(componentFactory)) {
t... | {
return type instanceof ComponentFactory;
} | identifier_body |
lib.rs | // Zinc, the bare metal stack for rust.
// Copyright 2014 Vladimir "farcaller" Pouzanov <farcaller@gmail.com>
//
// 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.o... |
// extern crate regex;
extern crate syntax;
extern crate regex;
#[cfg(test)] extern crate hamcrest;
pub mod builder;
pub mod node;
pub mod parser;
#[path="../../src/hal/lpc17xx/platformtree.rs"] mod lpc17xx_pt;
#[path="../../src/hal/tiva_c/platformtree.rs"] mod tiva_c_pt;
#[path="../../src/drivers/drivers_pt.rs"] mo... |
//! Platform tree operations crate
#![feature(quote, rustc_private)] | random_line_split |
lib.rs | #![doc(html_logo_url = "https://avatars0.githubusercontent.com/u/7853871?s=128", html_favicon_url = "https://avatars0.githubusercontent.com/u/7853871?s=256", html_root_url = "http://ironframework.io/core/iron")]
#![cfg_attr(test, deny(warnings))]
#![deny(missing_docs)]
//! The main crate for Iron.
//!
//! ## Overview
... | //! writes and locking in the core framework.
//!
//! ## Hello World
//!
//! ```no_run
//! extern crate iron;
//!
//! use iron::prelude::*;
//! use iron::status;
//!
//! fn main() {
//! Iron::new(|_: &mut Request| {
//! Ok(Response::with((status::Ok, "Hello World!")))
//! }).http("localhost:3000").unwra... | //! approach to ownership in both single threaded and multi threaded contexts.
//!
//! Iron is highly concurrent and can scale horizontally on more machines behind a
//! load balancer or by running more threads on a more powerful machine. Iron
//! avoids the bottlenecks encountered in highly concurrent code by avoiding... | random_line_split |
fromdb.rs | /*
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this | use rusqlite::Row;
use crate::catalog::CatalogVersion;
/// Trait to define loading from a database.
pub trait FromDb: Sized {
/// Read one element from a database Row obtained through a query
/// build with the tables and columns provided.
/// The version of the catalog allow selecting the proper variant.... | file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
| random_line_split |
fromdb.rs | /*
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
use rusqlite::Row;
use crate::catalog::CatalogVersion;
/// Trait to define loading from a database.
pub trait FromD... | (_version: CatalogVersion) -> &'static str {
""
}
}
| read_join_where | identifier_name |
fromdb.rs | /*
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
use rusqlite::Row;
use crate::catalog::CatalogVersion;
/// Trait to define loading from a database.
pub trait FromD... |
}
| {
""
} | identifier_body |
unrelated_documents.py | from odoo import api, fields, models, tools
class UnrelatedDocumentsReport(models.Model):
_name = "sicon.unrelated_documents.report"
_description = 'Documents not related yet to any concession'
_auto = False
dependence_id = fields.Many2one(comodel_name='tmc.dependence',
... |
def init(self):
tools.drop_view_if_exists(self.env.cr, self._table)
self.env.cr.execute("""
CREATE OR REPLACE VIEW sicon_unrelated_documents_report AS (
SELECT
doc.id,
doc.document_object,
doc.name
... | random_line_split | |
unrelated_documents.py | from odoo import api, fields, models, tools
class UnrelatedDocumentsReport(models.Model):
_name = "sicon.unrelated_documents.report"
_description = 'Documents not related yet to any concession'
_auto = False
dependence_id = fields.Many2one(comodel_name='tmc.dependence',
... | (self):
tools.drop_view_if_exists(self.env.cr, self._table)
self.env.cr.execute("""
CREATE OR REPLACE VIEW sicon_unrelated_documents_report AS (
SELECT
doc.id,
doc.document_object,
doc.name
FROM (
... | init | identifier_name |
unrelated_documents.py | from odoo import api, fields, models, tools
class UnrelatedDocumentsReport(models.Model):
| 'sicon.event': ['document_id']
}
def init(self):
tools.drop_view_if_exists(self.env.cr, self._table)
self.env.cr.execute("""
CREATE OR REPLACE VIEW sicon_unrelated_documents_report AS (
SELECT
doc.id,
doc.document_objec... | _name = "sicon.unrelated_documents.report"
_description = 'Documents not related yet to any concession'
_auto = False
dependence_id = fields.Many2one(comodel_name='tmc.dependence',
readonly=True)
document_type_id = fields.Many2one(comodel_name='tmc.document_type',
... | identifier_body |
ChartComponentModel.js | /*
* Copyright (C) 2005 - 2014 TIBCO Software Inc. All rights reserved.
* http://www.jaspersoft.com.
*
* Unless you have purchased a commercial license agreement from Jaspersoft,
* the following license terms apply:
*
* This program is free software: you can redistribute it and/or modify
* it under the terms... | changeChartTypeData: {
chartComponentUuid: this.get("id"),
chartType: this.get("charttype")
}
}
}
},
initialize: function(){
if (this.has("hcinstancedata")){
v... |
actions: {
"change:charttype": function() {
return {
actionName: 'changeChartType', | random_line_split |
ChartComponentModel.js | /*
* Copyright (C) 2005 - 2014 TIBCO Software Inc. All rights reserved.
* http://www.jaspersoft.com.
*
* Unless you have purchased a commercial license agreement from Jaspersoft,
* the following license terms apply:
*
* This program is free software: you can redistribute it and/or modify
* it under the terms... |
// JSON.parse(JSON.stringify(.... deep clone.
// JR services are changing model by initialization, therefore deep clone is done to avoid data corruption
// should be replaced with true deep clone if JRS-1450 implemented
this.config = JSON.parse(JSON.stringify(this.toJSON... | {
var hcinstancedata = this.get("hcinstancedata"),
creator = this._detectCreator(hcinstancedata);
if (reportCreators.AD_HOC_DESIGNER === creator){
//workaround to stretch adhoc's
delete hcinstancedata.width;
... | conditional_block |
readonlyradiobutton.py | # -*- coding: utf-8 -*-
#
# (c) Copyright 2001-2009 Hewlett-Packard Development Company, L.P.
#
# This program 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 2 of the License, or
# (at your opt... | (QRadioButton):
def __init__(self, parent):
QRadioButton.__init__(self, parent)
self.setFocusPolicy(Qt.NoFocus)
self.clearFocus()
def mousePressEvent(self, e):
if e.button() == Qt.LeftButton:
return
QRadioButton.mousePressEvent(e)
def mouseReleaseEven... | ReadOnlyRadioButton | identifier_name |
readonlyradiobutton.py | # -*- coding: utf-8 -*-
#
# (c) Copyright 2001-2009 Hewlett-Packard Development Company, L.P.
#
# This program 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 2 of the License, or
# (at your opt... |
QRadioButton.mousePressEvent(e)
def mouseReleaseEvent(self, e):
if e.button() == Qt.LeftButton:
return
QRadioButton.mouseReleaseEvent(e)
def mouseMoveEvent(self, e):
return
def keyPressEvent(self, e):
if e.key() not in (Qt.Key_Up, Qt.Key_Left, Qt.... | return | conditional_block |
readonlyradiobutton.py | # -*- coding: utf-8 -*-
#
# (c) Copyright 2001-2009 Hewlett-Packard Development Company, L.P.
#
# This program 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 2 of the License, or
# (at your opt... |
def keyPressEvent(self, e):
if e.key() not in (Qt.Key_Up, Qt.Key_Left, Qt.Key_Right,
Qt.Key_Down, Qt.Key_Escape):
return
QRadioButton.keyPressEvent(e)
def keyReleaseEvent(self, e):
return
| return | identifier_body |
readonlyradiobutton.py | # -*- coding: utf-8 -*-
#
# (c) Copyright 2001-2009 Hewlett-Packard Development Company, L.P.
#
# This program 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 2 of the License, or
# (at your opt... | QRadioButton.mouseReleaseEvent(e)
def mouseMoveEvent(self, e):
return
def keyPressEvent(self, e):
if e.key() not in (Qt.Key_Up, Qt.Key_Left, Qt.Key_Right,
Qt.Key_Down, Qt.Key_Escape):
return
QRadioButton.keyPressEvent(e)
def keyRe... | random_line_split | |
__init__.py | # -*- coding: utf-8 -*-
"""A simple Python library for performing language identification
using an easy-to-understand n-gram based algorithm."""
from __future__ import division
from __future__ import print_function
import nltk
import json
import scipy
import regex
import unicodedata
from collections import Counter
f... | 'ngrams': self.ngrams
}
return json.dumps(model)
def dump_to_python(self, lang='xx'):
"""Dump a PyLID object as Python code."""
def escape(text):
text = text.replace("'", r"\'")
text = text.replace('\n', r'\n')
return text
... | model = {
'n': self.n,
'lang': self.lang, | random_line_split |
__init__.py | # -*- coding: utf-8 -*-
"""A simple Python library for performing language identification
using an easy-to-understand n-gram based algorithm."""
from __future__ import division
from __future__ import print_function
import nltk
import json
import scipy
import regex
import unicodedata
from collections import Counter
f... |
self.classifier = nltk.NaiveBayesClassifier.train(featuresets)
| for (ngram, count) in model.ngrams.iteritems():
num = int((count/model.total_ngrams)*1000)
featuresets += [({'ngram': ngram}, model.lang)] * num | conditional_block |
__init__.py | # -*- coding: utf-8 -*-
"""A simple Python library for performing language identification
using an easy-to-understand n-gram based algorithm."""
from __future__ import division
from __future__ import print_function
import nltk
import json
import scipy
import regex
import unicodedata
from collections import Counter
f... | (self, text):
"""Accepts a string containing plain text and counts each n-gram of
length PyLID.n in the text.
"""
text = text.lower()
text = unicodedata.normalize('NFC', text)
text = punct_digit_re.sub('', text)
text = '#'.join(ws_re.split(text))
for ngra... | add_ngrams_in_text | identifier_name |
__init__.py | # -*- coding: utf-8 -*-
"""A simple Python library for performing language identification
using an easy-to-understand n-gram based algorithm."""
from __future__ import division
from __future__ import print_function
import nltk
import json
import scipy
import regex
import unicodedata
from collections import Counter
f... |
py = '#!/usr/bin/env python\n'
py += '# -*- coding: utf-8 -*-\n\n'
py += 'import pylid\n'
py += 'from collections import Counter\n\n'
py += '{} = pylid.PyLID({})\n'.format(lang, self.n)
py += '{}.total_ngrams = {}\n'.format(lang, self.total_ngrams)
py += "{0}.lan... | text = text.replace("'", r"\'")
text = text.replace('\n', r'\n')
return text | identifier_body |
domtokenlist.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::attr::{Attr, AttrHelpers};
use dom::bindings::codegen::Bindings::DOMTokenListBinding;
use dom::bindings::... | }
}
}
}
// https://dom.spec.whatwg.org/#stringification-behavior
fn Stringifier(self) -> DOMString {
let tokenlist = self.element.root().r().get_tokenlist_attribute(&self.local_name);
str_join(&tokenlist, "\x20")
}
// check-tidy: no specs after t... | _ => {
atoms.push(token);
element.r().set_atomic_tokenlist_attribute(&self.local_name, atoms);
Ok(true) | random_line_split |
domtokenlist.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::attr::{Attr, AttrHelpers};
use dom::bindings::codegen::Bindings::DOMTokenListBinding;
use dom::bindings::... |
fn check_token_exceptions(self, token: &str) -> Fallible<Atom> {
match token {
"" => Err(Syntax),
slice if slice.find(HTML_SPACE_CHARACTERS).is_some() => Err(InvalidCharacter),
slice => Ok(Atom::from_slice(slice))
}
}
}
// https://dom.spec.whatwg.org/#domto... | {
let element = self.element.root();
element.r().get_attribute(&ns!(""), &self.local_name)
} | identifier_body |
domtokenlist.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::attr::{Attr, AttrHelpers};
use dom::bindings::codegen::Bindings::DOMTokenListBinding;
use dom::bindings::... | (self) -> u32 {
self.attribute().map(|attr| {
let attr = attr.r();
attr.value().tokens().map(|tokens| tokens.len()).unwrap_or(0)
}).unwrap_or(0) as u32
}
// https://dom.spec.whatwg.org/#dom-domtokenlist-item
fn Item(self, index: u32) -> Option<DOMString> {
se... | Length | identifier_name |
_attachment.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os,sys, re, json, requests
from oxapi import *
def get_a_task(ox):
folder = ox.get_standard_folder('tasks')
task = list(ox.get_tasks(folder.id))[0]
return task
def upload(bean, args=[{'content':None,'file':None, 'mimetype':'text/plain','name':'attachme... |
if __name__ == '__main__':
with OxHttpAPI.get_session() as ox:
task = get_a_task(ox)
# args = [{ 'file':'attachments_module.py' }]
# upload(task, args)
#create_attachment(ox,task)
#attachments = list(ox.get_attachments(task))
attachments = ox.get_attachments(tas... | match = re.search(regex, response.content)
if match:
return json.loads(match.group(1))
return None | random_line_split |
_attachment.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os,sys, re, json, requests
from oxapi import *
def get_a_task(ox):
folder = ox.get_standard_folder('tasks')
task = list(ox.get_tasks(folder.id))[0]
return task
def upload(bean, args=[{'content':None,'file':None, 'mimetype':'text/plain','name':'attachme... | with OxHttpAPI.get_session() as ox:
task = get_a_task(ox)
# args = [{ 'file':'attachments_module.py' }]
# upload(task, args)
#create_attachment(ox,task)
#attachments = list(ox.get_attachments(task))
attachments = ox.get_attachments(task)
pass | conditional_block | |
_attachment.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os,sys, re, json, requests
from oxapi import *
def get_a_task(ox):
folder = ox.get_standard_folder('tasks')
task = list(ox.get_tasks(folder.id))[0]
return task
def upload(bean, args=[{'content':None,'file':None, 'mimetype':'text/plain','name':'attachme... | content_type = ''.join(('multipart/mixed',) + content_type.partition(';')[1:])
headers = {'Content-Type': content_type}
response = requests.post(url, cookies=ox._cookies, params=params, headers=headers, data=post_body)
if response and response.status_code == 200:
regex='\(... | from requests.packages.urllib3.fields import RequestField
from requests.packages.urllib3.filepost import encode_multipart_formdata
url = ox._url('attachment', 'attach')
params = ox._params()
json_0 = {'module': task.module_type,
'attached': task.id,
... | identifier_body |
_attachment.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os,sys, re, json, requests
from oxapi import *
def | (ox):
folder = ox.get_standard_folder('tasks')
task = list(ox.get_tasks(folder.id))[0]
return task
def upload(bean, args=[{'content':None,'file':None, 'mimetype':'text/plain','name':'attachment.txt'}]):
from requests.packages.urllib3.fields import RequestField
from requests.packages.urllib3.filep... | get_a_task | identifier_name |
query04.rs | use timely::order::TotalOrder;
use timely::dataflow::*;
use timely::dataflow::operators::probe::Handle as ProbeHandle;
use differential_dataflow::operators::*;
use differential_dataflow::lattice::Lattice;
use {Arrangements, Experiment, Collections};
// -- $ID$
// -- TPC-H/TPC-R Order Priority Checking Query (Q4)
// ... | // from
// orders
// where
// o_orderdate >= date ':1'
// and o_orderdate < date ':1' + interval '3' month
// and exists (
// select
// *
// from
// lineitem
// where
// l_orderkey = o_orderkey
// and l_commitdate < l_receiptdate
//... | // :o
// select
// o_orderpriority,
// count(*) as order_count | random_line_split |
query04.rs | use timely::order::TotalOrder;
use timely::dataflow::*;
use timely::dataflow::operators::probe::Handle as ProbeHandle;
use differential_dataflow::operators::*;
use differential_dataflow::lattice::Lattice;
use {Arrangements, Experiment, Collections};
// -- $ID$
// -- TPC-H/TPC-R Order Priority Checking Query (Q4)
// ... | {
let arrangements = arrangements.in_scope(scope, experiment);
experiment
.lineitem(scope)
.flat_map(|l| if l.commit_date < l.receipt_date { Some((l.order_key, ())) } else { None })
.distinct_total()
.join_core(&arrangements.order, |_k,&(),o| {
if o.order_date >= ::t... | identifier_body | |
query04.rs | use timely::order::TotalOrder;
use timely::dataflow::*;
use timely::dataflow::operators::probe::Handle as ProbeHandle;
use differential_dataflow::operators::*;
use differential_dataflow::lattice::Lattice;
use {Arrangements, Experiment, Collections};
// -- $ID$
// -- TPC-H/TPC-R Order Priority Checking Query (Q4)
// ... | <G: Scope<Timestamp=usize>>(
scope: &mut G,
probe: &mut ProbeHandle<usize>,
experiment: &mut Experiment,
arrangements: &mut Arrangements,
)
where
G::Timestamp: Lattice+TotalOrder+Ord
{
let arrangements = arrangements.in_scope(scope, experiment);
experiment
.lineitem(scope)
.... | query_arranged | identifier_name |
query04.rs | use timely::order::TotalOrder;
use timely::dataflow::*;
use timely::dataflow::operators::probe::Handle as ProbeHandle;
use differential_dataflow::operators::*;
use differential_dataflow::lattice::Lattice;
use {Arrangements, Experiment, Collections};
// -- $ID$
// -- TPC-H/TPC-R Order Priority Checking Query (Q4)
// ... |
})
.count_total()
.probe_with(probe);
} | {
None
} | conditional_block |
backend_termion.rs | #[cfg(feature = "termion")]
#[test]
fn backend_termion_should_only_write_diffs() -> Result<(), Box<dyn std::error::Error>> | })?;
terminal.draw(|f| {
f.render_widget(Paragraph::new("ab"), area);
})?;
terminal.draw(|f| {
f.render_widget(Paragraph::new("abc"), area);
})?;
}
let expected = {
use termion::{color, cursor, style};
let mut s = String::new();
... | {
use std::{fmt::Write, io::Cursor};
let mut bytes = Vec::new();
let mut stdout = Cursor::new(&mut bytes);
{
use tui::{
backend::TermionBackend, layout::Rect, widgets::Paragraph, Terminal, TerminalOptions,
Viewport,
};
let backend = TermionBackend::new(&m... | identifier_body |
backend_termion.rs | #[cfg(feature = "termion")]
#[test]
fn backend_termion_should_only_write_diffs() -> Result<(), Box<dyn std::error::Error>> {
use std::{fmt::Write, io::Cursor};
let mut bytes = Vec::new();
let mut stdout = Cursor::new(&mut bytes);
{
use tui::{
backend::TermionBackend, layout::Rect, w... | };
assert_eq!(std::str::from_utf8(&bytes)?, expected);
Ok(())
} | s | random_line_split |
backend_termion.rs | #[cfg(feature = "termion")]
#[test]
fn | () -> Result<(), Box<dyn std::error::Error>> {
use std::{fmt::Write, io::Cursor};
let mut bytes = Vec::new();
let mut stdout = Cursor::new(&mut bytes);
{
use tui::{
backend::TermionBackend, layout::Rect, widgets::Paragraph, Terminal, TerminalOptions,
Viewport,
};... | backend_termion_should_only_write_diffs | identifier_name |
nasnet_utils.py | class NasNetABaseCell(object):
"""NASNet Cell class that is used as a 'layer' in image architectures.
Args:
num_conv_filters: The number of filters for each convolution operation.
operations: List of operations that are performed in the NASNet Cell in
order.
used_hiddenstates: Binary array that s... | if drop_path_keep_prob < 1.0:
assert drop_connect_version in ['v1', 'v2', 'v3']
if drop_connect_version in ['v2', 'v3']: | random_line_split | |
nasnet_utils.py | .dtype)
net = net * keep_prob_inv * binary_tensor
return net
def _operation_to_filter_shape(operation):
splitted_operation = operation.split('x')
filter_shape = int(splitted_operation[0][-1])
assert filter_shape == int(
splitted_operation[1][0]), 'Rectangular filters not supported.'
return filter... | net = tf.nn.relu6(net) | conditional_block | |
nasnet_utils.py | [:, 1:, 1:, :]
concat_axis = 3
else:
pad_arr = [[0, 0], [0, 0], [0, 1], [0, 1]]
path2 = tf.pad(tensor=net, paddings=pad_arr)[:, :, 1:, 1:]
concat_axis = 1
path2 = tf.compat.v2.nn.avg_pool2d(
input=path2,
ksize=[1, 1, 1, 1],
strides=stride_spec,
padding='VALID',
data_fo... | """Runs the conv cell."""
self._cell_num = cell_num
self._filter_scaling = filter_scaling
self._filter_size = int(self._num_conv_filters * filter_scaling)
i = 0
with tf.compat.v1.variable_scope(scope):
net = self._cell_base(net, prev_layer)
for iteration in range(5):
with tf.com... | identifier_body | |
nasnet_utils.py | .relu(net)
net = slim.conv2d(net, num_filters, 1, scope='1x1')
net = slim.batch_norm(net, scope='beginning_bn')
# num_or_size_splits=1
net = [net]
net.append(prev_layer)
return net
def __call__(self, net, scope=None, filter_scaling=1, stride=1,
prev_layer=None, cell_num=-1, cur... | __init__ | identifier_name | |
pos.py | , c.conversion_factor, it.item_tax_template, it.valid_from
from
`tabItem` i
left join `tabItem Default` id on id.parent = i.name and id.company = %s
left join `tabItem Tax` it on it.parent = i.name
left join `tabUOM Conversion Detail` c on i.name = c.parent and i.sales_uom = c.uom
where
i.disabled = 0 a... | pricing_rules = ""
if doc.ignore_pricing_rule == 0:
pricing_rules = frappe.db.sql(""" Select * from `tabPricing Rule` where docstatus < 2
and ifnull(for_price_list, '') in (%(price_list)s, '') and selling = 1
and ifnull(company, '') in (%(company)s, '') and disable = 0 and %(date)s
between ifnull(v... | identifier_body | |
pos.py | _letter_head
doc.ignore_pricing_rule = pos_profile.get('ignore_pricing_rule') or 0
doc.apply_discount_on = pos_profile.get('apply_discount_on') or 'Grand Total'
doc.customer_group = pos_profile.get('customer_group') or get_root('Customer Group')
doc.territory = pos_profile.get('territory') or get_root('Territory')
... |
return itemwise_barcode
def get_item_tax_data():
# get default tax of an item
# example: {'Consulting Services': {'Excise 12 - TS': '12.000'}}
itemwise_tax = {}
taxes = frappe.db.sql(""" select parent, tax_type, tax_rate from `tabItem Tax Template Detail`""", as_dict=1)
for tax in taxes | if item.item_code not in itemwise_barcode:
itemwise_barcode.setdefault(item.item_code, [])
itemwise_barcode[item.item_code].append(barcode.get("barcode")) | conditional_block |
pos.py | _data = {}
if address:
address_data = address[0]
address_data.update({'full_name': data.customer_name, 'customer_pos_id': data.customer_pos_id})
customer_address[data.name] = address_data
return customer_address
def get_contacts(customers):
customer_contact = {}
if isinstance(customers, string_types):
... | make_customer_and_address | identifier_name | |
pos.py | doctype_meta = {
'customer': frappe.get_meta('Customer'),
'invoice': frappe.get_meta('Sales Invoice')
}
for row in frappe.get_all('DocField', fields=['fieldname', 'options'],
filters={'parent': 'Sales Invoice', 'fieldtype': 'Table'}):
doctype_meta[row.fieldname] = frappe.get_meta(row.options)
re... | pos_profile.get("currency"), nowdate(), args="for_selling") or 1.0
return conversion_rate
def get_meta(): | random_line_split | |
facebook.js | EasySocial.module( 'oauth/facebook', function($) {
var module = this;
EasySocial.require()
.done(function() {
EasySocial.Controller( 'OAuth.Facebook',
{
defaultOptions :
{
"{login}" : "[data-oauth-facebook-login]",
"{revoke}" : "[data-oauth-facebook-revoke]",
"{pushInput}" : "[data-oauth-f... |
},
"{login} click" : function()
{
self.openDialog( self.options.url );
},
"{revoke} click" : function()
{
var callback = self.element.data( 'callback' );
EasySocial.dialog(
{
content : EasySocial.ajax( 'site/views/oauth/confirmRevoke' , { "client" : 'facebook... | {
self.openDialog( self.options.revokePublishURL );
} | conditional_block |
facebook.js | EasySocial.module( 'oauth/facebook', function($) {
var module = this; |
EasySocial.Controller( 'OAuth.Facebook',
{
defaultOptions :
{
"{login}" : "[data-oauth-facebook-login]",
"{revoke}" : "[data-oauth-facebook-revoke]",
"{pushInput}" : "[data-oauth-facebook-push]"
}
},
function( self )
{
return {
init : function()
{
},
openDialog : fun... |
EasySocial.require()
.done(function() { | random_line_split |
index.d.ts | // Type definitions for PebbleKit JS v4.0.0
// Project: https://developer.pebble.com/docs/js/Pebble/
// Definitions by: Makoto Kawasaki <https://github.com/makotokw>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare namespace PebbleKit {
interface Error {
message: string;
}
... |
/**
* Returns a unique account token that is associated with the Pebble account of the current user.
* @return WatchInfo
*/
getActiveWatchInfo(): WatchInfo;
/**
* Returns a unique account token that is associated with the Pebble account of the current user.
... | * The length of the list should be checked to determine whether the user is subscribed to at least one topic.
* @param successCb The developer-defined function to process the retuned list of topic strings.
* @param errorCb The developer-defined function to gracefully handle any erro... | random_line_split |
oai_harvest.py | # -*- coding: utf-8 -*-
#
# This file is part of Invenio Demosite.
# Copyright (C) 2013 CERN.
#
# Invenio Demosite 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 2 of the
# License, or (at your... | f1 = u'reportnumber'
f2 = u'division'
f3 = u''
setRecList = None
setDefinition = u'c=;p1=CERN;f1=reportnumber;m1=a;p2=TH;f2=division;m2=e;p3=;f3=;m3=;'
last_updated = datetime.now()
id = 3
setSpec = u'cern:theory'
setDescription = u''
p3 = ... | class OaiREPOSITORY_2:
f1 = u'reportnumber'
f2 = u'division'
f3 = u''
setRecList = None
setDefinition = u'c=;p1=CERN;f1=reportnumber;m1=a;p2=(EP|PPE);f2=division;m2=r;p3=;f3=;m3=;'
last_updated = datetime.now()
id = 2
setSpec = u'cern:experiment'
s... | identifier_body |
oai_harvest.py | # -*- coding: utf-8 -*-
#
# This file is part of Invenio Demosite.
# Copyright (C) 2013 CERN.
#
# Invenio Demosite 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 2 of the
# License, or (at your... | (DataSet):
class OaiREPOSITORY_2:
f1 = u'reportnumber'
f2 = u'division'
f3 = u''
setRecList = None
setDefinition = u'c=;p1=CERN;f1=reportnumber;m1=a;p2=(EP|PPE);f2=division;m2=r;p3=;f3=;m3=;'
last_updated = datetime.now()
id = 2
setSpec = u'cern:exper... | OaiREPOSITORYData | identifier_name |
oai_harvest.py | # -*- coding: utf-8 -*-
# | # modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Invenio Demosite is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of... | # This file is part of Invenio Demosite.
# Copyright (C) 2013 CERN.
#
# Invenio Demosite is free software; you can redistribute it and/or | random_line_split |
conf.py | # All configuration values have a default; values that are commented out
# serve to show the default.
import sys
import os
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abs... | # Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_... | random_line_split | |
search.service.spec.ts | import { Injector, NgZone } from '@angular/core';
import { fakeAsync, tick } from '@angular/core/testing';
import { of } from 'rxjs';
import { SearchService } from './search.service';
import { WebWorkerClient } from 'app/shared/web-worker';
describe('SearchService', () => {
let injector: Injector;
let service: Se... | it('should send a "query-index" message to the worker', () => {
service.search('some query').subscribe();
expect(mockWorker.sendMessage).toHaveBeenCalledWith('query-index', 'some query');
});
it('should push the response to the returned observable', () => {
const mockSearchResults = { res... | expect(mockWorker.sendMessage).toHaveBeenCalledWith('load-index');
});
| random_line_split |
script.js | $(document).ready(function() {
// Toggle Extra Informations for single Topic by Click +
$('.toggle-sibling').click(function() {
var infoBox = $(this).parent().next('.details-wrapper');
// console.log(infoBox);
if (infoBox.hasClass('active')) {
// if info box is open, close it and remove stat... |
// Detect Browser Language
console.log(window.navigator.language);
});
| {
// close all <section> with class "active"
$('section.active').slideUp('fast').removeClass('active');
// open the requested info-box and add class "active"
$(id).slideDown('fast').addClass('active');
} | identifier_body |
script.js | $(document).ready(function() {
// Toggle Extra Informations for single Topic by Click +
$('.toggle-sibling').click(function() {
var infoBox = $(this).parent().next('.details-wrapper');
// console.log(infoBox);
if (infoBox.hasClass('active')) {
// if info box is open, close it and remove stat... | };
return false;
});
// Close all open info-boxes and open the requested info-box
function openInfoBox (id) {
// close all <section> with class "active"
$('section.active').slideUp('fast').removeClass('active');
// open the requested info-box and add class "active"
$(id).slideDown('... | random_line_split | |
script.js | $(document).ready(function() {
// Toggle Extra Informations for single Topic by Click +
$('.toggle-sibling').click(function() {
var infoBox = $(this).parent().next('.details-wrapper');
// console.log(infoBox);
if (infoBox.hasClass('active')) {
// if info box is open, close it and remove stat... | ;
return false;
});
// Close all open info-boxes and open the requested info-box
function openInfoBox (id) {
// close all <section> with class "active"
$('section.active').slideUp('fast').removeClass('active');
// open the requested info-box and add class "active"
$(id).slideDown('fast'... | { // open info-box 2
openInfoBox('#col-2');
} | conditional_block |
script.js | $(document).ready(function() {
// Toggle Extra Informations for single Topic by Click +
$('.toggle-sibling').click(function() {
var infoBox = $(this).parent().next('.details-wrapper');
// console.log(infoBox);
if (infoBox.hasClass('active')) {
// if info box is open, close it and remove stat... | (id) {
// close all <section> with class "active"
$('section.active').slideUp('fast').removeClass('active');
// open the requested info-box and add class "active"
$(id).slideDown('fast').addClass('active');
}
// Detect Browser Language
console.log(window.navigator.language);
});
| openInfoBox | identifier_name |
arena.ts | import { h, VNode } from 'snabbdom';
import { bind, dataIcon } from 'common/snabbdom';
import TournamentController from '../ctrl';
import { player as renderPlayer, ratio2percent, playerName } from './util';
import { teamName } from './battle';
import { MaybeVNodes, Pagination, PodiumPlayer, Score, StandingPlayer } from... | );
}
function podiumUsername(p: PodiumPlayer) {
return h(
'a.text.ulpt.user-link',
{
attrs: { href: '/@/' + p.name },
},
playerName(p)
);
}
function podiumStats(p: PodiumPlayer, berserkable: boolean, ctrl: TournamentController): VNode {
const noarg = ctrl.trans.noarg,
nb = p.nb;
re... | random_line_split | |
arena.ts | import { h, VNode } from 'snabbdom';
import { bind, dataIcon } from 'common/snabbdom';
import TournamentController from '../ctrl';
import { player as renderPlayer, ratio2percent, playerName } from './util';
import { teamName } from './battle';
import { MaybeVNodes, Pagination, PodiumPlayer, Score, StandingPlayer } from... | },
},
tableBody
),
]
);
}
| preloadUserTips(vnode.elm as HTMLElement);
},
| identifier_body |
arena.ts | import { h, VNode } from 'snabbdom';
import { bind, dataIcon } from 'common/snabbdom';
import TournamentController from '../ctrl';
import { player as renderPlayer, ratio2percent, playerName } from './util';
import { teamName } from './battle';
import { MaybeVNodes, Pagination, PodiumPlayer, Score, StandingPlayer } from... | (ctrl: TournamentController, player: StandingPlayer) {
const userId = player.name.toLowerCase(),
nbScores = player.sheet.scores.length;
const battle = ctrl.data.teamBattle;
return h(
'tr',
{
key: userId,
class: {
me: ctrl.opts.userId === userId,
long: nbScores > 35,
... | playerTr | identifier_name |
urls.py | """is_teklif_sistemi URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home'... | urlpatterns = [
url(r'^admin/', admin.site.urls),
] | from django.contrib import admin
| random_line_split |
test.js | "use strict";
var expect = require('chai').expect
, protolib = require(__dirname + '/../')
;
describe('protolib', function() {
describe('clone', function() {
it('should create a clone of the given object', function() {
var object = {
name: 'Philip'
, hello: function() { return 'Hell... | expect(object).to.have.deep.property('values[2]', 3);
});
});
}); | random_line_split | |
network.py | import re
import sys
sys.path.append('..')
from src.link import Link
from src.node import Node
class Network(object):
def __init__(self, config):
self.config = config
self.nodes = {}
self.address = 1
self.build()
def build(self):
state = 'network'
with open(s... |
def set_delay(self, link, delay):
numeric_delay = self.convert(delay)
if delay.endswith("ms"):
link.propagation = numeric_delay / 1000.0
if delay.endswith("seconds"):
link.propagation = numeric_delay
def set_queue(self, link, size):
numeric_size = self.... | numeric_rate = self.convert(rate)
if rate.endswith("Gbps"):
link.bandwidth = numeric_rate * 1000000000
elif rate.endswith("Mbps"):
link.bandwidth = numeric_rate * 1000000
elif rate.endswith("Kbps"):
link.bandwidth = numeric_rate * 1000
elif rate.endswi... | identifier_body |
network.py | import re
import sys
sys.path.append('..')
from src.link import Link
from src.node import Node
class Network(object):
def __init__(self, config):
self.config = config
self.nodes = {}
self.address = 1
self.build()
def build(self):
state = 'network'
with open(s... | for node in self.nodes.values():
for link in node.links:
link.loss = loss
def set_bandwidth(self, link, rate):
numeric_rate = self.convert(rate)
if rate.endswith("Gbps"):
link.bandwidth = numeric_rate * 1000000000
elif rate.endswith("Mbps"):
... | if name not in self.nodes:
self.nodes[name] = Node(name)
return self.nodes[name]
def loss(self, loss): | random_line_split |
network.py | import re
import sys
sys.path.append('..')
from src.link import Link
from src.node import Node
class Network(object):
def | (self, config):
self.config = config
self.nodes = {}
self.address = 1
self.build()
def build(self):
state = 'network'
with open(self.config) as f:
for line in f.readlines():
if line.startswith('#'):
continue
... | __init__ | identifier_name |
network.py | import re
import sys
sys.path.append('..')
from src.link import Link
from src.node import Node
class Network(object):
def __init__(self, config):
self.config = config
self.nodes = {}
self.address = 1
self.build()
def build(self):
state = 'network'
with open(s... |
if fields[i].endswith("pkts"):
self.set_queue(l, fields[i])
if fields[i].endswith("loss"):
self.set_loss(l, fields[i])
def get_node(self, name):
if name not in self.nodes:
self.nodes[name] = Node(name)
return self.nodes[name]
... | self.set_delay(l, fields[i]) | conditional_block |
Markdown.ts | import marked from 'marked';
import { unescape } from 'lodash';
export enum TokenType {
HEADING = 'heading',
LIST = 'list',
LIST_ITEM = 'listItem',
PARAGRAPH = 'paragraph',
TEXT = 'text',
BLOCKQUOTE = 'blockquote',
SPACE = 'space',
CODE = 'code',
}
type SimpleToken<Type> = { type: Type; raw?: string }... |
return output + EOL;
}
listItem(token: ListItemToken, ctx: RenderingContext): string {
const indent = ctx.indent ?? 0;
const bullet = ctx.orderedList ? `${ctx.itemIndex ?? 1}.` : '-';
let output = this.indent(indent) + bullet + ' ';
if (token.tokens[0]) {
output += this.renderToken(toke... | {
output += this.listItem(token.items[i], {
...ctx,
orderedList: token.ordered,
itemIndex: i + 1,
});
} | conditional_block |
Markdown.ts | import marked from 'marked';
import { unescape } from 'lodash';
export enum TokenType {
HEADING = 'heading',
LIST = 'list',
LIST_ITEM = 'listItem',
PARAGRAPH = 'paragraph',
TEXT = 'text',
BLOCKQUOTE = 'blockquote',
SPACE = 'space',
CODE = 'code',
}
type SimpleToken<Type> = { type: Type; raw?: string }... | orderedList: token.ordered,
itemIndex: i + 1,
});
}
return output + EOL;
}
listItem(token: ListItemToken, ctx: RenderingContext): string {
const indent = ctx.indent ?? 0;
const bullet = ctx.orderedList ? `${ctx.itemIndex ?? 1}.` : '-';
let output = this.indent(indent) + bu... | output += this.listItem(token.items[i], {
...ctx, | random_line_split |
Markdown.ts | import marked from 'marked';
import { unescape } from 'lodash';
export enum TokenType {
HEADING = 'heading',
LIST = 'list',
LIST_ITEM = 'listItem',
PARAGRAPH = 'paragraph',
TEXT = 'text',
BLOCKQUOTE = 'blockquote',
SPACE = 'space',
CODE = 'code',
}
type SimpleToken<Type> = { type: Type; raw?: string }... |
/**
* Type guard for ListItemToken type.
*/
export function isListItemToken(token: Token): token is ListItemToken {
return token.type === TokenType.LIST_ITEM;
}
/**
* Indents subsequent lines in given string.
*/
export function indentMultilineString(str: string, depth: number = 0, indent: string = ' ') {
re... | {
return token.type === TokenType.LIST;
} | identifier_body |
Markdown.ts | import marked from 'marked';
import { unescape } from 'lodash';
export enum TokenType {
HEADING = 'heading',
LIST = 'list',
LIST_ITEM = 'listItem',
PARAGRAPH = 'paragraph',
TEXT = 'text',
BLOCKQUOTE = 'blockquote',
SPACE = 'space',
CODE = 'code',
}
type SimpleToken<Type> = { type: Type; raw?: string }... | (depth: number = 1): ListToken {
return {
type: TokenType.LIST,
depth,
items: [],
};
}
export function createListItemToken(text: string, depth: number = 0): ListItemToken {
return {
type: TokenType.LIST_ITEM,
depth,
text,
tokens: [createTextToken(text)],
};
}
/**
* Type guard for ... | createListToken | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.