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 |
|---|---|---|---|---|
back-live-detail.component.ts | import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router, ActivatedRouteSnapshot, RouterState, RouterStateSnapshot } from '@angular/router';
import { BackLiveDetailService } from "./service/back-live-detail.service";
import { ProfileService } from "../../../service/profile.service";
declare... | }
showShare(e) {
e.target.parentNode.querySelector('.sharedPanel').style.display = 'block'
;
this.shareCode = new QRCode(e.target.parentNode.querySelector('.sharedPanel .qrcode .code'), {
text: this.shareUrl,
width: 140,
height: 140,
});
}
hideShare(e) {
e.target.parentNode.q... | etailService.addFollow(id)
.subscribe(
data => {
console.log(data)
layer.msg("關注成功");
this.isFollow = true;
},
error => console.log(error)
)
} else {
this.backLiveDetailService.cancelFollow(id)
.subscribe(
data => {
... | identifier_body |
back-live-detail.component.ts | import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router, ActivatedRouteSnapshot, RouterState, RouterStateSnapshot } from '@angular/router';
import { BackLiveDetailService } from "./service/back-live-detail.service";
import { ProfileService } from "../../../service/profile.service";
declare... | data => {
console.log(data);
layer.msg("已取消關注");
this.isFollow = false;
},
error => console.log(error)
)
}
}
showShare(e) {
e.target.parentNode.querySelector('.sharedPanel').style.display = 'block';
this.shareCode = new QRCode(e.target.parentNode.qu... | ata => {
console.log(data)
layer.msg("關注成功");
this.isFollow = true;
},
error => console.log(error)
)
} else {
this.backLiveDetailService.cancelFollow(id)
.subscribe(
| conditional_block |
back-live-detail.component.ts | import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router, ActivatedRouteSnapshot, RouterState, RouterStateSnapshot } from '@angular/router';
import { BackLiveDetailService } from "./service/back-live-detail.service";
import { ProfileService } from "../../../service/profile.service";
declare... | }
clipboradShare(e) {// 复制分享地址
let clipboard = new Clipboard('.copy');
clipboard.on('success', (e) => {
layer.msg('復製成功');
});
clipboard.on('error', (e) => {
layer.msg('複製失敗');
});
}
shareToQQ(url, pics, event) {//手动分享到qq
let source = event.target.ownerDocument.querySelecto... |
hideShare(e) {
e.target.parentNode.querySelector('.sharedPanel').style.display = 'none';
e.target.parentNode.querySelector('.sharedPanel .qrcode .code').innerHTML = '';
this.shareCode.clear(); | random_line_split |
back-live-detail.component.ts | import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router, ActivatedRouteSnapshot, RouterState, RouterStateSnapshot } from '@angular/router';
import { BackLiveDetailService } from "./service/back-live-detail.service";
import { ProfileService } from "../../../service/profile.service";
declare... | sole.log(source, cover);
this.player = new prismplayer({
id: "J_prismPlayer", // 容器id
source: source,
autoplay: true, //自动播放:否
width: "100%", // 播放器宽度
height: "inherit", // 播放器高度
preload: true,
cover: cover
});
this.player.on("pause", function () {
... | / con | identifier_name |
zsi_init.js | //initialize Settings.
zsi.init({
baseURL : base_url
,errorUpdateURL : base_url + "common/errors_update"
,sqlConsoleName : "runsql"
,excludeAjaxWatch : ["checkDataExist","employe_search_json"]
});
//check cookie and load user menus.
var userInfo = readCookie("userinfo");
if(u... |
function displayMenu(data){
var nav = $("#navbar-main");
var m = '<ul class="nav navbar-nav">';
$.each(data,function(){
var mlength= this.subMenus.length;
m += '<li class="dropdown">';
m += '<a data-toggle="dropdown" class="dropdown-toggle" href="#">' + this.na... | {
$.getJSON(base_url + "users/getuserinfo",function(data){
createCookie("userinfo", "*",1);
localStorage.setItem("userinfo", JSON.stringify(data));
userInfo = data;
});
} | identifier_body |
zsi_init.js | //initialize Settings.
zsi.init({
baseURL : base_url
,errorUpdateURL : base_url + "common/errors_update"
,sqlConsoleName : "runsql"
,excludeAjaxWatch : ["checkDataExist","employe_search_json"]
});
//check cookie and load user menus.
var userInfo = readCookie("userinfo");
if(u... | (){
if(typeof(Storage) !== "undefined") return true; else return false;
}
function loadMenu(){
$.getJSON(base_url + "menu_types/getdata_json",function(data){
if(isLocalStorageSupport()) {
localStorage.setItem("menuInfo", JSON.stringify(data));
}
displayMenu(data... | isLocalStorageSupport | identifier_name |
zsi_init.js | //initialize Settings.
zsi.init({
baseURL : base_url
,errorUpdateURL : base_url + "common/errors_update"
,sqlConsoleName : "runsql"
,excludeAjaxWatch : ["checkDataExist","employe_search_json"]
});
//check cookie and load user menus.
var userInfo = readCookie("userinfo");
| if(menuInfo){
displayMenu( JSON.parse(menuInfo));
}
}else{
loadMenu();
loadUserInfo();
}
}else{
loadMenu();
loadUserInfo();
}
function isLocalStorageSupport(){
if(typeof(Storage) !== "undefined") return true; else return false;
}
functi... | if(userInfo){
if(isLocalStorageSupport()) {
userInfo = JSON.parse(localStorage.getItem("userinfo"));
var menuInfo = localStorage.getItem("menuInfo");
| random_line_split |
zsi_init.js | //initialize Settings.
zsi.init({
baseURL : base_url
,errorUpdateURL : base_url + "common/errors_update"
,sqlConsoleName : "runsql"
,excludeAjaxWatch : ["checkDataExist","employe_search_json"]
});
//check cookie and load user menus.
var userInfo = readCookie("userinfo");
if(u... | else{
loadMenu();
loadUserInfo();
}
function isLocalStorageSupport(){
if(typeof(Storage) !== "undefined") return true; else return false;
}
function loadMenu(){
$.getJSON(base_url + "menu_types/getdata_json",function(data){
if(isLocalStorageSupport()) {
localStorage... | {
if(isLocalStorageSupport()) {
userInfo = JSON.parse(localStorage.getItem("userinfo"));
var menuInfo = localStorage.getItem("menuInfo");
if(menuInfo){
displayMenu( JSON.parse(menuInfo));
}
}else{
loadMenu();
loadUserInfo();
}
} | conditional_block |
collect_2.py | import threading
import urllib2
import time, json
import requests
import os.path
#"284330,150810,09,1109,52,071040,17,28432,7406"
countrylist = ["brazil","canada","china","france","japan","india","mexico","russia","uk","us"]
yrs = ["2011","2012","2013","2014","2015"]
dataTable ={"284330":"gold","150810":"crude","09":... | if data_json[j]['yr'] == 2011:
a = (countrylist[k],"2011")
elif data_json[j]['yr'] == 2012:
a = (countrylist[k],"2012")
elif data_json[j]['yr'] == 2013:
a = (countrylist[k],"2013")
elif data_json[j]['yr'] == 2014:
... | with open(file_list[k],"r") as json_data:
data_json = json.load(json_data)
for j in range(0,len(data_json)): | random_line_split |
collect_2.py |
import threading
import urllib2
import time, json
import requests
import os.path
#"284330,150810,09,1109,52,071040,17,28432,7406"
countrylist = ["brazil","canada","china","france","japan","india","mexico","russia","uk","us"]
yrs = ["2011","2012","2013","2014","2015"]
dataTable ={"284330":"gold","150810":"crude","09... |
#
threads = [threading.Thread(target=fetch_url, args=(urls[i],i,)) for i in range(0,len(urls)) ]
for thread in threads:
thread.start()
time.sleep(12)
for thread in threads:
thread.join()
#final data identifier
res_data = {}
for k in range(0,len(countrylist)):
with open(file_list[k],"r") as jso... | file_name = "file_"+countrylist[i]+".json"
file_list.append(file_name)
response = requests.get(url, verify=False)
data = response.json()
if not os.path.isfile("./"+file_name):
with open(file_name, 'w') as outfile:
json.dump(data["dataset"], outfile)
print "'%s\' fetched in %s... | identifier_body |
collect_2.py |
import threading
import urllib2
import time, json
import requests
import os.path
#"284330,150810,09,1109,52,071040,17,28432,7406"
countrylist = ["brazil","canada","china","france","japan","india","mexico","russia","uk","us"]
yrs = ["2011","2012","2013","2014","2015"]
dataTable ={"284330":"gold","150810":"crude","09... | (url, i):
file_name = "file_"+countrylist[i]+".json"
file_list.append(file_name)
response = requests.get(url, verify=False)
data = response.json()
if not os.path.isfile("./"+file_name):
with open(file_name, 'w') as outfile:
json.dump(data["dataset"], outfile)
print "'%s\'... | fetch_url | identifier_name |
collect_2.py |
import threading
import urllib2
import time, json
import requests
import os.path
#"284330,150810,09,1109,52,071040,17,28432,7406"
countrylist = ["brazil","canada","china","france","japan","india","mexico","russia","uk","us"]
yrs = ["2011","2012","2013","2014","2015"]
dataTable ={"284330":"gold","150810":"crude","09... |
elif data_json[j]['yr'] == 2012:
a = (countrylist[k],"2012")
elif data_json[j]['yr'] == 2013:
a = (countrylist[k],"2013")
elif data_json[j]['yr'] == 2014:
a = (countrylist[k],"2014")
elif data_json[j]['yr'] == 2015:
... | a = (countrylist[k],"2011") | conditional_block |
psd.py | #!/usr/bin/env python3
import math, logging, threading, concurrent.futures
import numpy
import simplespectral
from soapypower import threadpool
logger = logging.getLogger(__name__)
class PSD:
"""Compute averaged power spectral density using Welch's method"""
def __init__(self, bins, sample_rate, fft_windo... |
def update(self, psd_state, samples_array):
"""Compute PSD from samples and update average for given center frequency"""
freq_array, pwr_array = simplespectral.welch(samples_array, self._sample_rate, nperseg=self._bins,
window=self._fft_window, ... | """Remove result from future to release memory"""
future._result = None | identifier_body |
psd.py | #!/usr/bin/env python3
import math, logging, threading, concurrent.futures
import numpy
import simplespectral
from soapypower import threadpool
logger = logging.getLogger(__name__)
class PSD:
"""Compute averaged power spectral density using Welch's method"""
def __init__(self, bins, sample_rate, fft_windo... | (self, psd_state):
"""Wait for all PSD threads to finish and return result"""
if len(psd_state['futures']) > 1:
concurrent.futures.wait(psd_state['futures'])
elif psd_state['futures']:
psd_state['futures'][0].result()
return self.result(psd_state)
def result_... | wait_for_result | identifier_name |
psd.py | #!/usr/bin/env python3
import math, logging, threading, concurrent.futures
import numpy
import simplespectral
from soapypower import threadpool
logger = logging.getLogger(__name__)
class PSD:
"""Compute averaged power spectral density using Welch's method"""
def __init__(self, bins, sample_rate, fft_windo... |
if psd_state['repeats'] > 1:
pwr_array = pwr_array / psd_state['repeats']
if self._log_scale:
pwr_array = 10 * numpy.log10(pwr_array)
return (freq_array, pwr_array)
def wait_for_result(self, psd_state):
"""Wait for all PSD threads to finish and return res... | crop_bins_half = round((self._crop_factor * self._bins) / 2)
freq_array = freq_array[crop_bins_half:-crop_bins_half]
pwr_array = pwr_array[crop_bins_half:-crop_bins_half] | conditional_block |
psd.py | #!/usr/bin/env python3
import math, logging, threading, concurrent.futures
import numpy
import simplespectral
from soapypower import threadpool
logger = logging.getLogger(__name__)
class PSD:
"""Compute averaged power spectral density using Welch's method"""
def __init__(self, bins, sample_rate, fft_windo... | self._sample_rate = sample_rate
self._fft_window = fft_window
self._fft_overlap = fft_overlap
self._fft_overlap_bins = math.floor(self._bins * self._fft_overlap)
self._crop_factor = crop_factor
self._log_scale = log_scale
self._remove_dc = remove_dc
self._... | crop_factor=0, log_scale=True, remove_dc=False, detrend=None,
lnb_lo=0, max_threads=0, max_queue_size=0):
self._bins = bins | random_line_split |
dom.js | /**
* Created by Administrator on 2015/12/26.
* 一些变量
$.fn.extend({
// 通过一定的条件,删选自身 | find 查找子节点, 调用的是jQuery.find == Sizzle, jQuery.unique == Sizzle.unique ;
has 指子元素有没有,返回自身的。。
not filter 指自身有没有,返回自身的。。
is 返回true or false
closest 找满足条件的最近父节点(包括自身)
index 返回元素在兄弟节点中的索引值
add
addBack
});
function sibling(){}
jQuery.each({
parent // parentNode
parents // parentNode 循环
parentsUntil ... | random_line_split | |
DataProviderService.ts | import {Injectable} from 'angular2/core';
import {GEDCOMX_SCHEMA} from './GedcomXDummy';
import {GEDCOMX_DATA} from './demoData/GedcomX.data';
import {GEDCOMX_DATA2} from './demoData/GedcomX.data2';
import {GEDCOMX_DATA3} from './demoData/GedcomX.data3';
import {GEDCOMX_DATA4} from './demoData/GedcomX.data4';
declare v... | (){
return Promise.resolve(this.data.agents);
}
getAgent(id:string){
return Promise.resolve(this.data.agents).then(agents => agents.filter(a => a.id === id)[0]);
}
createAgent(){
let newAgent=this.createNewObject("agent");
this.setArrayValue("agents",newAgent);
return newAgent.id;
}
getE... | getAgents | identifier_name |
DataProviderService.ts | import {Injectable} from 'angular2/core';
import {GEDCOMX_SCHEMA} from './GedcomXDummy';
import {GEDCOMX_DATA} from './demoData/GedcomX.data';
import {GEDCOMX_DATA2} from './demoData/GedcomX.data2';
import {GEDCOMX_DATA3} from './demoData/GedcomX.data3';
import {GEDCOMX_DATA4} from './demoData/GedcomX.data4';
declare v... |
getSchema(){
return new Promise(
(resolve, reject)=> {
if(this._resolved)
resolve(this._dataSchema);
else
this._callbacks.push(()=>{resolve(this._dataSchema)});
});
}
getRefs(){
return new Promise(
(resolve, r... | {
JsonRefs.resolveRefs(this._dataSchema)
.then(res =>{
// Do something with the response
// res.refs: JSON Reference locations and details
// res.resolved: The document with the appropriate JSON References resolved
this._dataSchema=res.resolved;
th... | identifier_body |
DataProviderService.ts | import {Injectable} from 'angular2/core';
import {GEDCOMX_SCHEMA} from './GedcomXDummy';
import {GEDCOMX_DATA} from './demoData/GedcomX.data';
import {GEDCOMX_DATA2} from './demoData/GedcomX.data2';
import {GEDCOMX_DATA3} from './demoData/GedcomX.data3';
import {GEDCOMX_DATA4} from './demoData/GedcomX.data4';
declare v... | this._refs=res.refs;
this._resolved=true;
this._callbacks.forEach(callback=>{callback.call});
}, err => {console.log(err.stack);}
);
}
getSchema(){
return new Promise(
(resolve, reject)=> {
if(this._resolved)
resolve(this.... | .then(res =>{
// Do something with the response
// res.refs: JSON Reference locations and details
// res.resolved: The document with the appropriate JSON References resolved
this._dataSchema=res.resolved; | random_line_split |
main.rs |
use std::thread;
use std::thread::JoinHandle;
mod factorial;
use factorial::util::t_log;
use factorial::find_factors;
fn get_chunk(index: u64, chunk_size: u64, max: u64) -> Option<(u64, u64)> {
let mut result = None;
let low = chunk_size * (index - 1);
let high = chunk_size * index;
if high <= max {... |
}
t_log("waiting in main...");
for handle in handles.into_iter() {
handle.join().unwrap();
}
t_log("Ready.");
}
#[allow(unused_imports)]
mod tests {
use super::*;
#[test]
fn test_get_chunk_low_boundary() {
let index: u64 = 1;
let chunk: u64 = 10;
let ... | {
done = true;
} | conditional_block |
main.rs |
use std::thread;
use std::thread::JoinHandle;
mod factorial;
use factorial::util::t_log;
use factorial::find_factors;
fn get_chunk(index: u64, chunk_size: u64, max: u64) -> Option<(u64, u64)> {
let mut result = None;
let low = chunk_size * (index - 1);
let high = chunk_size * index;
if high <= max {... | () {
let index: u64 = 1;
let chunk: u64 = 10;
let max: u64 = 25;
// test
let (low, high) = get_chunk(index, chunk, max).unwrap();
assert_eq!(low, 0);
assert_eq!(high, 10);
}
#[test]
fn test_get_chunk_basic() {
let index: u64 = 2;
let... | test_get_chunk_low_boundary | identifier_name |
main.rs | use std::thread;
use std::thread::JoinHandle;
mod factorial;
use factorial::util::t_log;
use factorial::find_factors;
fn get_chunk(index: u64, chunk_size: u64, max: u64) -> Option<(u64, u64)> {
let mut result = None;
let low = chunk_size * (index - 1);
let high = chunk_size * index;
if high <= max {
... |
assert_eq!(result.is_none(), true);
}
} | let result = get_chunk(index, chunk, max); | random_line_split |
main.rs |
use std::thread;
use std::thread::JoinHandle;
mod factorial;
use factorial::util::t_log;
use factorial::find_factors;
fn get_chunk(index: u64, chunk_size: u64, max: u64) -> Option<(u64, u64)> {
let mut result = None;
let low = chunk_size * (index - 1);
let high = chunk_size * index;
if high <= max {... |
}
| {
let index: u64 = 4;
let chunk: u64 = 10;
let max: u64 = 25;
// test
let result = get_chunk(index, chunk, max);
assert_eq!(result.is_none(), true);
} | identifier_body |
mod.rs | pub use self::os::{FNM_NOMATCH};
pub use self::os::{FNM_PATHNAME};
pub use self::os::{FNM_PERIOD};
pub use self::os::{FNM_NOESCAPE};
use {NTStr, int_t, char_t};
#[cfg(target_os = "linux")]
#[path = "linux/mod.rs"]
mod os;
pub fn fnmatch<T: NTStr, U: NTStr>(pattern: &T, string: &U, flags: int_t) -> int_t {
extern... |
}
| {
let pat = "abc*123".to_nt_str();
let stn = "abcTE/ST123".to_nt_str();
let pat2 = "*123".to_nt_str();
let stn2 = ".123".to_nt_str();
assert_eq!(super::fnmatch(&pat, &stn, 0), 0);
assert_eq!(super::fnmatch(&pat, &stn, super::FNM_PATHNAME), super::FNM... | identifier_body |
mod.rs | pub use self::os::{FNM_NOMATCH};
pub use self::os::{FNM_PATHNAME};
pub use self::os::{FNM_PERIOD};
pub use self::os::{FNM_NOESCAPE};
use {NTStr, int_t, char_t};
#[cfg(target_os = "linux")]
#[path = "linux/mod.rs"]
mod os;
pub fn fnmatch<T: NTStr, U: NTStr>(pattern: &T, string: &U, flags: int_t) -> int_t {
extern... | unsafe { fnmatch(pattern.as_ptr(), string.as_ptr(), flags) }
}
#[cfg(test)]
mod tests {
use {ToNTStr};
#[test]
fn test() {
let pat = "abc*123".to_nt_str();
let stn = "abcTE/ST123".to_nt_str();
let pat2 = "*123".to_nt_str();
let stn2 = ".123".to_nt_str();
assert_... | random_line_split | |
mod.rs | pub use self::os::{FNM_NOMATCH};
pub use self::os::{FNM_PATHNAME};
pub use self::os::{FNM_PERIOD};
pub use self::os::{FNM_NOESCAPE};
use {NTStr, int_t, char_t};
#[cfg(target_os = "linux")]
#[path = "linux/mod.rs"]
mod os;
pub fn | <T: NTStr, U: NTStr>(pattern: &T, string: &U, flags: int_t) -> int_t {
extern {
fn fnmatch(pattern: *const char_t, name: *const char_t, flags: int_t) -> int_t;
}
unsafe { fnmatch(pattern.as_ptr(), string.as_ptr(), flags) }
}
#[cfg(test)]
mod tests {
use {ToNTStr};
#[test]
fn test() {
... | fnmatch | identifier_name |
guide-items.ts | import { Injectable } from '@angular/core';
export interface GuideItem {
id: string;
name: string;
document: string;
url: string;
}
const GUIDES: GuideItem[] = [
{
id: 'getting-started',
document: 'assets/docs/guides/getting-started.html',
url: 'doc/guides/getting-started',
name: 'Getting St... | {
getAllItems(): GuideItem[] {
return this.getGuideItems();
}
getGuideItems(): GuideItem[] {
return GUIDES;
}
getGuideItemById(id: string): GuideItem {
return GUIDES.find(i => i.id === id);
}
}
| GuideItemsService | identifier_name |
guide-items.ts | import { Injectable } from '@angular/core';
export interface GuideItem {
id: string;
name: string;
document: string;
url: string;
}
const GUIDES: GuideItem[] = [
{
id: 'getting-started',
document: 'assets/docs/guides/getting-started.html',
url: 'doc/guides/getting-started',
name: 'Getting St... | }
getGuideItemById(id: string): GuideItem {
return GUIDES.find(i => i.id === id);
}
} | return GUIDES; | random_line_split |
__openerp__.py | # -*- encoding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2010 Savoir-faire Linux (<http://www.savoirfairelinux.com>).
#
# This program is free software: you can redistribute it and/or modify
# it und... | "name": "Hazard Risk",
"version": "8.0.1.1.0",
"author": "Savoir-faire Linux, Odoo Community Association (OCA)",
"website": "http://www.savoirfairelinux.com",
"license": "AGPL-3",
"category": "Management System",
"depends": [
'mgmtsystem_hazard',
'hr'
],
"data": [
... | #
##############################################################################
{ | random_line_split |
defaults.py | #!/usr/bin/env python
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:fdm=marker:ai
from __future__ import (unicode_literals, division, absolute_import,
print_function)
__license__ = 'GPL v3'
__copyright__ = '2012, Kovid Goyal <kovid at kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
... | (object):
def __init__(self):
self.rules = (
# Amazon devices
({'vendor':0x1949}, {
'format_map': ['azw3', 'mobi', 'azw',
'azw1', 'azw4', 'pdf'],
'send_to': ['documents', 'books', 'kindle'],
... | DeviceDefaults | identifier_name |
defaults.py | #!/usr/bin/env python
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:fdm=marker:ai
from __future__ import (unicode_literals, division, absolute_import,
print_function)
__license__ = 'GPL v3'
__copyright__ = '2012, Kovid Goyal <kovid at kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
... |
for rule in self.rules:
tests = rule[0]
matches = True
for k, v in tests.iteritems():
if k == 'vendor' and v != vid:
matches = False
break
if k == 'product' and v != pid:
matches = Fa... | vid, pid = int(m.group(1), 16), int(m.group(2), 16)
except:
traceback.print_exc()
else:
vid, pid = device.vendor_id, device.product_id | random_line_split |
defaults.py | #!/usr/bin/env python
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:fdm=marker:ai
from __future__ import (unicode_literals, division, absolute_import,
print_function)
__license__ = 'GPL v3'
__copyright__ = '2012, Kovid Goyal <kovid at kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
... |
return {}
| tests = rule[0]
matches = True
for k, v in tests.iteritems():
if k == 'vendor' and v != vid:
matches = False
break
if k == 'product' and v != pid:
matches = False
break
if ... | conditional_block |
defaults.py | #!/usr/bin/env python
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:fdm=marker:ai
from __future__ import (unicode_literals, division, absolute_import,
print_function)
__license__ = 'GPL v3'
__copyright__ = '2012, Kovid Goyal <kovid at kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
... |
def __call__(self, device, driver):
if iswindows:
vid = pid = 0xffff
m = re.search(r'(?i)vid_([0-9a-fA-F]+)&pid_([0-9a-fA-F]+)', device)
if m is not None:
try:
vid, pid = int(m.group(1), 16), int(m.group(2), 16)
except... | self.rules = (
# Amazon devices
({'vendor':0x1949}, {
'format_map': ['azw3', 'mobi', 'azw',
'azw1', 'azw4', 'pdf'],
'send_to': ['documents', 'books', 'kindle'],
}
),
) | identifier_body |
elf.py | #!/usr/bin/env python
# -*- coding: utf-8 -*- | from elftools.elf.segments import NoteSegment
class ReadELF(object):
def __init__(self, file):
self.elffile = ELFFile(file)
def get_build(self):
for segment in self.elffile.iter_segments():
if isinstance(segment, NoteSegment):
for note in segment.iter_notes():
... |
import sys
from elftools.elf.elffile import ELFFile
from elftools.common.exceptions import ELFError | random_line_split |
elf.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
from elftools.elf.elffile import ELFFile
from elftools.common.exceptions import ELFError
from elftools.elf.segments import NoteSegment
class ReadELF(object):
def __init__(self, file):
|
def get_build(self):
for segment in self.elffile.iter_segments():
if isinstance(segment, NoteSegment):
for note in segment.iter_notes():
print note
def main():
if(len(sys.argv) < 2):
print "Missing argument"
sys.exit(1)
with open(sy... | self.elffile = ELFFile(file) | identifier_body |
elf.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
from elftools.elf.elffile import ELFFile
from elftools.common.exceptions import ELFError
from elftools.elf.segments import NoteSegment
class ReadELF(object):
def __init__(self, file):
self.elffile = ELFFile(file)
def | (self):
for segment in self.elffile.iter_segments():
if isinstance(segment, NoteSegment):
for note in segment.iter_notes():
print note
def main():
if(len(sys.argv) < 2):
print "Missing argument"
sys.exit(1)
with open(sys.argv[1], 'rb') as... | get_build | identifier_name |
elf.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
from elftools.elf.elffile import ELFFile
from elftools.common.exceptions import ELFError
from elftools.elf.segments import NoteSegment
class ReadELF(object):
def __init__(self, file):
self.elffile = ELFFile(file)
def get_build(self):
f... |
def main():
if(len(sys.argv) < 2):
print "Missing argument"
sys.exit(1)
with open(sys.argv[1], 'rb') as file:
try:
readelf = ReadELF(file)
readelf.get_build()
except ELFError as err:
sys.stderr.write('ELF error: %s\n' % err)
sys... | print note | conditional_block |
main.py | print system output. This is the default for '
'non-system commands and setup.',
)
common_parser.add_argument(
'-v', '--verbose', dest='verbose', default=False, action='store_true',
help=u'Print system output. This is the default for system '
u'commands, except setup.'... | = u' '.join(args.criteria)
session = get_session(args)
lookup = get_lookup(args, session=session, recreate=False)
results = lookup.lookup(name)
if not results:
print("No matches.")
elif results[0].exact:
print("Matched:")
else:
print("Fuzzy-matched:")
for result i... | identifier_body | |
main.py | Build and return an ArgumentParser.
"""
# Slightly clumsy workaround to make both `setup -v` and `-v setup` work
common_parser = argparse.ArgumentParser(add_help=False)
common_parser.add_argument(
'-e', '--engine', dest='engine_uri', default=None,
help=u'By default, all commands try to u... | cmd_help.set_defaults(func=command_help)
cmd_lookup = cmds.add_parser(
'lookup', help=u'Look up something in the Pokédex',
parents=[common_parser])
cmd_lookup.set_defaults(func=command_lookup)
cmd_lookup.add_argument('criteria', nargs='+')
cmd_search = cmds.add_parser(
'sea... | 'help', help=u'Display this message',
parents=[common_parser]) | random_line_split |
main.py | and return an ArgumentParser.
"""
# Slightly clumsy workaround to make both `setup -v` and `-v setup` work
common_parser = argparse.ArgumentParser(add_help=False)
common_parser.add_argument(
'-e', '--engine', dest='engine_uri', default=None,
help=u'By default, all commands try to use a ... | ser, args):
args.directory = None
# Database, and a lame check for whether it's been inited at least once
session = get_session(args)
print(" - OK! Connected successfully.")
if pokedex.db.tables.Pokemon.__table__.exists(session.bind):
print(" - OK! Database seems to contain some data."... | and_status(par | identifier_name |
main.py | and return an ArgumentParser.
"""
# Slightly clumsy workaround to make both `setup -v` and `-v setup` work
common_parser = argparse.ArgumentParser(add_help=False)
common_parser.add_argument(
'-e', '--engine', dest='engine_uri', default=None,
help=u'By default, all commands try to use a ... | if args.langs == 'none':
langs = []
elif args.langs is None:
langs = None
else:
langs = [l.strip() for l in args.langs.split(',')]
session = get_session(args)
get_csv_directory(args)
pokedex.db.load.load(
session,
directory=args.directory,
drop_tab... | t("WARNING: You're reloading the default database, but not the lookup index. They")
print(" might get out of sync, and pokedex commands may not work correctly!")
print("To fix this, run `pokedex reindex` when this command finishes. Or, just use")
print("`pokedex setup` to do both at on... | conditional_block |
flatxml2po.py | # -*- coding: utf-8 -*-
#
# Copyright 2018 BhaaL
#
# This file is part of translate.
#
# translate is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any lat... | """Convert a source format unit to a target format unit."""
target_unit = self.TargetUnitClass.buildfromunit(unit)
return target_unit
def convert_store(self):
"""Convert a single source file to a target format file."""
for source_unit in self.source_store.units:
... | """Convert a single XML file to a single PO file."""
SourceStoreClass = flatxml.FlatXMLFile
TargetStoreClass = po.pofile
TargetUnitClass = po.pounit
def __init__(self, inputfile, outputfile, templatefile=None,
root="root", value="str", key="key", ns=None):
"""Initialize the co... | identifier_body |
flatxml2po.py | # -*- coding: utf-8 -*-
#
# Copyright 2018 BhaaL
#
# This file is part of translate.
#
# translate is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any lat... | :
"""Convert a single XML file to a single PO file."""
SourceStoreClass = flatxml.FlatXMLFile
TargetStoreClass = po.pofile
TargetUnitClass = po.pounit
def __init__(self, inputfile, outputfile, templatefile=None,
root="root", value="str", key="key", ns=None):
"""Initialize ... | flatxml2po | identifier_name |
flatxml2po.py | # -*- coding: utf-8 -*-
#
# Copyright 2018 BhaaL
#
# This file is part of translate.
#
# translate is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any lat... | default="key",
help='name of the XML key attribute (default: "key")')
parser.add_option("-n", "--namespace", action="store", dest="ns",
default=None,
help="XML namespace uri (default: None)")
parser.passthrough.append("root... | help='name of the XML root element (default: "root")')
parser.add_option("-v", "--value", action="store", dest="value",
default="str",
help='name of the XML value element (default: "str")')
parser.add_option("-k", "--key", action="store", dest="k... | random_line_split |
flatxml2po.py | # -*- coding: utf-8 -*-
#
# Copyright 2018 BhaaL
#
# This file is part of translate.
#
# translate is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any lat... |
def run(self):
"""Run the converter."""
self.convert_store()
if self.target_store.isempty():
return 0
self.target_store.serialize(self.outputfile)
return 1
def run_converter(inputfile, outputfile, templatefile=None,
root="root", value="str"... | self.target_store.addunit(self.convert_unit(source_unit)) | conditional_block |
InfiniteScrollNewsArticle.tsx | import { data as sd } from "sharify"
import { getENV } from "v2/Utils/getENV"
import moment from "moment"
import styled from "styled-components"
import React, { Component, Fragment } from "react"
import { flatten, throttle } from "lodash"
import Waypoint from "react-waypoint"
import { positronql } from "desktop/lib/pos... | (props) {
super(props)
const article = props.articles[0] || {}
const date = this.getDateField(article)
const omit = props.article ? props.article.id : null
const offset = props.article ? 0 : 6
this.throttledDateChange = throttle(this.onDateChange, 50)
this.state = {
activeArticle: "... | constructor | identifier_name |
InfiniteScrollNewsArticle.tsx | import { data as sd } from "sharify"
import { getENV } from "v2/Utils/getENV"
import moment from "moment"
import styled from "styled-components"
import React, { Component, Fragment } from "react"
import { flatten, throttle } from "lodash"
import Waypoint from "react-waypoint"
import { positronql } from "desktop/lib/pos... | const currentDate = this.getDateField(article).substring(0, 10)
return beforeDate !== currentDate
}
getDateField = article => {
const { published_at, scheduled_publish_at } = article
return published_at || scheduled_publish_at || moment().toISOString()
}
renderContent = () => {
const { ac... | random_line_split | |
InfiniteScrollNewsArticle.tsx | import { data as sd } from "sharify"
import { getENV } from "v2/Utils/getENV"
import moment from "moment"
import styled from "styled-components"
import React, { Component, Fragment } from "react"
import { flatten, throttle } from "lodash"
import Waypoint from "react-waypoint"
import { positronql } from "desktop/lib/pos... |
dismissAuthModal() {
Cookies.set("editorial-signup-dismissed", 1, { expires: 864000 })
}
fetchNextArticles = async () => {
const { articles, offset, omit, relatedArticles } = this.state
this.setState({
isLoading: true,
})
try {
const data = await positronql({
query: ne... | {
const editorialAuthDismissedCookie = Cookies.get(
"editorial-signup-dismissed"
)
if (
!sd.CURRENT_USER &&
!editorialAuthDismissedCookie &&
!this.props.isMobile
) {
this.showAuthModal()
}
} | identifier_body |
InfiniteScrollNewsArticle.tsx | import { data as sd } from "sharify"
import { getENV } from "v2/Utils/getENV"
import moment from "moment"
import styled from "styled-components"
import React, { Component, Fragment } from "react"
import { flatten, throttle } from "lodash"
import Waypoint from "react-waypoint"
import { positronql } from "desktop/lib/pos... |
}
onActiveArticleChange = id => {
this.setState({ activeArticle: id })
}
hasNewDate = (article, i) => {
const { articles } = this.state
const beforeArticle = articles[i - 1] || {}
const beforeDate = this.getDateField(beforeArticle).substring(0, 10)
const currentDate = this.getDateField(ar... | {
// Commenting this out as we're noticing that when a user is scrolling
// and the top date is updated, it leads to a reset of the current scroll
// position, preventing the user from scrolling down the page.
// FIXME: Reenable once newsfeed scrolling bug tracked down.
this.setState({ dat... | conditional_block |
calls.rs | use crate::types::{Error, Params, Value};
use crate::BoxFuture;
use std::fmt;
use std::future::Future;
use std::sync::Arc;
/// Metadata trait
pub trait Metadata: Clone + Send + 'static {}
impl Metadata for () {}
impl<T: Metadata> Metadata for Option<T> {}
impl<T: Metadata> Metadata for Box<T> {}
impl<T: Sync + Send + ... | (self) -> BoxFuture<Result<T, E>> {
self
}
}
/// A synchronous or asynchronous method.
pub trait RpcMethodSync: Send + Sync + 'static {
/// Call method
fn call(&self, params: Params) -> BoxFuture<crate::Result<Value>>;
}
/// Asynchronous Method
pub trait RpcMethodSimple: Send + Sync + 'static {
/// Output futur... | into_future | identifier_name |
calls.rs | use crate::types::{Error, Params, Value};
use crate::BoxFuture;
use std::fmt;
use std::future::Future;
use std::sync::Arc;
/// Metadata trait
pub trait Metadata: Clone + Send + 'static {}
impl Metadata for () {} | /// A future-conversion trait.
pub trait WrapFuture<T, E> {
/// Convert itself into a boxed future.
fn into_future(self) -> BoxFuture<Result<T, E>>;
}
impl<T: Send + 'static, E: Send + 'static> WrapFuture<T, E> for Result<T, E> {
fn into_future(self) -> BoxFuture<Result<T, E>> {
Box::pin(async { self })
}
}
imp... | impl<T: Metadata> Metadata for Option<T> {}
impl<T: Metadata> Metadata for Box<T> {}
impl<T: Sync + Send + 'static> Metadata for Arc<T> {}
| random_line_split |
calls.rs | use crate::types::{Error, Params, Value};
use crate::BoxFuture;
use std::fmt;
use std::future::Future;
use std::sync::Arc;
/// Metadata trait
pub trait Metadata: Clone + Send + 'static {}
impl Metadata for () {}
impl<T: Metadata> Metadata for Option<T> {}
impl<T: Metadata> Metadata for Box<T> {}
impl<T: Sync + Send + ... |
}
impl<F: Send + Sync + 'static, T> RpcNotification<T> for F
where
T: Metadata,
F: Fn(Params, T),
{
fn execute(&self, params: Params, meta: T) {
self(params, meta)
}
}
| {
Box::pin(self(params, meta))
} | identifier_body |
mutex.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 ... | }
#[inline]
#[cfg(target_os = "dragonfly")]
pub unsafe fn destroy(&self) {
use libc;
let r = ffi::pthread_mutex_destroy(self.inner.get());
// On DragonFly pthread_mutex_destroy() returns EINVAL if called on a
// mutex that was just initialized with ffi::PTHREAD_MUTEX_INIT... | pub unsafe fn destroy(&self) {
let r = ffi::pthread_mutex_destroy(self.inner.get());
debug_assert_eq!(r, 0); | random_line_split |
mutex.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 ... | (&self) {
}
}
#[cfg(not(feature = "thread"))]
pub const MUTEX_INIT: Mutex = Mutex;
| destroy | identifier_name |
event-recipe.js | /**
* Created by ko on 2016-07-15.
*/
$(document).ready(function () {
var pageNo= 1;
// webtoon
$("#recipe").on("click", function () {
$("#travel_content").html("");
$("#youtube_content").html("");
$("#honbap_content").html("");
$("#game_content").html(""); | $("#resultArea").html("");
$("#prodInfo_content").css("display", "none");
pageNo=1;
$("#cvs_content").css("display", "none");
common_module.moveYoutubeMenu();
recipe_module.recipeTitle();
recipe_module.showRecipe(1);
$(window).unbind('scroll');
$... | $("#parcelArea").css("display","none"); | random_line_split |
event-recipe.js | /**
* Created by ko on 2016-07-15.
*/
$(document).ready(function () {
var pageNo= 1;
// webtoon
$("#recipe").on("click", function () {
$("#travel_content").html("");
$("#youtube_content").html("");
$("#honbap_content").html("");
$("#game_content").html("");
$("#pa... |
});
$("#webtoon_content").css("display", "none");
});
});
| {
pageNo +=1;
recipe_module.showRecipe(pageNo);
$(".loadingArea").html('<img src = "https://cdn.rawgit.com/kokk9239/singleLife_web/master/src/img/preloader.gif" style="width: 60px; height: 60px">');
} | conditional_block |
mod.rs | // Copyright 2021 TiKV Project Authors. Licensed under Apache-2.0.
mod engine;
mod engine_factory;
mod mvcc;
mod storage;
mod txn;
use std::fmt; | use self::engine::bench_engine;
use self::engine_factory::{BTreeEngineFactory, EngineFactory, RocksEngineFactory};
use self::mvcc::bench_mvcc;
use self::storage::bench_storage;
use self::txn::bench_txn;
use criterion::Criterion;
use tikv::storage::Engine;
const DEFAULT_ITERATIONS: usize = 10;
const DEFAULT_KEY_LENGTHS... | random_line_split | |
mod.rs | // Copyright 2021 TiKV Project Authors. Licensed under Apache-2.0.
mod engine;
mod engine_factory;
mod mvcc;
mod storage;
mod txn;
use std::fmt;
use self::engine::bench_engine;
use self::engine_factory::{BTreeEngineFactory, EngineFactory, RocksEngineFactory};
use self::mvcc::bench_mvcc;
use self::storage::bench_stor... | <F> {
pub key_length: usize,
pub value_length: usize,
pub engine_factory: F,
}
impl<F: fmt::Debug> fmt::Debug for BenchConfig<F> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"{:?}_KL{:?}_VL{:?}",
self.engine_factory, self.key_length... | BenchConfig | identifier_name |
mod.rs | // Copyright 2021 TiKV Project Authors. Licensed under Apache-2.0.
mod engine;
mod engine_factory;
mod mvcc;
mod storage;
mod txn;
use std::fmt;
use self::engine::bench_engine;
use self::engine_factory::{BTreeEngineFactory, EngineFactory, RocksEngineFactory};
use self::mvcc::bench_mvcc;
use self::storage::bench_stor... |
fn main() {
let mut c = Criterion::default().configure_from_args();
let btree_engine_configs = load_configs(BTreeEngineFactory {});
let rocks_engine_configs = load_configs(RocksEngineFactory {});
bench_engine(&mut c, &btree_engine_configs);
bench_engine(&mut c, &rocks_engine_configs);
bench_... | {
let key_lengths = DEFAULT_KEY_LENGTHS;
let value_lengths = DEFAULT_VALUE_LENGTHS;
let mut configs = vec![];
for &kl in &key_lengths {
for &vl in &value_lengths {
configs.push(BenchConfig {
key_length: kl,
value_length: vl,
engine_fac... | identifier_body |
CreateStrategy.tsx | import { useHistory } from 'react-router-dom';
import useUiConfig from '../../../hooks/api/getters/useUiConfig/useUiConfig';
import useToast from '../../../hooks/useToast';
import FormTemplate from '../../common/FormTemplate/FormTemplate';
import { useStrategyForm } from '../hooks/useStrategyForm';
import { StrategyFor... | --header 'Content-Type: application/json' \\
--data-raw '${JSON.stringify(getStrategyPayload(), undefined, 2)}'`;
};
const handleCancel = () => {
history.goBack();
};
return (
<FormTemplate
loading={loading}
title="Create strategy type"
description="... | const formatApiCode = () => {
return `curl --location --request POST '${
uiConfig.unleashUrl
}/api/admin/strategies' \\
--header 'Authorization: INSERT_API_KEY' \\ | random_line_split |
CreateStrategy.tsx | import { useHistory } from 'react-router-dom';
import useUiConfig from '../../../hooks/api/getters/useUiConfig/useUiConfig';
import useToast from '../../../hooks/useToast';
import FormTemplate from '../../common/FormTemplate/FormTemplate';
import { useStrategyForm } from '../hooks/useStrategyForm';
import { StrategyFor... |
};
const formatApiCode = () => {
return `curl --location --request POST '${
uiConfig.unleashUrl
}/api/admin/strategies' \\
--header 'Authorization: INSERT_API_KEY' \\
--header 'Content-Type: application/json' \\
--data-raw '${JSON.stringify(getStrategyPayload(), undefined, 2)}'`;
... | {
const payload = getStrategyPayload();
try {
await createStrategy(payload);
refetchStrategies();
history.push(`/strategies/${strategyName}`);
setToastData({
title: 'Strategy created',
text: '... | conditional_block |
admin.module.ts | import { NgModule } from "@angular/core";
import { AdminComponent } from "./admin.component";
import { FormBuilder, FormsModule, ReactiveFormsModule } from "@angular/forms";
import { TranslateService, TranslateModule } from "ng2-translate";
import { RouterModule } from "@angular/router";
import { AdminViewComponent } f... | CommonModule,
TranslateModule,
RouterModule,
FormsModule,
ReactiveFormsModule,
BreadcrumbModule,
ChartModule,
NavbarModule,
DashboardModule
],
declarations: [ADMIN_DECLARATION],
exports: [ADMIN_DECLARATION],
providers: [
Tra... | imports: [ | random_line_split |
admin.module.ts | import { NgModule } from "@angular/core";
import { AdminComponent } from "./admin.component";
import { FormBuilder, FormsModule, ReactiveFormsModule } from "@angular/forms";
import { TranslateService, TranslateModule } from "ng2-translate";
import { RouterModule } from "@angular/router";
import { AdminViewComponent } f... | {
} | AdminModule | identifier_name |
modals.js | Element.prototype.remove = function() {
this.parentElement.removeChild(this);
} | const addIcon = (icon) => `<i class="fa fa-${icon}"></i>`
const headerTxt = (type) => {
switch (type) {
case 'error':
return `${addIcon('ban')} Error`
case 'warning':
return `${addIcon('exclamation')} Warning`
case 'success':
return `${addIcon('check')} S... | random_line_split | |
__init__.py | # coding=utf-8
from __future__ import unicode_literals
from random import randint
from .. import Provider as AddressProvider
class Provider(AddressProvider):
address_formats = ['{{street_address}}, {{city}}, {{postcode}}']
building_number_formats = ['#', '##', '###']
city_formats = ['{{city_prefix}} {{f... | identifier_body | ||
__init__.py | # coding=utf-8
from __future__ import unicode_literals
from random import randint
from .. import Provider as AddressProvider
class Provider(AddressProvider):
address_formats = ['{{street_address}}, {{city}}, {{postcode}}']
building_number_formats = ['#', '##', '###']
city_formats = ['{{city_prefix}} {{f... | 'Самоа', 'Сан-Марино', 'Сан-Томе і Принсіпі', 'Саудівська Аравія',
'Свазіленд', 'Сейшельські Острови', 'Сенегал',
'Сент-Вінсент і Гренадини', 'Сент-Кіттс і Невіс', 'Сент-Люсія',
'Сербія', 'Сінгапур', 'Сирія', 'Словаччина', 'Словенія',
'Соломонові Острови', 'Сомалі', 'Судан', 'Сур... | 'Нідерланди', 'Нікарагуа', 'Німеччина', 'Нова Зеландія', 'Норвегія',
'ОАЕ', 'Оман', 'Пакистан', 'Палау', 'Палестинська держава', 'Панама',
'Папуа Нова Гвінея', 'ПАР', 'Парагвай', 'Перу', 'Південний Судан',
'Польща', 'Португалія', 'Росія', 'Руанда', 'Румунія', 'Сальвадор', | random_line_split |
__init__.py | # coding=utf-8
from __future__ import unicode_literals
from random import randint
from .. import Provider as AddressProvider
class Provider(AddressProvider):
address_formats = ['{{street_address}}, {{city}}, {{postcode}}']
building_number_formats = ['#', '##', '###']
city_formats = ['{{city_prefix}} {{f... | identifier_name | ||
array.rs | //! Helper Module to treat Vec and fixed sized arrays as generic in some contexts
use crate::linear_algebra::Vector;
/// This trait is used to make up for the lack of generics over array lengths
pub trait Array {
/// Element type of the array
type Element;
/// Corresponding Vector type with same dimension... | }
fn at_ref(&self, index: usize) -> &T {
&self[index]
}
fn at_mut(&mut self, index: usize) -> &mut T {
&mut self[index]
}
}
};
}
array_impl_for! { 1 }
array_impl_for! { 2 }
array_impl_for! { 3 }
array_impl_for! { ... |
fn length(&self) -> usize {
$v | random_line_split |
lib.rs | use wasm_bindgen::prelude::*;
#[rustfmt::skip]
#[wasm_bindgen]
pub fn | (
r: f64,
g: f64,
b: f64,
a: f64,
ref_x: f64,
ref_y: f64,
ref_z: f64,
) -> Vec<f64> {
let mut r = r / 255.0;
let mut g = g / 255.0;
let mut b = b / 255.0;
// Need lto = true in Cargo.toml to link pow
r = if r > 0.04045 { ((r + 0.055) / 1.055).powf(2.4) } else { r / 12.92... | rgba2laba | identifier_name |
lib.rs | use wasm_bindgen::prelude::*;
#[rustfmt::skip]
#[wasm_bindgen]
pub fn rgba2laba(
r: f64,
g: f64,
b: f64,
a: f64,
ref_x: f64,
ref_y: f64,
ref_z: f64,
) -> Vec<f64> | y /= ref_y;
z /= ref_z;
x = if x > 0.008856 { x.powf(1.0 / 3.0) } else { x * 7.787 + 16.0 / 116.0 };
y = if y > 0.008856 { y.powf(1.0 / 3.0) } else { y * 7.787 + 16.0 / 116.0 };
z = if z > 0.008856 { z.powf(1.0 / 3.0) } else { z * 7.787 + 16.0 / 116.0 };
let out_l = 116.0 * y - 16.0;
let o... | {
let mut r = r / 255.0;
let mut g = g / 255.0;
let mut b = b / 255.0;
// Need lto = true in Cargo.toml to link pow
r = if r > 0.04045 { ((r + 0.055) / 1.055).powf(2.4) } else { r / 12.92 };
g = if g > 0.04045 { ((g + 0.055) / 1.055).powf(2.4) } else { g / 12.92 };
b = if b > 0.04045 { ((b ... | identifier_body |
lib.rs | use wasm_bindgen::prelude::*;
#[rustfmt::skip]
#[wasm_bindgen]
pub fn rgba2laba(
r: f64,
g: f64,
b: f64,
a: f64,
ref_x: f64,
ref_y: f64,
ref_z: f64,
) -> Vec<f64> {
let mut r = r / 255.0;
let mut g = g / 255.0;
let mut b = b / 255.0;
// Need lto = true in Cargo.toml to link... | g2: f64,
b2: f64,
a2: f64,
ref_x: f64,
ref_y: f64,
ref_z: f64,
) -> f64 {
let left = rgba2laba(r1, g1, b1, a1, ref_x, ref_y, ref_z);
let right = rgba2laba(r2, g2, b2, a2, ref_x, ref_y, ref_z);
let dist = ((right[0] - left[0]).powf(2.0) + (right[1] - left[1]).powf(2.0) + (right[2] - l... | b1: f64,
a1: f64,
r2: f64, | random_line_split |
lib.rs | use wasm_bindgen::prelude::*;
#[rustfmt::skip]
#[wasm_bindgen]
pub fn rgba2laba(
r: f64,
g: f64,
b: f64,
a: f64,
ref_x: f64,
ref_y: f64,
ref_z: f64,
) -> Vec<f64> {
let mut r = r / 255.0;
let mut g = g / 255.0;
let mut b = b / 255.0;
// Need lto = true in Cargo.toml to link... | ;
b = if b > 0.04045 { ((b + 0.055) / 1.055).powf(2.4) } else { b / 12.92 };
r *= 100.0;
g *= 100.0;
b *= 100.0;
// Observer= 2° (Only use CIE 1931!)
let mut x = r * 0.4124 + g * 0.3576 + b * 0.1805;
let mut y = r * 0.2126 + g * 0.7152 + b * 0.0722;
let mut z = r * 0.0193 + g * 0.1192 ... | { g / 12.92 } | conditional_block |
settings.py | import os
from django.contrib.messages import constants
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECR... | ],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
# Insert your TEMPLATE_CONTEXT_PROCESSORS here or use this
# list if you haven't customized them:
'django.contrib.auth.context_processors.auth',
'django.template.... | 'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
# insert your TEMPLATE_DIRS here | random_line_split |
settings.py | # Django settings for example project.
import os
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
('Tester', 'test@example.com'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
'N... | 'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'provider',
'provider.oauth2',
) | ROOT_URLCONF = 'tests.urls'
INSTALLED_APPS = (
'django.contrib.auth', | random_line_split |
main.rs | extern crate clap;
extern crate pwhash;
extern crate termios;
extern crate users;
use clap::{App, Arg};
use std::error;
use std::fmt;
use std::fs::File;
use std::io::{self, BufRead, BufReader, Write};
use std::path::Path;
use termios::{tcsetattr, Termios};
#[derive(Debug)] |
impl From<io::Error> for Error {
fn from(err: io::Error) -> Error {
Error::Io(err)
}
}
impl From<pwhash::error::Error> for Error {
fn from(err: pwhash::error::Error) -> Error {
Error::PwHash(err)
}
}
impl From<String> for Error {
fn from(err: String) -> Error {
Error::Str(... | enum Error {
Io(io::Error),
PwHash(pwhash::error::Error),
Str(String),
} | random_line_split |
main.rs | extern crate clap;
extern crate pwhash;
extern crate termios;
extern crate users;
use clap::{App, Arg};
use std::error;
use std::fmt;
use std::fs::File;
use std::io::{self, BufRead, BufReader, Write};
use std::path::Path;
use termios::{tcsetattr, Termios};
#[derive(Debug)]
enum Error {
Io(io::Error),
PwHash(p... | (&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Error::Io(ref err) => write!(f, "IO error: {}", err),
Error::PwHash(ref err) => write!(f, "PwHash error: {}", err),
Error::Str(ref err) => f.write_str(err),
}
}
}
impl error::Error for Error {
fn ... | fmt | identifier_name |
compare-flags.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
""" | """
import sys
import subprocess
from typing import Set
from pathlib import Path
# A list of known-undocumented flags. This should be considered to be a to-do
# list of flags that need to be documented.
EXPECTED_UNDOCUMENTED_PATH = \
Path(__file__).parent / 'expected-undocumented-flags.txt'
EXPECTED_UNDOCUMENTED... | Linter to verify that all flags reported by GHC's --show-options mode
are documented in the user's guide. | random_line_split |
compare-flags.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Linter to verify that all flags reported by GHC's --show-options mode
are documented in the user's guide.
"""
import sys
import subprocess
from typing import Set
from pathlib import Path
# A list of known-undocumented flags. This should be considered to be a to-do
# ... | in()
| conditional_block | |
compare-flags.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Linter to verify that all flags reported by GHC's --show-options mode
are documented in the user's guide.
"""
import sys
import subprocess
from typing import Set
from pathlib import Path
# A list of known-undocumented flags. This should be considered to be a to-do
# ... | now_documented = EXPECTED_UNDOCUMENTED.intersection(doc_flags)
if len(now_documented) > 0:
print(f'Found flags that are documented yet listed in {EXPECTED_UNDOCUMENTED_PATH}:')
print('\n'.join(f' {flag}' for flag in sorted(now_documented)))
print()
failed = True
if failed:
... | port argparse
parser = argparse.ArgumentParser()
parser.add_argument('--ghc', type=argparse.FileType('r'),
help='path of GHC executable')
parser.add_argument('--doc-flags', type=argparse.FileType('r'),
help='path of ghc-flags.txt output from Sphinx')
args ... | identifier_body |
compare-flags.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Linter to verify that all flags reported by GHC's --show-options mode
are documented in the user's guide.
"""
import sys
import subprocess
from typing import Set
from pathlib import Path
# A list of known-undocumented flags. This should be considered to be a to-do
# ... | -> None:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--ghc', type=argparse.FileType('r'),
help='path of GHC executable')
parser.add_argument('--doc-flags', type=argparse.FileType('r'),
help='path of ghc-flags.txt output from Sp... | in() | identifier_name |
xhrio.js | link #onReadyStateChange_}. This is used so that
* entry point calls to {@link #onReadyStateChange_} can be routed through
* {@link #onReadyStateChangeEntryPoint_}.
* @private
*/
goog.net.XhrIo.prototype.onReadyStateChangeHelper_ = function() {
if (!this.active_) {
// can get called inside abort call
ret... | * @param {string=} opt_xssiPrefix Optional XSSI prefix string to use for
* stripping of the response before parsing. This needs to be set only if
* your backend server prepends the same prefix string to the JSON response.
* @return {Object|undefined} JavaScript object.
*/ | random_line_split | |
xhrio.js | string|goog.Uri} url Uri to make request to.
* @param {string=} opt_method Send method, default: GET.
* @param {string|GearsBlob=} opt_content Post data. This can be a Gears blob
* if the underlying HTTP request object is a Gears HTTP request.
* @param {Object|goog.structs.Map=} opt_headers Map of headers to ad... | {
// Were not being called from within a call to this.xhr_.send
// this.xhr_.abort, or this.xhr_.open, so this is an entry point
this.onReadyStateChangeEntryPoint_();
} | conditional_block | |
tap.py | # Copyright 2013 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.
import os
from telemetry.page.actions import page_action
class TapAction(page_action.PageAction):
def __init__(self, selector=None, text=None, element_f... |
gesture_source_type = page_action.GetGestureSourceTypeFromOptions(tab)
tap_cmd = ('''
window.__tapAction.start({
element: element,
left_position_percentage: %s,
top_position_percentage: %s,
duration_ms: %s,
gesture_source_type: %s
});'''
... | self.element_function = 'document.body' | conditional_block |
tap.py | # Copyright 2013 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.
import os
from telemetry.page.actions import page_action
class TapAction(page_action.PageAction):
def __init__(self, selector=None, text=None, element_f... |
def RunAction(self, tab):
if not self.HasElementSelector():
self.element_function = 'document.body'
gesture_source_type = page_action.GetGestureSourceTypeFromOptions(tab)
tap_cmd = ('''
window.__tapAction.start({
element: element,
left_position_percentage: %s,
... | return (self.element_function is not None or self.selector is not None or
self.text is not None) | identifier_body |
tap.py | # Copyright 2013 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.
import os
from telemetry.page.actions import page_action
class TapAction(page_action.PageAction):
def __init__(self, selector=None, text=None, element_f... | if not self.HasElementSelector():
self.element_function = 'document.body'
gesture_source_type = page_action.GetGestureSourceTypeFromOptions(tab)
tap_cmd = ('''
window.__tapAction.start({
element: element,
left_position_percentage: %s,
top_position_percentage: %s,... | def RunAction(self, tab): | random_line_split |
tap.py | # Copyright 2013 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.
import os
from telemetry.page.actions import page_action
class TapAction(page_action.PageAction):
def __init__(self, selector=None, text=None, element_f... | (self, tab):
for js_file in ['gesture_common.js', 'tap.js']:
with open(os.path.join(os.path.dirname(__file__), js_file)) as f:
js = f.read()
tab.ExecuteJavaScript(js)
# Fail if browser doesn't support synthetic tap gestures.
if not tab.EvaluateJavaScript('window.__TapAction_SupportedB... | WillRunAction | identifier_name |
utils.py | # 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 t... |
class DummyGroupKeyResponse(object):
def __init__(self, signature, metadata, group_key):
self.signature = signature
self.metadata = metadata
self.group_key = group_key
def request(self, path, method, **kwargs):
return self
def json(self):
return {"signature": se... | return {"name": self.name} | identifier_body |
utils.py | # 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 t... | def request(self, path, method, **kwargs):
self.name = path.split('/')[-1]
return self
def json(self):
return {"generation": self.generation,
"name": self.name}
class DummyTicketResponse(object):
def __init__(self, signature, metadata, ticket):
self.signat... | def __init__(self, gen=1):
self.generation = gen
self.name = ""
| random_line_split |
utils.py | # 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 t... | (object):
def __init__(self, gen=1):
self.generation = gen
self.name = ""
def request(self, path, method, **kwargs):
self.name = path.split('/')[-1]
return self
def json(self):
return {"generation": self.generation,
"name": self.name}
class DummyT... | DummyKeyResponse | identifier_name |
metadata_resolver.d.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import { StaticSymbol, StaticSymbolCache } from './aot/static_symbol';
import * as cpl from './compile_metadata';
imp... | {
private _config;
private _htmlParser;
private _ngModuleResolver;
private _directiveResolver;
private _pipeResolver;
private _summaryResolver;
private _schemaRegistry;
private _directiveNormalizer;
private _console;
private _staticSymbolCache;
private _reflector;
privat... | CompileMetadataResolver | identifier_name |
metadata_resolver.d.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import { StaticSymbol, StaticSymbolCache } from './aot/static_symbol';
import * as cpl from './compile_metadata';
imp... | private _ngModuleCache;
private _ngModuleOfTypes;
constructor(_config: CompilerConfig, _htmlParser: HtmlParser, _ngModuleResolver: NgModuleResolver, _directiveResolver: DirectiveResolver, _pipeResolver: PipeResolver, _summaryResolver: SummaryResolver<any>, _schemaRegistry: ElementSchemaRegistry, _directiveN... | private _pipeCache; | random_line_split |
boxplot.py | import numpy as np
import pandas as pd
from bokeh.plotting import *
# Generate some synthetic time series for six different categories
cats = list("abcdef")
y = np.random.randn(2000)
g = np.random.choice(cats, 2000)
for i, l in enumerate(cats):
y[g == l] += i // 2
df = pd.DataFrame(dict(score=y, group=g))
# Find ... | tools="", background_fill="#EFE8E2", line_color="black", title="")
# EXERCISE: draw the lower segment
# Draw the upper box of the box plot using `rect`
rect(cats, (q3.score+q2.score)/2, 0.7, q3.score-q2.score,
fill_color="#E08E79", line_width=2, line_color="black")
# EXERCISE: use `rect` to draw the bot... | random_line_split | |
boxplot.py | import numpy as np
import pandas as pd
from bokeh.plotting import *
# Generate some synthetic time series for six different categories
cats = list("abcdef")
y = np.random.randn(2000)
g = np.random.choice(cats, 2000)
for i, l in enumerate(cats):
y[g == l] += i // 2
df = pd.DataFrame(dict(score=y, group=g))
# Find ... |
out = groups.apply(outliers).dropna()
# Prepare outlier data for plotting, we need and x (categorical) and y (numeric)
# coordinate for every outlier.
outx = []
outy = []
for cat in cats:
for value in out[cat]:
outx.append(cat)
outy.append(value)
# EXERCISE: output static HTML file
# EXERCISE: t... | cat = group.name
return group[(group.score > upper.loc[cat][0]) | (group.score < lower.loc[cat][0])]['score'] | identifier_body |
boxplot.py | import numpy as np
import pandas as pd
from bokeh.plotting import *
# Generate some synthetic time series for six different categories
cats = list("abcdef")
y = np.random.randn(2000)
g = np.random.choice(cats, 2000)
for i, l in enumerate(cats):
y[g == l] += i // 2
df = pd.DataFrame(dict(score=y, group=g))
# Find ... | (group):
cat = group.name
return group[(group.score > upper.loc[cat][0]) | (group.score < lower.loc[cat][0])]['score']
out = groups.apply(outliers).dropna()
# Prepare outlier data for plotting, we need and x (categorical) and y (numeric)
# coordinate for every outlier.
outx = []
outy = []
for cat in cats:
fo... | outliers | identifier_name |
boxplot.py | import numpy as np
import pandas as pd
from bokeh.plotting import *
# Generate some synthetic time series for six different categories
cats = list("abcdef")
y = np.random.randn(2000)
g = np.random.choice(cats, 2000)
for i, l in enumerate(cats):
|
df = pd.DataFrame(dict(score=y, group=g))
# Find the quartiles, IQR, and outliers for each category
groups = df.groupby('group')
q1 = groups.quantile(q=0.25)
q2 = groups.quantile(q=0.5)
q3 = groups.quantile(q=0.75)
iqr = q3 - q1
upper = q2 + 1.5*iqr
lower = q2 - 1.5*iqr
def outliers(group):
cat = group.name
ret... | y[g == l] += i // 2 | conditional_block |
filter.js | /**
* Filtering sensitive information
*/
const _ = require('lodash');
/**
* reset option
* @param {string|object|array} opt filter option
* @param {array} filterKeys filter keys
* @param {string|function} replaceChat replace chat or function
* @param {boolean} recursion whether recursive , true of false
*/
c... |
});
return result;
} else if (typeof result === 'number') {
return result;
} else if (result instanceof Array && result.length > 0) {
return result;
}
return result;
};
/**
* filter sensitive information
* @param {object} message log message
* @param {*} option filter option
*/
const filte... | {
result[key] = replaceChat;
} | conditional_block |
filter.js | /**
* Filtering sensitive information
*/
const _ = require('lodash');
/**
* reset option
* @param {string|object|array} opt filter option
* @param {array} filterKeys filter keys
* @param {string|function} replaceChat replace chat or function
* @param {boolean} recursion whether recursive , true of false
*/
c... | * filter sensitive information
* @param {object} message log message
* @param {*} option filter option
*/
const filteringSensitiveInfo = (message, option = false) => {
if (!option) {
return message;
}
if (typeof option === 'function') {
return option(message);
}
return filterNoRecursion(message, s... | random_line_split | |
urls.py | from django.conf.urls.defaults import patterns, include, url
from file_uploader import settings
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
| # Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
# url(r'^admin/', include(admin.site.urls)),
url(r'^media/(?P<path>.*)$', "django.views.static.serve",{'document_root':... | urlpatterns = patterns('',
# Examples:
# url(r'^$', 'file_uploader.views.home', name='home'),
# url(r'^file_uploader/', include('file_uploader.foo.urls')),
| random_line_split |
setup.py | with open('README.txt') as f:
long_description = f.read()
from distutils.core import setup
setup(
name = "nomit",
packages = ["nomit"],
version = "1.0",
description = "Process Monit HTTP/XML",
author = "Markus Juenemann",
author_email = "markus@juenemann.net",
url = "https://github.com/... | "Topic :: Software Development :: Libraries :: Python Modules",
"Topic :: System :: Monitoring",
],
long_description = long_description
) | "Development Status :: 4 - Beta",
"Environment :: Other Environment",
"Intended Audience :: Developers",
"License :: OSI Approved :: BSD License",
"Operating System :: OS Independent", | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.