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 |
|---|---|---|---|---|
toaiff.py | """Convert "arbitrary" sound files to AIFF (Apple and SGI's audio format).
Input may be compressed.
Uncompressed file type may be AIFF, WAV, VOC, 8SVX, NeXT/Sun, and others.
An exception is raised if the file is not of a recognized type.
Returned filename is either the input filename or a temporary filename;
in the la... | if type(msg) == type(()) and len(msg) == 2 and \
type(msg[0]) == type(0) and type(msg[1]) == type(''):
msg = msg[1]
if type(msg) != type(''):
msg = `msg`
raise error, filename + ': ' + msg
if ftype == 'aiff':
return fname
if ftype is None o... | if ftype:
ftype = ftype[0] # All we're interested in
except IOError, msg: | random_line_split |
toaiff.py | """Convert "arbitrary" sound files to AIFF (Apple and SGI's audio format).
Input may be compressed.
Uncompressed file type may be AIFF, WAV, VOC, 8SVX, NeXT/Sun, and others.
An exception is raised if the file is not of a recognized type.
Returned filename is either the input filename or a temporary filename;
in the la... |
def toaiff(filename):
temps = []
ret = None
try:
ret = _toaiff(filename, temps)
finally:
for temp in temps[:]:
if temp != ret:
try:
os.unlink(temp)
except os.error:
pass
temps.remove(tem... | pass | identifier_body |
toaiff.py | """Convert "arbitrary" sound files to AIFF (Apple and SGI's audio format).
Input may be compressed.
Uncompressed file type may be AIFF, WAV, VOC, 8SVX, NeXT/Sun, and others.
An exception is raised if the file is not of a recognized type.
Returned filename is either the input filename or a temporary filename;
in the la... | (filename):
temps = []
ret = None
try:
ret = _toaiff(filename, temps)
finally:
for temp in temps[:]:
if temp != ret:
try:
os.unlink(temp)
except os.error:
pass
temps.remove(temp)
retur... | toaiff | identifier_name |
threaded.py | import queue
import logging
import platform
import threading
import datetime as dt
import serial
import serial.threaded
import serial_device
from .or_event import OrEvent
logger = logging.getLogger(__name__)
# Flag to indicate whether queues should be polled.
# XXX Note that polling performance may vary by platfor... |
self.connected.clear()
# Loop to try to reconnect to serial device.
def write(self, data, timeout_s=None):
'''
Write to serial port.
Waits for serial connection to be established before writing.
Parameters
----------
data : ... | self.closed.set()
return | conditional_block |
threaded.py | import queue
import logging
import platform
import threading
import datetime as dt
import serial
import serial.threaded
import serial_device
from .or_event import OrEvent
logger = logging.getLogger(__name__)
# Flag to indicate whether queues should be polled.
# XXX Note that polling performance may vary by platfor... | while True:
# Wait for requested serial port to become available.
while self.comport not in (serial_device
.comports(only_available=True).index):
# Assume serial port was disconnected temporarily. Wait and
# periodic... | random_line_split | |
threaded.py | import queue
import logging
import platform
import threading
import datetime as dt
import serial
import serial.threaded
import serial_device
from .or_event import OrEvent
logger = logging.getLogger(__name__)
# Flag to indicate whether queues should be polled.
# XXX Note that polling performance may vary by platfor... | (self, protocol_class, comport, **kwargs):
super(KeepAliveReader, self).__init__()
self.daemon = True
self.protocol_class = protocol_class
self.comport = comport
self.kwargs = kwargs
self.protocol = None
self.default_timeout_s = kwargs.pop('default_timeout_s', Non... | __init__ | identifier_name |
threaded.py | import queue
import logging
import platform
import threading
import datetime as dt
import serial
import serial.threaded
import serial_device
from .or_event import OrEvent
logger = logging.getLogger(__name__)
# Flag to indicate whether queues should be polled.
# XXX Note that polling performance may vary by platfor... |
def request(device, response_queue, payload, timeout_s=None, poll=POLL_QUEUES):
'''
Send payload to serial device and wait for response.
Parameters
----------
device : serial.Serial
Serial instance.
response_queue : Queue.Queue
Queue to wait for response on.
payload : str... | """Leave context: close port"""
self.close()
self.closed.wait() | identifier_body |
getNoTestsFoundMessage.ts | /**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import type {Config} from '@jest/types';
import getNoTestFound from './getNoTestFound';
import getNoTestFound... | {
if (globalConfig.onlyFailures) {
return getNoTestFoundFailed(globalConfig);
}
if (globalConfig.onlyChanged) {
return getNoTestFoundRelatedToChangedFiles(globalConfig);
}
if (globalConfig.passWithNoTests) {
return getNoTestFoundPassWithNoTests();
}
return testRunData.length === 1 || globalCon... | identifier_body | |
getNoTestsFoundMessage.ts | /** | */
import type {Config} from '@jest/types';
import getNoTestFound from './getNoTestFound';
import getNoTestFoundFailed from './getNoTestFoundFailed';
import getNoTestFoundPassWithNoTests from './getNoTestFoundPassWithNoTests';
import getNoTestFoundRelatedToChangedFiles from './getNoTestFoundRelatedToChangedFiles';
im... | * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree. | random_line_split |
getNoTestsFoundMessage.ts | /**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import type {Config} from '@jest/types';
import getNoTestFound from './getNoTestFound';
import getNoTestFound... |
if (globalConfig.passWithNoTests) {
return getNoTestFoundPassWithNoTests();
}
return testRunData.length === 1 || globalConfig.verbose
? getNoTestFoundVerbose(testRunData, globalConfig)
: getNoTestFound(testRunData, globalConfig);
}
| {
return getNoTestFoundRelatedToChangedFiles(globalConfig);
} | conditional_block |
getNoTestsFoundMessage.ts | /**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import type {Config} from '@jest/types';
import getNoTestFound from './getNoTestFound';
import getNoTestFound... | (
testRunData: TestRunData,
globalConfig: Config.GlobalConfig,
): string {
if (globalConfig.onlyFailures) {
return getNoTestFoundFailed(globalConfig);
}
if (globalConfig.onlyChanged) {
return getNoTestFoundRelatedToChangedFiles(globalConfig);
}
if (globalConfig.passWithNoTests) {
return getNoT... | getNoTestsFoundMessage | identifier_name |
app.component.spec.ts | /**
* Copyright 2020 BloomReach Inc. (https://www.bloomreach.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unles... |
describe('AppComponent', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
HttpClientTestingModule,
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useFactory: HttpLoaderFactory,
deps: [ HttpClient ]
... | {
return new TranslateHttpLoader(http, './i18n/', `.json`);
} | identifier_body |
app.component.spec.ts | /**
* Copyright 2020 BloomReach Inc. (https://www.bloomreach.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unles... | }); | random_line_split | |
app.component.spec.ts | /**
* Copyright 2020 BloomReach Inc. (https://www.bloomreach.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unles... | (http: HttpClient) {
return new TranslateHttpLoader(http, './i18n/', `.json`);
}
describe('AppComponent', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
HttpClientTestingModule,
TranslateModule.forRoot({
loader: {
provide: TranslateLoade... | HttpLoaderFactory | identifier_name |
query.py | import os
from hanziconv import HanziConv # 简繁转换
from app.ResultParse import ResultParse
from app.statistics import analysis
from interface.api import LookUp, Search, Association
from tools.parse_and_filter import parse_sentence
from tools.translate import Translate
class Query:
def __init__(self, debug=False)... | ion, Type='c', lang='zh', limit=100, s_to_t=True):
lookup = LookUp(lang=lang, Type=Type, limit=limit)
if s_to_t:
data = lookup.search_concept(HanziConv.toTraditional(conception))
else:
data = lookup.search_concept(conception)
r = ResultParse(data)
if r.ge... | kup(concept | identifier_name |
query.py | import os
from hanziconv import HanziConv # 简繁转换
from app.ResultParse import ResultParse
from app.statistics import analysis
from interface.api import LookUp, Search, Association
from tools.parse_and_filter import parse_sentence
from tools.translate import Translate
class Query:
def __init__(self, debug=False)... | # print("句子是"+sentence)
query.commonsense_query(sentence)
query.stastics() | random_line_split | |
query.py | import os
from hanziconv import HanziConv # 简繁转换
from app.ResultParse import ResultParse
from app.statistics import analysis
from interface.api import LookUp, Search, Association
from tools.parse_and_filter import parse_sentence
from tools.translate import Translate
class Query:
def __init__(self, debug=False)... | f.conceptions = parse_sentence(sentences)
self.concept_search(False)
# self.conception_association()
# self.tranlate_to_simple()
return self.commonsense
def stastics(self):
len_conceptiton = len(self.conceptions)
self.analysis.write_commonsense(self.commonsense... | nziConv.toSimplified(item[0]) if item[0] else 'No text'
s = HanziConv.toSimplified(item[1])
e = HanziConv.toSimplified(item[2])
self.commonsense.remove(item)
self.commonsense.add((text, s, e, item[3]))
def commonsense_query(self, sentences):
sel | identifier_body |
query.py | import os
from hanziconv import HanziConv # 简繁转换
from app.ResultParse import ResultParse
from app.statistics import analysis
from interface.api import LookUp, Search, Association
from tools.parse_and_filter import parse_sentence
from tools.translate import Translate
class Query:
def __init__(self, debug=False)... | conditional_block | ||
aiplatform_generated_aiplatform_v1beta1_metadata_service_query_context_lineage_subgraph_async.py | # -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
# | # http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing pe... | # 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
# | random_line_split |
aiplatform_generated_aiplatform_v1beta1_metadata_service_query_context_lineage_subgraph_async.py | # -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | ():
# Create a client
client = aiplatform_v1beta1.MetadataServiceAsyncClient()
# Initialize request argument(s)
request = aiplatform_v1beta1.QueryContextLineageSubgraphRequest(
context="context_value",
)
# Make the request
response = await client.query_context_lineage_subgraph(requ... | sample_query_context_lineage_subgraph | identifier_name |
aiplatform_generated_aiplatform_v1beta1_metadata_service_query_context_lineage_subgraph_async.py | # -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... |
# [END aiplatform_generated_aiplatform_v1beta1_MetadataService_QueryContextLineageSubgraph_async]
| client = aiplatform_v1beta1.MetadataServiceAsyncClient()
# Initialize request argument(s)
request = aiplatform_v1beta1.QueryContextLineageSubgraphRequest(
context="context_value",
)
# Make the request
response = await client.query_context_lineage_subgraph(request=request)
# Handle the... | identifier_body |
lib.rs | of the License, or
// (at your option) any later version.
// Seni 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 Affero General Public License for more details.
// You should ... | () {
// vm.ip wasn't being set to 0 in-between running the preamble and running the user's program
let mut vm: Vm = Default::default();
let mut context: Context = Default::default();
let s = "(rect)";
is_rendering_num_verts(&mut vm, &mut context, &s, 4);
}
// #[test]
... | bug_running_preamble_crashed_vm | identifier_name |
lib.rs | of the License, or
// (at your option) any later version.
// Seni 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 Affero General Public License for more details.
// You should ... |
#[cfg(test)]
pub mod tests {
use super::*;
fn is_rendering_num_verts(
vm: &mut Vm,
context: &mut Context,
s: &str,
expected_num_verts: usize,
) {
let program = program_from_source(s).unwrap();
let _ = run_program_with_preamble(vm, context, &program).unwrap(... | {
s.len() as i32
} | identifier_body |
lib.rs | 3 of the License, or
// (at your option) any later version.
// Seni 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 | // along with this program. If not, see <https://www.gnu.org/licenses/>.
#![cfg_attr(
feature = "cargo-clippy",
allow(
clippy::many_single_char_names,
clippy::too_many_arguments,
clippy::excessive_precision
)
)]
/*!
The core crate provides the basic functionality of the Seni syste... | // GNU Affero General Public License for more details.
// You should have received a copy of the GNU Affero General Public License | random_line_split |
table_core.js |
/*
* mobile table unit tests
*/
(function($){
module( "Basic Table", {
setup: function(){
var hash = "#basic-table-test";
if( location.hash != hash ){
stop();
$(document).one("pagechange", function() {
start();
});
$.mobile.changePage( hash );
}
},
teardown: function() {
}... | else {
ok( headers.is( ".ui-table-cell-hidden" ) );
}
}, 800);
},
function() {
start();
}
]);
});
})(jQuery);
| {
ok( headers.not( ".ui-table-cell-hidden" ) );
} | conditional_block |
table_core.js | /*
* mobile table unit tests
*/
(function($){
module( "Basic Table", {
setup: function(){
var hash = "#basic-table-test";
if( location.hash != hash ){
stop();
$(document).one("pagechange", function() {
start();
});
$.mobile.changePage( hash );
} | },
teardown: function() {
}
});
asyncTest( "The page should be enhanced correctly" , function(){
setTimeout(function() {
var $table = $('#basic-table-test .ui-table');
ok( $table.length, ".ui-table class added to table element" );
start();
}, 800);
});
asyncTest( "Has data object attributed to t... | random_line_split | |
dummy_variables.rs | use std::default::Default;
use std::marker::PhantomData;
use variable::GetVariable;
/// Struct that implement [`Index`],
/// used to fake variables when don't needed in expressions.
///
/// Prefer using this container with the [`DummyVariable`] fake type.
///
/// [`Index`]: https://doc.rust-lang.org/std/ops/trait.Inde... |
}
impl<T> GetVariable<()> for DummyVariables<T> {
type Output = T;
fn get_variable(&self, _: ()) -> Option<&Self::Output> {
None
}
}
| {
DummyVariables(PhantomData::default())
} | identifier_body |
dummy_variables.rs | use std::default::Default;
use std::marker::PhantomData;
use variable::GetVariable;
/// Struct that implement [`Index`],
/// used to fake variables when don't needed in expressions.
///
/// Prefer using this container with the [`DummyVariable`] fake type.
///
/// [`Index`]: https://doc.rust-lang.org/std/ops/trait.Inde... | }
}
impl<T> GetVariable<()> for DummyVariables<T> {
type Output = T;
fn get_variable(&self, _: ()) -> Option<&Self::Output> {
None
}
} | fn default() -> Self {
DummyVariables(PhantomData::default()) | random_line_split |
dummy_variables.rs | use std::default::Default;
use std::marker::PhantomData;
use variable::GetVariable;
/// Struct that implement [`Index`],
/// used to fake variables when don't needed in expressions.
///
/// Prefer using this container with the [`DummyVariable`] fake type.
///
/// [`Index`]: https://doc.rust-lang.org/std/ops/trait.Inde... | (&self, _: ()) -> Option<&Self::Output> {
None
}
}
| get_variable | identifier_name |
switch.py | """
Support for Eneco Slimmer stekkers (Smart Plugs).
This provides controls for the z-wave smart plugs Toon can control.
"""
import logging
from homeassistant.components.switch import SwitchDevice
import custom_components.toon as toon_main
_LOGGER = logging.getLogger(__name__)
def setup_platform(hass, config, add... | (self):
"""Return the ID of this switch."""
return self.smartplug.device_uuid
@property
def name(self):
"""Return the name of the switch if any."""
return self.smartplug.name
@property
def current_power_w(self):
"""Current power usage in W."""
return sel... | unique_id | identifier_name |
switch.py | """
Support for Eneco Slimmer stekkers (Smart Plugs).
This provides controls for the z-wave smart plugs Toon can control.
"""
import logging
from homeassistant.components.switch import SwitchDevice
import custom_components.toon as toon_main
_LOGGER = logging.getLogger(__name__)
def setup_platform(hass, config, add... |
@property
def name(self):
"""Return the name of the switch if any."""
return self.smartplug.name
@property
def current_power_w(self):
"""Current power usage in W."""
return self.toon_data_store.get_data('current_power', self.name)
@property
def today_energy_kw... | """Return the ID of this switch."""
return self.smartplug.device_uuid | identifier_body |
switch.py | """
Support for Eneco Slimmer stekkers (Smart Plugs).
This provides controls for the z-wave smart plugs Toon can control.
"""
import logging
from homeassistant.components.switch import SwitchDevice
import custom_components.toon as toon_main
_LOGGER = logging.getLogger(__name__)
def setup_platform(hass, config, add... |
add_devices_callback(switch_items)
class EnecoSmartPlug(SwitchDevice):
"""Representation of a Smart Plug."""
def __init__(self, hass, plug):
"""Initialize the Smart Plug."""
self.smartplug = plug
self.toon_data_store = hass.data[toon_main.TOON_HANDLE]
@property
def shou... | switch_items.append(EnecoSmartPlug(hass, plug)) | conditional_block |
switch.py | """
Support for Eneco Slimmer stekkers (Smart Plugs).
This provides controls for the z-wave smart plugs Toon can control.
"""
import logging
from homeassistant.components.switch import SwitchDevice
import custom_components.toon as toon_main
_LOGGER = logging.getLogger(__name__)
def setup_platform(hass, config, add... |
@property
def available(self):
"""True if switch is available."""
return self.smartplug.can_toggle
def turn_on(self, **kwargs):
"""Turn the switch on."""
return self.smartplug.turn_on()
def turn_off(self):
"""Turn the switch off."""
return self.smartplu... | """Return true if switch is on. Standby is on."""
return self.toon_data_store.get_data('current_state', self.name) | random_line_split |
graph.rs | ;
// use ::Diff;
// use lattice::Lattice;
use trace::{Batch, BatchReader, Builder, Merger, Cursor, Trace, TraceReader};
use trace::description::Description;
use trace::rc_blanket_impls::RcBatchCursor;
// use trace::layers::MergeBuilder;
use super::spine_fueled::Spine;
use super::merge_batcher::MergeBatcher;
use ti... |
fn close(&mut self) {
self.spine.close()
}
}
///
#[derive(Debug, Abomonation)]
pub struct GraphBatch<N> {
index: usize,
peers: usize,
keys: Vec<Node>,
nodes: Vec<usize>,
edges: Vec<N>,
desc: Description<Product<RootTimestamp,()>>,
}
impl<N> BatchReader<Node, N, Product<RootTi... | {
self.spine.insert(batch)
} | identifier_body |
graph.rs | ;
// use ::Diff;
// use lattice::Lattice;
use trace::{Batch, BatchReader, Builder, Merger, Cursor, Trace, TraceReader};
use trace::description::Description;
use trace::rc_blanket_impls::RcBatchCursor;
// use trace::layers::MergeBuilder;
use super::spine_fueled::Spine;
use super::merge_batcher::MergeBatcher;
use ti... |
}
fn rewind_keys(&mut self, storage: &Self::Storage) { self.key_pos = 0; self.key = storage.index as Node; }
fn rewind_vals(&mut self, storage: &Self::Storage) {
if self.key_valid(storage) {
self.val_pos = storage.nodes[self.key_pos];
}
}
}
/// A builder for creating layers... | {
let lower = self.val_pos;
let upper = storage.nodes[self.key_pos + 1];
self.val_pos += advance(&storage.edges[lower .. upper], |tuple| tuple < val);
} | conditional_block |
graph.rs | ;
// use ::Diff;
// use lattice::Lattice;
use trace::{Batch, BatchReader, Builder, Merger, Cursor, Trace, TraceReader};
use trace::description::Description;
use trace::rc_blanket_impls::RcBatchCursor;
// use trace::layers::MergeBuilder;
use super::spine_fueled::Spine;
use super::merge_batcher::MergeBatcher;
use ti... | }
}
// Ideally, this method acts as insertion of `batch`, even if we are not yet able to begin
// merging the batch. This means it is a good time to perform amortized work proportional
// to the size of batch.
fn insert(&mut self, batch: Self::Batch) {
self.spine.insert(batch)
}... | GraphSpine {
spine: Spine::<Node, N, Product<RootTimestamp, ()>, isize, Rc<GraphBatch<N>>>::new() | random_line_split |
graph.rs | ;
// use ::Diff;
// use lattice::Lattice;
use trace::{Batch, BatchReader, Builder, Merger, Cursor, Trace, TraceReader};
use trace::description::Description;
use trace::rc_blanket_impls::RcBatchCursor;
// use trace::layers::MergeBuilder;
use super::spine_fueled::Spine;
use super::merge_batcher::MergeBatcher;
use ti... | <'a>(&self, storage: &'a Self::Storage) -> &'a N { &storage.edges[self.val_pos] }
fn map_times<L: FnMut(&Product<RootTimestamp,()>, isize)>(&mut self, _storage: &Self::Storage, mut logic: L) {
logic(&Product::new(RootTimestamp, ()), 1);
}
fn key_valid(&self, storage: &Self::Storage) -> bool { (self.... | val | identifier_name |
server.py | # telegram-bot-server
# Copyright (C) 2017 quasiyoke
#
# You should have received a copy of the GNU Lesser General Public License v3
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import asyncio
import logging
import traceback
from .error import BotError
from .middleware import AuthMiddleware,... | web.run_app(
self._app,
host='0.0.0.0',
port=self._configuration.port,
) | identifier_body | |
server.py | # telegram-bot-server
# Copyright (C) 2017 quasiyoke
#
# You should have received a copy of the GNU Lesser General Public License v3
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import asyncio
import logging
import traceback
from .error import BotError
from .middleware import AuthMiddleware,... | reason = 'Bad Request: URL isn\'t specified'
LOGGER.warning('%s. Request data were "%s". %s', reason, request.data, err)
raise web.HTTPBadRequest(reason=reason) from err
description = 'Webhook was set' if await request.bot.set_webhook(url) else 'Webhook is already set'
... | try:
url = request.data['url']
except (KeyError, TypeError) as err: | random_line_split |
server.py | # telegram-bot-server
# Copyright (C) 2017 quasiyoke
#
# You should have received a copy of the GNU Lesser General Public License v3
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import asyncio
import logging
import traceback
from .error import BotError
from .middleware import AuthMiddleware,... |
return Response(result=updates_dicts)
async def _handle_send_message(self, request):
"""
Raises:
aiohttp.web.HTTPException
"""
LOGGER.info('"sendMessage" method.')
return Response()
async def _handle_set_webhook(self, request):
"""
... | del self._updates_futures[request.bot.bot_id]
updates = updates_future.result()
if len(updates):
await self._update_service.confirm_updates(request.bot.bot_id, updates[-1].bot_id + 1)
updates_dicts = [update.dict for update in updat... | conditional_block |
server.py | # telegram-bot-server
# Copyright (C) 2017 quasiyoke
#
# You should have received a copy of the GNU Lesser General Public License v3
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import asyncio
import logging
import traceback
from .error import BotError
from .middleware import AuthMiddleware,... | (self, request):
"""
Raises:
aiohttp.web.HTTPException
"""
LOGGER.info('"sendMessage" method.')
return Response()
async def _handle_set_webhook(self, request):
"""
Raises:
aiohttp.web.HTTPException
"""
LOGGER.info('"s... | _handle_send_message | identifier_name |
tmux.rs | use fastup::{Document, Node};
use fastup::Node::*;
use color::Color888;
use std::fmt;
#[derive(Debug, Copy, Clone, Default)]
pub struct Renderer;
impl super::Renderer for Renderer {
fn render(&self, doc: &Document) -> String {
let env = Environment::default();
tmux_from_document(doc, &env) + "#[de... |
if let Some(color) = env.background {
style += &format!(",bg=#{}", color);
}
if env.bold {
style += &format!(",bold");
}
style += "]";
style
}
}
impl fmt::Display for Environment {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result ... | {
style += &format!(",fg=#{}", color);
} | conditional_block |
tmux.rs | use fastup::{Document, Node};
use fastup::Node::*;
use color::Color888;
use std::fmt;
#[derive(Debug, Copy, Clone, Default)]
pub struct Renderer;
impl super::Renderer for Renderer {
fn render(&self, doc: &Document) -> String {
let env = Environment::default();
tmux_from_document(doc, &env) + "#[de... | style += &format!(",bold");
}
style += "]";
style
}
}
impl fmt::Display for Environment {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", String::from(self))
}
}
fn tmux_from_document(doc: &Document, env: &Environment) -> String {
... | random_line_split | |
tmux.rs | use fastup::{Document, Node};
use fastup::Node::*;
use color::Color888;
use std::fmt;
#[derive(Debug, Copy, Clone, Default)]
pub struct Renderer;
impl super::Renderer for Renderer {
fn render(&self, doc: &Document) -> String {
let env = Environment::default();
tmux_from_document(doc, &env) + "#[de... | (env: &'a Environment) -> Self {
let mut style = "#[default".to_string();
if let Some(color) = env.foreground {
style += &format!(",fg=#{}", color);
}
if let Some(color) = env.background {
style += &format!(",bg=#{}", color);
}
if env.bold {
... | from | identifier_name |
capa_problem.py | """
Return the IDs of all the responses -- these are the keys used for
the dicts returned by grade_answers and get_question_answers. (Though
get_question_answers may only return a subset of these.
"""
answer_ids = []
for response in self.responders.keys():
re... | _preprocess_problem | identifier_name | |
capa_problem.py | _strs
]
return max(queuetimes)
def grade_answers(self, answers):
"""
Grade student responses. Called by capa_module.check_problem.
`answers` is a dict of all the entries from request.POST, but with the first part
of each key removed (the string before the first "_... | """
Extract content of <script>...</script> from the problem.xml file, and exec it in the
context of this problem. Provides ability to randomize problems, and also set
variables for problem answer checking.
Problem XML goes to Python execution context. Runs everything in script tags.
... | identifier_body | |
capa_problem.py | ponsetype instance to do actual grading
for responder in self.responders.values():
# File objects are passed only if responsetype explicitly allows
# for file submissions. But we have no way of knowing if
# student_answers contains a proper answer or the filename of
... | msg = self.correct_map.get_msg(pid)
hint = self.correct_map.get_hint(pid)
hintmode = self.correct_map.get_hintmode(pid) | random_line_split | |
capa_problem.py | self.correct_map)
def get_recentmost_queuetime(self):
"""
Returns a DateTime object that represents the timestamp of the most recent
queueing request, or None if not queued
"""
if not self.is_queued():
return None
# Get a list of timestamps of all queue... | if not dir:
continue
# path is an absolute path or a path relative to the data dir
dir = os.path.join(self.capa_system.filestore.root_path, dir)
# Check that we are within the filestore tree.
reldir = os.path.relpath(dir, self.capa_system.filestore.root_p... | conditional_block | |
edit.component.ts | import { Component, Inject, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { DepartmentsService } from '../../services/departments.service';
import { ActivatedRoute, Router } from '@angular/router';
import { OperationResult } from '../../../shared/models/opera... | (
private router: Router,
private activatedRoute: ActivatedRoute,
private formBuilder: FormBuilder,
private service: DepartmentsService,
private alertSerivce: AlertService,
) {
this.id = activatedRoute.snapshot.params['id'];
if (!this.id) {
router.... | constructor | identifier_name |
edit.component.ts | import { Component, Inject, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { DepartmentsService } from '../../services/departments.service';
import { ActivatedRoute, Router } from '@angular/router';
import { OperationResult } from '../../../shared/models/opera... |
ngOnInit() {
this.service.getDepartment(this.id).subscribe(result => {
this.form.setValue(result);
})
}
submit(form: any) {
this.service.editDepartment(this.id, form).subscribe(result => this.checkResult(result));
}
public goBack(): void {
this.ro... | {
this.id = activatedRoute.snapshot.params['id'];
if (!this.id) {
router.navigateByUrl("['/404']");
}
this.form = this.formBuilder.group({
"id": [this.id, Validators.required],
"name": ["", Validators.required],
"shortName": [""]
})... | identifier_body |
edit.component.ts | import { Component, Inject, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { DepartmentsService } from '../../services/departments.service';
import { ActivatedRoute, Router } from '@angular/router';
import { OperationResult } from '../../../shared/models/opera... | {
this.errors = result.errors;
}
}
remove(){
this.service.deleteDepartment(this.id).subscribe(result=> this.checkResult(result));
}
}
| {
this.goBack();
this.alertSerivce.info("Данные успешно обновлены", true);
}
else
| conditional_block |
edit.component.ts | import { Component, Inject, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { DepartmentsService } from '../../services/departments.service';
import { ActivatedRoute, Router } from '@angular/router';
import { OperationResult } from '../../../shared/models/opera... | this.router.navigate(['/departments']);
}
public checkResult(result:OperationResult):void{
if(!result.hasErrors)
{
this.goBack();
this.alertSerivce.info("Данные успешно обновлены", true);
}
else
{
this.errors = result.errors;
... | public goBack(): void { | random_line_split |
select2-kv.min.js | /*! | * Additional enhancements for Select2 widget extension for Yii 2.0.
*
* Author: Kartik Visweswaran
* Copyright: 2014, Kartik Visweswaran, Krajee.com
* For more JQuery plugins visit http://plugins.krajee.com
* For more Yii related demos visit http://demos.krajee.com
*/(function($){initSelect2Loading=function(e){... | * @copyright Copyright © Kartik Visweswaran, Krajee.com, 2014
* @version 3.0.0
* | random_line_split |
htmliframeelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::HTMLIFrameElementBinding;
use dom::bindings::utils::{DOMString, ErrorResult, null_str_... |
pub fn Srcdoc(&self) -> DOMString {
None
}
pub fn SetSrcdoc(&mut self, _srcdoc: &DOMString) -> ErrorResult {
Ok(())
}
pub fn Name(&self) -> DOMString {
None
}
pub fn SetName(&mut self, _name: &DOMString) -> ErrorResult {
Ok(())
}
pub fn Sandbox(&... | {
Ok(())
} | identifier_body |
htmliframeelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::HTMLIFrameElementBinding;
use dom::bindings::utils::{DOMString, ErrorResult, null_str_... | (&mut self, _allow: bool) -> ErrorResult {
Ok(())
}
pub fn Width(&self) -> DOMString {
None
}
pub fn SetWidth(&mut self, _width: &DOMString) -> ErrorResult {
Ok(())
}
pub fn Height(&self) -> DOMString {
None
}
pub fn SetHeight(&mut self, _height: &DOMS... | SetAllowFullscreen | identifier_name |
htmliframeelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::HTMLIFrameElementBinding;
use dom::bindings::utils::{DOMString, ErrorResult, null_str_... |
pub fn Srcdoc(&self) -> DOMString {
None
}
pub fn SetSrcdoc(&mut self, _srcdoc: &DOMString) -> ErrorResult {
Ok(())
}
pub fn Name(&self) -> DOMString {
None
}
pub fn SetName(&mut self, _name: &DOMString) -> ErrorResult {
Ok(())
}
pub fn Sandbox(&s... | random_line_split | |
capture.rs | fn main() | // that. Immediately borrows `count`.
//
// A `mut` is required on `inc` because a `&mut` is stored inside.
// Thus, calling the closure mutates the closure which requires
// a `mut`.
let mut inc = || {
count += 1;
println!("`count`: {}", count);
};
// Call the closure.
... | {
use std::mem;
let color = "green";
// A closure to print `color` which immediately borrows (`&`)
// `color` and stores the borrow and closure in the `print`
// variable. It will remain borrowed until `print` goes out of
// scope. `println!` only requires `by reference` so it doesn't
... | identifier_body |
capture.rs | fn | () {
use std::mem;
let color = "green";
// A closure to print `color` which immediately borrows (`&`)
// `color` and stores the borrow and closure in the `print`
// variable. It will remain borrowed until `print` goes out of
// scope. `println!` only requires `by reference` so it doesn't
... | main | identifier_name |
capture.rs | fn main() {
use std::mem;
let color = "green";
// A closure to print `color` which immediately borrows (`&`)
// `color` and stores the borrow and closure in the `print`
// variable. It will remain borrowed until `print` goes out of
// scope. `println!` only requires `by reference` so it do... | //consume();
// ^ TODO: Try uncommenting this line.
} | random_line_split | |
delegate.js | // (C) Copyright 2015 Martin Dougiamas
//
// 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 agre... | */
.provider('$mmFileUploaderDelegate', function() {
var handlers = {},
self = {};
/**
* Register a file picker handler.
*
* @module mm.core.fileuploader
* @ngdoc method
* @name $mmFileUploaderDelegate#registerHandler
* @param {String} addon The addon's name (mmaFiles, mm... | * @module mm.core.fileuploader
* @ngdoc provider
* @name $mmFileUploaderDelegate | random_line_split |
delegate.js | // (C) Copyright 2015 Martin Dougiamas
//
// 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 agre... |
if (!$mmSite.isLoggedIn()) {
promise = $q.reject();
} else {
promise = $q.when(handlerInfo.instance.isEnabled());
}
// Checks if the content is enabled.
return promise.catch(function() {
return false;
... | {
handlerInfo.instance = $mmUtil.resolveObject(handlerInfo.handler, true);
} | conditional_block |
reject.js | var _complement = require('./internal/_complement');
var _curry2 = require('./internal/_curry2');
var filter = require('./filter');
/**
* Similar to `filter`, except that it keeps only values for which the given predicate
* function returns falsy. The predicate function is passed one argument: *(value)*.
*
* Acts... | return filter(_complement(fn), list);
}); | random_line_split | |
scrape_google_scholar_from_bing.py | import requests
from urllib.parse import parse_qs, urlparse
from lxml.html import fromstring
_HEADERS = {
'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/41.0.2272.76 Chrome/41.0.2272.76 Safari/537.36',
'accept': 'text/html,application/xhtml+xml,application... |
print(links)
| link = result.get('href')
qs = urlparse(link).query
links.extend(parse_qs(qs).get('user', [])) | conditional_block |
scrape_google_scholar_from_bing.py | import requests
from urllib.parse import parse_qs, urlparse
from lxml.html import fromstring
_HEADERS = {
'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/41.0.2272.76 Chrome/41.0.2272.76 Safari/537.36',
'accept': 'text/html,application/xhtml+xml,application... | # get results from search
query = {"q": "site:scholar.google.com \"From Mechanism to Mouse\" "}
url = "https://cn.bing.com/search"
html = requests.get(url, headers=_HEADERS, params=query)
print(html.request.headers)
print(html.url)
print(html.content)
tree = fromstring(html.content)
results = tree.xpath(".//*[@id='b_r... | random_line_split | |
mod.rs | /*!
Test supports module.
*/
#![allow(dead_code)]
use glium::{self, glutin};
use glium::backend::Facade;
use glium::index::PrimitiveType;
use std::env;
/// Builds a display for tests.
#[cfg(not(feature = "test_headless"))]
pub fn build_display() -> glium::Display {
let version = parse_version();
let event_... | {
glium::Texture2d::empty(facade, 1024, 1024).unwrap()
} | identifier_body | |
mod.rs | /*!
Test supports module.
*/
#![allow(dead_code)]
use glium::{self, glutin};
use glium::backend::Facade;
use glium::index::PrimitiveType;
use std::env;
/// Builds a display for tests.
#[cfg(not(feature = "test_headless"))]
pub fn build_display() -> glium::Display {
let version = parse_version();
let event_... | (display: &glium::Display) {
let version = parse_version();
let event_loop = glutin::event_loop::EventLoop::new();
let wb = glutin::window::WindowBuilder::new().with_visible(false);
let cb = glutin::ContextBuilder::new()
.with_gl_debug_flag(true)
.with_gl(version);
display.rebuild(wb... | rebuild_display | identifier_name |
mod.rs | /*!
Test supports module.
*/
#![allow(dead_code)]
use glium::{self, glutin};
use glium::backend::Facade;
use glium::index::PrimitiveType;
use std::env;
/// Builds a display for tests.
#[cfg(not(feature = "test_headless"))]
pub fn build_display() -> glium::Display {
let version = parse_version();
let event_... | pub fn build_unicolor_texture2d<F: ?Sized>(facade: &F, red: f32, green: f32, blue: f32)
-> glium::Texture2d where F: Facade
{
let color = ((red * 255.0) as u8, (green * 255.0) as u8, (blue * 255.0) as u8);
glium::texture::Texture2d::new(facade, vec![
vec![color, color],
vec![color, color],
... | Err(_) => glutin::GlRequest::Latest,
}
}
/// Builds a 2x2 unicolor texture. | random_line_split |
grid.inlinedit.js | jgrid.edit.bClose); }
if (e=="e2") { $.jgrid.info_dialog($.jgrid.errors.errcap,"function 'custom_value' "+$.jgrid.edit.msg.novalue,$.jgrid.edit.bClose); }
else { $.jgrid.info_dialog($.jgrid.errors.errcap,e.message,$.jgrid.edit.bClose); }
}
break;
}
cv = $.jgrid.checkValues(tmp[nm... | if (!this.grid ) { return; }
var $t = this;
if(p.useDefValues === true) { | random_line_split | |
grid.inlinedit.js | (cm.editoptions.custom_value)) {
tmp[nm] = cm.editoptions.custom_value.call($t, $(".customelement",this),'get');
if (tmp[nm] === undefined) { throw "e2"; }
} else { throw "e1"; }
} catch (e) {
if (e=="e1") { $.jgrid.info_dialog($.jgrid.errors.errcap,"function 'custom_value' "+$.... | {
o.afterrestorefunc.call($t, rowid);
} | conditional_block | |
test_update_license.py | #!/usr/bin/env python
import unittest
import os
import json
from updatable import utils as updatable_utils
PATH = os.path.dirname(os.path.realpath(__file__))
def get_pypi_package_data_monkey(package_name, version=None):
if version:
|
else:
json_file = 'pypi-%s.json' % package_name
with open(os.path.join(PATH, 'fixtures', json_file)) as data_file:
return json.load(data_file)
class TestUpdateLicense(unittest.TestCase):
"""
Tests package updatability
"""
def setUp(self):
self.get_pypi_package_data_o... | json_file = 'pypi-%s-%s.json' % (package_name, version) | conditional_block |
test_update_license.py | #!/usr/bin/env python
import unittest
import os
import json
from updatable import utils as updatable_utils
PATH = os.path.dirname(os.path.realpath(__file__))
def get_pypi_package_data_monkey(package_name, version=None):
if version:
json_file = 'pypi-%s-%s.json' % (package_name, version)
else:
... |
def setUp(self):
self.get_pypi_package_data_orig = updatable_utils.get_pypi_package_data
updatable_utils.get_pypi_package_data = get_pypi_package_data_monkey
def tearDown(self):
updatable_utils.get_pypi_package_data = self.get_pypi_package_data_orig
def test_update_license(self):
... |
class TestUpdateLicense(unittest.TestCase):
"""
Tests package updatability
""" | random_line_split |
test_update_license.py | #!/usr/bin/env python
import unittest
import os
import json
from updatable import utils as updatable_utils
PATH = os.path.dirname(os.path.realpath(__file__))
def get_pypi_package_data_monkey(package_name, version=None):
if version:
json_file = 'pypi-%s-%s.json' % (package_name, version)
else:
... |
if __name__ == '__main__':
unittest.main()
| """
Test update count for a package that has only major releases
"""
updates = updatable_utils.get_package_update_list('package3', '1.0.0')
self.assertEqual(updates['current_release'], '1.0.0')
self.assertEqual(updates['latest_release'], '3.0.0')
self.assertEqual(updates[... | identifier_body |
test_update_license.py | #!/usr/bin/env python
import unittest
import os
import json
from updatable import utils as updatable_utils
PATH = os.path.dirname(os.path.realpath(__file__))
def get_pypi_package_data_monkey(package_name, version=None):
if version:
json_file = 'pypi-%s-%s.json' % (package_name, version)
else:
... | (self):
self.get_pypi_package_data_orig = updatable_utils.get_pypi_package_data
updatable_utils.get_pypi_package_data = get_pypi_package_data_monkey
def tearDown(self):
updatable_utils.get_pypi_package_data = self.get_pypi_package_data_orig
def test_update_license(self):
"""
... | setUp | identifier_name |
Compiler.ts | /// <reference path="Common.ts" />
/// <reference path="Model.ts" />
/// <reference path="Directives.ts" />
/// <reference path="Controllers.ts" />
/// <reference path="dir/Bind.ts" />
/// <reference path="dir/Component.ts" />
/// <reference path="dir/Controller.ts" />
/// <reference path="dir/For.ts" />
/// <reference... | else {
return _bind(directiveIndex + 1, model, node, controllers);
}
}
export function bind(model: Dictionary, view: Element): void {
_bind(0, Model.create(model), view, ControllerFrame.create());
}
export function bindBody(model: Dictionary): void {
MVC.bind(model, document.body);
}
} // namespace MV... | {
return new DirectiveConstructor((model, node, controllers) => {
return _bind(directiveIndex + 1, model, node, controllers);
}, model, node, controllers);
} | conditional_block |
Compiler.ts | /// <reference path="Common.ts" />
/// <reference path="Model.ts" />
/// <reference path="Directives.ts" />
/// <reference path="Controllers.ts" />
/// <reference path="dir/Bind.ts" />
/// <reference path="dir/Component.ts" />
/// <reference path="dir/Controller.ts" />
/// <reference path="dir/For.ts" />
/// <reference... | (model: Dictionary): void {
MVC.bind(model, document.body);
}
} // namespace MVC
| bindBody | identifier_name |
Compiler.ts | /// <reference path="Common.ts" />
/// <reference path="Model.ts" />
/// <reference path="Directives.ts" />
/// <reference path="Controllers.ts" />
/// <reference path="dir/Bind.ts" />
/// <reference path="dir/Component.ts" />
/// <reference path="dir/Controller.ts" />
/// <reference path="dir/For.ts" />
/// <reference... |
export function bind(model: Dictionary, view: Element): void {
_bind(0, Model.create(model), view, ControllerFrame.create());
}
export function bindBody(model: Dictionary): void {
MVC.bind(model, document.body);
}
} // namespace MVC
| {
const registry = MVC.Directives.REGISTRY;
const DirectiveConstructor = registry[directiveIndex % registry.length];
if (DirectiveConstructor.matches(node)) {
return new DirectiveConstructor((model, node, controllers) => {
return _bind(directiveIndex + 1, model, node, controllers);
}, model, node, c... | identifier_body |
Compiler.ts | /// <reference path="Common.ts" />
/// <reference path="Model.ts" />
/// <reference path="Directives.ts" />
/// <reference path="Controllers.ts" />
/// <reference path="dir/Bind.ts" />
/// <reference path="dir/Component.ts" />
/// <reference path="dir/Controller.ts" />
/// <reference path="dir/For.ts" />
/// <reference... |
export const REGISTRY: DirectiveConstructorInterface[] = [
WithDirective,
ForDirective,
IfDirective,
ControllerDirective,
IncludeDirective,
ComponentDirective,
OnDirective,
BindDirective,
RootDirective,
];
} // namespace Directives
function _bind(directiveIndex: number, model: Model, node: Node... |
export namespace Directives { | random_line_split |
in_flight_requests.rs | use crate::{
context,
util::{Compact, TimeUntil},
PollIo, Response, ServerError,
};
use fnv::FnvHashMap;
use futures::ready;
use log::{debug, trace};
use std::{
collections::hash_map,
io,
task::{Context, Poll},
};
use tokio::sync::oneshot;
use tokio_util::time::delay_queue::{self, DelayQueue};
... |
debug!(
"No in-flight request found for request_id = {}.",
response.request_id
);
// If the response completion was absent, then the request was already canceled.
false
}
/// Cancels a request without completing (typically used when a request handle wa... | {
self.request_data.compact(0.1);
trace!("[{}] Received response.", request_data.ctx.trace_id());
self.deadlines.remove(&request_data.deadline_key);
request_data.complete(response);
return true;
} | conditional_block |
in_flight_requests.rs | use crate::{
context,
util::{Compact, TimeUntil},
PollIo, Response, ServerError,
};
use fnv::FnvHashMap;
use futures::ready;
use log::{debug, trace};
use std::{
collections::hash_map,
io,
task::{Context, Poll},
};
use tokio::sync::oneshot;
use tokio_util::time::delay_queue::{self, DelayQueue};
... |
}
| {
let _ = self.response_completion.send(response);
} | identifier_body |
in_flight_requests.rs | use crate::{
context,
util::{Compact, TimeUntil},
PollIo, Response, ServerError,
};
use fnv::FnvHashMap;
use futures::ready;
use log::{debug, trace};
use std::{
collections::hash_map,
io,
task::{Context, Poll},
};
use tokio::sync::oneshot;
use tokio_util::time::delay_queue::{self, DelayQueue};
... | ) -> Result<(), AlreadyExistsError> {
match self.request_data.entry(request_id) {
hash_map::Entry::Vacant(vacant) => {
let timeout = ctx.deadline.time_until();
trace!(
"[{}] Queuing request with timeout {:?}.",
ctx.trace_id(... | pub fn insert_request(
&mut self,
request_id: u64,
ctx: context::Context,
response_completion: oneshot::Sender<Response<Resp>>, | random_line_split |
in_flight_requests.rs | use crate::{
context,
util::{Compact, TimeUntil},
PollIo, Response, ServerError,
};
use fnv::FnvHashMap;
use futures::ready;
use log::{debug, trace};
use std::{
collections::hash_map,
io,
task::{Context, Poll},
};
use tokio::sync::oneshot;
use tokio_util::time::delay_queue::{self, DelayQueue};
... | (&mut self, response: Response<Resp>) -> bool {
if let Some(request_data) = self.request_data.remove(&response.request_id) {
self.request_data.compact(0.1);
trace!("[{}] Received response.", request_data.ctx.trace_id());
self.deadlines.remove(&request_data.deadline_key);
... | complete_request | identifier_name |
_generate-readme.py | #! /usr/bin/env python
# -*- coding: utf-8 -*-
import subprocess
import os
def path(*path_segments):
return os.path.join(os.getcwd(), *path_segments)
def open_file(*path_segments):
file_path = path(*path_segments)
open(file_path, 'w').close()
return open(file_path, 'a')
header = open(path('READM... |
readme.close()
sphinx.close()
| readme.write(line) | conditional_block |
_generate-readme.py | #! /usr/bin/env python
# -*- coding: utf-8 -*-
import subprocess
import os
def path(*path_segments):
return os.path.join(os.getcwd(), *path_segments)
def open_file(*path_segments):
file_path = path(*path_segments)
open(file_path, 'w').close() |
header = open(path('README_header.rst'), 'r')
readme = open_file('README.rst')
sphinx = open_file('doc', 'source', 'cli.rst')
sphinx_header = (
'Comande line interface\n',
'======================\n',
'\n',
'.. code-block:: text\n',
'\n',
)
for line in sphinx_header:
sphinx.write(str(line))
... | return open(file_path, 'a') | random_line_split |
_generate-readme.py | #! /usr/bin/env python
# -*- coding: utf-8 -*-
import subprocess
import os
def | (*path_segments):
return os.path.join(os.getcwd(), *path_segments)
def open_file(*path_segments):
file_path = path(*path_segments)
open(file_path, 'w').close()
return open(file_path, 'a')
header = open(path('README_header.rst'), 'r')
readme = open_file('README.rst')
sphinx = open_file('doc', 'source... | path | identifier_name |
_generate-readme.py | #! /usr/bin/env python
# -*- coding: utf-8 -*-
import subprocess
import os
def path(*path_segments):
|
def open_file(*path_segments):
file_path = path(*path_segments)
open(file_path, 'w').close()
return open(file_path, 'a')
header = open(path('README_header.rst'), 'r')
readme = open_file('README.rst')
sphinx = open_file('doc', 'source', 'cli.rst')
sphinx_header = (
'Comande line interface\n',
'... | return os.path.join(os.getcwd(), *path_segments) | identifier_body |
remove_student_data.py |
# Andrew Erlichson
# MongoDB, Inc.
# M101P - Copyright 2015, All Rights Reserved
import pymongo
import datetime
import sys
# establish a connection to the database
connection = pymongo.MongoClient("mongodb://localhost")
# removes one student
def remove_student(student_id):
# get a handle to the schoo... |
remove_student(1)
find_student_data(1)
| db=connection.school
scores = db.scores
print "Searching for student data for student with id = ", student_id
try:
docs = scores.find({'student_id':student_id})
for doc in docs:
print doc
except Exception as e:
print "Exception: ", type(e), e | identifier_body |
remove_student_data.py |
# Andrew Erlichson
# MongoDB, Inc.
# M101P - Copyright 2015, All Rights Reserved
import pymongo
import datetime
import sys
# establish a connection to the database
connection = pymongo.MongoClient("mongodb://localhost")
# removes one student
def remove_student(student_id):
# get a handle to the schoo... | (student_id):
# get a handle to the school database
db=connection.school
scores = db.scores
print "Searching for student data for student with id = ", student_id
try:
docs = scores.find({'student_id':student_id})
for doc in docs:
print doc
except Exception as e... | find_student_data | identifier_name |
remove_student_data.py | # Andrew Erlichson | # MongoDB, Inc.
# M101P - Copyright 2015, All Rights Reserved
import pymongo
import datetime
import sys
# establish a connection to the database
connection = pymongo.MongoClient("mongodb://localhost")
# removes one student
def remove_student(student_id):
# get a handle to the school database
db=co... | random_line_split | |
remove_student_data.py |
# Andrew Erlichson
# MongoDB, Inc.
# M101P - Copyright 2015, All Rights Reserved
import pymongo
import datetime
import sys
# establish a connection to the database
connection = pymongo.MongoClient("mongodb://localhost")
# removes one student
def remove_student(student_id):
# get a handle to the schoo... |
except Exception as e:
print "Exception: ", type(e), e
remove_student(1)
find_student_data(1)
| print doc | conditional_block |
util.ts | import * as Long from "long";
import * as loader from "../lib/loader/src";
export { Long, loader };
export const arrayHeaderSize = 12; // capacity:i32 + length:i32 + base:i32
export function hexdump(memory: WebAssembly.Memory, offset: number, length: number): string {
var buffer = new Uint8Array(memory.buffer);
v... | out.push("\n");
out.push("> " + l + ":");
}
out.push(" " + b);
}
return out.join("");
} | let l = (offset + i).toString(16);
while (l.length < 6) l = "0" + l;
if (i > 0) | random_line_split |
util.ts | import * as Long from "long";
import * as loader from "../lib/loader/src";
export { Long, loader };
export const arrayHeaderSize = 12; // capacity:i32 + length:i32 + base:i32
export function hexdump(memory: WebAssembly.Memory, offset: number, length: number): string | {
var buffer = new Uint8Array(memory.buffer);
var out: string[] = [];
for (let i = 0; i < length; ++i) {
let b = buffer[offset + i].toString(16);
if (b.length < 2) b = "0" + b;
if ((i % 16) === 0) {
let l = (offset + i).toString(16);
while (l.length < 6) l = "0" + l;
if (i > 0)
... | identifier_body | |
util.ts | import * as Long from "long";
import * as loader from "../lib/loader/src";
export { Long, loader };
export const arrayHeaderSize = 12; // capacity:i32 + length:i32 + base:i32
export function | (memory: WebAssembly.Memory, offset: number, length: number): string {
var buffer = new Uint8Array(memory.buffer);
var out: string[] = [];
for (let i = 0; i < length; ++i) {
let b = buffer[offset + i].toString(16);
if (b.length < 2) b = "0" + b;
if ((i % 16) === 0) {
let l = (offset + i).toStrin... | hexdump | identifier_name |
util.ts | import * as Long from "long";
import * as loader from "../lib/loader/src";
export { Long, loader };
export const arrayHeaderSize = 12; // capacity:i32 + length:i32 + base:i32
export function hexdump(memory: WebAssembly.Memory, offset: number, length: number): string {
var buffer = new Uint8Array(memory.buffer);
v... |
out.push(" " + b);
}
return out.join("");
}
| {
let l = (offset + i).toString(16);
while (l.length < 6) l = "0" + l;
if (i > 0)
out.push("\n");
out.push("> " + l + ":");
} | conditional_block |
Gruntfile.js | if (!saucekey) {
console.warn('Unable to load Saucelabs key');
}
grunt.initConfig({
jade: {
release: {
files: {
'tests/index.html': ['tests/views/index.jade']
}
}
},
clean: ['tests/inde... | module.exports = function (grunt) {
'use strict';
// Project configuration.
var saucekey = process.env.saucekey;
| random_line_split | |
Gruntfile.js | module.exports = function (grunt) {
'use strict';
// Project configuration.
var saucekey = process.env.saucekey;
if (!saucekey) {
console.warn('Unable to load Saucelabs key');
}
grunt.initConfig({
jade: {
release: {
files: {
... |
grunt.registerTask('dev', devJobs);
grunt.registerTask('phantom', karmaJobs);
grunt.registerTask('test', function () {
var testJobs = karmaJobs.concat('connect');
if (saucekey && !process.env.TRAVIS_PULL_REQUEST) {
console.info('adding Saucelabs integration');
... | {
karmaJobs.push('karma:dev-single');
} | conditional_block |
__init__.py | __author__ = 'mwn'
import os
import sys
import logging
from logging.handlers import RotatingFileHandler
from flask import Flask, render_template
app = Flask(__name__)
app.config.from_object('config')
handler = RotatingFileHandler('yapki.log', maxBytes=10000, backupCount=1)
handler.setLevel(logging.DEBUG)
app.logger.... | (error):
return render_template('404.html'), 404
@app.after_request
def after_request(response):
response.headers.add('X-Test', 'This is only test.')
response.headers.add('Access-Control-Allow-Origin', '*') # TODO: set to real origin
return response
from app.web.controller import webBp
app.register_b... | not_found | identifier_name |
__init__.py | __author__ = 'mwn'
import os
import sys
import logging
from logging.handlers import RotatingFileHandler
from flask import Flask, render_template
app = Flask(__name__)
app.config.from_object('config')
handler = RotatingFileHandler('yapki.log', maxBytes=10000, backupCount=1)
handler.setLevel(logging.DEBUG)
app.logger.... |
print('head -c 24 /dev/urandom > {filename}'.format(filename=filename))
sys.exit(1)
if not app.config['DEBUG']:
install_secret_key(app)
@app.errorhandler(404)
def not_found(error):
return render_template('404.html'), 404
@app.after_request
def after_request(response):
response.headers.ad... | print('mkdir -p {filename}'.format(filename=full_path)) | conditional_block |
__init__.py | __author__ = 'mwn'
import os
import sys
import logging
from logging.handlers import RotatingFileHandler
from flask import Flask, render_template
app = Flask(__name__)
app.config.from_object('config')
handler = RotatingFileHandler('yapki.log', maxBytes=10000, backupCount=1)
handler.setLevel(logging.DEBUG)
app.logger.... |
try:
app.config['SECRET_KEY'] = open(filename, 'rb').read()
except IOError:
print('Error: No secret key. Create it with:')
full_path = os.path.dirname(filename)
if not os.path.isdir(full_path):
print('mkdir -p {filename}'.format(filename=full_path))
print('he... | then exit.
"""
filename = os.path.join(app.instance_path, filename) | random_line_split |
__init__.py | __author__ = 'mwn'
import os
import sys
import logging
from logging.handlers import RotatingFileHandler
from flask import Flask, render_template
app = Flask(__name__)
app.config.from_object('config')
handler = RotatingFileHandler('yapki.log', maxBytes=10000, backupCount=1)
handler.setLevel(logging.DEBUG)
app.logger.... |
if not app.config['DEBUG']:
install_secret_key(app)
@app.errorhandler(404)
def not_found(error):
return render_template('404.html'), 404
@app.after_request
def after_request(response):
response.headers.add('X-Test', 'This is only test.')
response.headers.add('Access-Control-Allow-Origin', '*') # TO... | """Configure the SECRET_KEY from a file
in the instance directory.
If the file does not exist, print instructions
to create it from a shell with a random key,
then exit.
"""
filename = os.path.join(app.instance_path, filename)
try:
app.config['SECRET_KEY'] = open(filename, 'rb').re... | identifier_body |
Snackbar.js | import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { fetchIP } from '../../actions/fetchIP';
import { Snackbar } from 'react-toolbox';
import theme from './Snackbar.css';
class SnackbarComponent extends Component {
constructor(props) {... | (props) {
this.setState({
active: props.error,
message: props.message
});
}
componentDidMount() {
this._isMounted = true;
}
componentWillUnmount() {
this._isMounted = false;
}
render() {
return (
<section>
<Snackbar
theme={theme}
... | componentWillReceiveProps | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.