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 |
|---|---|---|---|---|
mainTelemetryService.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | for (let i = 0; i < allAppenders.length; i++) {
allAppenders[i].log(eventName, data);
}
}
protected addCommonProperties(data?: any): void {
data = data || {};
let eventDate: Date = new Date();
data['sessionID'] = this.sessionId;
data['timestamp'] = eventDate;
data['version'] = this.config.version;... | {
if (this.hardIdleMonitor && this.hardIdleMonitor.getStatus() === UserStatus.Idle) {
return;
}
// don't send telemetry when channel is not enabled
if (!this.config.enableTelemetry) {
return;
}
// don't send events when the user is optout unless the event is flaged as optin friendly
if(!this.confi... | identifier_body |
mainTelemetryService.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... |
this.sessionId = this.config.sessionID || (uuid.generateUuid() + Date.now());
if (this.config.enableHardIdle) {
this.hardIdleMonitor = new IdleMonitor();
}
if (this.config.enableSoftIdle) {
this.softIdleMonitor = new IdleMonitor(MainTelemetryService.SOFT_IDLE_TIME);
this.softIdleMonitor.addOneTimeAct... | private startTime: Date;
private optInFriendly: string[];
constructor(config?: ITelemetryServiceConfig) {
super(config); | random_line_split |
mainTelemetryService.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... |
// don't send telemetry when channel is not enabled
if (!this.config.enableTelemetry) {
return;
}
// don't send events when the user is optout unless the event is flaged as optin friendly
if(!this.config.userOptIn && this.optInFriendly.indexOf(eventName) === -1) {
return;
}
this.eventCount++;
... | {
return;
} | conditional_block |
job.rs | use std::collections::HashSet;
use std::net::SocketAddr;
use std::time;
use crate::control::cio;
use crate::torrent::Torrent;
use crate::util::UHashMap;
pub trait Job<T: cio::CIO> {
fn update(&mut self, torrents: &mut UHashMap<Torrent<T>>);
}
pub struct TrackerUpdate;
impl<T: cio::CIO> Job<T> for TrackerUpdate ... |
}
if !torrent.complete() {
torrent.rank_peers();
}
if !self.active.contains_key(id) {
self.active.insert(*id, active);
}
let prev = self.active.get_mut(id).unwrap();
if *prev != active {
... | {
torrent.rpc_update_pieces();
self.piece_update = time::Instant::now();
} | conditional_block |
job.rs | use std::collections::HashSet;
use std::net::SocketAddr;
use std::time;
use crate::control::cio;
use crate::torrent::Torrent;
use crate::util::UHashMap;
pub trait Job<T: cio::CIO> {
fn update(&mut self, torrents: &mut UHashMap<Torrent<T>>);
}
pub struct TrackerUpdate;
impl<T: cio::CIO> Job<T> for TrackerUpdate ... |
impl<T: cio::CIO> Job<T> for SessionUpdate {
fn update(&mut self, torrents: &mut UHashMap<Torrent<T>>) {
for (_, torrent) in torrents.iter_mut() {
if torrent.dirty() {
torrent.serialize();
}
}
}
}
pub struct TorrentTxUpdate {
piece_update: time::Inst... | random_line_split | |
job.rs | use std::collections::HashSet;
use std::net::SocketAddr;
use std::time;
use crate::control::cio;
use crate::torrent::Torrent;
use crate::util::UHashMap;
pub trait Job<T: cio::CIO> {
fn update(&mut self, torrents: &mut UHashMap<Torrent<T>>);
}
pub struct TrackerUpdate;
impl<T: cio::CIO> Job<T> for TrackerUpdate ... | {
piece_update: time::Instant,
active: UHashMap<bool>,
}
impl TorrentTxUpdate {
pub fn new() -> TorrentTxUpdate {
TorrentTxUpdate {
piece_update: time::Instant::now(),
active: UHashMap::default(),
}
}
}
impl<T: cio::CIO> Job<T> for TorrentTxUpdate {
fn upda... | TorrentTxUpdate | identifier_name |
2_4_1_a.rs | /*
2.4.6:
a) S -> + S S | - S S | a
$> rustc -o parser 2_4_1_a.rs
$> ./parser
*/
static CODE: &'static str = "-+aa-aa";
pub fn sa(mut head: i32) -> i32 |
fn main() {
let head = sa(0);
if head as usize!= CODE.len() {
panic!("parsed {} chars, but totally {} chars", head, CODE.len());
}
}
| {
match CODE.chars().nth(head as usize){
None => {
panic!("missing required element!");
},
Some('a') => {
head += 1;
},
Some('+') | Some('-') => {
head += 1;
head = sa(head);
head = sa(head);
},
_ => ... | identifier_body |
2_4_1_a.rs | /*
2.4.6:
a) S -> + S S | - S S | a
$> rustc -o parser 2_4_1_a.rs
$> ./parser
*/
static CODE: &'static str = "-+aa-aa";
pub fn sa(mut head: i32) -> i32 {
match CODE.chars().nth(head as usize){
None => {
panic!("missing required element!");
},
Some('a') => {
... |
}
| {
panic!("parsed {} chars, but totally {} chars", head, CODE.len());
} | conditional_block |
2_4_1_a.rs | /*
2.4.6:
a) S -> + S S | - S S | a
$> rustc -o parser 2_4_1_a.rs
$> ./parser
*/
static CODE: &'static str = "-+aa-aa";
pub fn sa(mut head: i32) -> i32 {
match CODE.chars().nth(head as usize){
None => {
panic!("missing required element!");
},
Some('a') => {
... | () {
let head = sa(0);
if head as usize!= CODE.len() {
panic!("parsed {} chars, but totally {} chars", head, CODE.len());
}
}
| main | identifier_name |
2_4_1_a.rs | /*
2.4.6:
a) S -> + S S | - S S | a
$> rustc -o parser 2_4_1_a.rs
$> ./parser
*/
static CODE: &'static str = "-+aa-aa";
pub fn sa(mut head: i32) -> i32 {
match CODE.chars().nth(head as usize){
None => {
panic!("missing required element!");
},
Some('a') => {
... | },
_ => { panic!("undefind element!"); }
}
head
}
fn main() {
let head = sa(0);
if head as usize!= CODE.len() {
panic!("parsed {} chars, but totally {} chars", head, CODE.len());
}
} | random_line_split | |
start.js | 'use strict';
// Do this as the first thing so that any code reading it knows the right env.
process.env.BABEL_ENV = 'development';
process.env.NODE_ENV = 'development';
// Makes the script crash on unhandled rejections instead of silently
// ignoring them. In the future, promise rejections that are not handled will
... |
if (isInteractive) {
clearConsole();
}
console.log(chalk.cyan('Starting the development server...\n'));
openBrowser(urls.localUrlForBrowser);
});
['SIGINT', 'SIGTERM'].forEach(function(sig) {
process.on(sig, function() {
devServer.close();
process.exit();
... | {
return console.log(err);
} | conditional_block |
start.js | 'use strict';
// Do this as the first thing so that any code reading it knows the right env.
process.env.BABEL_ENV = 'development';
process.env.NODE_ENV = 'development';
| });
// Ensure environment variables are read.
require('../config/env');
const fs = require('fs');
const chalk = require('chalk');
const webpack = require('webpack');
const WebpackDevServer = require('webpack-dev-server');
const clearConsole = require('react-dev-utils/clearConsole');
const checkRequiredFiles = require... | // Makes the script crash on unhandled rejections instead of silently
// ignoring them. In the future, promise rejections that are not handled will
// terminate the Node.js process with a non-zero exit code.
process.on('unhandledRejection', err => {
throw err; | random_line_split |
team.ts | const team = {
sidemenu: 'Side menu',
sidemenuTooltip: 'The vertical menu bar on the left side of the screen, the top half of which can be customized by team',
subTitle: 'Manage team members & settings',
add: 'Add team',
name: 'Team name',
addMember: 'Add member',
member: 'Team member',
... | toMember: 'To member',
leave: 'Leave team',
delete: 'Delete team',
isPublicTips: 'Set to public means users not in this team can also use this sidemenu',
menuNotExist: 'Target sidemenu is not exist',
menuNotPublic: 'Target sidement is not public',
mainTeamTips: 'Every user will be in global ... | random_line_split | |
error.rs | use std::{error, fmt, str};
use string::SafeString; | pub struct Error {
desc: SafeString,
}
impl Error {
/// Creates a new Error.
pub fn new(desc: &str) -> Error {
Self {
desc: SafeString::from(desc),
}
}
}
impl fmt::Debug for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Error: {}", er... |
/// An error object.
#[repr(C)]
#[derive(Clone, PartialEq)] | random_line_split |
error.rs | use std::{error, fmt, str};
use string::SafeString;
/// An error object.
#[repr(C)]
#[derive(Clone, PartialEq)]
pub struct Error {
desc: SafeString,
}
impl Error {
/// Creates a new Error.
pub fn new(desc: &str) -> Error {
Self {
desc: SafeString::from(desc),
}
}
}
impl fm... | () {
let msg = "out of bounds";
let err = Error::new(msg);
assert_eq!(error::Error::description(&err), msg);
}
}
| description | identifier_name |
environment.py | import yaml
from os import makedirs
from os.path import join,dirname,realpath,isdir
script_dir = dirname(realpath(__file__))
default_yml_filepath = join(script_dir,'defaults.yml')
defaults = {
"output_dir": 'output',
"header_img_dir": 'imgs/headers/',
"scaled_img_dir": 'imgs/scaled/',
"original_img_d... |
if not isdir(path):
makedirs(path) | raise RuntimeError('config not loaded yet')
for key in ['header_img_dir','scaled_img_dir','original_img_dir']:
path = config[key] | random_line_split |
environment.py | import yaml
from os import makedirs
from os.path import join,dirname,realpath,isdir
script_dir = dirname(realpath(__file__))
default_yml_filepath = join(script_dir,'defaults.yml')
defaults = {
"output_dir": 'output',
"header_img_dir": 'imgs/headers/',
"scaled_img_dir": 'imgs/scaled/',
"original_img_d... | path = config[key]
if not isdir(path):
makedirs(path) | conditional_block | |
environment.py | import yaml
from os import makedirs
from os.path import join,dirname,realpath,isdir
script_dir = dirname(realpath(__file__))
default_yml_filepath = join(script_dir,'defaults.yml')
defaults = {
"output_dir": 'output',
"header_img_dir": 'imgs/headers/',
"scaled_img_dir": 'imgs/scaled/',
"original_img_d... | ():
if not config:
raise RuntimeError('config not loaded yet')
return config
def loadConfig(yml_filepath):
config.update(defaults)
with open(yml_filepath) as f:
patch = yaml.load(f.read())
config.update(patch)
# make paths absolute
config['header_img_dir'] = join(config... | getConfig | identifier_name |
environment.py | import yaml
from os import makedirs
from os.path import join,dirname,realpath,isdir
script_dir = dirname(realpath(__file__))
default_yml_filepath = join(script_dir,'defaults.yml')
defaults = {
"output_dir": 'output',
"header_img_dir": 'imgs/headers/',
"scaled_img_dir": 'imgs/scaled/',
"original_img_d... |
def loadConfig(yml_filepath):
config.update(defaults)
with open(yml_filepath) as f:
patch = yaml.load(f.read())
config.update(patch)
# make paths absolute
config['header_img_dir'] = join(config['output_dir'],config['header_img_dir'])
config['scaled_img_dir'] = join(config['output_d... | if not config:
raise RuntimeError('config not loaded yet')
return config | identifier_body |
binder.py | # Tweepy
# Copyright 2009-2010 Joshua Roesslein
# See LICENSE for details.
import httplib
import urllib
import time
import re
from tweepy.error import TweepError
from tweepy.utils import convert_to_utf8_str
from tweepy.models import Model
re_path_template = re.compile('{\w+}')
def bind_api(**config):
class AP... |
self.path = self.path.replace(variable, value)
def execute(self):
# Build the request URL
url = self.api_root + self.path
if len(self.parameters):
url = '%s?%s' % (url, urllib.urlencode(self.parameters))
# Query the cache if one... | try:
value = urllib.quote(self.parameters[name])
except KeyError:
raise TweepError('No parameter value found for path variable: %s' % name)
del self.parameters[name] | conditional_block |
binder.py | # Tweepy
# Copyright 2009-2010 Joshua Roesslein
# See LICENSE for details.
import httplib
import urllib
import time
import re
from tweepy.error import TweepError
from tweepy.utils import convert_to_utf8_str
from tweepy.models import Model
re_path_template = re.compile('{\w+}')
def bind_api(**config):
class AP... | # Exit request loop if non-retry error code
if self.retry_errors:
if resp.status not in self.retry_errors: break
else:
if resp.status == 200: break
# Sleep before retrying request again
time.sleep(se... | resp = conn.getresponse()
except Exception, e:
raise TweepError('Failed to send request: %s' % e)
| random_line_split |
binder.py | # Tweepy
# Copyright 2009-2010 Joshua Roesslein
# See LICENSE for details.
import httplib
import urllib
import time
import re
from tweepy.error import TweepError
from tweepy.utils import convert_to_utf8_str
from tweepy.models import Model
re_path_template = re.compile('{\w+}')
def bind_api(**config):
| self.retry_delay = kargs.pop('retry_delay', api.retry_delay)
self.retry_errors = kargs.pop('retry_errors', api.retry_errors)
self.headers = kargs.pop('headers', {})
self.build_parameters(args, kargs)
# Pick correct URL root to use
if self.search_a... | class APIMethod(object):
path = config['path']
payload_type = config.get('payload_type', None)
payload_list = config.get('payload_list', False)
allowed_param = config.get('allowed_param', [])
method = config.get('method', 'GET')
require_auth = config.get('require_auth', ... | identifier_body |
binder.py | # Tweepy
# Copyright 2009-2010 Joshua Roesslein
# See LICENSE for details.
import httplib
import urllib
import time
import re
from tweepy.error import TweepError
from tweepy.utils import convert_to_utf8_str
from tweepy.models import Model
re_path_template = re.compile('{\w+}')
def | (**config):
class APIMethod(object):
path = config['path']
payload_type = config.get('payload_type', None)
payload_list = config.get('payload_list', False)
allowed_param = config.get('allowed_param', [])
method = config.get('method', 'GET')
require_auth = config.get... | bind_api | identifier_name |
task.rs | use std::collections::HashMap;
use std::str::FromStr;
use author::Author;
#[derive(Debug)]
pub struct Task {
pub task_type: String,
pub id: u32,
pub title: String,
description: Option<String>,
assignees: Vec<Author>,
properties: HashMap<String, String>,
}
impl Task {
pub fn new(lines: &Ve... | else {
let index = subject.find(id_str).unwrap();
subject[index + id_str.len() + 1..].trim().to_string()
};
Task {
id: id,
title: title,
task_type: task_type,
description: None,
assignees: Vec::new(),
... | {
let index = subject.find('-').unwrap();
subject[index + 1..].trim().to_string()
} | conditional_block |
task.rs | use std::collections::HashMap;
use std::str::FromStr;
use author::Author;
#[derive(Debug)]
pub struct Task {
pub task_type: String,
pub id: u32,
pub title: String,
description: Option<String>,
assignees: Vec<Author>,
properties: HashMap<String, String>,
}
impl Task {
pub fn new(lines: &Ve... | title: title,
task_type: task_type,
description: None,
assignees: Vec::new(),
properties: HashMap::new(),
}
}
}
| {
let subject = lines[0][4..].to_string();
let words: Vec<&str> = lines[0][4..].split_whitespace().collect();
let task_type = words[0].to_string();
let id_str = words[1];
let id: u32 = FromStr::from_str(id_str).unwrap();
let title =
if words[2] == "-" {
... | identifier_body |
task.rs | use std::collections::HashMap;
use std::str::FromStr;
use author::Author;
#[derive(Debug)]
pub struct Task {
pub task_type: String,
pub id: u32,
pub title: String,
description: Option<String>,
assignees: Vec<Author>,
properties: HashMap<String, String>,
}
impl Task {
pub fn | (lines: &Vec<&str>) -> Task {
let subject = lines[0][4..].to_string();
let words: Vec<&str> = lines[0][4..].split_whitespace().collect();
let task_type = words[0].to_string();
let id_str = words[1];
let id: u32 = FromStr::from_str(id_str).unwrap();
let title =
... | new | identifier_name |
task.rs | use std::collections::HashMap;
use std::str::FromStr;
use author::Author;
#[derive(Debug)]
pub struct Task {
pub task_type: String,
pub id: u32,
pub title: String,
description: Option<String>,
assignees: Vec<Author>,
properties: HashMap<String, String>,
}
impl Task {
pub fn new(lines: &Ve... |
Task {
id: id,
title: title,
task_type: task_type,
description: None,
assignees: Vec::new(),
properties: HashMap::new(),
}
}
} | subject[index + 1..].trim().to_string()
} else {
let index = subject.find(id_str).unwrap();
subject[index + id_str.len() + 1..].trim().to_string()
}; | random_line_split |
struct-return.rs | // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | () {
unsafe {
let f = Floats { a: 1.234567890e-15_f64,
b: 0b_1010_1010_u8,
c: 1.0987654321e-15_f64 };
let ff = rustrt::rust_dbg_abi_2(f);
println!("a: {}", ff.a as f64);
println!("b: {}", ff.b as uint);
println!("c: {}", ff.c as f64);
... | test2 | identifier_name |
struct-return.rs | // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... |
#[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))]
fn test2() {
unsafe {
let f = Floats { a: 1.234567890e-15_f64,
b: 0b_1010_1010_u8,
c: 1.0987654321e-15_f64 };
let ff = rustrt::rust_dbg_abi_2(f);
println!("a: {}", ff.a as f64);
println!(... | {
unsafe {
let q = Quad { a: 0xaaaa_aaaa_aaaa_aaaa_u64,
b: 0xbbbb_bbbb_bbbb_bbbb_u64,
c: 0xcccc_cccc_cccc_cccc_u64,
d: 0xdddd_dddd_dddd_dddd_u64 };
let qq = rustrt::rust_dbg_abi_1(q);
println!("a: {:x}", qq.a as uint);
println!("b: {... | identifier_body |
struct-return.rs | // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | b: 0b_1010_1010_u8,
c: 1.0987654321e-15_f64 };
let ff = rustrt::rust_dbg_abi_2(f);
println!("a: {}", ff.a as f64);
println!("b: {}", ff.b as uint);
println!("c: {}", ff.c as f64);
assert_eq!(ff.a, f.c + 1.0f64);
assert_eq!(ff.b, 0xff_u8);... | random_line_split | |
fork.py | from pwn.internal.shellcode_helper import *
@shellcode_reqs(arch=['i386', 'amd64'], os=['linux', 'freebsd']) | if arch == 'i386':
if os in ['linux', 'freebsd']:
return _fork_i386(parent, child)
elif arch == 'amd64':
if os in ['linux', 'freebsd']:
return _fork_amd64(parent, child)
bug('OS/arch combination (%s, %s) was not supported for fork' % (os, arch))
def _fork_amd64(pare... | def fork(parent, child = None, os = None, arch = None):
"""Fork this shit."""
| random_line_split |
fork.py | from pwn.internal.shellcode_helper import *
@shellcode_reqs(arch=['i386', 'amd64'], os=['linux', 'freebsd'])
def fork(parent, child = None, os = None, arch = None):
"""Fork this shit."""
if arch == 'i386':
if os in ['linux', 'freebsd']:
return _fork_i386(parent, child)
elif arch == 'am... | code = """
push SYS_fork
pop eax
int 0x80
test eax, eax
jne %s
""" % parent
if child is not None:
code += 'jmp %s\n' % child
return code | identifier_body | |
fork.py | from pwn.internal.shellcode_helper import *
@shellcode_reqs(arch=['i386', 'amd64'], os=['linux', 'freebsd'])
def fork(parent, child = None, os = None, arch = None):
"""Fork this shit."""
if arch == 'i386':
if os in ['linux', 'freebsd']:
return _fork_i386(parent, child)
elif arch == 'am... | (parent, child):
code = """
push SYS_fork
pop eax
int 0x80
test eax, eax
jne %s
""" % parent
if child is not None:
code += 'jmp %s\n' % child
return code
| _fork_i386 | identifier_name |
fork.py | from pwn.internal.shellcode_helper import *
@shellcode_reqs(arch=['i386', 'amd64'], os=['linux', 'freebsd'])
def fork(parent, child = None, os = None, arch = None):
"""Fork this shit."""
if arch == 'i386':
if os in ['linux', 'freebsd']:
return _fork_i386(parent, child)
elif arch == 'am... |
bug('OS/arch combination (%s, %s) was not supported for fork' % (os, arch))
def _fork_amd64(parent, child):
code = """
push SYS_fork
pop rax
syscall
test rax, rax
jne %s
""" % parent
if child is not None:
code += 'jmp %s\n' % child
return code
def _fork_i386(parent, child... | if os in ['linux', 'freebsd']:
return _fork_amd64(parent, child) | conditional_block |
ray.rs | use std::f32;
use linalg::{Point, Vector};
/// Ray is a standard 3D ray, starting at origin `o` and heading in direction `d`
/// The min and max points along the ray can be specified with `min_t` and `max_t`
/// `depth` is the recursion depth of the ray
#[derive(Debug, Copy, Clone, PartialEq)]
pub struct Ray {
//... |
/// Create a child ray from the parent starting at `o` and heading in `d`
pub fn child(&self, o: &Point, d: &Vector) -> Ray {
Ray { o: *o, d: *d, min_t: 0f32, max_t: f32::INFINITY, depth: self.depth + 1 }
}
/// Create a child ray segment from `o + min_t * d` to `o + max_t * d`
pub fn child_... | {
Ray { o: *o, d: *d, min_t: min_t, max_t: max_t, depth: 0}
} | identifier_body |
ray.rs | use std::f32;
use linalg::{Point, Vector};
/// Ray is a standard 3D ray, starting at origin `o` and heading in direction `d`
/// The min and max points along the ray can be specified with `min_t` and `max_t`
/// `depth` is the recursion depth of the ray
#[derive(Debug, Copy, Clone, PartialEq)]
pub struct | {
/// Origin of the ray
pub o: Point,
/// Direction the ray is heading
pub d: Vector,
/// Point along the ray that the actual ray starts at, `p = o + min_t * d`
pub min_t: f32,
/// Point along the ray at which it stops, will be inf if the ray is infinite
pub max_t: f32,
/// Recursio... | Ray | identifier_name |
ray.rs | use std::f32;
use linalg::{Point, Vector}; |
/// Ray is a standard 3D ray, starting at origin `o` and heading in direction `d`
/// The min and max points along the ray can be specified with `min_t` and `max_t`
/// `depth` is the recursion depth of the ray
#[derive(Debug, Copy, Clone, PartialEq)]
pub struct Ray {
/// Origin of the ray
pub o: Point,
//... | random_line_split | |
lint-shorthand-field.rs | // Copyright 2014 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 main() {
{
let Foo {
x: x, //~ ERROR the `x:` in this pattern is redundant
y: ref y, //~ ERROR the `y:` in this pattern is redundant
} = Foo { x: 0, y: 0 };
let Foo {
x,
ref y,
} = Foo { x: 0, y: 0 };
}
{
const x: i... | x: isize,
y: isize,
}
| random_line_split |
lint-shorthand-field.rs | // Copyright 2014 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 ... | {
x: Foo,
}
enum Foo { x }
match (Bar { x: Foo::x }) {
Bar { x: Foo::x } => {},
}
}
}
| Bar | identifier_name |
testcaselinkedlistsource0.rs | use List::*;
enum List {
// Cons: Un tuple contenant un élément(i.e. u32) et un pointeur vers le noeud suivant (i.e. Box<List>).
Cons(u32, Box<List>),
// Nil: Un noeud témoignant de la fin de la liste.
Nil,
}
// Il est possible de lier, d'implémenter des méthodes
// pour une énumération.
impl List {
... | 32) -> List {
// `Cons` est également une variante de `List`.
Cons(elem, Box::new(self))
}
// Renvoie la longueur de la liste.
fn len(&self) -> u32 {
// `self` doit être analysé car le comportement de cette méthode
// dépend du type de variante auquel appartient `self`.
... | elem: u | identifier_name |
testcaselinkedlistsource0.rs | use List::*;
enum List {
// Cons: Un tuple contenant un élément(i.e. u32) et un pointeur vers le noeud suivant (i.e. Box<List>).
Cons(u32, Box<List>),
// Nil: Un noeud témoignant de la fin de la liste.
Nil,
}
// Il est possible de lier, d'implémenter des méthodes
// pour une énumération.
impl List {
... | Consomme, s'approprie la liste et renvoie une copie de cette même liste
// avec un nouvel élément ajouté à la suite.
fn prepend(self, elem: u32) -> List {
// `Cons` est également une variante de `List`.
Cons(elem, Box::new(self))
}
// Renvoie la longueur de la liste.
fn len(&self) ... | // `Nil` est une variante de `List`.
Nil
}
// | identifier_body |
testcaselinkedlistsource0.rs | use List::*;
enum List {
// Cons: Un tuple contenant un élément(i.e. u32) et un pointeur vers le noeud suivant (i.e. Box<List>).
Cons(u32, Box<List>),
// Nil: Un noeud témoignant de la fin de la liste.
Nil,
}
// Il est possible de lier, d'implémenter des méthodes
// pour une énumération.
impl List {
... | fn stringify(&self) -> String {
match *self {
Cons(head, ref tail) => {
// `format!` est équivalente à `println!` mais elle renvoie
// une chaîne de caractères allouée dans le tas (wrapper)
// plutôt que de l'afficher dans la console.
... | // (wrapper) | random_line_split |
testcaselinkedlistsource0.rs | use List::*;
enum List {
// Cons: Un tuple contenant un élément(i.e. u32) et un pointeur vers le noeud suivant (i.e. Box<List>).
Cons(u32, Box<List>),
// Nil: Un noeud témoignant de la fin de la liste.
Nil,
}
// Il est possible de lier, d'implémenter des méthodes
// pour une énumération.
impl List {
... | Nil")
},
}
}
}
fn main() {
// Créé une liste vide.
let mut list = List::new();
// On ajoute quelques éléments.
list = list.prepend(1);
list = list.prepend(2);
list = list.prepend(3);
// Affiche l'état définitif de la liste.
println!("La linked list possède une ... | ente à `println!` mais elle renvoie
// une chaîne de caractères allouée dans le tas (wrapper)
// plutôt que de l'afficher dans la console.
format!("{}, {}", head, tail.stringify())
},
Nil => {
format!(" | conditional_block |
flags.ts |
export enum ErrorRecoverySet {
None = 0,
Comma = 1, // Comma
SColon = 1 << 1, // SColon
Asg = 1 << 2, // Asg
BinOp = 1 << 3, // Lsh, Rsh, Rs2, Le, Ge, INSTANCEOF, EQ, NE, Eqv, NEqv, LogAnd, LogOr, AsgMul, AsgDiv
// AsgMod, AsgAdd, AsgSub, AsgLsh, AsgRsh, Asg... | {
return (val & flag) != 0;
} | identifier_body | |
flags.ts | gRs2, AsgAnd, AsgXor, AsgOr, QMark, Mult, Div,
// Pct, GT, LT, And, Xor, Or
RBrack = 1 << 4, // RBrack
RCurly = 1 << 5, // RCurly
RParen = 1 << 6, // RParen
Dot = 1 << 7, // Dot
Colon = 1 << 8, // Colon
PrimType = 1 << 9, // number, string, bool
A... | RegExp = 1 << 13, // RegExp
LParen = 1 << 14, // LParen
LBrack = 1 << 15, // LBrack
Scope = 1 << 16, // Scope
In = 1 << 17, // IN
SCase = 1 << 18, // CASE, DEFAULT
Else = 1 << 19, // ELSE
Catch = 1 << 20, // CATCH, FINALLY
Var = 1 << 21, //... | random_line_split | |
flags.ts | , PRIVATE, STATIC, INTERFACE, CLASS, MODULE, EXPORT, IMPORT
ExprStart = SColon | AddOp | LCurly | PreOp | RegExp | LParen | LBrack | ID | Prefix | RLit | Func | Literal,
StmtStart = ExprStart | SColon | Var | Stmt | While | TypeScriptS,
Postfix = Dot | LParen | LBrack,
}
export en... | {
if ((flags & i) != 0) {
for (var k in e) {
if (e[k] == i) {
if (builder.length > 0) {
builder += "|";
}
builder += k;
break;
... | conditional_block | |
flags.ts | // ID
Prefix = 1 << 25, // VOID, DELETE, TYPEOF, AWAIT
Literal = 1 << 26, // IntCon, FltCon, StrCon
RLit = 1 << 27, // THIS, TRUE, FALSE, NULL
Func = 1 << 28, // FUNCTION
EOF = 1 << 29, // EOF
TypeScriptS = 1 << 30, // PROPERTY, PRIVATE, STATIC, INTERFACE, CLASS, M... | flagsToString | identifier_name | |
get.js | import baseGet from './_baseGet.js';
/**
* Gets the value at `path` of `object`. If the resolved value is
* `undefined`, the `defaultValue` is returned in its place.
*
* @static
* @memberOf _
* @since 3.7.0
* @category Object
* @param {Object} object The object to query.
* @param {Array|string} path The path ... |
export default get;
| {
var result = object == null ? undefined : baseGet(object, path);
return result === undefined ? defaultValue : result;
} | identifier_body |
get.js | import baseGet from './_baseGet.js';
/**
* Gets the value at `path` of `object`. If the resolved value is
* `undefined`, the `defaultValue` is returned in its place.
*
* @static
* @memberOf _
* @since 3.7.0
* @category Object
* @param {Object} object The object to query.
* @param {Array|string} path The path ... | (object, path, defaultValue) {
var result = object == null ? undefined : baseGet(object, path);
return result === undefined ? defaultValue : result;
}
export default get;
| get | identifier_name |
get.js | import baseGet from './_baseGet.js';
/**
* Gets the value at `path` of `object`. If the resolved value is
* `undefined`, the `defaultValue` is returned in its place.
*
* @static
* @memberOf _
* @since 3.7.0
* @category Object
* @param {Object} object The object to query.
* @param {Array|string} path The path ... | export default get; | random_line_split | |
partialpressure.component.ts | import { Component } from '@angular/core';
import { BlendCalculatorService } from '../../services/blendCalculator.service';
import { MeasureMode } from '../../models/calculator/measureMode';
import { Gas } from '../../models/calculator/gas';
import { PartialPressureRequest } from '../../models/calculator/partialPressu... | ppUpdateGas(gas: Gas): void {
this.gas = gas;
let request = new PartialPressureRequest();
request.depth = this.depth;
request.gas = this.gas;
request.system = this.ppImperialSelected ? MeasureMode.Imperial : MeasureMode.Metric;
this.result = this.service.calculatePart... | this.ppImperialSelected = value;
this.ppMeasurement = this.ppImperialSelected ? 'feet' : 'meeters';
this.ppUpdateDepth();
}
| identifier_body |
partialpressure.component.ts | import { Component } from '@angular/core';
import { BlendCalculatorService } from '../../services/blendCalculator.service';
import { MeasureMode } from '../../models/calculator/measureMode';
import { Gas } from '../../models/calculator/gas';
import { PartialPressureRequest } from '../../models/calculator/partialPressu... | alculator: BlendCalculatorService) {
this.service = calculator;
this.gas = new Gas();
}
ngOnInit() {
this.gas.oxygen = 21;
this.gas.nitrogen = 79;
this.gas.helium = 0;
this.depth = 0;
this.ppSystemSelectionChange(true);
}
ppSystemSelectionChange(... | nstructor(c | identifier_name |
partialpressure.component.ts | import { Component } from '@angular/core';
import { BlendCalculatorService } from '../../services/blendCalculator.service';
import { MeasureMode } from '../../models/calculator/measureMode';
import { Gas } from '../../models/calculator/gas';
import { PartialPressureRequest } from '../../models/calculator/partialPressu... | gas: Gas;
constructor(calculator: BlendCalculatorService) {
this.service = calculator;
this.gas = new Gas();
}
ngOnInit() {
this.gas.oxygen = 21;
this.gas.nitrogen = 79;
this.gas.helium = 0;
this.depth = 0;
this.ppSystemSelectionChange(true);
... | depth: number;
result: PartialPressureResult; | random_line_split |
submaker_updatezip.py | from .submaker import Submaker
from inception.tools.signapk import SignApk
import shutil
import os
from inception.constants import InceptionConstants
class UpdatezipSubmaker(Submaker):
def make(self, updatePkgDir):
|
assert os.path.exists(signApkPath), "'%s' from %s does not exist" % (signApkPath, signApkKey)
assert os.path.exists(javaPath), "'%s' from %s does not exist" % (javaPath, javaKey)
signApk = SignApk(javaPath, signApkPath)
targetPath = updatePkgDir + "/../" + InceptionCon... | keys_name = self.getValue("keys")
signingKeys = self.getMaker().getConfig().getKeyConfig(keys_name) if keys_name else None
updateBinaryKey, updateBinary = self.getTargetBinary("update-binary")
assert updateBinary, "%s is not set" % updateBinaryKey
if keys_name:
assert signin... | identifier_body |
submaker_updatezip.py | from .submaker import Submaker
from inception.tools.signapk import SignApk
import shutil
import os
from inception.constants import InceptionConstants
class UpdatezipSubmaker(Submaker):
def make(self, updatePkgDir):
keys_name = self.getValue("keys")
signingKeys = self.getMaker().getConfig().getKeyCo... |
return updateZipPath
| javaKey, javaPath = self.getHostBinary("java")
signApkKey, signApkPath = self.getHostBinary("signapk")
assert signApkPath, "%s is not set" % signApkKey
assert os.path.exists(signApkPath), "'%s' from %s does not exist" % (signApkPath, signApkKey)
assert os.path.exists(ja... | conditional_block |
submaker_updatezip.py | from .submaker import Submaker
from inception.tools.signapk import SignApk
import shutil
import os
from inception.constants import InceptionConstants
class UpdatezipSubmaker(Submaker):
def make(self, updatePkgDir):
keys_name = self.getValue("keys")
signingKeys = self.getMaker().getConfig().getKeyCo... | return updateZipPath | random_line_split | |
submaker_updatezip.py | from .submaker import Submaker
from inception.tools.signapk import SignApk
import shutil
import os
from inception.constants import InceptionConstants
class | (Submaker):
def make(self, updatePkgDir):
keys_name = self.getValue("keys")
signingKeys = self.getMaker().getConfig().getKeyConfig(keys_name) if keys_name else None
updateBinaryKey, updateBinary = self.getTargetBinary("update-binary")
assert updateBinary, "%s is not set" % updateBina... | UpdatezipSubmaker | identifier_name |
generate-certs.py | #!/usr/bin/python
# Copyright (c) 2016 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
A chain with four possible intermediates with different notBefore and notAfter
dates, for testing path bulding prioritization.
"""
... |
int_ac = gencerts.create_intermediate_certificate('Intermediate', root)
int_ac.set_validity_range(DATE_A, DATE_C)
int_ad = gencerts.create_intermediate_certificate('Intermediate', root)
int_ad.set_validity_range(DATE_A, DATE_D)
int_ad.set_key(int_ac.get_key())
int_bc = gencerts.create_intermediate_certificate('Inter... |
root = gencerts.create_self_signed_root_certificate('Root')
root.set_validity_range(DATE_A, DATE_D) | random_line_split |
blob.test.ts | /**
* Copyright 2017 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to i... | it('Blobs are merged with strings correctly', () => {
const blob = new FbsBlob(new Uint8Array([1, 2, 3, 4]));
const merged = FbsBlob.getBlob('what', blob, '\ud83d\ude0a ');
testShared.assertUint8ArrayEquals(
merged.uploadData() as Uint8Array,
new Uint8Array([
0x77,
0x68,
... | sliced.uploadData() as Uint8Array,
new Uint8Array([2, 3, 4, 5])
);
}); | random_line_split |
execute_brainfuck.rs | // http://rosettacode.org/wiki/Execute_Brain****
use std::collections::HashMap;
use std::env;
use std::fs::File;
use std::io::prelude::*;
use std::io::stdin;
use std::num::Wrapping;
fn main() {
let args: Vec<_> = env::args().collect();
if args.len() < 2 {
println!("Usage: {} [path] (--debug)", args[0]... | else {
print!("{}", val as char);
}
}
',' => {
mem[ptr] = Wrapping(reader.next().unwrap().unwrap());
}
_ => { /* ignore */ }
}
pc += 1;
}
}
| {
println!("(BFDB) STDOUT: '{}'", val as char); // Intercept output
} | conditional_block |
execute_brainfuck.rs | // http://rosettacode.org/wiki/Execute_Brain****
use std::collections::HashMap;
use std::env;
use std::fs::File;
use std::io::prelude::*;
use std::io::stdin;
use std::num::Wrapping;
fn main() {
let args: Vec<_> = env::args().collect();
if args.len() < 2 {
println!("Usage: {} [path] (--debug)", args[0]... | ',' => {
mem[ptr] = Wrapping(reader.next().unwrap().unwrap());
}
_ => { /* ignore */ }
}
pc += 1;
}
} | } else {
print!("{}", val as char);
}
} | random_line_split |
execute_brainfuck.rs | // http://rosettacode.org/wiki/Execute_Brain****
use std::collections::HashMap;
use std::env;
use std::fs::File;
use std::io::prelude::*;
use std::io::stdin;
use std::num::Wrapping;
fn | () {
let args: Vec<_> = env::args().collect();
if args.len() < 2 {
println!("Usage: {} [path] (--debug)", args[0]);
return;
}
let src: Vec<char> = {
let mut buf = String::new();
match File::open(&args[1])
{
Ok(mut f) => { f.read_to_string(&mut buf).un... | main | identifier_name |
execute_brainfuck.rs | // http://rosettacode.org/wiki/Execute_Brain****
use std::collections::HashMap;
use std::env;
use std::fs::File;
use std::io::prelude::*;
use std::io::stdin;
use std::num::Wrapping;
fn main() |
// Launch options
let debug = args.contains(&"--debug".to_owned());
// One pass to find bracket pairs.
let brackets: HashMap<usize, usize> = {
let mut m = HashMap::new();
let mut scope_stack = Vec::new();
for (idx, ch) in src.iter().enumerate() {
match ch {
... | {
let args: Vec<_> = env::args().collect();
if args.len() < 2 {
println!("Usage: {} [path] (--debug)", args[0]);
return;
}
let src: Vec<char> = {
let mut buf = String::new();
match File::open(&args[1])
{
Ok(mut f) => { f.read_to_string(&mut buf).unwra... | identifier_body |
strict_and_lenient_forms.rs | #![feature(plugin, custom_derive)]
#![plugin(rocket_codegen)]
extern crate rocket;
use rocket::request::{Form, LenientForm};
use rocket::http::RawStr;
#[derive(FromForm)]
struct | <'r> {
field: &'r RawStr,
}
#[post("/strict", data = "<form>")]
fn strict<'r>(form: Form<'r, MyForm<'r>>) -> String {
form.get().field.as_str().into()
}
#[post("/lenient", data = "<form>")]
fn lenient<'r>(form: LenientForm<'r, MyForm<'r>>) -> String {
form.get().field.as_str().into()
}
mod strict_and_len... | MyForm | identifier_name |
strict_and_lenient_forms.rs | #![feature(plugin, custom_derive)]
#![plugin(rocket_codegen)]
extern crate rocket;
use rocket::request::{Form, LenientForm};
use rocket::http::RawStr;
#[derive(FromForm)]
struct MyForm<'r> {
field: &'r RawStr,
}
#[post("/strict", data = "<form>")]
fn strict<'r>(form: Form<'r, MyForm<'r>>) -> String {
form.g... | let mut response = client.post("/lenient")
.header(ContentType::Form)
.body(format!("field={}&extra=whoops", FIELD_VALUE))
.dispatch();
assert_eq!(response.status(), Status::Ok);
assert_eq!(response.body_string(), Some(FIELD_VALUE.into()));
}
} | assert_eq!(response.status(), Status::Ok);
assert_eq!(response.body_string(), Some(FIELD_VALUE.into()));
| random_line_split |
strict_and_lenient_forms.rs | #![feature(plugin, custom_derive)]
#![plugin(rocket_codegen)]
extern crate rocket;
use rocket::request::{Form, LenientForm};
use rocket::http::RawStr;
#[derive(FromForm)]
struct MyForm<'r> {
field: &'r RawStr,
}
#[post("/strict", data = "<form>")]
fn strict<'r>(form: Form<'r, MyForm<'r>>) -> String |
#[post("/lenient", data = "<form>")]
fn lenient<'r>(form: LenientForm<'r, MyForm<'r>>) -> String {
form.get().field.as_str().into()
}
mod strict_and_lenient_forms_tests {
use super::*;
use rocket::local::Client;
use rocket::http::{Status, ContentType};
const FIELD_VALUE: &str = "just_some_value"... | {
form.get().field.as_str().into()
} | identifier_body |
e12n.ts | 甸之约', capture: false }),
netRegexKo: NetRegexes.ability({ id: '4B48', source: '에덴의 약속', capture: false }),
run: (data) => data.seenIntermission = true,
},
{
id: 'E12N Maleficium',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ id: '5872', source: 'Eden\'s Promise', capture... | },
alertText: (data, matches, output) => {
if (data.me === matches.target)
return output.stackOnYou!();
},
infoText: (data, _matches, output) => {
if (!data.stacks || data.stacks.length === 1)
return;
const names = data.stacks.map((x) => data.ShortName... | data.stacks ??= [];
data.stacks.push(matches.target); | random_line_split |
constants.ts | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you... | export const DANGER_TOAST = ToastType.DANGER; | export const INFO_TOAST = ToastType.INFO;
export const SUCCES_TOAST = ToastType.SUCCESS;
export const WARNING_TOAST = ToastType.WARNING; | random_line_split |
main.rs | fn main() {
// demonstrate the Option<T> and Some
let five = Some(5);
let six = plus_one(five);
let none = plus_one(None);
println!("Five: {:?}", five);
println!("Six: {:?}", six);
println!("None: {:?}", none);
// simpler syntax if you want to do something with
// only one value (o... | else {
println!("Found something different");
}
}
fn plus_one(x: Option<i32>) -> Option<i32> {
// if no value, return none, otherwise return
// the addition of the value plus one
match x {
None => None,
Some(i) => Some(i + 1),
}
}
| {
println!("Found 2");
} | conditional_block |
main.rs | fn main() {
// demonstrate the Option<T> and Some
let five = Some(5);
let six = plus_one(five);
let none = plus_one(None);
println!("Five: {:?}", five);
println!("Six: {:?}", six);
println!("None: {:?}", none);
// simpler syntax if you want to do something with
// only one value (o... | (x: Option<i32>) -> Option<i32> {
// if no value, return none, otherwise return
// the addition of the value plus one
match x {
None => None,
Some(i) => Some(i + 1),
}
}
| plus_one | identifier_name |
main.rs | fn main() | } else {
println!("Found something different");
}
}
fn plus_one(x: Option<i32>) -> Option<i32> {
// if no value, return none, otherwise return
// the addition of the value plus one
match x {
None => None,
Some(i) => Some(i + 1),
}
}
| {
// demonstrate the Option<T> and Some
let five = Some(5);
let six = plus_one(five);
let none = plus_one(None);
println!("Five: {:?}", five);
println!("Six: {:?}", six);
println!("None: {:?}", none);
// simpler syntax if you want to do something with
// only one value (one pattern... | identifier_body |
ApplicationPlatformViewView.ts | /**
* @license
* Copyright color-coding studio. All Rights Reserved.
*
* Use of this source code is governed by an Apache License, Version 2.0
* that can be found in the LICENSE file at http://www.apache.org/licenses/LICENSE-2.0
*/
import * as ibas from "ibas/index";
import * as openui5 from "openui5/index";
imp... | type: sap.m.ButtonType.Transparent,
icon: "sap-icon://action",
press: function (event: any): void {
that.fireViewEvents(that.callServicesEvent, {
displayServices(services: ibas.IServiceAge... | t that: this = this;
this.form = new sap.ui.layout.form.SimpleForm("", {
content: [
]
});
this.page = new sap.m.Page("", {
showHeader: false,
subHeader: new sap.m.Bar("", {
contentLeft: [
new sap.m.Button("", {
... | identifier_body |
ApplicationPlatformViewView.ts | /**
* @license
* Copyright color-coding studio. All Rights Reserved.
*
* Use of this source code is governed by an Apache License, Version 2.0
* that can be found in the LICENSE file at http://www.apache.org/licenses/LICENSE-2.0
*/
import * as ibas from "ibas/index";
import * as openui5 from "openui5/index";
imp... | let popover: sap.m.Popover = new sap.m.Popover("", {
showHeader: false,
placement: sap.m.PlacementType.Bottom,
});
for (let service of services... | return;
}
| conditional_block |
ApplicationPlatformViewView.ts | /**
* @license
* Copyright color-coding studio. All Rights Reserved.
*
* Use of this source code is governed by an Apache License, Version 2.0
* that can be found in the LICENSE file at http://www.apache.org/licenses/LICENSE-2.0
*/
import * as ibas from "ibas/index";
import * as openui5 from "openui5/index";
imp... | icon: service.icon,
press: function (): void {
service.run();
popover.close();
}
... | type: sap.m.ButtonType.Transparent, | random_line_split |
ApplicationPlatformViewView.ts | /**
* @license
* Copyright color-coding studio. All Rights Reserved.
*
* Use of this source code is governed by an Apache License, Version 2.0
* that can be found in the LICENSE file at http://www.apache.org/licenses/LICENSE-2.0
*/
import * as ibas from "ibas/index";
import * as openui5 from "openui5/index";
imp... | let that: this = this;
this.form = new sap.ui.layout.form.SimpleForm("", {
content: [
]
});
this.page = new sap.m.Page("", {
showHeader: false,
subHeader: new sap.m.Bar("", {
contentLeft: [
new sap.m.Button... | {
| identifier_name |
molpro.py | # -*- coding: utf-8 -*-
# HORTON: Helpful Open-source Research TOol for N-fermion systems.
# Copyright (C) 2011-2016 The HORTON Development Team
#
# This file is part of HORTON.
#
# HORTON is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by th... | # Write integrals and core energy
for i in xrange(nactive):
for j in xrange(i+1):
for k in xrange(nactive):
for l in xrange(k+1):
if (i*(i+1))/2+j >= (k*(k+1))/2+l:
value = two_mo.get_element(i,k,j,l)
... | print >> f, ' &FCI NORB=%i,NELEC=%i,MS2=%i,' % (nactive, nelec, ms2)
print >> f, ' ORBSYM= '+",".join(str(1) for v in xrange(nactive))+","
print >> f, ' ISYM=1'
print >> f, ' &END'
| random_line_split |
molpro.py | # -*- coding: utf-8 -*-
# HORTON: Helpful Open-source Research TOol for N-fermion systems.
# Copyright (C) 2011-2016 The HORTON Development Team
#
# This file is part of HORTON.
#
# HORTON is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by th... | ms2 = getattr(data, 'ms2', 0)
# Write header
print >> f, ' &FCI NORB=%i,NELEC=%i,MS2=%i,' % (nactive, nelec, ms2)
print >> f, ' ORBSYM= '+",".join(str(1) for v in xrange(nactive))+","
print >> f, ' ISYM=1'
print >> f, ' &END'
# Write integrals and core energy
... | '''Write one- and two-electron integrals in the Molpro 2012 FCIDUMP format.
Works only for restricted wavefunctions.
Keep in mind that the FCIDUMP format changed in Molpro 2012, so files
written with this function cannot be used with older versions of Molpro
filename
The filen... | identifier_body |
molpro.py | # -*- coding: utf-8 -*-
# HORTON: Helpful Open-source Research TOol for N-fermion systems.
# Copyright (C) 2011-2016 The HORTON Development Team
#
# This file is part of HORTON.
#
# HORTON is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by th... |
if words[3] != '0':
ii = int(words[1])-1
ij = int(words[2])-1
ik = int(words[3])-1
il = int(words[4])-1
# Uncomment the following line if you want to assert that the
# FCIDUMP file does not contain duplicate 4-i... | raise IOError('Expecting 5 fields on each data line in FCIDUMP') | conditional_block |
molpro.py | # -*- coding: utf-8 -*-
# HORTON: Helpful Open-source Research TOol for N-fermion systems.
# Copyright (C) 2011-2016 The HORTON Development Team
#
# This file is part of HORTON.
#
# HORTON is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by th... | (filename, data):
'''Write one- and two-electron integrals in the Molpro 2012 FCIDUMP format.
Works only for restricted wavefunctions.
Keep in mind that the FCIDUMP format changed in Molpro 2012, so files
written with this function cannot be used with older versions of Molpro
filename... | dump_fcidump | identifier_name |
getAnimatedPngDataIfExists.ts | // Copyright 2020-2021 Signal Messenger, LLC
// SPDX-License-Identifier: AGPL-3.0-only
const PNG_SIGNATURE = new Uint8Array([137, 80, 78, 71, 13, 10, 26, 10]);
const ACTL_CHUNK_BYTES = new TextEncoder().encode('acTL');
const IDAT_CHUNK_BYTES = new TextEncoder().encode('IDAT');
const MAX_BYTES_TO_READ = 1024 * 1024;
t... |
bytes: Uint8Array
): null | AnimatedPngData {
if (!hasPngSignature(bytes)) {
return null;
}
let numPlays: void | number;
const dataView = new DataView(bytes.buffer);
let i = PNG_SIGNATURE.length;
while (i < bytes.byteLength && i <= MAX_BYTES_TO_READ) {
const chunkTypeBytes = bytes.slice(i + 4,... | etAnimatedPngDataIfExists( | identifier_name |
getAnimatedPngDataIfExists.ts | // Copyright 2020-2021 Signal Messenger, LLC
// SPDX-License-Identifier: AGPL-3.0-only
const PNG_SIGNATURE = new Uint8Array([137, 80, 78, 71, 13, 10, 26, 10]);
const ACTL_CHUNK_BYTES = new TextEncoder().encode('acTL');
const IDAT_CHUNK_BYTES = new TextEncoder().encode('IDAT');
const MAX_BYTES_TO_READ = 1024 * 1024;
t... |
if (a.byteLength !== b.byteLength) {
return false;
}
for (let i = 0; i < a.byteLength; i += 1) {
if (a[i] !== b[i]) {
return false;
}
}
return true;
}
| identifier_body | |
getAnimatedPngDataIfExists.ts | // Copyright 2020-2021 Signal Messenger, LLC
// SPDX-License-Identifier: AGPL-3.0-only
const PNG_SIGNATURE = new Uint8Array([137, 80, 78, 71, 13, 10, 26, 10]);
const ACTL_CHUNK_BYTES = new TextEncoder().encode('acTL');
const IDAT_CHUNK_BYTES = new TextEncoder().encode('IDAT');
const MAX_BYTES_TO_READ = 1024 * 1024;
t... | function hasPngSignature(bytes: Uint8Array): boolean {
return areBytesEqual(bytes.slice(0, 8), PNG_SIGNATURE);
}
function areBytesEqual(a: Uint8Array, b: Uint8Array): boolean {
if (a.byteLength !== b.byteLength) {
return false;
}
for (let i = 0; i < a.byteLength; i += 1) {
if (a[i] !== b[i]) {
re... | }
| random_line_split |
getAnimatedPngDataIfExists.ts | // Copyright 2020-2021 Signal Messenger, LLC
// SPDX-License-Identifier: AGPL-3.0-only
const PNG_SIGNATURE = new Uint8Array([137, 80, 78, 71, 13, 10, 26, 10]);
const ACTL_CHUNK_BYTES = new TextEncoder().encode('acTL');
const IDAT_CHUNK_BYTES = new TextEncoder().encode('IDAT');
const MAX_BYTES_TO_READ = 1024 * 1024;
t... |
// Jump over the length (4 bytes), the type (4 bytes), the data, and the CRC checksum
// (4 bytes).
i += 12 + dataView.getUint32(i);
}
return null;
}
function hasPngSignature(bytes: Uint8Array): boolean {
return areBytesEqual(bytes.slice(0, 8), PNG_SIGNATURE);
}
function areBytesEqual(a: Uint8Ar... |
return null;
}
| conditional_block |
type_resolver.rs | use std::iter;
use crate::model;
use crate::model::WithLoc;
use crate::protobuf_path::ProtobufPath;
use crate::pure::convert::WithFullName;
use crate::FileDescriptorPair;
use crate::ProtobufAbsPath;
use crate::ProtobufAbsPathRef;
use crate::ProtobufIdent;
use crate::ProtobufIdentRef;
use crate::ProtobufRelPath;
use cr... | (&self) -> &'a [model::WithLoc<model::Message>] {
match self {
&LookupScope::File(file) => &file.messages,
&LookupScope::Message(messasge, _) => &messasge.messages,
}
}
fn find_message(&self, simple_name: &ProtobufIdentRef) -> Option<&'a model::Message> {
self.me... | messages | identifier_name |
type_resolver.rs | use std::iter;
use crate::model;
use crate::model::WithLoc;
use crate::protobuf_path::ProtobufPath;
use crate::pure::convert::WithFullName;
use crate::FileDescriptorPair;
use crate::ProtobufAbsPath;
use crate::ProtobufAbsPathRef;
use crate::ProtobufIdent;
use crate::ProtobufIdentRef;
use crate::ProtobufRelPath;
use cr... |
}
| {
match name {
ProtobufPath::Abs(name) => Ok(self.find_message_or_enum_by_abs_name(&name)?),
ProtobufPath::Rel(name) => {
// find message or enum in current package
for p in scope.self_and_parents() {
let mut fq = p.to_owned();
... | identifier_body |
type_resolver.rs | use std::iter;
use crate::model;
use crate::model::WithLoc;
use crate::protobuf_path::ProtobufPath;
use crate::pure::convert::WithFullName;
use crate::FileDescriptorPair;
use crate::ProtobufAbsPath;
use crate::ProtobufAbsPathRef;
use crate::ProtobufIdent;
use crate::ProtobufIdentRef;
use crate::ProtobufRelPath;
use cr... | name: &ProtobufPath,
) -> anyhow::Result<WithFullName<MessageOrEnum>> {
match name {
ProtobufPath::Abs(name) => Ok(self.find_message_or_enum_by_abs_name(&name)?),
ProtobufPath::Rel(name) => {
// find message or enum in current package
for p in ... | pub(crate) fn resolve_message_or_enum(
&self,
scope: &ProtobufAbsPathRef, | random_line_split |
channels-widget.tsx | import * as React from 'react'
import * as Kb from '../../common-adapters'
import * as Styles from '../../styles'
import * as Types from '../../constants/types/teams'
import ChannelPopup from '../team/settings-tab/channel-popup'
import useAutocompleter from './use-autocompleter'
import {useAllChannelMetas} from './chan... | <ChannelPill
key={channel.channelname}
channelname={channel.channelname}
onRemove={channel.channelname === 'general' ? undefined : () => props.onRemoveChannel(channel)}
/>
))}
</Kb.Box2>
)}
</Kb.Box2>
)
type ChannelInputProps = {
disableGene... | <Kb.Box2 direction="horizontal" gap="xtiny" fullWidth={true} style={styles.pillContainer}>
{props.channels.map(channel => ( | random_line_split |
query.component.ts | import { Component, Input, OnDestroy } from '@angular/core';
import * as _ from 'lodash';
import { Subscription } from 'rxjs/Subscription';
import { APIManagerService } from '../core/api-manager/api-manager.service';
import { QueryDataschemaGeneratorService } from '../core/schemas/query-dataschema-generator.service';... | (operation: Operation) {
this.apiManagerService.setActiveOperation(operation, {});
}
removeOperation(operation: Operation) {
if (this.activeAction.removeOperation(operation)) {
if (this.activeOperation == operation) {
let newActiveOperation: Operation = null;
if (this.activeAction.operations.... | selectOperation | identifier_name |
query.component.ts | import { Component, Input, OnDestroy } from '@angular/core';
import * as _ from 'lodash';
import { Subscription } from 'rxjs/Subscription';
import { APIManagerService } from '../core/api-manager/api-manager.service';
import { QueryDataschemaGeneratorService } from '../core/schemas/query-dataschema-generator.service';... |
this.apiManagerService.setActiveOperation(newActiveOperation, {});
}
}
}
performOperation() {
this.operationPerformerService.performOperation(this.activeOperation, this.data);
}
ngOnDestroy() {
this.activeActionSubscription.unsubscribe();
this.activeOperationSubscription... | {
newActiveOperation = this.activeAction.operations[0];
} | conditional_block |
query.component.ts | import { Component, Input, OnDestroy } from '@angular/core';
import * as _ from 'lodash';
import { Subscription } from 'rxjs/Subscription';
import { APIManagerService } from '../core/api-manager/api-manager.service';
import { QueryDataschemaGeneratorService } from '../core/schemas/query-dataschema-generator.service';... | this.activeOperationSubscription.unsubscribe();
}
} | ngOnDestroy() {
this.activeActionSubscription.unsubscribe(); | random_line_split |
query.component.ts | import { Component, Input, OnDestroy } from '@angular/core';
import * as _ from 'lodash';
import { Subscription } from 'rxjs/Subscription';
import { APIManagerService } from '../core/api-manager/api-manager.service';
import { QueryDataschemaGeneratorService } from '../core/schemas/query-dataschema-generator.service';... |
ngOnDestroy() {
this.activeActionSubscription.unsubscribe();
this.activeOperationSubscription.unsubscribe();
}
}
| {
this.operationPerformerService.performOperation(this.activeOperation, this.data);
} | identifier_body |
process.py | #!/usr/bin/env python3
# process.py
# This script consists of all core functions.
# Author: Orhan Odabasi (0rh.odabasi[at]gmail.com)
import locale
import csv
import os
from PIL import Image
import re
from collections import Counter
def scanDir(path):
# scan the path and collect media data for copy process
wh... | videos_dataset.append(v_data_list)
# total size of photos archive (only jpeg and png files)
totalsize = 0
for s in photos_dataset:
totalsize += int(s[2])
#total file count
dirs = []
for x in photos_dataset:
dirs.append(x[7])
foldercount = len(Counter(dirs).... | p_data_list.extend([file_name, file_path, file_size, date_taken, year, month, day, date_info])
photos_dataset.append(p_data_list)
elif name.lower().endswith((".mov", ".mkv", ".mp4", ".3gp", ".wmv", ".avi")):
v_data_list.extend([file_name, file_path, file_size,... | random_line_split |
process.py | #!/usr/bin/env python3
# process.py
# This script consists of all core functions.
# Author: Orhan Odabasi (0rh.odabasi[at]gmail.com)
import locale
import csv
import os
from PIL import Image
import re
from collections import Counter
def | (path):
# scan the path and collect media data for copy process
while os.path.exists(path) and os.path.isdir(path):
photos_dataset, totalsize, folder_count, videos_dataset = listphotos(path)
p_count = len(photos_dataset)
p_size = "{:.2f} MB".format(float(totalsize/1000000))
retur... | scanDir | identifier_name |
process.py | #!/usr/bin/env python3
# process.py
# This script consists of all core functions.
# Author: Orhan Odabasi (0rh.odabasi[at]gmail.com)
import locale
import csv
import os
from PIL import Image
import re
from collections import Counter
def scanDir(path):
# scan the path and collect media data for copy process
wh... |
def saveReport(photo_datas, video_datas, target_path):
# save summary data to a csv file
report_dest_p = os.path.join(target_path, "photo_list.csv")
report_dest_v = os.path.join(target_path, "video_list.csv")
with open(report_dest_p, "w") as f:
w = csv.writer(f, delimiter="\t")
w.write... | photos_dataset, totalsize, folder_count, videos_dataset = listphotos(path)
p_count = len(photos_dataset)
p_size = "{:.2f} MB".format(float(totalsize/1000000))
return p_count, p_size, folder_count, photos_dataset, videos_dataset | conditional_block |
process.py | #!/usr/bin/env python3
# process.py
# This script consists of all core functions.
# Author: Orhan Odabasi (0rh.odabasi[at]gmail.com)
import locale
import csv
import os
from PIL import Image
import re
from collections import Counter
def scanDir(path):
# scan the path and collect media data for copy process
wh... |
def listphotos(path):
# Listing all files in target directory
photos_dataset = []
videos_dataset = []
for root, dirs, files in os.walk(path):
for name in files:
p_data_list = []
v_data_list = []
# filename name [0]
file_name = name
# ... | report_dest_p = os.path.join(target_path, "photo_list.csv")
report_dest_v = os.path.join(target_path, "video_list.csv")
with open(report_dest_p, "w") as f:
w = csv.writer(f, delimiter="\t")
w.writerows(photo_datas)
f.close()
with open(report_dest_v, "w") as f:
w = csv.writer(... | identifier_body |
TypeGraphQLModule.ts |
/**
* @ignore
*/
@Module()
export class TypeGraphQLModule {
@Inject()
protected service: TypeGraphQLService;
@Inject()
protected injector: InjectorService;
@Configuration()
protected configuration: Configuration;
get settings(): {[key: string]: TypeGraphQLSettings} | undefined {
return this.conf... | import {Configuration, Inject, InjectorService, Module} from "@tsed/di";
import {TypeGraphQLSettings} from "./interfaces";
import {TypeGraphQLService} from "./services/TypeGraphQLService"; | random_line_split | |
TypeGraphQLModule.ts | import {Configuration, Inject, InjectorService, Module} from "@tsed/di";
import {TypeGraphQLSettings} from "./interfaces";
import {TypeGraphQLService} from "./services/TypeGraphQLService";
/**
* @ignore
*/
@Module()
export class | {
@Inject()
protected service: TypeGraphQLService;
@Inject()
protected injector: InjectorService;
@Configuration()
protected configuration: Configuration;
get settings(): {[key: string]: TypeGraphQLSettings} | undefined {
return this.configuration.get("graphql") || this.configuration.get("typegrap... | TypeGraphQLModule | identifier_name |
TypeGraphQLModule.ts | import {Configuration, Inject, InjectorService, Module} from "@tsed/di";
import {TypeGraphQLSettings} from "./interfaces";
import {TypeGraphQLService} from "./services/TypeGraphQLService";
/**
* @ignore
*/
@Module()
export class TypeGraphQLModule {
@Inject()
protected service: TypeGraphQLService;
@Inject()
... |
}
}
| {
Object.entries(settings).map(async ([key, options]) => {
const {path} = options;
displayLog(key, path);
});
} | conditional_block |
TypeGraphQLModule.ts | import {Configuration, Inject, InjectorService, Module} from "@tsed/di";
import {TypeGraphQLSettings} from "./interfaces";
import {TypeGraphQLService} from "./services/TypeGraphQLService";
/**
* @ignore
*/
@Module()
export class TypeGraphQLModule {
@Inject()
protected service: TypeGraphQLService;
@Inject()
... |
$afterListen(): Promise<any> | void {
const host = this.configuration.getBestHost();
const displayLog = (key: string, path: string) => {
const url = typeof host.port === "number" ? `${host.protocol}://${host.address}:${host.port}` : "";
this.injector.logger.info(`[${key}] GraphQL server is ava... | {
const {settings} = this;
if (settings) {
const promises = Object.entries(settings).map(async ([key, options]) => {
return this.service.createServer(key, options);
});
return Promise.all(promises);
}
} | identifier_body |
TODO.py | # mesa - toolkit for building dynamic python apps with zero downtime
# basis: package is inspected for all instances of specified abc and each added to internal mesa list
# Casa is a mesa obj is instantiated as holder of dynamic obj list, one for each abc type in specified package
# m = mesa.Casa(hideExceptions=False) ... | # DOTO: utility interface to implement by client app to take care of input for each specific data type
# DOTO: accompanying Method utility that once required args are declared once, elegant handling
# ie no passing from interface to host back to interface like it is in unit test right now
# TODO: meta method... | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.