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 |
|---|---|---|---|---|
hu.js | /*
Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
*/
CKEDITOR.plugins.setLang( 'image', 'hu', {
alt: 'Alternatív szöveg',
border: 'Keret',
btnUpload: 'Küldés a szerverre', | linkTab: 'Hivatkozás',
lockRatio: 'Arány megtartása',
menu: 'Kép tulajdonságai',
resetSize: 'Eredeti méret',
title: 'Kép tulajdonságai',
titleButton: 'Képgomb tulajdonságai',
upload: 'Feltöltés',
urlMissing: 'Hiányzik a kép URL-je.',
vSpace: 'Függ. táv',
validateBorder: 'A keret méretének egész számot kell be... | button2Img: 'Szeretne a kiválasztott képgombból sima képet csinálni?',
hSpace: 'Vízsz. táv',
img2Button: 'Szeretne a kiválasztott képből képgombot csinálni?',
infoTab: 'Alaptulajdonságok', | random_line_split |
apiKeyManager.js | const fs = require('fs');
const _ = require('lodash');
const cache = require('./state/cache');
const broadcast = cache.get('broadcast');
const apiKeysFile = __dirname + '/../SECRET-api-keys.json';
// on init:
const noApiKeysFile = !fs.existsSync(apiKeysFile);
if(noApiKeysFile)
fs.writeFileSync(
apiKeysFile,
... | fs.writeFileSync(apiKeysFile, JSON.stringify(apiKeys));
broadcast({
type: 'apiKeys',
exchanges: _.keys(apiKeys)
});
},
remove: exchange => {
if(!apiKeys[exchange])
return;
delete apiKeys[exchange];
fs.writeFileSync(apiKeysFile, JSON.stringify(apiKeys));
broadcast({
... | get: () => _.keys(apiKeys),
// note: overwrites if exists
add: (exchange, props) => {
apiKeys[exchange] = props; | random_line_split |
BpmnUtils.tsx | import { WorkflowActivityModel, WorkflowConnectionModel, WorkflowEntitiesDictionary } from "../Signum.Entities.Workflow";
export function isEvent(elementType: BPMN.ElementType): boolean {
return elementType == "bpmn:StartEvent" ||
elementType == "bpmn:EndEvent";
}
export function isTaskAnyKind(elementTyp... | {
var mod = entities[con.id] as (WorkflowConnectionModel | undefined);
if (mod && mod.type == "Decision") {
const gateway = (con.businessObject as BPMN.ConnectionModdleElemnet).sourceRef;
const activities = gateway.incoming!
.filter(c => c.sourceRef.$type == "bpmn:Task" || c.sourceRef.$type =... | identifier_body | |
BpmnUtils.tsx | import { WorkflowActivityModel, WorkflowConnectionModel, WorkflowEntitiesDictionary } from "../Signum.Entities.Workflow";
export function isEvent(elementType: BPMN.ElementType): boolean {
return elementType == "bpmn:StartEvent" ||
elementType == "bpmn:EndEvent";
}
export function isTaskAnyKind(elementTyp... | return undefined;
} | return doe?.element.style;
}
| random_line_split |
BpmnUtils.tsx | import { WorkflowActivityModel, WorkflowConnectionModel, WorkflowEntitiesDictionary } from "../Signum.Entities.Workflow";
export function isEvent(elementType: BPMN.ElementType): boolean {
return elementType == "bpmn:StartEvent" ||
elementType == "bpmn:EndEvent";
}
export function isTaskAnyKind(elementTyp... |
return undefined;
}
| {
const gateway = (con.businessObject as BPMN.ConnectionModdleElemnet).sourceRef;
const activities = gateway.incoming!
.filter(c => c.sourceRef.$type == "bpmn:Task" || c.sourceRef.$type == "bpmn:UserTask")
.map(c => entities[c.sourceRef.id] as WorkflowActivityModel);
const doe = activ... | conditional_block |
BpmnUtils.tsx | import { WorkflowActivityModel, WorkflowConnectionModel, WorkflowEntitiesDictionary } from "../Signum.Entities.Workflow";
export function isEvent(elementType: BPMN.ElementType): boolean {
return elementType == "bpmn:StartEvent" ||
elementType == "bpmn:EndEvent";
}
export function isTaskAnyKind(elementTyp... | (elementType: BPMN.ElementType): boolean {
return elementType == "bpmn:SequenceFlow" ||
elementType == "bpmn:MessageFlow";
}
export function findDecisionStyle(con: BPMN.Connection, entities: WorkflowEntitiesDictionary) {
var mod = entities[con.id] as (WorkflowConnectionModel | undefined);
if (mod &&... | isConnection | identifier_name |
__init__.py | """Support for Tibber."""
import asyncio
import logging
import aiohttp
import tibber
from homeassistant.const import (
CONF_ACCESS_TOKEN,
CONF_NAME,
EVENT_HOMEASSISTANT_STOP,
Platform,
)
from homeassistant.exceptions import ConfigEntryNotReady
from homeassistant.helpers import discovery
from homeassis... | await tibber_connection.update_info()
except asyncio.TimeoutError as err:
raise ConfigEntryNotReady from err
except aiohttp.ClientError as err:
_LOGGER.error("Error connecting to Tibber: %s ", err)
return False
except tibber.InvalidLogin as exp:
_LOGGER.error("Failed ... |
try: | random_line_split |
__init__.py | """Support for Tibber."""
import asyncio
import logging
import aiohttp
import tibber
from homeassistant.const import (
CONF_ACCESS_TOKEN,
CONF_NAME,
EVENT_HOMEASSISTANT_STOP,
Platform,
)
from homeassistant.exceptions import ConfigEntryNotReady
from homeassistant.helpers import discovery
from homeassis... | (hass, config):
"""Set up the Tibber component."""
hass.data[DATA_HASS_CONFIG] = config
return True
async def async_setup_entry(hass, entry):
"""Set up a config entry."""
tibber_connection = tibber.Tibber(
access_token=entry.data[CONF_ACCESS_TOKEN],
websession=async_get_clientses... | async_setup | identifier_name |
__init__.py | """Support for Tibber."""
import asyncio
import logging
import aiohttp
import tibber
from homeassistant.const import (
CONF_ACCESS_TOKEN,
CONF_NAME,
EVENT_HOMEASSISTANT_STOP,
Platform,
)
from homeassistant.exceptions import ConfigEntryNotReady
from homeassistant.helpers import discovery
from homeassis... |
entry.async_on_unload(hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, _close))
try:
await tibber_connection.update_info()
except asyncio.TimeoutError as err:
raise ConfigEntryNotReady from err
except aiohttp.ClientError as err:
_LOGGER.error("Error connecting to Tibber: %... | await tibber_connection.rt_disconnect() | identifier_body |
__init__.py | """Support for Tibber."""
import asyncio
import logging
import aiohttp
import tibber
from homeassistant.const import (
CONF_ACCESS_TOKEN,
CONF_NAME,
EVENT_HOMEASSISTANT_STOP,
Platform,
)
from homeassistant.exceptions import ConfigEntryNotReady
from homeassistant.helpers import discovery
from homeassis... |
return unload_ok
| tibber_connection = hass.data.get(DOMAIN)
await tibber_connection.rt_disconnect() | conditional_block |
official_holiday_wizard.py | # -*- coding: utf-8 -*-
# -*- encoding: utf-8 -*-
#############################################################################
#
# Copyright (c) 2007 Martin Reisenhofer <martin.reisenhofer@funkring.net>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU G... |
return { "type" : "ir.actions.act_window_close" }
_name = "official.holiday.template.wizard"
_description = "Official holiday template wizard"
_columns = {
"fiscalyear_id" : fields.many2one("account.fiscalyear", "Fiscal Year"),
"calendar_ids" : fields.many2many("resource.calendar"... | def do_create(self, cr, uid, ids, context=None):
holiday_obj = self.pool.get("official.holiday")
template_obj = self.pool.get("official.holiday.template")
user_obj = self.pool.get("res.users")
template_ids = template_obj.search(cr,uid,[("id","in",util.active_ids(context))])
comp... | identifier_body |
official_holiday_wizard.py | # -*- coding: utf-8 -*-
# -*- encoding: utf-8 -*-
#############################################################################
#
# Copyright (c) 2007 Martin Reisenhofer <martin.reisenhofer@funkring.net>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU G... | #
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp.osv import fields,osv
from openerp.addons.at_base import util
class official... | # This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. | random_line_split |
official_holiday_wizard.py | # -*- coding: utf-8 -*-
# -*- encoding: utf-8 -*-
#############################################################################
#
# Copyright (c) 2007 Martin Reisenhofer <martin.reisenhofer@funkring.net>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU G... | (osv.osv_memory):
def do_create(self, cr, uid, ids, context=None):
holiday_obj = self.pool.get("official.holiday")
template_obj = self.pool.get("official.holiday.template")
user_obj = self.pool.get("res.users")
template_ids = template_obj.search(cr,uid,[("id","in",util.active_ids(c... | official_holiday_template_wizard | identifier_name |
official_holiday_wizard.py | # -*- coding: utf-8 -*-
# -*- encoding: utf-8 -*-
#############################################################################
#
# Copyright (c) 2007 Martin Reisenhofer <martin.reisenhofer@funkring.net>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU G... |
return { "type" : "ir.actions.act_window_close" }
_name = "official.holiday.template.wizard"
_description = "Official holiday template wizard"
_columns = {
"fiscalyear_id" : fields.many2one("account.fiscalyear", "Fiscal Year"),
"calendar_ids" : fields.many2many("resource.calendar... | holiday_obj.create_calendar_entries(cr, uid, official_holiday_ids, fiscalyear_id=wizard.fiscalyear_id.id, company_id=company_id, context=context) | conditional_block |
intwriter.py | ys'] #source system code for UID lookup in MDM
self.intencoding = target['encoding'] #append method description (api, rest, query, etc.)
self.intname = target['name'] #name of table or procedure or whatever else
self.lookupcolumns = target['lookupcolumns']
self.pool = None
sel... |
else:
obj[key] = str(data[key]).replace('00000000-0000-0000-0000-000000000000', '#NULL')
obj['ActionID'] = 3 # Force-set action as "integration"
elif self.inttype == 'odsf1':
objectkeys = ['DataType','SystemID','ActionID','ExtractionDa... | if data[key] in self.lookup_table:
data[key] = self.lookup_table[data[key]]
obj['PeriodObjects'][0]['Attributes'].append({'Name': key, 'Value': str(data[key]).replace('00000000-0000-0000-0000-000000000000', '#NULL')}) | conditional_block |
intwriter.py | import psycopg2.extras
from psycopg2.pool import ThreadedConnectionPool
import datetime
from concurrent.futures import ThreadPoolExecutor, wait
import multiprocessing
import sys
import hashlib
from utils import *
THREADNUM = 16
class IntWriter:
def __init__(self, target):
self.inttype = target['type'] #d... | import os
import json
import pyodbc
import psycopg2 | random_line_split | |
intwriter.py | , (self.mdmssys,))
for row in cursor:
self.golden_table[row[0]] = row[1]
logging.info(len(self.golden_table), 'golden IDs are mapped to datasource. Memory used: ', sys.getsizeof(self.golden_table))
def ods_to_dwh_tracker(self):
cursor = pyodbc.connect(self.intconnstr).execute('s... | t = datetime.datetime.today()
count = 0
if self.inttype == 'apij1':
if params:
w = params
db = pyodbc.connect(self.intconnstr)
cursor = db.cursor()
cursor.execute('SET TRANSACTION ISOLATION LEVEL SNAPSHOT')
cursor.commit()
... | identifier_body | |
intwriter.py | ys'] #source system code for UID lookup in MDM
self.intencoding = target['encoding'] #append method description (api, rest, query, etc.)
self.intname = target['name'] #name of table or procedure or whatever else
self.lookupcolumns = target['lookupcolumns']
self.pool = None
sel... | (self):
return len(self.stream)
def append(self, data):
st = datetime.datetime.now()
BATCH_SIZE = 1
if self.inttype == 'apij1':
BATCH_SIZE = 1000
objectkeys = ['ExtractionDate','Migration','ActionID','SystemID','EntityID','UID','ParentUID','Verified','UXID',... | __len__ | identifier_name |
list-endpoints.rs | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
use aws_config::meta::region::RegionProviderChain;
use aws_sdk_mediapackage::{Client, Error, Region, PKG_VERSION};
use structopt::StructOpt;
#[derive(Debug, StructOpt)]
struct Opt {
/// The AWS Reg... |
// Displays your endpoint descriptions and URLs.
// snippet-start:[mediapackage.rust.list-endpoints]
async fn show_endpoints(client: &Client) -> Result<(), Error> {
let or_endpoints = client.list_origin_endpoints().send().await?;
println!("Endpoints:");
for e in or_endpoints.origin_endpoints().unwrap_or_... |
/// Whether to display additional information.
#[structopt(short, long)]
verbose: bool,
} | random_line_split |
list-endpoints.rs | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
use aws_config::meta::region::RegionProviderChain;
use aws_sdk_mediapackage::{Client, Error, Region, PKG_VERSION};
use structopt::StructOpt;
#[derive(Debug, StructOpt)]
struct Opt {
/// The AWS Reg... |
let shared_config = aws_config::from_env().region(region_provider).load().await;
let client = Client::new(&shared_config);
show_endpoints(&client).await
}
| {
println!("MediaPackage client version: {}", PKG_VERSION);
println!(
"Region: {}",
region_provider.region().await.unwrap().as_ref()
);
println!();
} | conditional_block |
list-endpoints.rs | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
use aws_config::meta::region::RegionProviderChain;
use aws_sdk_mediapackage::{Client, Error, Region, PKG_VERSION};
use structopt::StructOpt;
#[derive(Debug, StructOpt)]
struct Opt {
/// The AWS Reg... |
// snippet-end:[mediapackage.rust.list-endpoints]
/// Lists your AWS Elemental MediaPackage endpoint descriptions and URLs in the Region.
/// # Arguments
///
/// * `[-r REGION]` - The Region in which the client is created.
/// If not supplied, uses the value of the **AWS_REGION** environment variable.
/// If th... | {
let or_endpoints = client.list_origin_endpoints().send().await?;
println!("Endpoints:");
for e in or_endpoints.origin_endpoints().unwrap_or_default() {
let endpoint_url = e.url().unwrap_or_default();
let endpoint_description = e.description().unwrap_or_default();
println!(" Desc... | identifier_body |
list-endpoints.rs | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
use aws_config::meta::region::RegionProviderChain;
use aws_sdk_mediapackage::{Client, Error, Region, PKG_VERSION};
use structopt::StructOpt;
#[derive(Debug, StructOpt)]
struct Opt {
/// The AWS Reg... | () -> Result<(), Error> {
tracing_subscriber::fmt::init();
let Opt { region, verbose } = Opt::from_args();
let region_provider = RegionProviderChain::first_try(region.map(Region::new))
.or_default_provider()
.or_else(Region::new("us-west-2"));
println!();
if verbose {
prin... | main | identifier_name |
main_raw.rs | #[global_allocator]
static GLOBAL: snmalloc_rs::SnMalloc = snmalloc_rs::SnMalloc;
use std::{future::Future, io, pin::Pin, task::Context, task::Poll};
use ntex::{fn_service, http::h1, io::Io, util::ready, util::BufMut, util::PoolId};
mod utils;
#[cfg(target_os = "macos")]
use serde_json as simd_json;
const JSON: &[u8... | {
io: Io,
codec: h1::Codec,
}
impl Future for App {
type Output = Result<(), ()>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let this = self.as_mut().get_mut();
loop {
if let Some(Ok((req, _))) = ready!(this.io.poll_read_next(&this.code... | App | identifier_name |
main_raw.rs | #[global_allocator]
static GLOBAL: snmalloc_rs::SnMalloc = snmalloc_rs::SnMalloc;
use std::{future::Future, io, pin::Pin, task::Context, task::Poll};
use ntex::{fn_service, http::h1, io::Io, util::ready, util::BufMut, util::PoolId};
mod utils;
#[cfg(target_os = "macos")]
use serde_json as simd_json;
const JSON: &[u8... |
// start http server
ntex::server::build()
.backlog(1024)
.bind("techempower", "0.0.0.0:8080", |cfg| {
cfg.memory_pool(PoolId::P1);
PoolId::P1.set_read_params(65535, 8192);
PoolId::P1.set_write_params(65535, 8192);
fn_service(|io| App {
... |
#[ntex::main]
async fn main() -> io::Result<()> {
println!("Started http server: 127.0.0.1:8080"); | random_line_split |
main_raw.rs | #[global_allocator]
static GLOBAL: snmalloc_rs::SnMalloc = snmalloc_rs::SnMalloc;
use std::{future::Future, io, pin::Pin, task::Context, task::Poll};
use ntex::{fn_service, http::h1, io::Io, util::ready, util::BufMut, util::PoolId};
mod utils;
#[cfg(target_os = "macos")]
use serde_json as simd_json;
const JSON: &[u8... |
"/plaintext" => {
buf.extend_from_slice(PLAIN);
this.codec.set_date_header(buf);
buf.extend_from_slice(BODY);
}
_ => {
buf.extend_from_... | {
buf.extend_from_slice(JSON);
this.codec.set_date_header(buf);
let _ = simd_json::to_writer(
crate::utils::Writer(buf),
&Message {
mess... | conditional_block |
AADHelper.ts | );
if (refreshedToken.accessToken) {
return {
accessToken: refreshedToken.accessToken,
idToken: refreshedToken.idToken
};
} else {
throw new Error();
}
} catch (e) {
throw new Error('Unavailable due to network problems');
}
}
private getTokenClaims(accessToken: string): ITokenCl... | } else {
this._tokens.push(token);
} | random_line_split | |
AADHelper.ts | : string): Promise<vscode.AuthenticationSession> {
let uriEventListener: vscode.Disposable;
return new Promise((resolve: (value: vscode.AuthenticationSession) => void, reject) => {
uriEventListener = this._uriHandler.event(async (uri: vscode.Uri) => {
try {
const query = parseQuery(uri);
const code... | {
session = this.convertToSessionSync(token);
} | conditional_block | |
AADHelper.ts | crets.onDidChange(() => this.checkForUpdates));
}
private parseStoredData(data: string): IStoredSession[] {
return JSON.parse(data);
}
private async storeTokenData(): Promise<void> |
private async checkForUpdates(): Promise<void> {
const added: vscode.AuthenticationSession[] = [];
let removed: vscode.AuthenticationSession[] = [];
const storedData = await this._keychain.getToken();
if (storedData) {
try {
const sessions = this.parseStoredData(storedData);
let promises = session... | {
const serializedData: IStoredSession[] = this._tokens.map(token => {
return {
id: token.sessionId,
refreshToken: token.refreshToken,
scope: token.scope,
account: token.account
};
});
await this._keychain.setToken(JSON.stringify(serializedData));
} | identifier_body |
AADHelper.ts | (uri: vscode.Uri) {
this.fire(uri);
}
}
export class AzureActiveDirectoryService {
private _tokens: IToken[] = [];
private _refreshTimeouts: Map<string, NodeJS.Timeout> = new Map<string, NodeJS.Timeout>();
private _uriHandler: UriEventHandler;
private _disposables: vscode.Disposable[] = [];
// Used to keep tr... | handleUri | identifier_name | |
paper.service.ts | import { Injectable } from '@angular/core';
import { Headers, Http, Response } from '@angular/http';
import 'rxjs/add/operator/toPromise';
import { Subject } from '../../sharedClasses/subject'
import { Question } from '../../sharedClasses/question';
@Injectable()
export class PaperService {
| (private _http: Http) { }
getQuestions(subjectID, time): Promise<Question[]> {
let api_url = 'questions/getQuestionIdTime/' + subjectID + '/' + time;
return this._http.get(api_url)
.toPromise()
.then(response => response.json().questions as Question[])
.catch(th... | constructor | identifier_name |
paper.service.ts | import { Injectable } from '@angular/core';
import { Headers, Http, Response } from '@angular/http';
import 'rxjs/add/operator/toPromise';
import { Subject } from '../../sharedClasses/subject'
import { Question } from '../../sharedClasses/question';
@Injectable()
export class PaperService {
constructor(private ... | return Promise.reject(error.message || error);
}
} | random_line_split | |
paper.service.ts | import { Injectable } from '@angular/core';
import { Headers, Http, Response } from '@angular/http';
import 'rxjs/add/operator/toPromise';
import { Subject } from '../../sharedClasses/subject'
import { Question } from '../../sharedClasses/question';
@Injectable()
export class PaperService {
constructor(private ... |
} | {
console.error('An error occurred', error); // for demo purposes only
return Promise.reject(error.message || error);
} | identifier_body |
foursquare.py | # -*- coding: utf-8 -*-
# Copyright (C) 2014 Osmo Salomaa
#
# 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 pr... | f parse_text(item):
"""Parse blurb text from search result `item`."""
lines = []
with poor.util.silent(Exception):
lines.append('<font color="Theme.highlightColor">'
'<big>{}</big>'
'</font>'
.format(html.escape(item.venue.name)))
s... | arse hyperlink from search result `item`."""
return ("http://foursquare.com/v/{}?ref={}"
.format(item.venue.id, CLIENT_ID))
de | identifier_body |
foursquare.py | # -*- coding: utf-8 -*-
# Copyright (C) 2014 Osmo Salomaa
#
# 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 pr... | m):
"""Parse hyperlink from search result `item`."""
return ("http://foursquare.com/v/{}?ref={}"
.format(item.venue.id, CLIENT_ID))
def parse_text(item):
"""Parse blurb text from search result `item`."""
lines = []
with poor.util.silent(Exception):
lines.append('<font color="The... | e_link(ite | identifier_name |
foursquare.py | # -*- coding: utf-8 -*-
# Copyright (C) 2014 Osmo Salomaa
#
# 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 pr... |
with poor.util.silent(Exception):
category = html.escape(item.venue.categories[0].name)
subtitle.append("<small>{}</small>".format(category))
lines.append(" ".join(subtitle))
with poor.util.silent(Exception):
quote = html.escape(item.tips[0].text)
lines.append("<s... | .format(float(item.venue.rating))) | random_line_split |
foursquare.py | # -*- coding: utf-8 -*-
# Copyright (C) 2014 Osmo Salomaa
#
# 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 pr... |
return x, y, results
def parse_description(item):
"""Parse description from search result `item`."""
description = []
with poor.util.silent(Exception):
rating = float(item.venue.rating)
description.append("{:.1f}/10".format(rating))
with poor.util.silent(Exception):
descrip... | cache[url] = copy.deepcopy((x, y, results)) | conditional_block |
tabs-adv.js | /*!
* Ext JS Library 3.4.0
* Copyright(c) 2006-2011 Sencha Inc.
* licensing@sencha.com
* http://www.sencha.com/license
*/
Ext.onReady(function(){
var tabs = new Ext.TabPanel({
renderTo:'tabs',
resizeTabs:true, // turn on tab resizing
minTabWidth: 115,
tabWidth:135,
enab... | (){
tabs.add({
title: 'New Tab 测试 ' + (++index),
iconCls: 'tabs',
html: 'Tab Body ' + (index) + '<br/><br/>'
+ Ext.example.bogusMarkup,
closable:true
}).show();
}
new Ext.Button({
text: 'Add Tab',
handler: addTa... | addTab | identifier_name |
tabs-adv.js | /*!
* Ext JS Library 3.4.0
* Copyright(c) 2006-2011 Sencha Inc.
* licensing@sencha.com
* http://www.sencha.com/license
*/
Ext.onReady(function(){
var tabs = new Ext.TabPanel({
renderTo:'tabs',
resizeTabs:true, // turn on tab resizing
minTabWidth: 115,
tabWidth:135,
enab... |
function addTab(){
tabs.add({
title: 'New Tab 测试 ' + (++index),
iconCls: 'tabs',
html: 'Tab Body ' + (index) + '<br/><br/>'
+ Ext.example.bogusMarkup,
closable:true
}).show();
}
new Ext.Button({
text: 'Add Tab... | {
addTab();
} | conditional_block |
tabs-adv.js | /*!
* Ext JS Library 3.4.0
* Copyright(c) 2006-2011 Sencha Inc.
* licensing@sencha.com
* http://www.sencha.com/license
*/
Ext.onReady(function(){
var tabs = new Ext.TabPanel({
renderTo:'tabs',
resizeTabs:true, // turn on tab resizing
minTabWidth: 115,
tabWidth:135,
enab... | new Ext.Button({
text: 'Add Tab',
handler: addTab,
iconCls:'new-tab'
}).render(document.body, 'tabs');
}); | {
tabs.add({
title: 'New Tab 测试 ' + (++index),
iconCls: 'tabs',
html: 'Tab Body ' + (index) + '<br/><br/>'
+ Ext.example.bogusMarkup,
closable:true
}).show();
}
| identifier_body |
tabs-adv.js | /*!
* Ext JS Library 3.4.0
* Copyright(c) 2006-2011 Sencha Inc.
* licensing@sencha.com
* http://www.sencha.com/license
*/
Ext.onReady(function(){
var tabs = new Ext.TabPanel({
renderTo:'tabs',
resizeTabs:true, // turn on tab resizing
minTabWidth: 115,
tabWidth:135,
enab... | html: 'Tab Body ' + (index) + '<br/><br/>'
+ Ext.example.bogusMarkup,
closable:true
}).show();
}
new Ext.Button({
text: 'Add Tab',
handler: addTab,
iconCls:'new-tab'
}).render(document.body, 'tabs');
}); | iconCls: 'tabs', | random_line_split |
http-errors-tests.ts | import * as createError from 'http-errors';
import * as express from 'express';
var app = express();
declare global {
namespace Express {
export interface Request {
user?: any
}
}
}
app.use(function (req, res, next) {
if (!req.user) return next(createError(401, 'Please login t... |
// createError(msg, status)
var err = createError('LOL', 404);
// createError(msg)
var err = createError('LOL');
// createError(msg, props)
var err = createError('LOL', {id: 1});
// createError(err)
var err = createError(new Error('LOL'));
// createError(err, props)
var err = createError(new Error('LOL'), {id: 1})... | // createError(props)
var err = createError({id: 1});
console.log((<any> err).id); | random_line_split |
test_messages.py | # -*- coding: utf-8 -*-
import json
from catmaid.models import Message
from .common import CatmaidApiTestCase
class MessagesApiTests(CatmaidApiTestCase):
def test_read_message_error(self):
self.fake_authentication()
message_id = 5050
response = self.client.post(f'/messages/{message_id}... |
def test_read_message_with_action(self):
self.fake_authentication()
message_id = 1
response = self.client.post(f'/messages/{message_id}/mark_read')
self.assertEqual(response.status_code, 302)
message = Message.objects.filter(id=message_id)[0]
self.assertEqual(True... | self.fake_authentication()
message_id = 3
response = self.client.post(f'/messages/{message_id}/mark_read')
self.assertStatus(response)
parsed_response = json.loads(response.content.decode('utf-8'))
message = Message.objects.get(id=message_id)
self.assertEqual(True, mess... | identifier_body |
test_messages.py | # -*- coding: utf-8 -*-
import json
from catmaid.models import Message
from .common import CatmaidApiTestCase
class MessagesApiTests(CatmaidApiTestCase):
def test_read_message_error(self):
self.fake_authentication()
message_id = 5050
response = self.client.post(f'/messages/{message_id}... | self.assertEqual(expected_result[mi], parsed_response[mi]) | conditional_block | |
test_messages.py | # -*- coding: utf-8 -*-
import json
from catmaid.models import Message
from .common import CatmaidApiTestCase
class MessagesApiTests(CatmaidApiTestCase):
def test_read_message_error(self):
self.fake_authentication()
message_id = 5050
response = self.client.post(f'/messages/{message_id}... | 'text': 'Contents of message 3.',
'time': '2014-10-05 11:12:01.360422+00:00',
'title': 'Message 3'
},
'1': {
'action': 'http://www.example.com/message2',
'id': 2,
'text... | 'id': 3, | random_line_split |
test_messages.py | # -*- coding: utf-8 -*-
import json
from catmaid.models import Message
from .common import CatmaidApiTestCase
class | (CatmaidApiTestCase):
def test_read_message_error(self):
self.fake_authentication()
message_id = 5050
response = self.client.post(f'/messages/{message_id}/mark_read')
self.assertEqual(response.status_code, 404)
parsed_response = json.loads(response.content.decode('utf-8'))
... | MessagesApiTests | identifier_name |
const-str-ptr.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT. | // option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::{str, string};
const A: [u8; 2] = ['h' as u8, 'i' as u8];
const B: &'static [u8; 2] = &A;
const C: *const u8 = B as *const u8;
pub fn main() {
unsafe {
let foo = &A as *const u8;
assert_... | //
// 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 http://opensource.org/licenses/MIT>, at your | random_line_split |
const-str-ptr.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | {
unsafe {
let foo = &A as *const u8;
assert_eq!(str::from_utf8_unchecked(&A), "hi");
assert_eq!(*C, A[0]);
assert_eq!(*(&B[0] as *const u8), A[0]);
}
} | identifier_body | |
const-str-ptr.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {
unsafe {
let foo = &A as *const u8;
assert_eq!(str::from_utf8_unchecked(&A), "hi");
assert_eq!(*C, A[0]);
assert_eq!(*(&B[0] as *const u8), A[0]);
}
}
| main | identifier_name |
train_convnet.py | #!/usr/bin/env python
# coding: utf-8
import sys, os
sys.path.append(os.pardir) # 親ディレクトリのファイルをインポートするための設定
import numpy as np
import matplotlib.pyplot as plt
from dataset.mnist import load_mnist
from simple_convnet import SimpleConvNet
from common.trainer import Trainer
# データの読み込み
(x_train, t_train), (x_test, t_tes... | plt.legend(loc='lower right')
plt.show() | random_line_split | |
utils.py | # This file is part of Indico.
# Copyright (C) 2002 - 2017 European Organization for Nuclear Research (CERN).
#
# Indico 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 (a... | """
Takes time as a value of seconds and deduces the delta in human-readable
HHh MMm SSs format.
"""
seconds = int(seconds)
minutes = seconds / 60
ti = {'h': 0, 'm': 0, 's': 0}
if seconds > 0:
ti['s'] = seconds % 60
ti['m'] = minutes % 60
ti['h'] = minutes / 60
... | identifier_body | |
utils.py | # This file is part of Indico.
# Copyright (C) 2002 - 2017 European Organization for Nuclear Research (CERN).
#
# Indico 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 (a... | (seconds=0):
"""
Takes time as a value of seconds and deduces the delta in human-readable
HHh MMm SSs format.
"""
seconds = int(seconds)
minutes = seconds / 60
ti = {'h': 0, 'm': 0, 's': 0}
if seconds > 0:
ti['s'] = seconds % 60
ti['m'] = minutes % 60
ti['h'] = m... | stringify_seconds | identifier_name |
utils.py | # This file is part of Indico.
# Copyright (C) 2002 - 2017 European Organization for Nuclear Research (CERN).
#
# Indico 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 (a... | """
Safely manage calls to the remote server by encapsulating JSON creation
from Piwik data.
"""
rawjson = func(**kwargs)
try:
data = json.loads(rawjson)
if isinstance(data, dict) and data.get('result') == 'error':
current_plugin.logger.error('The Piwik server respond... |
def get_json_from_remote_server(func, default={}, **kwargs): | random_line_split |
utils.py | # This file is part of Indico.
# Copyright (C) 2002 - 2017 European Organization for Nuclear Research (CERN).
#
# Indico 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 (a... |
return "%dh %dm %ds" % (ti['h'], ti['m'], ti['s'])
| ti['s'] = seconds % 60
ti['m'] = minutes % 60
ti['h'] = minutes / 60 | conditional_block |
select_multiple_control_value_accessor.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 { ElementRef, OnDestroy, Provider, Renderer } from '@angular/core';
import { ControlValueAccessor } from './co... | * <select multiple [compareWith]="compareFn" [(ngModel)]="selectedCountries">
* <option *ngFor="let country of countries" [ngValue]="country">
* {{country.name}}
* </option>
* </select>
*
* compareFn(c1: Country, c2: Country): boolean {
* return c1 && c2 ? c1.id === c2.id : c1 === c2;
* }
... | * ``` | random_line_split |
select_multiple_control_value_accessor.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 { ElementRef, OnDestroy, Provider, Renderer } from '@angular/core';
import { ControlValueAccessor } from './co... | implements OnDestroy {
private _element;
private _renderer;
private _select;
id: string;
constructor(_element: ElementRef, _renderer: Renderer, _select: SelectMultipleControlValueAccessor);
ngValue: any;
value: any;
ngOnDestroy(): void;
}
| NgSelectMultipleOption | identifier_name |
linked_tap.py | from __future__ import print_function
import numpy as np
from bokeh.client import push_session
from bokeh.io import curdoc
from bokeh.models import (ColumnDataSource, DataRange1d, Plot, Circle, WidgetBox,
Row, Button, TapTool)
N = 9
x = np.linspace(-2, 2, N)
y = x**2
source1 = ColumnData... | source1.selected = {
'0d': {'flag': False, 'indices': []},
'1d': {'indices': []},
'2d': {'indices': {}}
}
source2.selected = {
'0d': {'flag': False, 'indices': []},
'1d': {'indices': []},
'2d': {'indices': {}}
}
reset.on_click(on_reset_click)
widgetBox =... | source2.on_change('selected', on_selection_change2)
reset = Button(label="Reset")
def on_reset_click(): | random_line_split |
linked_tap.py | from __future__ import print_function
import numpy as np
from bokeh.client import push_session
from bokeh.io import curdoc
from bokeh.models import (ColumnDataSource, DataRange1d, Plot, Circle, WidgetBox,
Row, Button, TapTool)
N = 9
x = np.linspace(-2, 2, N)
y = x**2
source1 = ColumnData... |
reset.on_click(on_reset_click)
widgetBox = WidgetBox(children=[reset], width=150)
row = Row(children=[widgetBox, plot1, plot2])
document = curdoc()
document.add_root(row)
if __name__ == "__main__":
print("\npress ctrl-C to exit")
session = push_session(document)
session.show()
session.loop_until_cl... | source1.selected = {
'0d': {'flag': False, 'indices': []},
'1d': {'indices': []},
'2d': {'indices': {}}
}
source2.selected = {
'0d': {'flag': False, 'indices': []},
'1d': {'indices': []},
'2d': {'indices': {}}
} | identifier_body |
linked_tap.py | from __future__ import print_function
import numpy as np
from bokeh.client import push_session
from bokeh.io import curdoc
from bokeh.models import (ColumnDataSource, DataRange1d, Plot, Circle, WidgetBox,
Row, Button, TapTool)
N = 9
x = np.linspace(-2, 2, N)
y = x**2
source1 = ColumnData... | ():
source1.selected = {
'0d': {'flag': False, 'indices': []},
'1d': {'indices': []},
'2d': {'indices': {}}
}
source2.selected = {
'0d': {'flag': False, 'indices': []},
'1d': {'indices': []},
'2d': {'indices': {}}
}
reset.on_click(on_reset_click)
widgetB... | on_reset_click | identifier_name |
linked_tap.py | from __future__ import print_function
import numpy as np
from bokeh.client import push_session
from bokeh.io import curdoc
from bokeh.models import (ColumnDataSource, DataRange1d, Plot, Circle, WidgetBox,
Row, Button, TapTool)
N = 9
x = np.linspace(-2, 2, N)
y = x**2
source1 = ColumnData... |
else:
radius = [0.1]*N
source1.data["radius"] = radius
source2.on_change('selected', on_selection_change2)
reset = Button(label="Reset")
def on_reset_click():
source1.selected = {
'0d': {'flag': False, 'indices': []},
'1d': {'indices': []},
'2d': {'indices': {}}
}
... | [index] = inds
radius = [0.1]*N
radius[index] = 0.2 | conditional_block |
base.py | import pytest
from pontoon.test import factories
@pytest.fixture
def | ():
"""Admin - a superuser"""
return factories.UserFactory.create(username="admin", is_superuser=True,)
@pytest.fixture
def client_superuser(client, admin):
"""Provides a client with a logged in superuser. """
client.force_login(admin)
return client
@pytest.fixture
def user_a():
return facto... | admin | identifier_name |
base.py | import pytest
from pontoon.test import factories
@pytest.fixture
def admin():
"""Admin - a superuser"""
return factories.UserFactory.create(username="admin", is_superuser=True,)
@pytest.fixture
def client_superuser(client, admin):
"""Provides a client with a logged in superuser. """
client.force_lo... |
@pytest.fixture
def project_b():
return factories.ProjectFactory(slug="project_b", name="Project B")
@pytest.fixture
def system_project_a():
return factories.ProjectFactory(
slug="system_project_a",
name="System Project A",
repositories=[],
system_project=True,
)
@pyte... | return factories.ProjectFactory(
slug="project_a", name="Project A", repositories=[],
) | identifier_body |
base.py | import pytest
from pontoon.test import factories
@pytest.fixture
def admin():
"""Admin - a superuser"""
return factories.UserFactory.create(username="admin", is_superuser=True,)
@pytest.fixture
def client_superuser(client, admin):
"""Provides a client with a logged in superuser. """
client.force_lo... |
@pytest.fixture
def resource_b(project_b):
return factories.ResourceFactory(
project=project_b, path="resource_b.po", format="po"
)
@pytest.fixture
def entity_a(resource_a):
return factories.EntityFactory(resource=resource_a, string="entity a")
@pytest.fixture
def entity_b(resource_b):
ret... | random_line_split | |
get_all_groups.rs | extern crate philipshue;
use std::env;
use philipshue::bridge::Bridge;
mod discover;
use discover::discover;
fn main() {
let args: Vec<String> = env::args().collect();
if args.len() < 2 {
println!("Usage : {:?} <username>", args[0]);
return;
}
let bridge = Bridge::new(discover().pop().... | }
}
impl<'a, T: 'a + Debug> Debug for Show<'a, T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self.0 {
Some(ref x) => x.fmt(f),
_ => Display::fmt("N/A", f),
}
}
} | Some(ref x) => x.fmt(f),
_ => Display::fmt("N/A", f),
} | random_line_split |
get_all_groups.rs | extern crate philipshue;
use std::env;
use philipshue::bridge::Bridge;
mod discover;
use discover::discover;
fn main() {
let args: Vec<String> = env::args().collect();
if args.len() < 2 {
println!("Usage : {:?} <username>", args[0]);
return;
}
let bridge = Bridge::new(discover().pop().... | (&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self.0 {
Some(ref x) => x.fmt(f),
_ => Display::fmt("N/A", f),
}
}
}
impl<'a, T: 'a + Debug> Debug for Show<'a, T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self.0 {
Some(re... | fmt | identifier_name |
get_all_groups.rs | extern crate philipshue;
use std::env;
use philipshue::bridge::Bridge;
mod discover;
use discover::discover;
fn main() | type_len);
for (id, group) in groups.iter() {
println!("{:2} {:name_len$} {:type_len$} {:12} {:6} {:6} {:3} {:?}",
id,
group.name,
group.group_type,
Show(&group.class),
... | {
let args: Vec<String> = env::args().collect();
if args.len() < 2 {
println!("Usage : {:?} <username>", args[0]);
return;
}
let bridge = Bridge::new(discover().pop().unwrap(), &*args[1]);
match bridge.get_all_groups() {
Ok(groups) => {
let name_len = groups.valu... | identifier_body |
menu-item.ts | /**
* @license
* Copyright Google LLC 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 {Component, ChangeDetectionStrategy, ViewEncapsulation} from '@angular/core';
import {MatMenuItem as BaseMatMe... | extends BaseMatMenuItem {}
| MatMenuItem | identifier_name |
menu-item.ts | /**
* @license
* Copyright Google LLC 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
*/ | * Single item inside of a `mat-menu`. Provides the menu item styling and accessibility treatment.
*/
@Component({
selector: '[mat-menu-item]',
exportAs: 'matMenuItem',
inputs: ['disabled', 'disableRipple'],
host: {
'[attr.role]': 'role',
// The MatMenuItem parent class adds `mat-menu-item` and `mat-f... |
import {Component, ChangeDetectionStrategy, ViewEncapsulation} from '@angular/core';
import {MatMenuItem as BaseMatMenuItem} from '@angular/material/menu';
/** | random_line_split |
carousel.js | /**
* myCarousel
*/
angular.module(PKG.name+'.directives').directive('myCarousel',
function myCarouselDirective ($interval) {
return {
restrict: 'AC',
link: function (scope, element, attrs) {
element.addClass('my-carousel');
var currentSlide = 1,
allSlides = element.find('section'),... |
var tick = $interval(function() {
console.log('carousel tick');
scope.nextSlide();
}, 5000);
function cancelInterval() {
$interval.cancel(tick);
}
scope.$on('$destroy', cancelInterval);
function setAnimationClass (d) {
var am = 'am-slide-';
... | {
if(currentSlide > slideCount) {
currentSlide = 1;
}
else if(currentSlide <= 0) {
currentSlide = slideCount;
}
} | identifier_body |
carousel.js | /**
* myCarousel
*/
angular.module(PKG.name+'.directives').directive('myCarousel',
function myCarouselDirective ($interval) { |
link: function (scope, element, attrs) {
element.addClass('my-carousel');
var currentSlide = 1,
allSlides = element.find('section'),
slideCount = allSlides.length;
function boundaries() {
if(currentSlide > slideCount) {
currentSlide = 1;
}
e... | return {
restrict: 'AC', | random_line_split |
carousel.js | /**
* myCarousel
*/
angular.module(PKG.name+'.directives').directive('myCarousel',
function myCarouselDirective ($interval) {
return {
restrict: 'AC',
link: function (scope, element, attrs) {
element.addClass('my-carousel');
var currentSlide = 1,
allSlides = element.find('section'),... |
setAnimationClass('right');
boundaries(currentSlide++);
}
scope.prevSlide = function (event) {
if(event) {
cancelInterval();
}
setAnimationClass('left');
boundaries(currentSlide--);
}
}
};
});
| {
cancelInterval();
} | conditional_block |
carousel.js | /**
* myCarousel
*/
angular.module(PKG.name+'.directives').directive('myCarousel',
function myCarouselDirective ($interval) {
return {
restrict: 'AC',
link: function (scope, element, attrs) {
element.addClass('my-carousel');
var currentSlide = 1,
allSlides = element.find('section'),... | () {
if(currentSlide > slideCount) {
currentSlide = 1;
}
else if(currentSlide <= 0) {
currentSlide = slideCount;
}
}
var tick = $interval(function() {
console.log('carousel tick');
scope.nextSlide();
}, 5000);
function cancelI... | boundaries | identifier_name |
mod.rs | &str = "Can not covert from ";
/// The types of `Json` which follows https://tools.ietf.org/html/rfc7159#section-3
#[derive(Eq, PartialEq, FromPrimitive, Clone, Debug, Copy)]
pub enum JsonType {
Object = 0x01,
Array = 0x03,
Literal = 0x04,
I64 = 0x09,
U64 = 0x0a,
Double = 0x0b,
String = 0x... |
/// Creates a `number` JSON from an `i64`
pub fn from_i64(v: i64) -> Result<Self> {
let mut value = vec![];
value.write_json_i64(v)?;
Ok(Self::new(JsonType::I64, value))
}
/// Creates a `array` JSON from a collection of `JsonRef`
pub fn from_ref_array(array: Vec<JsonRef<'_... | {
let mut value = vec![];
value.write_json_f64(v)?;
Ok(Self::new(JsonType::Double, value))
} | identifier_body |
mod.rs | : &str = "Can not covert from ";
/// The types of `Json` which follows https://tools.ietf.org/html/rfc7159#section-3
#[derive(Eq, PartialEq, FromPrimitive, Clone, Debug, Copy)]
pub enum JsonType {
Object = 0x01,
Array = 0x03,
Literal = 0x04,
I64 = 0x09,
U64 = 0x0a,
Double = 0x0b,
String = 0... | (&self) -> &'a [u8] {
&self.value
}
// Returns the JSON value as u64
//
// See `GetUint64()` in TiDB `json/binary.go`
pub(crate) fn get_u64(&self) -> u64 {
assert_eq!(self.type_code, JsonType::U64);
NumberCodec::decode_u64_le(self.value())
}
// Returns the JSON valu... | value | identifier_name |
mod.rs | //! array |
//! literal |
//! number |
//! string |
//! object ::= element-count size key-entry* value-entry* key* value*
//! array ::= element-count size value-entry* value*
//!
//! // the number of members in object or number of elements in array
//! element-count ::= uint32
//!
//... | //! object | | random_line_split | |
pypowerscout.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# from http://homepage.hispeed.ch/py430/python/daemon.py
###########################################################################
# configure these paths:
LOGFILE = '/var/log/powerscout.log'
PIDFILE = '/var/run/powerscout.pid'
# and let USERPROG be the main function of ... | except OSError, e:
print >>sys.stderr, "fork #2 failed: %d (%s)" % (e.errno, e.strerror)
sys.exit(1)
# start the daemon main loop
main() | pen(PIDFILE,'w').write("%d"%pid)
sys.exit(0)
| conditional_block |
pypowerscout.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# from http://homepage.hispeed.ch/py430/python/daemon.py
###########################################################################
# configure these paths:
LOGFILE = '/var/log/powerscout.log'
PIDFILE = '/var/run/powerscout.pid'
# and let USERPROG be the main function of ... | def write(self, s):
self.f.write(s)
self.f.flush()
def main():
#change to data directory if needed
os.chdir("/")
#redirect outputs to a logfile
sys.stdout = sys.stderr = Log(open(LOGFILE, 'a+'))
#ensure the that the daemon runs a normal user
#os.setegid(20) #set group fi... | elf.f = f
| identifier_body |
pypowerscout.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# from http://homepage.hispeed.ch/py430/python/daemon.py
###########################################################################
# configure these paths:
LOGFILE = '/var/log/powerscout.log'
PIDFILE = '/var/run/powerscout.pid'
# and let USERPROG be the main function of ... | if __name__ == "__main__":
# do the UNIX double-fork magic, see Stevens' "Advanced
# Programming in the UNIX Environment" for details (ISBN 0201563177)
try:
pid = os.fork()
if pid > 0:
# exit first parent
sys.exit(0)
except OSError, e:
print >>sys.stderr, ... | os.setegid(0)
os.seteuid(0)
#start the user program here:
USERPROG()
| random_line_split |
pypowerscout.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# from http://homepage.hispeed.ch/py430/python/daemon.py
###########################################################################
# configure these paths:
LOGFILE = '/var/log/powerscout.log'
PIDFILE = '/var/run/powerscout.pid'
# and let USERPROG be the main function of ... | ):
#change to data directory if needed
os.chdir("/")
#redirect outputs to a logfile
sys.stdout = sys.stderr = Log(open(LOGFILE, 'a+'))
#ensure the that the daemon runs a normal user
#os.setegid(20) #set group first "dialout" so we can access port
#os.seteuid(1000) #set user "pydaemon... | ain( | identifier_name |
client.rs | // Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0.
#[macro_use]
extern crate log;
use rand;
#[macro_use]
extern crate serde_derive;
#[path = "../log_util.rs"]
mod log_util;
mod util;
use std::sync::Arc;
use std::thread;
use std::time::Duration;
use futures_util::{SinkExt as _, TryStreamExt as _};
us... |
info!("-------------- RecordRoute --------------");
record_route(&client).await?;
info!("-------------- RouteChat --------------");
route_chat(&client).await?;
Ok(())
}
fn main() {
futures_executor::block_on(async_main()).unwrap()
} | random_line_split | |
client.rs | // Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0.
#[macro_use]
extern crate log;
use rand;
#[macro_use]
extern crate serde_derive;
#[path = "../log_util.rs"]
mod log_util;
mod util;
use std::sync::Arc;
use std::thread;
use std::time::Duration;
use futures_util::{SinkExt as _, TryStreamExt as _};
us... |
async fn record_route(client: &RouteGuideClient) -> Result<()> {
let features = util::load_db();
let mut rng = rand::thread_rng();
let (mut sink, receiver) = client.record_route()?;
for _ in 0..10usize {
let f = features.choose(&mut rng).unwrap();
let point = f.get_location();
... | {
let rect = new_rect(400_000_000, -750_000_000, 420_000_000, -730_000_000);
info!("Looking for features between 40, -75 and 42, -73");
let mut list_features = client.list_features(&rect)?;
while let Some(feature) = list_features.try_next().await? {
let loc = feature.get_location();
info... | identifier_body |
client.rs | // Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0.
#[macro_use]
extern crate log;
use rand;
#[macro_use]
extern crate serde_derive;
#[path = "../log_util.rs"]
mod log_util;
mod util;
use std::sync::Arc;
use std::thread;
use std::time::Duration;
use futures_util::{SinkExt as _, TryStreamExt as _};
us... |
if f.get_name().is_empty() {
warn!("Found no feature at {}", util::format_point(point));
return Ok(());
}
info!(
"Found feature called {} at {}",
f.get_name(),
util::format_point(point)
);
Ok(())
}
async fn list_features(client: &RouteGuideClient) -> Result<... | {
warn!("Server returns incomplete feature.");
return Ok(());
} | conditional_block |
client.rs | // Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0.
#[macro_use]
extern crate log;
use rand;
#[macro_use]
extern crate serde_derive;
#[path = "../log_util.rs"]
mod log_util;
mod util;
use std::sync::Arc;
use std::thread;
use std::time::Duration;
use futures_util::{SinkExt as _, TryStreamExt as _};
us... | (client: &RouteGuideClient) -> Result<()> {
let (mut sink, mut receiver) = client.route_chat()?;
let send = async move {
let notes = vec![
("First message", 0, 0),
("Second message", 0, 1),
("Third message", 1, 0),
("Fourth message", 0, 0),
];
... | route_chat | identifier_name |
print_mail.py | import os
import sys
import glob
import json
import subprocess
from collections import defaultdict
from utils import UnicodeReader, slugify, count_pages, combine_pdfs, parser
import addresscleaner
from click2mail import Click2MailBatch
parser.add_argument("directory", help="Path to downloaded mail batch")
parser.add_... | (mailing_dir, letters, page=1):
# Sort by recipient.
recipient_letters = defaultdict(list)
for letter in letters:
recipient_letters[(letter['recipient'], letter['sender'])].append(letter)
# Assemble list of files and jobs.
files = []
jobs = {}
for (recipient, sender), letters in rec... | collate_letters | identifier_name |
print_mail.py | import os
import sys
import glob
import json
import subprocess
from collections import defaultdict
from utils import UnicodeReader, slugify, count_pages, combine_pdfs, parser
import addresscleaner
from click2mail import Click2MailBatch
parser.add_argument("directory", help="Path to downloaded mail batch")
parser.add_... |
def main():
args = parser.parse_args()
if args.directory.endswith(".zip"):
directory = os.path.abspath(args.directory[0:-len(".zip")])
if not os.path.exists(directory):
subprocess.check_call([
"unzip", args.directory, "-d", os.path.dirname(args.directory)
... | filename = combine_pdfs(files)
print "Building job with", filename
batch = Click2MailBatch(
username=args.username,
password=args.password,
filename=filename,
jobs=jobs,
staging=args.staging)
if batch.run(args.dry_run):
os.remove(filename) | identifier_body |
print_mail.py | import os
import sys
import glob
import json
import subprocess
from collections import defaultdict
from utils import UnicodeReader, slugify, count_pages, combine_pdfs, parser
import addresscleaner
from click2mail import Click2MailBatch
parser.add_argument("directory", help="Path to downloaded mail batch")
parser.add_... |
end = page + count
jobs[recipient] = {
"startingPage": page,
"endingPage": end - 1,
"recipients": [fix_lines(addresscleaner.parse_address(recipient))],
"sender": addresscleaner.parse_address(sender),
"type": "letter"
}
... | filename = os.path.join(mailing_dir, letter["file"])
files.append(filename)
count += count_pages(filename) | conditional_block |
print_mail.py | import os
import sys
import glob
import json
import subprocess
from collections import defaultdict
from utils import UnicodeReader, slugify, count_pages, combine_pdfs, parser
import addresscleaner
from click2mail import Click2MailBatch
parser.add_argument("directory", help="Path to downloaded mail batch")
parser.add_... | "organization", and subsequent ones in "addressN".
"""
lines = [a for a in [
address.get('organization', None),
address.get('address1', None),
address.get('address2', None),
address.get('address3', None)] if a]
if len(lines) == 1:
address['organization'] = ''
... | line, put it in "address1". If we have more, put the first in | random_line_split |
keyboardEvent.ts | define(33, KeyCode.PageUp);
define(34, KeyCode.PageDown);
define(35, KeyCode.End);
define(36, KeyCode.Home);
define(37, KeyCode.LeftArrow);
define(38, KeyCode.UpArrow);
define(39, KeyCode.RightArrow);
define(40, KeyCode.DownArrow);
define(45, KeyCode.Insert);
define(46, KeyCode.Delete);
define(48, KeyCode.K... | {
result |= altKeyMod;
} | conditional_block | |
keyboardEvent.ts | KeyCode.KEY_4);
define(53, KeyCode.KEY_5);
define(54, KeyCode.KEY_6);
define(55, KeyCode.KEY_7);
define(56, KeyCode.KEY_8);
define(57, KeyCode.KEY_9);
define(65, KeyCode.KEY_A);
define(66, KeyCode.KEY_B);
define(67, KeyCode.KEY_C);
define(68, KeyCode.KEY_D);
define(69, KeyCode.KEY_E);
define(70, KeyCode.KE... | {
let key = KeyCode.Unknown;
if (this.keyCode !== KeyCode.Ctrl && this.keyCode !== KeyCode.Shift && this.keyCode !== KeyCode.Alt && this.keyCode !== KeyCode.Meta) {
key = this.keyCode;
}
return new SimpleKeybinding(this.ctrlKey, this.shiftKey, this.altKey, this.metaKey, key);
} | identifier_body | |
keyboardEvent.ts | number, keyCode: KeyCode): void {
KEY_CODE_MAP[code] = keyCode;
INVERSE_KEY_CODE_MAP[keyCode] = code;
}
define(3, KeyCode.PauseBreak); // VK_CANCEL 0x03 Control-break processing
define(8, KeyCode.Backspace);
define(9, KeyCode.Tab);
define(13, KeyCode.Enter);
define(16, KeyCode.Shift);
define(17, KeyCode.Ct... | }
| random_line_split | |
keyboardEvent.ts | 0; i < INVERSE_KEY_CODE_MAP.length; i++) {
INVERSE_KEY_CODE_MAP[i] = -1;
}
function define(code: number, keyCode: KeyCode): void {
KEY_CODE_MAP[code] = keyCode;
INVERSE_KEY_CODE_MAP[keyCode] = code;
}
define(3, KeyCode.PauseBreak); // VK_CANCEL 0x03 Control-break processing
define(8, KeyCode.Backspace);
... | (keyCode: KeyCode): number {
return INVERSE_KEY_CODE_MAP[keyCode];
}
export interface IKeyboardEvent {
readonly browserEvent: KeyboardEvent;
readonly target: HTMLElement;
readonly ctrlKey: boolean;
readonly shiftKey: boolean;
readonly altKey: boolean;
readonly metaKey: boolean;
readonly keyCode: KeyCode;
rea... | getCodeForKeyCode | identifier_name |
disable-submit.js | /**
* Copyright 2017-present, Facebook, Inc. All rights reserved.
*
* This source code is licensed under the license found in the
* LICENSE file in the root directory of this source tree.
*/
/* eslint-disable max-len */
/**
* Displays the password mismatch error message and status icons.
*
* @returns {undefin... | lse {
console.log("the field am calling is",field);
removeStatusFromField(field);
}
});
passwordsMatch();
};
/**
* Apply check icon to all filled out fieldsets marked required
*
* @returns {Boolean} true if all required fields have been filled
*/
const requiredFieldsFilled = () => {
const requir... | console.log("field value is",field)
//applyCheckToField(field);
} e | conditional_block |
disable-submit.js | /**
* Copyright 2017-present, Facebook, Inc. All rights reserved.
*
* This source code is licensed under the license found in the
* LICENSE file in the root directory of this source tree.
*/
/* eslint-disable max-len */
/**
* Displays the password mismatch error message and status icons.
*
* @returns {undefin... | const applyCheckToFilledFields = () => {
const requiredFields = Array.apply(
null,
document.getElementsByClassName('required')
);
requiredFields.forEach((field) => {
if (field.value) {
console.log("field value is",field)
//applyCheckToField(field);
} else {
console.log("the field am ca... | /**
* Apply check icon to all filled out fieldsets marked required
*
* @returns {undefined}
*/ | random_line_split |
converters.py | # -*- coding: utf-8 -*-
# Module containing functions for converting biofloat DataFrames to other formats
from collections import OrderedDict
def | (df, odv_file_name, vars=None):
'''Output biofloat DataFrame in Ocean Data View spreadsheet format to
file named odv_file_name. Pass in a OrderedDict named vars to override
the default variable list of TEMP_ADJUSTED, PSAL_ADJUSTED, DOXY_ADJUSTED.
'''
fixed_bot_depth = 4000.0
if not vars:
... | to_odv | identifier_name |
converters.py | # -*- coding: utf-8 -*-
# Module containing functions for converting biofloat DataFrames to other formats
from collections import OrderedDict
def to_odv(df, odv_file_name, vars=None):
|
header = header_base + header_vars + '\n'
with open(odv_file_name, 'w') as odv:
odv.write(header)
for i, r in df.iterrows():
rec_base = [i[0], i[4], 'C', i[1].strftime('%m/%d/%Y'),
i[1].strftime('%H:%M'), i[2], i[3], fixed_bot_depth,
... | '''Output biofloat DataFrame in Ocean Data View spreadsheet format to
file named odv_file_name. Pass in a OrderedDict named vars to override
the default variable list of TEMP_ADJUSTED, PSAL_ADJUSTED, DOXY_ADJUSTED.
'''
fixed_bot_depth = 4000.0
if not vars:
vars = OrderedDict([
... | identifier_body |
converters.py | # -*- coding: utf-8 -*-
# Module containing functions for converting biofloat DataFrames to other formats
from collections import OrderedDict
def to_odv(df, odv_file_name, vars=None):
'''Output biofloat DataFrame in Ocean Data View spreadsheet format to
file named odv_file_name. Pass in a OrderedDict named va... | rec_base = [i[0], i[4], 'C', i[1].strftime('%m/%d/%Y'),
i[1].strftime('%H:%M'), i[2], i[3], fixed_bot_depth,
i[5], 0]
rec_vars = '\t'.join([('{:f}\t0').format(r[v])
for v in vars.keys()])
odv.write(fmt_base.form... | conditional_block | |
converters.py | # -*- coding: utf-8 -*-
# Module containing functions for converting biofloat DataFrames to other formats
from collections import OrderedDict
def to_odv(df, odv_file_name, vars=None):
'''Output biofloat DataFrame in Ocean Data View spreadsheet format to | the default variable list of TEMP_ADJUSTED, PSAL_ADJUSTED, DOXY_ADJUSTED.
'''
fixed_bot_depth = 4000.0
if not vars:
vars = OrderedDict([
('TEMP_ADJUSTED', 'degree_Celsius'),
('PSAL_ADJUSTED', 'psu'),
('DOXY_ADJUS... | file named odv_file_name. Pass in a OrderedDict named vars to override | random_line_split |
directive-helpers.d.ts | /**
* @license
* Copyright 2020 Google LLC
* SPDX-License-Identifier: BSD-3-Clause
*/
import { Part, DirectiveParent, TemplateResult } from './lit-html.js';
import { DirectiveResult, DirectiveClass, PartInfo } from './directive.js';
declare type Primitive = null | undefined | boolean | number | string | symbol | bi... | export declare const TemplateResultType: {
readonly HTML: 1;
readonly SVG: 2;
};
export declare type TemplateResultType = typeof TemplateResultType[keyof typeof TemplateResultType];
/**
* Tests if a value is a TemplateResult.
*/
export declare const isTemplateResult: (value: unknown, type?: TemplateResultType... | * See https://tc39.github.io/ecma262/#sec-typeof-operator
*/
export declare const isPrimitive: (value: unknown) => value is Primitive; | random_line_split |
test_connect_helpers.py | # GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with NEST. If not, see <http://www.gnu.org/licenses/>.
import numpy as np
import scipy.stats
import nest
from scipy.stats import truncexpon
try:
from mpi4py import MPI
haveMPI4Py = Tru... | (data_array):
'''
Gathers data from all mpi processes by collecting all element in a list if
data is a list and summing all elements to one numpy-array if data is one
numpy-array. Returns gathered data if rank of current mpi node is zero and
None otherwise.
'''
if haveMPI4Py:
data_a... | gather_data | identifier_name |
test_connect_helpers.py | # GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with NEST. If not, see <http://www.gnu.org/licenses/>.
import numpy as np
import scipy.stats
import nest
from scipy.stats import truncexpon
try:
from mpi4py import MPI
haveMPI4Py = Tru... |
# copied from Masterthesis, Daniel Hjertholm
def counter(x, fan, source_pop, target_pop):
'''
Count similar elements in list.
Parameters
----------
x: Any list.
Return values
-------------
list containing counts of similar elements.
'''
N_p = len(source_pop) if fan... | conns = nest.GetConnections(TestCase.pop1, TestCase.pop2)
conn_params = conns.get(param)
TestCase.assertTrue(all_equal(conn_params))
TestCase.assertTrue(conn_params[0] == values[i]) | conditional_block |
test_connect_helpers.py |
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with NEST. If not, see <http://www.gnu.org/licenses/>.
import numpy as np
import scipy.stats
import nest
from scipy.stats import truncexpon
try:
from mpi4py import MPI
haveMPI4Py = Tr... | data_front[-1] = (deg, exp + cumexp, obs,
num + bins_combined)
else:
continue
else:
data_front.append((degree - bins_combined + 1, cumexp, 0,
bins_combined))
cumexp = 0.0
... | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.