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 |
|---|---|---|---|---|
customer.js | //列操作
var caozuo = function(value, row, index) {
return formatString('<img title="编辑" onclick="customer_editNode(\'{0}\');" src="{1}"/> <img title="删除" onclick="customer_delete(\'{2}\')" src="{3}"/> <img title="查看" onclick="customer_check(\'{4}\');" src="{5}"/>',
row.guid,'./ui/style/images/extjs_icons... | iconCls : 'icon-ok',
handler : function() {
$.messager.progress();
var isValid = $('#customer_addForm').form('validate');
if (!isValid){
$.messager.progress('close');
return;
}
var d = $(this).closest('.window-body');
var data =serializeObject($('#customer_addForm'),true);
va... | random_line_split | |
customer.js |
//列操作
var caozuo = function(value, row, index) {
return formatString('<img title="编辑" onclick="customer_editNode(\'{0}\');" src="{1}"/> <img title="删除" onclick="customer_delete(\'{2}\')" src="{3}"/> <img title="查看" onclick="customer_check(\'{4}\');" src="{5}"/>',
row.guid,'./ui/style/images/extjs_ico... | Record', code);
}
var node = $('#customer_datagrid').datagrid('getSelected');
$.messager.confirm('询问', '您确定要删除当前【'+node.name+'】记录?', function(b) {
if(b){
$.messager.progress();
var d = $(this).closest('.window-body');
var rainbow = new Rainbow();
rainbow.addRows({"guid":code});
rainbow.setS... | {
if (code != undefined) {
$('#customer_datagrid').datagrid('select | conditional_block |
customer.js |
//列操作
var caozuo = function(value, row, index) {
return formatString('<img title="编辑" onclick="customer_editNode(\'{0}\');" src="{1}"/> <img title="删除" onclick="customer_delete(\'{2}\')" src="{3}"/> <img title="查看" onclick="customer_check(\'{4}\');" src="{5}"/>',
row.guid,'./ui/style/images/extjs_ico... | ,
handler : function() {
if(isValid('customer_addForm') == true){
var d = $(this).closest('.window-body');
var data =serializeObject($('#customer_addForm'),true);
var rainbow = new Rainbow();
rainbow.setAttr(data);
rainbow.setService("customerService");
rainbow.setMethod("in... | : 'icon-ok' | identifier_name |
customer.js |
//列操作
var caozuo = function(value, row, index) {
return formatString('<img title="编辑" onclick="customer_editNode(\'{0}\');" src="{1}"/> <img title="删除" onclick="customer_delete(\'{2}\')" src="{3}"/> <img title="查看" onclick="customer_check(\'{4}\');" src="{5}"/>',
row.guid,'./ui/style/images/extjs_ico... | t').val('');
customer_reload();
};
| true,'查看信息','customer_addForm',node);
}
//查询过滤
var customer_query = function(){
var datas =serializeObject($('#customer_queryForm'));
$('#customer_datagrid').datagrid('load',datas);
};
//清空查询条件
var customer_query_clear = function(){
$('#customer_queryForm inpu | identifier_body |
ads-loader.service.ts | /**
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to... | (error: HttpErrorResponse): Observable<never> {
if (error.error instanceof ErrorEvent) {
return throwError(new Error(`${error.error.message}`));
} else {
return throwError(new Error(`${error.message}`));
}
}
}
| handleFetchError | identifier_name |
ads-loader.service.ts | /**
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to... |
return this.fetchInternal(adTagUrl, undefined)
.pipe(
flatMap(vast => forkJoin([
of(vast),
...vast.ads.filter(ad => ad instanceof VASTWrapper)
.map(
ad => this.fetchInternal(
(ad as VASTWrapper).vastAdTagURI,
... | {
adTagUrl = this.appendNonce(adTagUrl, session.nonce);
} | conditional_block |
ads-loader.service.ts | /**
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to... | }),
switchMap((session: PalSession) => {
return this.requestAdsInternal(adsRequest, session);
}));
} else {
return this.requestAdsInternal(adsRequest);
}
}
private getDescriptionUrl(): string {
return window.location.protocol + '//' + window.location.host... | this.palSessionLoaded.emit({ session }); | random_line_split |
lib.rs | //! An asynchronous implementation of [STUN][RFC 5389] server and client.
//!
//! # Examples
//!
//! An example that issues a `BINDING` request:
//!
//! ```
//! # extern crate fibers_global;
//! # extern crate fibers_transport;
//! # extern crate futures;
//! # extern crate rustun;
//! # extern crate stun_codec;
//! # ... | () -> Result<(), MainError> {
let server = fibers_global::execute(UdpServer::start(
fibers_global::handle(),
"127.0.0.1:0".parse().unwrap(),
BindingHandler,
))?;
let server_addr = server.local_addr();
fibers_global::spawn(server.map(|_| ()).map_err(|e|... | basic_udp_test | identifier_name |
lib.rs | //! An asynchronous implementation of [STUN][RFC 5389] server and client.
//!
//! # Examples
//!
//! An example that issues a `BINDING` request:
//!
//! ```
//! # extern crate fibers_global;
//! # extern crate fibers_transport;
//! # extern crate futures;
//! # extern crate rustun;
//! # extern crate stun_codec;
//! # ... | let response = track!(fibers_global::execute(response))?;
assert!(response.is_ok());
Ok(())
}
}
| {
let server = fibers_global::execute(TcpServer::start(
fibers_global::handle(),
"127.0.0.1:0".parse().unwrap(),
DefaultFactory::<BindingHandler>::new(),
))?;
let server_addr = server.local_addr();
fibers_global::spawn(server.map(|_| ()).map_err(|e| p... | identifier_body |
lib.rs | //! An asynchronous implementation of [STUN][RFC 5389] server and client.
//!
//! # Examples
//!
//! An example that issues a `BINDING` request:
//!
//! ```
//! # extern crate fibers_global;
//! # extern crate fibers_transport;
//! # extern crate futures;
//! # extern crate rustun;
//! # extern crate stun_codec;
//! # ... | fibers_global::spawn(server.map(|_| ()).map_err(|e| panic!("{}", e)));
thread::sleep(Duration::from_millis(50));
let response = TcpTransporter::<MessageEncoder<_>, MessageDecoder<_>>::connect(server_addr)
.map_err(Error::from)
.map(StunTcpTransporter::new)
.m... | random_line_split | |
popups.rs | use core::fmt::Write;
use libtww::game::Console;
use libtww::game::Flag;
use libtww::system::get_frame_count;
use libtww::system::memory::read;
use libtww::Addr;
use crate::flag_menu::FLAGS;
static mut global_flags_cache: [u8; 64] = [0; 64];
static mut end_frame: u32 = 0;
pub static mut visible: bool = false;
static ... | else {
let _ = write!(
console.lines[0].begin(),
"Flag {:02X} {} has been set",
0xFF & addr,
bit
);
}
}
for (index, cached_value) in unsafe { global_flags_cache.iter_mut().enumerate() } {
let addr = 0x803B8... | {
let text = if text.len() > 50 { &text[..50] } else { text };
let _ = write!(console.lines[0].begin(), "{}", text);
} | conditional_block |
popups.rs | use core::fmt::Write;
use libtww::game::Console;
use libtww::game::Flag;
use libtww::system::get_frame_count;
use libtww::system::memory::read;
use libtww::Addr;
use crate::flag_menu::FLAGS;
static mut global_flags_cache: [u8; 64] = [0; 64];
static mut end_frame: u32 = 0;
pub static mut visible: bool = false;
static ... | {
unsafe {
end_frame = get_frame_count() + 200;
visible = true;
flag = Flag(addr, bit);
}
} | identifier_body | |
popups.rs | use core::fmt::Write;
use libtww::game::Console;
use libtww::game::Flag;
use libtww::system::get_frame_count;
use libtww::system::memory::read;
use libtww::Addr;
use crate::flag_menu::FLAGS;
static mut global_flags_cache: [u8; 64] = [0; 64];
static mut end_frame: u32 = 0;
pub static mut visible: bool = false;
static ... | (f: Flag) -> Option<&'static str> {
for &(text, known_flag) in FLAGS.iter() {
if known_flag == f {
return Some(text);
}
}
None
}
pub fn check_global_flags() {
if unsafe { visible } && get_frame_count() > unsafe { end_frame } {
unsafe {
visible = false;
... | get_flag_str | identifier_name |
popups.rs | use core::fmt::Write;
use libtww::game::Console;
use libtww::game::Flag;
use libtww::system::get_frame_count;
use libtww::system::memory::read;
use libtww::Addr;
use crate::flag_menu::FLAGS;
static mut global_flags_cache: [u8; 64] = [0; 64];
static mut end_frame: u32 = 0;
pub static mut visible: bool = false;
static ... | let current_value = read::<u8>(addr);
let diff = current_value & (0xFF ^ *cached_value);
if diff != 0 {
for bit in 0..8 {
if diff & (1 << bit) != 0 {
show_popup(addr, bit);
}
}
*cached_value |= diff;
... |
for (index, cached_value) in unsafe { global_flags_cache.iter_mut().enumerate() } {
let addr = 0x803B872C + index; | random_line_split |
xbmc_library.py | # -*- coding: utf-8 -*-
#
# Copyright (C) 2015 Thomas Amland
#
# 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 3 of the License, or
# (at your option) any later version.
#
# This ... | (self):
params = {'properties': ['imdbnumber']}
tvshows = jsonrpc('VideoLibrary.GetTVShows', params)['result']\
.get('tvshows', [])
ret = []
for tvshow in tvshows:
params = {
'tvshowid': tvshow['tvshowid'],
'properties': ['season', ... | episodes | identifier_name |
xbmc_library.py | # -*- coding: utf-8 -*-
#
# Copyright (C) 2015 Thomas Amland
#
# 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 3 of the License, or
# (at your option) any later version.
#
# This ... |
return response
| logger.error("jsonrpc error: %r" % response)
return None | conditional_block |
xbmc_library.py | # -*- coding: utf-8 -*-
#
# Copyright (C) 2015 Thomas Amland
#
# 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 3 of the License, or
# (at your option) any later version.
#
# This ... |
def movies(self):
params = {'properties': self._movie_properties}
response = jsonrpc('VideoLibrary.GetMovies', params)
movies = response['result'].get('movies', [])
movies = map(_load_movie, movies)
return [m for m in movies if m is not None]
def episodes(self):
... | params = {
'episodeid': episodeid,
'properties': ['season', 'episode', 'playcount', 'tvshowid'],
}
episode = jsonrpc('VideoLibrary.GetEpisodeDetails', params)['result']['episodedetails']
params = {'tvshowid': episode['tvshowid'], 'properties': ['imdbnumber']}
tvsh... | identifier_body |
xbmc_library.py | # -*- coding: utf-8 -*-
#
# Copyright (C) 2015 Thomas Amland
#
# 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 3 of the License, or
# (at your option) any later version.
#
# This ... | 'method': method,
'params': params,
}
payload = json.dumps(payload, encoding='utf-8')
try:
import xbmc
except:
import requests
response = requests.post(
"http://localhost:8081/jsonrpc",
data=payload,
headers={'content-type': 'ap... | if params is None:
params = {}
payload = {
'jsonrpc': '2.0',
'id': 1, | random_line_split |
hero-detail.component.ts | // #docplaster
// #docregion
import { switchMap } from 'rxjs/operators';
import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute, ParamMap } from '@angular/router';
import { Observable } from 'rxjs';
import { HeroService } from '../hero.service';
import { Hero } from '../hero';
@Component(... |
// #enddocregion redirect
}
| {
let heroId = hero ? hero.id : null;
// Pass along the hero id if available
// so that the HeroList component can select that hero.
// Include a junk 'foo' property for fun.
this.router.navigate(['/superheroes', { id: heroId, foo: 'foo' }]);
} | identifier_body |
hero-detail.component.ts | // #docplaster
// #docregion
import { switchMap } from 'rxjs/operators';
import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute, ParamMap } from '@angular/router';
import { Observable } from 'rxjs';
import { HeroService } from '../hero.service';
import { Hero } from '../hero';
@Component(... |
constructor(
private route: ActivatedRoute,
private router: Router,
private service: HeroService
) {}
ngOnInit() {
this.hero$ = this.route.paramMap.pipe(
switchMap((params: ParamMap) =>
this.service.getHero(params.get('id')))
);
}
// #docregion redirect
gotoHeroes(hero: ... | styleUrls: ['./hero-detail.component.css']
})
export class HeroDetailComponent implements OnInit {
hero$: Observable<Hero>; | random_line_split |
hero-detail.component.ts | // #docplaster
// #docregion
import { switchMap } from 'rxjs/operators';
import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute, ParamMap } from '@angular/router';
import { Observable } from 'rxjs';
import { HeroService } from '../hero.service';
import { Hero } from '../hero';
@Component(... | (
private route: ActivatedRoute,
private router: Router,
private service: HeroService
) {}
ngOnInit() {
this.hero$ = this.route.paramMap.pipe(
switchMap((params: ParamMap) =>
this.service.getHero(params.get('id')))
);
}
// #docregion redirect
gotoHeroes(hero: Hero) {
le... | constructor | identifier_name |
5th Anniversary Maple Weapon.js | var status, sel, sel2;
var maple35 = [1302020, 1382009,1452016,1462014,1472030,1492020,1482020];
// sword, staff, bow, crow, claw, gun, knuckle
var maple43 = [1302030,1332025,1382012,1412011,1422014,1432012,1442024,1452022,
1462019,1472032,1492021,1482021];
// soul singer, wagner, lama staff, dragon axe, doom singe... | (mode, type, selection) {
if (mode != 1) {
cm.dispose();
return false;
} else {
status++;
}
if (status == 0) {
sel = selection;
text = "Which of the following items would you like to buy?\r\n\r\n";
if (selection == 0 || selection == 1) {
... | action | identifier_name |
5th Anniversary Maple Weapon.js | var status, sel, sel2;
var maple35 = [1302020, 1382009,1452016,1462014,1472030,1492020,1482020];
// sword, staff, bow, crow, claw, gun, knuckle
var maple43 = [1302030,1332025,1382012,1412011,1422014,1432012,1442024,1452022,
1462019,1472032,1492021,1482021];
// soul singer, wagner, lama staff, dragon axe, doom singe... |
function action(mode, type, selection) {
if (mode != 1) {
cm.dispose();
return false;
} else {
status++;
}
if (status == 0) {
sel = selection;
text = "Which of the following items would you like to buy?\r\n\r\n";
if (selection == 0 || selection =... | {
status = -1;
cm.sendSimple("What options would you like to view?\r\n\r\n#b#L0#Level 35 Maple Weapons\r\n#L1#Level 43 Maple Weapons\r\n#L2#Level 64 Maple Weapons");
} | identifier_body |
5th Anniversary Maple Weapon.js | var status, sel, sel2;
var maple35 = [1302020, 1382009,1452016,1462014,1472030,1492020,1482020];
// sword, staff, bow, crow, claw, gun, knuckle
var maple43 = [1302030,1332025,1382012,1412011,1422014,1432012,1442024,1452022,
1462019,1472032,1492021,1482021];
// soul singer, wagner, lama staff, dragon axe, doom singe... | cm.dispose();
} else {
cm.sendOk("You have received a #i"+maple64[sel2]+"# in exchange for #b"+cost64[selection]+"#k #i"+leaf+"#.");
cm.gainItem(leaf, -cost64[selection]);
cm.gainItem(maple64[sel2],1);
cm.gainItem(req64[fag][selection],-1);
... | } else if (status == 2) {
if (!cm.haveItem(leaf, cost64[selection]) || !cm.haveItem(req64[fag][selection])) {
cm.sendOk("You do not have the sufficient item(s) needed to complete this transaction. Please check the requirements again."); | random_line_split |
5th Anniversary Maple Weapon.js | var status, sel, sel2;
var maple35 = [1302020, 1382009,1452016,1462014,1472030,1492020,1482020];
// sword, staff, bow, crow, claw, gun, knuckle
var maple43 = [1302030,1332025,1382012,1412011,1422014,1432012,1442024,1452022,
1462019,1472032,1492021,1482021];
// soul singer, wagner, lama staff, dragon axe, doom singe... |
cm.sendSimple(text);
}
} else if (status == 1) {
sel2 = selection;
if (sel == 0 || sel == 1) {
if (!cm.haveItem(leaf, items3543[sel])) {
cm.sendOk("You do not have enough leaves for this transaction. You are currently lacking"+
" "+(it... | {
text += "#L"+i+"##i"+maple64[i]+"# #t"+maple64[i]+"##l\r\n";
} | conditional_block |
ghost.js | var fs = require('fs'),
request = require('request');
process.env.NODE_TLS_REJECT_UNAUTHORIZED = 0;
const GHOST_ENDPOINT = {
protocol: 'https:',
host: '52.49.91.111',
port: 8443,
path: '/ghost'
};
const GHOST_URL = GHOST_ENDPOINT.protocol + '//' + GHOST_ENDPOINT.host + ':' +
GHOST_ENDPOINT.por... | port: GHOST_ENDPOINT.port,
path: GHOST_ENDPOINT.path,
headers: {
'Range': `bytes=4017-8120`
}
}
var request2 = require('http2').get(options);
// Ignore the response
request2.on('response', function(response) {
// Ignore
//response.pipe(process.stdout);
});
// Receive push streams
reque... | // After watching the image, with code 4017-8120, we request that Range, with HTTP/2.0
var options = {
protocol: GHOST_ENDPOINT.protocol,
host: GHOST_ENDPOINT.host, | random_line_split |
ghost.js | var fs = require('fs'),
request = require('request');
process.env.NODE_TLS_REJECT_UNAUTHORIZED = 0;
const GHOST_ENDPOINT = {
protocol: 'https:',
host: '52.49.91.111',
port: 8443,
path: '/ghost'
};
const GHOST_URL = GHOST_ENDPOINT.protocol + '//' + GHOST_ENDPOINT.host + ':' +
GHOST_ENDPOINT.por... |
base64Image += body;
// bytesRead += parseInt(res.headers['content-length']); // Can be wrong data
bytesRead += body.length;
if (res.statusCode === 206) {
getImage(callback);
} else {
callback();
}
});
};
getImage(function() {
var buffer =... | {
throw err;
} | conditional_block |
providers.py | providers_by_class`
restrict_version: Checks provider version in yamls if `True`
required_tags: List of tags that must be set in yamls
inverted: Inclusive if `False`, exclusive otherwise
conjunctive: If true, all subfilters are applied and all must match (default)
If... |
return True
def _filter_restricted_version(self, provider):
""" Filters by yaml version restriction; not applied if SSH is not available """
if self.restrict_version:
# TODO
# get rid of this since_version hotfix by translating since_version
# to restric... | test_flags = [flag.strip() for flag in self.required_flags]
defined_flags = conf.cfme_data.get('test_flags', '')
if isinstance(defined_flags, six.string_types):
defined_flags = defined_flags.split(',')
defined_flags = [flag.strip() for flag in defined_flags]
... | conditional_block |
providers.py | self.conjunctive = conjunctive
def _filter_keys(self, provider):
""" Filters by provider keys """
if self.keys is None:
return None
return provider.key in self.keys
def _filter_classes(self, provider):
""" Filters by provider (base) classes """
if self.clas... | """ Creates a Provider object given a management_system key in cfme_data.
Usage:
get_crud('ec2east')
Returns: A Provider object that has methods that operate on CFME
"""
prov_config = providers_data[provider_key]
prov_type = prov_config.get('type')
return get_class_from_type(prov_type... | identifier_body | |
providers.py | ', operator.lt)])
def __init__(self, keys=None, classes=None, required_fields=None, required_tags=None,
required_flags=None, restrict_version=False, inverted=False, conjunctive=True):
self.keys = keys
self.classes = classes
self.required_fields = required_fields
sel... | get_crud | identifier_name | |
providers.py | be set in yamls
inverted: Inclusive if `False`, exclusive otherwise
conjunctive: If true, all subfilters are applied and all must match (default)
If false (disjunctive), at least one of the subfilters must match
"""
_version_operator_map = OrderedDict([('>=', operator.ge),
... | except: | random_line_split | |
entry.rs | use memory::Frame;
pub struct Entry(u64);
impl Entry {
pub fn is_unused(&self) -> bool {
self.0 == 0
}
pub fn set_unused(&mut self) {
self.0 = 0
}
pub fn flags(&self) -> EntryFlags {
EntryFlags::from_bits_truncate(self.0)
}
pub fn pointed_frame(&self) -> Option<F... | const NO_CACHE = 1 << 4,
const ACCESSED = 1 << 5,
const DIRTY = 1 << 6,
const HUGE_PAGE = 1 << 7,
const GLOBAL = 1 << 8,
const NO_EXECUTE = 1 << 63,
}
} | const WRITE_THROUGH = 1 << 3, | random_line_split |
entry.rs | use memory::Frame;
pub struct Entry(u64);
impl Entry {
pub fn is_unused(&self) -> bool {
self.0 == 0
}
pub fn set_unused(&mut self) {
self.0 = 0
}
pub fn flags(&self) -> EntryFlags {
EntryFlags::from_bits_truncate(self.0)
}
pub fn pointed_frame(&self) -> Option<F... |
}
pub fn set(&mut self, frame: Frame, flags: EntryFlags) {
assert!(frame.start_address() & ! 0x000fffff_fffff000 == 0);
self.0 = (frame.start_address() as u64) | flags.bits();
}
}
bitflags! {
pub flags EntryFlags: u64 {
const PRESENT = 1 << 0,
const WRITABLE = ... | {
None
} | conditional_block |
entry.rs | use memory::Frame;
pub struct Entry(u64);
impl Entry {
pub fn | (&self) -> bool {
self.0 == 0
}
pub fn set_unused(&mut self) {
self.0 = 0
}
pub fn flags(&self) -> EntryFlags {
EntryFlags::from_bits_truncate(self.0)
}
pub fn pointed_frame(&self) -> Option<Frame> {
if self.flags().contains(PRESENT) {
Some(Frame::c... | is_unused | identifier_name |
process_NCEI_03_prcp_180d.py | """
Python script 'process_NCEI_03_prcp_180d.py'
by Matthew Garcia, PhD student
Dept. of Forest and Wildlife Ecology
University of Wisconsin - Madison
matt.e.garcia@gmail.com
Copyright (C) 2015-2016 by Matthew Garcia
Licensed Gnu GPL v3; see 'LICENSE_GnuGPLv3.txt' for complete terms
Send questions, bug reports, any re... |
#
# if rolling accounting variable files exist to be carried over
# from previous year
if use_vars_file:
message('extracting prcp_180d datacube from %s' % varfname)
with hdf.File(varfname, 'r') as h5infile:
nrows = np.copy(h5infile['nrows'])
ncols = np.copy(h5infile['ncols'])
prcp_180d ... | if str(prev_year) in vars_file:
use_vars_file = True
varfname = vars_file
break | conditional_block |
process_NCEI_03_prcp_180d.py | """
Python script 'process_NCEI_03_prcp_180d.py'
by Matthew Garcia, PhD student
Dept. of Forest and Wildlife Ecology
University of Wisconsin - Madison
matt.e.garcia@gmail.com
Copyright (C) 2015-2016 by Matthew Garcia
Licensed Gnu GPL v3; see 'LICENSE_GnuGPLv3.txt' for complete terms
Send questions, bug reports, any re... | (char_string):
"""
prints a string to the terminal and flushes the buffer
"""
print char_string
sys.stdout.flush()
return
message(' ')
message('process_NCEI_03_prcp_180d.py started at %s' %
datetime.datetime.now().isoformat())
message(' ')
#
if len(sys.argv) < 4:
message('input war... | message | identifier_name |
process_NCEI_03_prcp_180d.py | """
Python script 'process_NCEI_03_prcp_180d.py'
by Matthew Garcia, PhD student
Dept. of Forest and Wildlife Ecology
University of Wisconsin - Madison
matt.e.garcia@gmail.com
Copyright (C) 2015-2016 by Matthew Garcia
Licensed Gnu GPL v3; see 'LICENSE_GnuGPLv3.txt' for complete terms
Send questions, bug reports, any re... | dates = sorted([j for j in all_dates if int(j // 1E4) == this_year])
message('- processing %d dates in %d' % (len(dates), this_year))
message(' ')
#
prev_year = this_year - 1
vars_files = sorted(glob.glob('%s/*_year_end_prcp_180d.h5' % path))
use_vars_file = False
if len(vars_files) > 0:
for vars_file in vars_files... | random_line_split | |
process_NCEI_03_prcp_180d.py | """
Python script 'process_NCEI_03_prcp_180d.py'
by Matthew Garcia, PhD student
Dept. of Forest and Wildlife Ecology
University of Wisconsin - Madison
matt.e.garcia@gmail.com
Copyright (C) 2015-2016 by Matthew Garcia
Licensed Gnu GPL v3; see 'LICENSE_GnuGPLv3.txt' for complete terms
Send questions, bug reports, any re... |
message(' ')
message('process_NCEI_03_prcp_180d.py started at %s' %
datetime.datetime.now().isoformat())
message(' ')
#
if len(sys.argv) < 4:
message('input warning: no input directory indicated,, using ./grids')
path = './grids'
else:
path = sys.argv[3]
#
if len(sys.argv) < 3:
message('input... | """
prints a string to the terminal and flushes the buffer
"""
print char_string
sys.stdout.flush()
return | identifier_body |
profiler.py | # This file is part of KTBS <http://liris.cnrs.fr/sbt-dev/ktbs>
# Copyright (C) 2011-2012 Pierre-Antoine Champin <pchampin@liris.cnrs.fr> /
# Universite de Lyon <http://www.universite-lyon.fr>
#
# KTBS is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General ... | join(self.DIRECTORY, filename))
return my_globals['RET']
def start_plugin(config):
if config.has_section('profiler') and config.has_option('profiler', 'directory'):
ProfilerMiddleware.DIRECTORY = config.get('profiler', 'directory')
register_middleware(TOP, Profil... | global RET
resp = req.get_response(self.app)
RET = list(resp(environ, start_response))
""",
my_globals, locals(), | random_line_split |
profiler.py | # This file is part of KTBS <http://liris.cnrs.fr/sbt-dev/ktbs>
# Copyright (C) 2011-2012 Pierre-Antoine Champin <pchampin@liris.cnrs.fr> /
# Universite de Lyon <http://www.universite-lyon.fr>
#
# KTBS is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General ... | (self, environ, start_response):
req = Request(environ)
params = environ['rdfrest.parameters']
do_profiling = params.pop('profiler', None)
if do_profiling is None:
resp = req.get_response(self.app)
return resp(environ, start_response)
else:
fil... | __call__ | identifier_name |
profiler.py | # This file is part of KTBS <http://liris.cnrs.fr/sbt-dev/ktbs>
# Copyright (C) 2011-2012 Pierre-Antoine Champin <pchampin@liris.cnrs.fr> /
# Universite de Lyon <http://www.universite-lyon.fr>
#
# KTBS is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General ... |
def __call__(self, environ, start_response):
req = Request(environ)
params = environ['rdfrest.parameters']
do_profiling = params.pop('profiler', None)
if do_profiling is None:
resp = req.get_response(self.app)
return resp(environ, start_response)
els... | self.app = app | identifier_body |
profiler.py | # This file is part of KTBS <http://liris.cnrs.fr/sbt-dev/ktbs>
# Copyright (C) 2011-2012 Pierre-Antoine Champin <pchampin@liris.cnrs.fr> /
# Universite de Lyon <http://www.universite-lyon.fr>
#
# KTBS is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General ... |
def start_plugin(config):
if config.has_section('profiler') and config.has_option('profiler', 'directory'):
ProfilerMiddleware.DIRECTORY = config.get('profiler', 'directory')
register_middleware(TOP, ProfilerMiddleware)
def stop_plugin():
unregister_middleware(ProfilerMiddleware)
| filename = '%s--%s--%s.profiler.dat' % (
datetime.now().strftime('%Y-%m-%d-%H:%M:%S'),
req.method,
req.url.replace('/', '_'),
)
my_globals = dict(globals())
run_in_profiler("""
global RET
resp = req.get_response(self.app)
RET = list(res... | conditional_block |
mod.rs | // Copyright 2020 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#[cfg(feature = "libvda")]
pub mod vda;
use base::AsRawDescriptor;
use crate::virtio::video::error::VideoResult;
use crate::virtio::video::{
form... |
/// Requests the encoder to flush. When completed, an `EncoderEvent::FlushResponse` event will
/// be readable from the event pipe.
fn flush(&mut self) -> VideoResult<()>;
/// Requests the encoder to use new encoding parameters provided by `bitrate` and `framerate`.
fn request_encoding_params_chan... | &mut self,
resource: GuestResourceHandle,
offset: u32,
size: u32,
) -> VideoResult<OutputBufferId>; | random_line_split |
chartjs.component.ts | import { Component } from '@angular/core';
@Component({
templateUrl: 'chartjs.component.html'
})
export class | {
// lineChart
public lineChartData: Array<any> = [
{data: [65, 59, 80, 81, 56, 55, 40], label: 'Series A'},
{data: [28, 48, 40, 19, 86, 27, 90], label: 'Series B'},
{data: [18, 48, 77, 9, 100, 27, 40], label: 'Series C'}
];
public lineChartLabels: Array<any> = ['January', 'February', 'March', 'Ap... | ChartJSComponent | identifier_name |
chartjs.component.ts | import { Component } from '@angular/core';
@Component({
templateUrl: 'chartjs.component.html'
})
export class ChartJSComponent {
// lineChart
public lineChartData: Array<any> = [
{data: [65, 59, 80, 81, 56, 55, 40], label: 'Series A'},
{data: [28, 48, 40, 19, 86, 27, 90], label: 'Series B'},
{data: ... |
public chartHovered(e: any): void {
console.log(e);
}
}
| {
console.log(e);
} | identifier_body |
chartjs.component.ts | import { Component } from '@angular/core';
@Component({
templateUrl: 'chartjs.component.html'
})
export class ChartJSComponent {
// lineChart
public lineChartData: Array<any> = [
{data: [65, 59, 80, 81, 56, 55, 40], label: 'Series A'},
{data: [28, 48, 40, 19, 86, 27, 90], label: 'Series B'},
{data: ... | backgroundColor: 'rgba(77,83,96,0.2)',
borderColor: 'rgba(77,83,96,1)',
pointBackgroundColor: 'rgba(77,83,96,1)',
pointBorderColor: '#fff',
pointHoverBackgroundColor: '#fff',
pointHoverBorderColor: 'rgba(77,83,96,1)'
},
{ // grey
backgroundColor: 'rgba(148,159,177,0.2)'... | { // dark grey | random_line_split |
BrandCard.tsx | import { Link } from 'react-router-dom';
import ReactMarkdown from 'react-markdown';
import { MarkdownLink } from '../MarkdownLink';
import { generateBrandPath } from '../URLGenerators';
import { Brand, ProjectConnection } from '../graphqlTypes.generated';
export type BrandCardProps = {
brand: Pick<Brand, 'name' | '... | </ReactMarkdown>
</div>
</div>
</>
);
}
| {
return (
<>
<div className="card mb-2">
<div className="card-header">
<h2 className="m-0">
<Link to={generateBrandPath(brand)} className="link-unstyled">
{brand.name}
</Link>{' '}
<small>
({brand.projects.totalCount} {brand.... | identifier_body |
BrandCard.tsx | import { Link } from 'react-router-dom';
import ReactMarkdown from 'react-markdown';
import { MarkdownLink } from '../MarkdownLink';
import { generateBrandPath } from '../URLGenerators';
import { Brand, ProjectConnection } from '../graphqlTypes.generated';
export type BrandCardProps = {
brand: Pick<Brand, 'name' | '... | ({ brand }: BrandCardProps): JSX.Element {
return (
<>
<div className="card mb-2">
<div className="card-header">
<h2 className="m-0">
<Link to={generateBrandPath(brand)} className="link-unstyled">
{brand.name}
</Link>{' '}
<small>
... | BrandCard | identifier_name |
BrandCard.tsx | import { Link } from 'react-router-dom';
import ReactMarkdown from 'react-markdown';
import { MarkdownLink } from '../MarkdownLink';
import { generateBrandPath } from '../URLGenerators';
import { Brand, ProjectConnection } from '../graphqlTypes.generated';
export type BrandCardProps = {
brand: Pick<Brand, 'name' | '... | <ReactMarkdown components={{ a: MarkdownLink }}>
{(brand.description ?? '').slice(0, 500) +
(brand.description && brand.description.length >= 500
? `[... (read more)](${generateBrandPath(brand)})`
: '')}
</ReactMarkdown>
</div>
... | random_line_split | |
client.js | var request = require('request');
var Client = (function () {
function Client() |
Client.prototype.connect = function (parent) {
var config = parent.config;
this.configure(config);
this._connector = parent;
parent.logger.trace('Connected to google custom search');
};
Client.prototype.disconnect = function (parent) {
this.config = {};
this.... | {
this.options = {
"url": "",
"method": "GET",
"bodyParams": {},
"gzip": true,
"json": true
};
} | identifier_body |
client.js | var request = require('request');
var Client = (function () {
function Client() {
this.options = {
"url": "",
"method": "GET",
"bodyParams": {},
"gzip": true,
"json": true
};
}
Client.prototype.connect = function (parent) {
... | return true;
};
Client.prototype._createIndividualModel = function (Model, data) {
var model = Model.instance(data, true);
model.setPrimaryKey(data.cacheId);
return model;
};
return Client;
})();
exports.Client = Client;
//# sourceMappingURL=client.js.map | random_line_split | |
client.js | var request = require('request');
var Client = (function () {
function | () {
this.options = {
"url": "",
"method": "GET",
"bodyParams": {},
"gzip": true,
"json": true
};
}
Client.prototype.connect = function (parent) {
var config = parent.config;
this.configure(config);
this._connect... | Client | identifier_name |
mendelian_randomization.py | """
Compute the GRS from genotypes and a GRS file.
"""
# This file is part of grstools.
#
# The MIT License (MIT)
#
# Copyright (c) 2017 Marc-Andre Legault
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# ... | ():
parser = argparse.ArgumentParser(
description=(
"Estimate the effect of an exposure on an outcome using "
"a GRS with an effect on the exposure.\n"
"Estimates are done using the ratio method."
)
)
parser.add_argument("--grs-filename", type=str)
pa... | parse_args | identifier_name |
mendelian_randomization.py | """ | # The MIT License (MIT)
#
# Copyright (c) 2017 Marc-Andre Legault
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy... | Compute the GRS from genotypes and a GRS file.
"""
# This file is part of grstools.
# | random_line_split |
mendelian_randomization.py | """
Compute the GRS from genotypes and a GRS file.
"""
# This file is part of grstools.
#
# The MIT License (MIT)
#
# Copyright (c) 2017 Marc-Andre Legault
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# ... |
elif args.outcome_type == "discrete":
y_g_test = "logistic"
else:
raise ValueError(
"Expected outcome type to be 'discrete' or 'continuous'."
)
if args.exposure_type == "continuous":
x_g_test = "linear"
elif args.exposure_type == "discrete":
x_g_test... | y_g_test = "linear" | conditional_block |
mendelian_randomization.py | """
Compute the GRS from genotypes and a GRS file.
"""
# This file is part of grstools.
#
# The MIT License (MIT)
#
# Copyright (c) 2017 Marc-Andre Legault
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# ... | else:
raise ValueError(
"Expected exposure type to be 'discrete' or 'continuous'."
)
n_iter = 1000
logger.info(
"Computing MR estimates using the ratio method. Bootstrapping "
"standard errors can take some time."
)
beta, low, high = mr_effect_estimate(
... | args = parse_args()
phenotypes = _create_genetest_phenotypes(
args.grs_filename, args.phenotypes_filename,
args.phenotypes_sample_column, args.phenotypes_separator
)
if args.outcome_type == "continuous":
y_g_test = "linear"
elif args.outcome_type == "discrete":
y_g_test... | identifier_body |
vc_usd_nt.py | #
# Copyright (c) 2017 Sugimoto Takaaki
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License. | # You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the Li... | random_line_split | |
vc_usd_nt.py | #
# Copyright (c) 2017 Sugimoto Takaaki
#
# 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... |
print outputString
| sock = urllib.urlopen(url)
jsonString = sock.read()
sock.close()
jsonCurrency = json.loads(jsonString)
price = jsonCurrency['ticker']['price']
outputString = outputString + price + " " | conditional_block |
generic-type-params-name-repr.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 ... | let _: HashMap<String, int> = ();
//~^ ERROR mismatched types: expected `HashMap<std::string::String,int>` but found `()`
let _: HashMap<String, int, Hash<String>> = ();
//~^ ERROR mismatched types: expected `HashMap<std::string::String,int>` but found `()`
// But not when there's a different type ... | // Including cases where the default is using previous type params. | random_line_split |
generic-type-params-name-repr.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 ... | ;
struct C;
struct Foo<T = A, U = B, V = C>;
struct Hash<T>;
struct HashMap<K, V, H = Hash<K>>;
fn main() {
// Ensure that the printed type doesn't include the default type params...
let _: Foo<int> = ();
//~^ ERROR mismatched types: expected `Foo<int>` but found `()`
// ...even when they're present,... | B | identifier_name |
systemd.py | # Copyright 2012-2014 Red Hat, 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... | if __name__ == '__main__':
# simple CLI for testing
if len(sys.argv) == 1:
notify()
elif len(sys.argv) >= 2:
timeout = float(sys.argv[1])
notify_socket = os.getenv('NOTIFY_SOCKET')
if notify_socket:
retval = onready(notify_socket, timeout)
sys.exit(ret... | random_line_split | |
systemd.py | # Copyright 2012-2014 Red Hat, 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... | retval = onready(notify_socket, timeout)
sys.exit(retval) | conditional_block | |
systemd.py | # Copyright 2012-2014 Red Hat, 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... |
def _sd_notify(unset_env, msg):
notify_socket = os.getenv('NOTIFY_SOCKET')
if notify_socket:
sock = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
try:
sock.connect(_abstractify(notify_socket))
sock.sendall(msg)
if unset_env:
del os.enviro... | if socket_name.startswith('@'):
# abstract namespace socket
socket_name = '\0%s' % socket_name[1:]
return socket_name | identifier_body |
systemd.py | # Copyright 2012-2014 Red Hat, 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... | ():
"""Send notification once to Systemd that service is ready.
Systemd sets NOTIFY_SOCKET environment variable with the name of the
socket listening for notifications from services.
This method removes the NOTIFY_SOCKET environment variable to ensure
notification is sent only once.
"""
_sd... | notify_once | identifier_name |
download.rs | use async_trait::async_trait;
use cucumber::given;
use snafu::ResultExt;
use crate::error;
use crate::error::Error;
use crate::state::{GlobalState, State, Step, StepStatus};
use tests::download;
// Download OSM
#[given(regex = r"osm file has been downloaded for (\S+)$")]
pub async fn download_osm(state: &mut GlobalS... | (&mut self, _state: &State) -> Result<StepStatus, Error> {
let Self { region } = self;
download::ntfs(region)
.await
.map(|status| status.into())
.context(error::DownloadSnafu)
}
}
| execute | identifier_name |
download.rs | use async_trait::async_trait;
use cucumber::given;
use snafu::ResultExt;
use crate::error;
use crate::error::Error;
use crate::state::{GlobalState, State, Step, StepStatus};
use tests::download;
// Download OSM
#[given(regex = r"osm file has been downloaded for (\S+)$")]
pub async fn download_osm(state: &mut GlobalS... |
}
| {
let Self { region } = self;
download::ntfs(region)
.await
.map(|status| status.into())
.context(error::DownloadSnafu)
} | identifier_body |
download.rs | use async_trait::async_trait;
use cucumber::given;
use snafu::ResultExt;
use crate::error;
use crate::error::Error;
use crate::state::{GlobalState, State, Step, StepStatus};
use tests::download;
// Download OSM
#[given(regex = r"osm file has been downloaded for (\S+)$")]
pub async fn download_osm(state: &mut GlobalS... | state
.execute_once(DownloadBano {
departments,
region,
})
.await
.expect("failed to download OSM file");
}
#[derive(PartialEq)]
pub struct DownloadBano {
pub departments: Vec<String>,
pub region: String,
}
#[async_trait(?Send)]
impl Step for Downloa... | random_line_split | |
__init__.py | send.
Received data is queued until read.
"""
def __init__(self):
self.send_buf = b""
self.receive_buf = b""
self.closed = False
self._custom_rx_handler = None
self._custom_close_handler = None
self._custom_connect_handler = None
self._connecting = False
self._shutdown_send = F... |
else:
pass
def _format_lists (rlist, wlist, elist):
everything = set()
everything.update(rlist)
everything.update(wlist)
everything.update(elist)
if len(everything) == 0: return "None"
everything = list(everything)
everything.sort()
msg = ""
for fd in everything:
msg += str(fd).strip("<>").re... | RecocoIOWorker.send_fast = RecocoIOWorker.send
log.debug("RecocoIOWorker.send_fast() not available") | conditional_block |
__init__.py | for send.
Received data is queued until read.
"""
def __init__(self):
self.send_buf = b""
self.receive_buf = b""
self.closed = False
self._custom_rx_handler = None
self._custom_close_handler = None
self._custom_connect_handler = None
self._connecting = False
self._shutdown_send... | # Not sure if this is a good idea, but it might be...
if self.close_handler is not None or callback is not None:
log.debug("Resetting close_handler on %s?", self)
if callback is None: callback = _dummy_handler
self._custom_close_handler = callback
@property
def rx_handler (self):
if self.... | @close_handler.setter
def close_handler (self, callback):
"""
Handler to call when closing
""" | random_line_split |
__init__.py | send.
Received data is queued until read.
"""
def __init__(self):
self.send_buf = b""
self.receive_buf = b""
self.closed = False
self._custom_rx_handler = None
self._custom_close_handler = None
self._custom_connect_handler = None
self._connecting = False
self._shutdown_send = F... | (self):
# called by Select loop
return len(self.send_buf) > 0 or self._connecting
def _consume_send_buf (self, l):
# Throw out the first l bytes of the send buffer
# Called by Select loop
assert(len(self.send_buf)>=l)
self.send_buf = self.send_buf[l:]
def close (self):
""" Close this... | _ready_to_send | identifier_name |
__init__.py | send.
Received data is queued until read.
"""
def __init__(self):
self.send_buf = b""
self.receive_buf = b""
self.closed = False
self._custom_rx_handler = None
self._custom_close_handler = None
self._custom_connect_handler = None
self._connecting = False
self._shutdown_send = F... |
@property
def _ready_to_send (self):
# called by Select loop
return len(self.send_buf) > 0 or self._connecting
def _consume_send_buf (self, l):
# Throw out the first l bytes of the send buffer
# Called by Select loop
assert(len(self.send_buf)>=l)
self.send_buf = self.send_buf[l:]
de... | """
Read up to length bytes from receive buffer
(defaults to all)
"""
if length is None:
length = len(self.receive_buf)
r = self.receive_buf[:length]
self.receive_buf = self.receive_buf[length:]
return r | identifier_body |
twist_joints_pulseaction.py | import pymel.core as pm
import pulse.nodes
import pulse.utilnodes
from pulse.buildItems import BuildAction, BuildActionError
class TwistJointsAction(BuildAction):
def validate(self):
if not self.twistJoint:
raise BuildActionError('twistJoint must be set')
if not self.alignJoint:
... | # since it may be driven directly by a control, and would then be equal to the animated world matrix.
# TODO: might want to expose an option for selecting the parent node explicitly.
align_parent = self.alignJoint.getParent()
if align_parent:
# get align j... | twist_blend = None
if self.twistControls:
# add attr to first control, then add proxy to the rest
for twist_ctl in self.twistControls:
if twist_blend is None:
twist_ctl.addAttr('twistBlend', at='double', min=0, max=1, keyable=True, defaultValue=1)
... | identifier_body |
twist_joints_pulseaction.py | import pymel.core as pm
import pulse.nodes
import pulse.utilnodes
from pulse.buildItems import BuildAction, BuildActionError
class TwistJointsAction(BuildAction):
def validate(self):
if not self.twistJoint:
raise BuildActionError('twistJoint must be set')
if not self.alignJoint:
... | raise BuildActionError(f"{node} cannot have an offsetParentMatrix connection "
"while also having inheritsTransform set to True")
return offset_mtx_inputs[0]
# get matrix from parent node
parent_node = node.getParent()
if parent... | if node.inheritsTransform.get(): | random_line_split |
twist_joints_pulseaction.py | import pymel.core as pm
import pulse.nodes
import pulse.utilnodes
from pulse.buildItems import BuildAction, BuildActionError
class | (BuildAction):
def validate(self):
if not self.twistJoint:
raise BuildActionError('twistJoint must be set')
if not self.alignJoint:
raise BuildActionError('alignJoint must be set')
def run(self):
twist_blend = None
if self.twistControls:
# add... | TwistJointsAction | identifier_name |
twist_joints_pulseaction.py | import pymel.core as pm
import pulse.nodes
import pulse.utilnodes
from pulse.buildItems import BuildAction, BuildActionError
class TwistJointsAction(BuildAction):
def validate(self):
if not self.twistJoint:
raise BuildActionError('twistJoint must be set')
if not self.alignJoint:
... |
else:
# add attr directly to joint, not usually desired because this can export with the joints as a curve
self.twistJoint.addAttr('twistBlend', at='double', min=0, max=1, keyable=True, defaultValue=1)
twist_blend = self.twistJoint.attr('twistBlend')
# get parent wo... | twist_ctl.addAttr('twistBlend', proxy=twist_blend) | conditional_block |
infer.py | import sys, os
import pickle
import nltk
import paths
from utils import *
def words_to_dict(words):
return dict(zip(words, range(0, len(words))))
nltk.data.path.append(paths.nltk_data_path)
use_wordnet = True
if use_wordnet:
stemmer = nltk.stem.wordnet.WordNetLemmatizer()
stem = stemmer.lemmatize
else... |
if args[0] in ["-n","--num"]:
if int(args[1]) in range(1,50):
num = int(args[1])
args = args[2:]
if args[0] in ["-d","--distance"]:
if args[1] in dist:
dfun = args[1]
args = args[2:]
model = os.path.joi... | if args[1] in modes:
mode = args[1]
args = args[2:] | conditional_block |
infer.py | import sys, os
import pickle
import nltk
import paths
from utils import *
def words_to_dict(words):
return dict(zip(words, range(0, len(words))))
nltk.data.path.append(paths.nltk_data_path)
use_wordnet = True
if use_wordnet:
stemmer = nltk.stem.wordnet.WordNetLemmatizer()
stem = stemmer.lemmatize
else... |
def make_bow(doc,d):
bow = {}
for word in doc:
if word in d:
wordid = d[word]
bow[wordid] = bow.get(wordid,0) + 1
# XXX we should notify something about non-stopwords that we couldn't parse
return bow
modes = ["fulltext","abstracts"]
ks = ["20","... | replacements = [("---"," "),
("--"," "),
("-", "")] # trying to capture multi-word keywords
for (src,tgt) in replacements:
text = text.replace(src,tgt)
return preprocess(text) | identifier_body |
infer.py | import sys, os
import pickle
import nltk
import paths
from utils import *
def words_to_dict(words):
return dict(zip(words, range(0, len(words))))
nltk.data.path.append(paths.nltk_data_path)
use_wordnet = True
if use_wordnet:
stemmer = nltk.stem.wordnet.WordNetLemmatizer()
stem = stemmer.lemmatize
else... | if args[1] in dist:
dfun = args[1]
args = args[2:]
model = os.path.join(mode,"lda" + k,"final")
words = os.path.join(mode,"vocab.dat")
docs = os.path.join(mode,"docs.dat")
pdf_file = args[0]
(base,_) = os.path.splitext(pdf_file)
text = ... |
if args[0] in ["-d","--distance"]: | random_line_split |
infer.py | import sys, os
import pickle
import nltk
import paths
from utils import *
def words_to_dict(words):
return dict(zip(words, range(0, len(words))))
nltk.data.path.append(paths.nltk_data_path)
use_wordnet = True
if use_wordnet:
stemmer = nltk.stem.wordnet.WordNetLemmatizer()
stem = stemmer.lemmatize
else... | (doc,d):
bow = {}
for word in doc:
if word in d:
wordid = d[word]
bow[wordid] = bow.get(wordid,0) + 1
# XXX we should notify something about non-stopwords that we couldn't parse
return bow
modes = ["fulltext","abstracts"]
ks = ["20","50","100","200... | make_bow | identifier_name |
qt3testsBenchmark.ts | import { Suite } from 'benchmark';
import {
Document,
evaluateXPathToBoolean,
evaluateXPathToFirstNode,
evaluateXPathToNodes,
evaluateXPathToNumber,
evaluateXPathToString,
Language,
} from 'fontoxpath';
import { Element, Node } from 'slimdom';
import getPerformanceTests from 'test-helpers/getPerformanceTests';... | (functions) {
Object.keys(functions).forEach((name) => {
suite.add(name, functions[name]);
});
}
function runTests() {
// tslint:disable-next-line: no-console
console.log('Tests are running...');
suite
// add listeners
.on('cycle', (event) => {
// tslint:disable-next-line: no-console
console.log(
... | addTests | identifier_name |
qt3testsBenchmark.ts | import { Suite } from 'benchmark';
import {
Document,
evaluateXPathToBoolean,
evaluateXPathToFirstNode,
evaluateXPathToNodes,
evaluateXPathToNumber,
evaluateXPathToString,
Language,
} from 'fontoxpath';
import { Element, Node } from 'slimdom';
import getPerformanceTests from 'test-helpers/getPerformanceTests';... | language: Language,
xpath: string,
contextNode: Node | undefined,
variablesInScope: {},
namespaceResolver: (prefix: string) => string | null,
name: string
): void {
const nodesFactory = {
createAttributeNS: assertNode.ownerDocument.createAttributeNS.bind(
assertNode.ownerDocument
),
createCDATASection: ... | function addTestCaseToBenchmark(
assertNode: Element, | random_line_split |
qt3testsBenchmark.ts | import { Suite } from 'benchmark';
import {
Document,
evaluateXPathToBoolean,
evaluateXPathToFirstNode,
evaluateXPathToNodes,
evaluateXPathToNumber,
evaluateXPathToString,
Language,
} from 'fontoxpath';
import { Element, Node } from 'slimdom';
import getPerformanceTests from 'test-helpers/getPerformanceTests';... | // In the tests of 'all-of' and 'any-of', there should be multiple tests. That's why
// function names are numbered.
case 'all-of':
case 'any-of': {
const innerAssertNodes: Element[] = evaluateXPathToNodes('*', assertNode);
innerAssertNodes.forEach((innerAssertNode, i) =>
addTestCaseToBenchmark(
... |
const nodesFactory = {
createAttributeNS: assertNode.ownerDocument.createAttributeNS.bind(
assertNode.ownerDocument
),
createCDATASection: assertNode.ownerDocument.createCDATASection.bind(
assertNode.ownerDocument
),
createComment: assertNode.ownerDocument.createComment.bind(assertNode.ownerDocument),... | identifier_body |
conf.py | # -*- coding: utf-8 -*-
#
# rtstock documentation build configuration file, created by
# sphinx-quickstart on Tue Jul 9 22:26:36 2013.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# A... | #html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#htm... | #html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names
# to template names. | random_line_split |
runTests.js | import compareTranspiled from "./compareTranspiled";
const tests = {
'should change relative paths': "examples/<dir>/relative2relative",
'should change relative paths dynamically': "examples/<dir>/relative2relativeD",
'should change path from a node module to relative': "examples/<dir>/module2relative",
'should dy... |
describeTests(tests);
}
| {
Object.keys(tests).map(description => {
const dir = tests[description];
if(typeof dir === "object") {
describe(description, () => {
describeTests(dir);
});
} else {
test(description, () => {
return compareTranspiled(dir.replace("<dir>", decl));
});
}
});
} | identifier_body |
runTests.js | import compareTranspiled from "./compareTranspiled";
const tests = {
'should change relative paths': "examples/<dir>/relative2relative",
'should change relative paths dynamically': "examples/<dir>/relative2relativeD",
'should change path from a node module to relative': "examples/<dir>/module2relative",
'should dy... | 'should dynamically change path from relative to a node module': "examples/<dir>/relative2moduleD",
'should not change when no matching redirect is found': "examples/<dir>/no_match",
'should change even when': {
'file at original relative path doesn\'t exist': "examples/<dir>/original_relative_not_exist",
'file ... | 'should change path from relative to a node module': "examples/<dir>/relative2module", | random_line_split |
runTests.js | import compareTranspiled from "./compareTranspiled";
const tests = {
'should change relative paths': "examples/<dir>/relative2relative",
'should change relative paths dynamically': "examples/<dir>/relative2relativeD",
'should change path from a node module to relative': "examples/<dir>/module2relative",
'should dy... | (tests) {
Object.keys(tests).map(description => {
const dir = tests[description];
if(typeof dir === "object") {
describe(description, () => {
describeTests(dir);
});
} else {
test(description, () => {
return compareTranspiled(dir.replace("<dir>", decl));
});
}
});
}
describ... | describeTests | identifier_name |
runTests.js | import compareTranspiled from "./compareTranspiled";
const tests = {
'should change relative paths': "examples/<dir>/relative2relative",
'should change relative paths dynamically': "examples/<dir>/relative2relativeD",
'should change path from a node module to relative': "examples/<dir>/module2relative",
'should dy... |
});
}
describeTests(tests);
}
| {
test(description, () => {
return compareTranspiled(dir.replace("<dir>", decl));
});
} | conditional_block |
lib.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/. */
#![feature(box_syntax)]
#![feature(custom_derive)]
#![feature(plugin)]
#![feature(mpsc_select)]
#![feature(plugin)... | pub use pipeline::UnprivilegedPipelineContent;
#[cfg(not(target_os = "windows"))]
pub use sandboxing::content_process_sandbox_profile; |
pub use constellation::{Constellation, InitialConstellationState}; | random_line_split |
issue13507.rs | // Copyright 2012-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-MI... | {
pub pub_foo_field: uint,
foo_field: uint
}
// Tests ty_tup
pub type FooTuple = (u8, i8, bool);
// Skipping ty_param
// Skipping ty_self
// Skipping ty_self
// Skipping ty_infer
// Skipping ty_err
}
| FooStruct | identifier_name |
issue13507.rs | // Copyright 2012-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-MI... |
// Tests ty_nil
pub type FooNil = ();
// Skipping ty_bot
// Tests ty_bool
pub type FooBool = bool;
// Tests ty_char
pub type FooChar = char;
// Tests ty_int (does not test all variants of IntTy)
pub type FooInt = int;
// Tests ty_uint (does not test all variants of UintTy)... | {
let mut ids = vec!();
ids.push(TypeId::of::<FooNil>());
ids.push(TypeId::of::<FooBool>());
ids.push(TypeId::of::<FooInt>());
ids.push(TypeId::of::<FooUint>());
ids.push(TypeId::of::<FooFloat>());
ids.push(TypeId::of::<FooEnum>());
ids.push(TypeId::of::<F... | identifier_body |
issue13507.rs | // Copyright 2012-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-MI... | }
// Tests ty_nil
pub type FooNil = ();
// Skipping ty_bot
// Tests ty_bool
pub type FooBool = bool;
// Tests ty_char
pub type FooChar = char;
// Tests ty_int (does not test all variants of IntTy)
pub type FooInt = int;
// Tests ty_uint (does not test all variants of Ui... | ids.push(TypeId::of::<FooTuple>());
ids | random_line_split |
tests.py | import sys
import traceback
from io import BytesIO
from unittest import TestCase
from wsgiref import simple_server
from django.core.servers.basehttp import get_internal_wsgi_application
from django.test import RequestFactory, override_settings
from .views import FILE_RESPONSE_HOLDER
# If data is too large, socket wi... |
def wsgi_app(environ, start_response):
start_response('200 OK', [('Content-Type', 'text/plain')])
return [b'Hello World!']
def wsgi_app_file_wrapper(environ, start_response):
start_response('200 OK', [('Content-Type', 'text/plain')])
return environ['wsgi.file_wrapper'](BytesIO(b'foo'))
class WSGI... | self._used_sendfile = True
return True | identifier_body |
tests.py | import sys
import traceback
from io import BytesIO
from unittest import TestCase
from wsgiref import simple_server
from django.core.servers.basehttp import get_internal_wsgi_application
from django.test import RequestFactory, override_settings
from .views import FILE_RESPONSE_HOLDER
# If data is too large, socket wi... | (self):
env = {'SERVER_PROTOCOL': 'HTTP/1.0'}
handler = FileWrapperHandler(None, BytesIO(), BytesIO(), env)
handler.run(wsgi_app)
self.assertFalse(handler._used_sendfile)
self.assertEqual(handler.stdout.getvalue().splitlines()[-1], b'Hello World!')
self.assertEqual(handle... | test_file_wrapper_no_sendfile | identifier_name |
tests.py | import sys
import traceback
from io import BytesIO
from unittest import TestCase
from wsgiref import simple_server
from django.core.servers.basehttp import get_internal_wsgi_application
from django.test import RequestFactory, override_settings
from .views import FILE_RESPONSE_HOLDER
# If data is too large, socket wi... |
else:
self.bytes_sent += len(data)
# XXX check Content-Length and truncate if too many bytes written?
data = BytesIO(data)
for chunk in iter(lambda: data.read(MAX_SOCKET_CHUNK_SIZE), b''):
self._write(chunk)
self._flush()
def error_output(self, ... | self.bytes_sent = len(data) # make sure we know content-length
self.send_headers() | conditional_block |
tests.py | import sys
import traceback
from io import BytesIO | from wsgiref import simple_server
from django.core.servers.basehttp import get_internal_wsgi_application
from django.test import RequestFactory, override_settings
from .views import FILE_RESPONSE_HOLDER
# If data is too large, socket will choke, so write chunks no larger than 32MB
# at a time. The rationale behind t... | from unittest import TestCase | random_line_split |
test_utilities.py | # Copyright 2015, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the f... | (
host, port, channel_credentials, server_host_override):
"""Creates an insecure Channel to a remote host.
Args:
host: The name of the remote host to which to connect.
port: The port of the remote host to which to connect.
channel_credentials: The implementations.ChannelCredentials with which to
... | not_really_secure_channel | identifier_name |
test_utilities.py | # Copyright 2015, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the f... | """Creates an insecure Channel to a remote host.
Args:
host: The name of the remote host to which to connect.
port: The port of the remote host to which to connect.
channel_credentials: The implementations.ChannelCredentials with which to
connect.
server_host_override: The target name used for ... | identifier_body | |
test_utilities.py | # Copyright 2015, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the f... | def not_really_secure_channel(
host, port, channel_credentials, server_host_override):
"""Creates an insecure Channel to a remote host.
Args:
host: The name of the remote host to which to connect.
port: The port of the remote host to which to connect.
channel_credentials: The implementations.Channe... | import grpc
from grpc.beta import implementations
| random_line_split |
ngES6.js | "use strict";
import angular from "angular/angular";
import "angular-ui/ui-router";
import "angular/bower-angular-animate";
import "angular/bower-angular-resource"; | import "angular-translate/bower-angular-translate-loader-url";
import "angular-translate/bower-angular-translate-storage-cookie";
import "angular-translate/bower-angular-translate-storage-local";
import "./common/main";
import "./home/main";
import "./poem/main";
import "./article/main";
var ngES6 = angular.module("n... | import "angular-cookies";
import "angular-translate";
import "angular-translate/bower-angular-translate-loader-static-files"; | random_line_split |
UserRouter.js | const _ = require("lodash");
const Qs = require("qs");
const Op = require("sequelize").Op;
function UserRouter(app) {
const { models } = app.data.sequelize;
const api = {
pathname: "/users",
middlewares: [
app.server.auth.isAuthenticated,
app.server.auth.isAuthorized
],
ops: {
ge... | limit: filter.limit,
order: [["createdAt", filter.order]],
offset: filter.offset,
where: filter.search && {
[Op.or]: [
{ username: { [Op.like]: `%${filter.search}%` } },
{ email: { [Op.like]: `%${filter.search}%` } }
... | limit: 100,
order: "DESC",
offset: 0
});
const result = await models.User.findAndCountAll({ | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.