file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
39k
suffix
large_stringlengths
0
36.1k
middle
large_stringlengths
0
29.4k
fim_type
large_stringclasses
4 values
i18n.py
import re from django.template import Node, Variable, VariableNode, _render_value_in_context from django.template import TemplateSyntaxError, TokenParser, Library from django.template import TOKEN_TEXT, TOKEN_VAR from django.utils import translation from django.utils.encoding import force_unicode register = L...
""" This will store the current language layout in the context. Usage:: {% get_current_language_bidi as bidi %} This will fetch the currently active language's layout and put it's value into the ``bidi`` context variable. True indicates right-to-left layout, otherwise left-to...
def do_get_current_language_bidi(parser, token):
random_line_split
i18n.py
import re from django.template import Node, Variable, VariableNode, _render_value_in_context from django.template import TemplateSyntaxError, TokenParser, Library from django.template import TOKEN_TEXT, TOKEN_VAR from django.utils import translation from django.utils.encoding import force_unicode register = L...
class BlockTranslateNode(Node): def __init__(self, extra_context, singular, plural=None, countervar=None, counter=None): self.extra_context = extra_context self.singular = singular self.plural = plural self.countervar = countervar self.counter = counter...
def __init__(self, value, noop): self.value = Variable(value) self.noop = noop def render(self, context): value = self.value.resolve(context) if self.noop: return value else: return _render_value_in_context(translation.ugettext(value), contex...
identifier_body
i18n.py
import re from django.template import Node, Variable, VariableNode, _render_value_in_context from django.template import TemplateSyntaxError, TokenParser, Library from django.template import TOKEN_TEXT, TOKEN_VAR from django.utils import translation from django.utils.encoding import force_unicode register = L...
(Node): def __init__(self, variable): self.variable = variable def render(self, context): context[self.variable] = translation.get_language() return '' class GetCurrentLanguageBidiNode(Node): def __init__(self, variable): self.variable = variable def render...
GetCurrentLanguageNode
identifier_name
i18n.py
import re from django.template import Node, Variable, VariableNode, _render_value_in_context from django.template import TemplateSyntaxError, TokenParser, Library from django.template import TOKEN_TEXT, TOKEN_VAR from django.utils import translation from django.utils.encoding import force_unicode register = L...
return ''.join(result), vars def render(self, context): tmp_context = {} for var, val in self.extra_context.items(): tmp_context[var] = val.render(context) # Update() works like a push(), so corresponding context.pop() is at # the end of function ...
if token.token_type == TOKEN_TEXT: result.append(token.contents) elif token.token_type == TOKEN_VAR: result.append(u'%%(%s)s' % token.contents) vars.append(token.contents)
conditional_block
mut_mut.rs
use clippy_utils::diagnostics::span_lint; use clippy_utils::higher; use rustc_hir as hir; use rustc_hir::intravisit; use rustc_lint::{LateContext, LateLintPass, LintContext}; use rustc_middle::hir::map::Map; use rustc_middle::lint::in_external_macro; use rustc_middle::ty; use rustc_session::{declare_lint_pass, declare_...
fn nested_visit_map(&mut self) -> intravisit::NestedVisitorMap<Self::Map> { intravisit::NestedVisitorMap::None } }
{ if in_external_macro(self.cx.sess(), ty.span) { return; } if let hir::TyKind::Rptr( _, hir::MutTy { ty: pty, mutbl: hir::Mutability::Mut, }, ) = ty.kind { if let hir::TyKind::Rptr( ...
identifier_body
mut_mut.rs
use clippy_utils::diagnostics::span_lint; use clippy_utils::higher; use rustc_hir as hir; use rustc_hir::intravisit; use rustc_lint::{LateContext, LateLintPass, LintContext}; use rustc_middle::hir::map::Map; use rustc_middle::lint::in_external_macro; use rustc_middle::ty; use rustc_session::{declare_lint_pass, declare_...
} intravisit::walk_ty(self, ty); } fn nested_visit_map(&mut self) -> intravisit::NestedVisitorMap<Self::Map> { intravisit::NestedVisitorMap::None } }
random_line_split
mut_mut.rs
use clippy_utils::diagnostics::span_lint; use clippy_utils::higher; use rustc_hir as hir; use rustc_hir::intravisit; use rustc_lint::{LateContext, LateLintPass, LintContext}; use rustc_middle::hir::map::Map; use rustc_middle::lint::in_external_macro; use rustc_middle::ty; use rustc_session::{declare_lint_pass, declare_...
<'a, 'tcx> { cx: &'a LateContext<'tcx>, } impl<'a, 'tcx> intravisit::Visitor<'tcx> for MutVisitor<'a, 'tcx> { type Map = Map<'tcx>; fn visit_expr(&mut self, expr: &'tcx hir::Expr<'_>) { if in_external_macro(self.cx.sess(), expr.span) { return; } if let Some(higher::For...
MutVisitor
identifier_name
event_details_converter.py
from collections import defaultdict from typing import cast, Dict, List, NewType from backend.common.consts.api_version import ApiMajorVersion from backend.common.models.event_details import EventDetails from backend.common.models.keys import TeamKey from backend.common.queries.dict_converters.converter_base import Co...
rankings = {} if event_details: rankings = event_details.renderable_rankings else: rankings = { "extra_stats_info": [], "rankings": [], "sort_order_info": None, } event_details_dict = { "al...
for team, value in cast(Dict[TeamKey, float], stats).items(): if "frc" not in team: # Normalize output team = "frc{}".format(team) normalized_oprs[stat_type][team] = value
conditional_block
event_details_converter.py
from collections import defaultdict from typing import cast, Dict, List, NewType from backend.common.consts.api_version import ApiMajorVersion from backend.common.models.event_details import EventDetails from backend.common.models.keys import TeamKey from backend.common.queries.dict_converters.converter_base import Co...
(cls, model_list: List[EventDetails], version: ApiMajorVersion): CONVERTERS = { 3: cls.eventsDetailsConverter_v3, } return CONVERTERS[version](model_list) @classmethod def eventsDetailsConverter_v3(cls, event_details: List[EventDetails]): return list(map(cls.eventDet...
_convert_list
identifier_name
event_details_converter.py
from collections import defaultdict from typing import cast, Dict, List, NewType from backend.common.consts.api_version import ApiMajorVersion from backend.common.models.event_details import EventDetails from backend.common.models.keys import TeamKey from backend.common.queries.dict_converters.converter_base import Co...
"alliances": event_details.alliance_selections if event_details else [], "district_points": event_details.district_points if event_details else {}, "insights": event_details.insights if event_details else {"qual": {}, "playoff": {}}, "oprs": normal...
"sort_order_info": None, } event_details_dict = {
random_line_split
event_details_converter.py
from collections import defaultdict from typing import cast, Dict, List, NewType from backend.common.consts.api_version import ApiMajorVersion from backend.common.models.event_details import EventDetails from backend.common.models.keys import TeamKey from backend.common.queries.dict_converters.converter_base import Co...
normalized_oprs = defaultdict(dict) if event_details and event_details.matchstats: for stat_type, stats in event_details.matchstats.items(): if stat_type in {"oprs", "dprs", "ccwms"}: for team, value in cast(Dict[TeamKey, float], stats).items(): ...
identifier_body
1.js
/* --- Day 15: Science for Hungry People --- Today, you set out on the task of perfecting your milk-dunking cookie recipe. All you have to do is find the right balance of ingredients. Your recipe leaves room for exactly 100 teaspoons of ingredients. You make a list of the remaining ingredients you could use to finish...
(id = 0, amount = AMOUNT) { if (amount === 0) { answer = Math.max(answer, score(ingredients, amounts)); } else if (id < ingredients.length) { for (let i = 0; i <= amount; i++) { amounts[id] = i; calc(id + 1, amount - i); } } return answer; } return calc(); };
calc
identifier_name
1.js
/* --- Day 15: Science for Hungry People --- Today, you set out on the task of perfecting your milk-dunking cookie recipe. All you have to do is find the right balance of ingredients. Your recipe leaves room for exactly 100 teaspoons of ingredients. You make a list of the remaining ingredients you could use to finish...
answer = Math.max(answer, score(ingredients, amounts)); } else if (id < ingredients.length) { for (let i = 0; i <= amount; i++) { amounts[id] = i; calc(id + 1, amount - i); } } return answer; } return calc(); };
let answer = 0; function calc(id = 0, amount = AMOUNT) { if (amount === 0) {
random_line_split
1.js
/* --- Day 15: Science for Hungry People --- Today, you set out on the task of perfecting your milk-dunking cookie recipe. All you have to do is find the right balance of ingredients. Your recipe leaves room for exactly 100 teaspoons of ingredients. You make a list of the remaining ingredients you could use to finish...
;
{ const ingredients = input.trim() .split('\n') .map(line => line.split(':').map(i => i.trim())) .map(([title, params]) => { return params.split(',') .map(i => i.trim().split(' ')) .reduce((a, i) => { a[i[0]] = parseInt(i[1]); return a; }, {}); }); ...
identifier_body
_output.py
""" Implementation of hooks and APIs for outputting log messages. """ import sys import traceback import inspect import json as pyjson from threading import Lock from functools import wraps from io import IOBase from pyrsistent import PClass, field from . import _bytesjson as bytesjson from zope.interface import Int...
def __call__(self, message): self.messages.append(message) while len(self.messages) > 1000: self.messages.pop(0) class Destinations(object): """ Manage a list of destinations for message dictionaries. The global instance of this class is where L{Logger} instances will ...
def __init__(self): self.messages = []
random_line_split
_output.py
""" Implementation of hooks and APIs for outputting log messages. """ import sys import traceback import inspect import json as pyjson from threading import Lock from functools import wraps from io import IOBase from pyrsistent import PClass, field from . import _bytesjson as bytesjson from zope.interface import Int...
(self): """ Clear all logged messages. Any logged tracebacks will also be cleared, and will therefore not cause a test failure. This is useful to ensure a logger is in a known state before testing logging of a specific code path. """ self.messages = [] ...
reset
identifier_name
_output.py
""" Implementation of hooks and APIs for outputting log messages. """ import sys import traceback import inspect import json as pyjson from threading import Lock from functools import wraps from io import IOBase from pyrsistent import PClass, field from . import _bytesjson as bytesjson from zope.interface import Int...
class Destinations(object): """ Manage a list of destinations for message dictionaries. The global instance of this class is where L{Logger} instances will send written messages. """ def __init__(self): self._destinations = [BufferingDestination()] self._any_added = False ...
""" Buffer messages in memory. """ def __init__(self): self.messages = [] def __call__(self, message): self.messages.append(message) while len(self.messages) > 1000: self.messages.pop(0)
identifier_body
_output.py
""" Implementation of hooks and APIs for outputting log messages. """ import sys import traceback import inspect import json as pyjson from threading import Lock from functools import wraps from io import IOBase from pyrsistent import PClass, field from . import _bytesjson as bytesjson from zope.interface import Int...
else: # Nothing we can do here, raising exception to caller will # break business logic, better to have that continue to # work even if logging isn't. pass def exclusively(f): """ Decorate a function to make it thread-safe by seriali...
for (exc_type, exception, exc_traceback) in e.errors: # Can't use same Logger as serialization errors because # if destination continues to error out we will get # infinite recursion. So instead we have to manually # construct a Logger that...
conditional_block
es-419.js
import regionSettingsMessages from 'ringcentral-integration/modules/RegionSettings/regionSettingsMessages'; export default { region: "Región", [regionSettingsMessages.saveSuccess]: "La configuración se guardó correctamente.", [regionSettingsMessages.dialingPlansChanged]: "Su cuenta ya no se admite para su cuenta....
// @key: @#@"[regionSettingsMessages.saveSuccess]"@#@ @source: @#@"Settings saved successfully."@#@ // @key: @#@"[regionSettingsMessages.dialingPlansChanged]"@#@ @source: @#@"The previous region is no longer supported for your account.\n Please verify your new {regionSettingsLink}."@#@ // @key: @#@"regionSettings"@#...
// @key: @#@"region"@#@ @source: @#@"Region"@#@
random_line_split
trafficlogger.py
## # Copyright (c) 2011-2015 Apple Inc. All rights reserved. # # 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 l...
return self._factories def getLogFiles(self): active = [] finished = [] for factoryref in self.factories: factory = factoryref() active.extend(factory.logs) finished.extend(factory.finishedLogs) return logstate(active, finished) de...
self._factories = []
conditional_block
trafficlogger.py
## # Copyright (c) 2011-2015 Apple Inc. All rights reserved. # # 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 l...
(self): if self._factories is None: self._factories = [] return self._factories def getLogFiles(self): active = [] finished = [] for factoryref in self.factories: factory = factoryref() active.extend(factory.logs) finished.ext...
factories
identifier_name
trafficlogger.py
## # Copyright (c) 2011-2015 Apple Inc. All rights reserved. # # 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 l...
self.finishedLogs = [] def unregisterProtocol(self, protocol): WrappingFactory.unregisterProtocol(self, protocol) self.logs.remove(protocol.logfile) self.finishedLogs.append(protocol.logfile) del self.finishedLogs[:-self.LOGFILE_LIMIT] def buildProtocol(self, addr): ...
def __init__(self, wrappedFactory): WrappingFactory.__init__(self, wrappedFactory) self.logs = []
random_line_split
trafficlogger.py
## # Copyright (c) 2011-2015 Apple Inc. All rights reserved. # # 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 l...
def buildProtocol(self, addr): logfile = StringIO() self.logs.append(logfile) return self.protocol( self, self.wrappedFactory.buildProtocol(addr), logfile, None, 0)
WrappingFactory.unregisterProtocol(self, protocol) self.logs.remove(protocol.logfile) self.finishedLogs.append(protocol.logfile) del self.finishedLogs[:-self.LOGFILE_LIMIT]
identifier_body
borrowed-unique-basic.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
() {()}
zzz
identifier_name
borrowed-unique-basic.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
// gdb-command:print/d *i8_ref // gdb-check:$4 = 68 // gdb-command:print *i16_ref // gdb-check:$5 = -16 // gdb-command:print *i32_ref // gdb-check:$6 = -32 // gdb-command:print *i64_ref // gdb-check:$7 = -64 // gdb-command:print *uint_ref // gdb-check:$8 = 1 // gdb-command:print/d *u8_ref // gdb-check:$9 = 100 /...
// gdb-command:print *char_ref // gdb-check:$3 = 97
random_line_split
borrowed-unique-basic.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
{()}
identifier_body
conf.py
# -*- coding: utf-8 -*- # # Blend documentation build configuration file, created by # sphinx-quickstart on Fri Feb 24 14:11:43 2012. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All c...
#latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output -------------------------------------------- # One entry per manual page. List of tuples # (source start fi...
# If true, show URL addresses after external links.
random_line_split
runtest.js
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. var error; function testGetDescriptor() { if (error !== undefined) { chrome.test.sendMessage('fail'); chrome.test.fail(error); } chrome.tes...
// 3. Known descriptor instanceId, but the mapped service is unknown. getDescriptor(descId, function (result) { if (expectError(result)) return; // 4. Known descriptor instanceId, but the mapped characteristic is // unknown. getDescriptor(descId, function (result) { if ...
// 2. Known descriptor instanceId, but the mapped device is unknown. getDescriptor(descId, function (result) { if (expectError(result)) return;
random_line_split
runtest.js
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. var error; function testGetDescriptor()
var getDescriptor = chrome.bluetoothLowEnergy.getDescriptor; var charId = 'char_id0'; var descId = 'desc_id0'; var badDescId = 'desc_id1'; var descriptor = null; function earlyError(message) { error = message; chrome.test.runTests([testGetDescriptor]); } function expectError(result) { if (result || !chrome....
{ if (error !== undefined) { chrome.test.sendMessage('fail'); chrome.test.fail(error); } chrome.test.assertTrue(descriptor != null, '\'descriptor\' is null'); chrome.test.assertEq('desc_id0', descriptor.instanceId); chrome.test.assertEq('00001221-0000-1000-8000-00805f9b34fb', descriptor.uuid); chro...
identifier_body
runtest.js
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. var error; function
() { if (error !== undefined) { chrome.test.sendMessage('fail'); chrome.test.fail(error); } chrome.test.assertTrue(descriptor != null, '\'descriptor\' is null'); chrome.test.assertEq('desc_id0', descriptor.instanceId); chrome.test.assertEq('00001221-0000-1000-8000-00805f9b34fb', descriptor.uuid); c...
testGetDescriptor
identifier_name
coherence-blanket-conflicts-with-specific-cross-crate.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
(&self, arg: isize) { } } impl GoMut for MyThingy { //~ ERROR conflicting implementations fn go_mut(&mut self, arg: isize) { } } fn main() { }
go
identifier_name
coherence-blanket-conflicts-with-specific-cross-crate.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
fn go_mut(&mut self, arg: isize) { } } fn main() { }
random_line_split
coherence-blanket-conflicts-with-specific-cross-crate.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
} impl GoMut for MyThingy { //~ ERROR conflicting implementations fn go_mut(&mut self, arg: isize) { } } fn main() { }
{ }
identifier_body
can_read_log_from_rosout.rs
use crossbeam::channel::unbounded; use std::collections::BTreeSet; mod util; mod msg { rosrust::rosmsg_include!(rosgraph_msgs / Log); } #[test] fn
() { let _roscore = util::run_roscore_for(util::Language::None, util::Feature::Log); rosrust::init("rosout_agg_listener"); let (tx, rx) = unbounded(); let _subscriber = rosrust::subscribe::<msg::rosgraph_msgs::Log, _>("/rosout_agg", 100, move |data| { tx.send((data.level, data.msg...
can_read_log_from_rosout
identifier_name
can_read_log_from_rosout.rs
use crossbeam::channel::unbounded; use std::collections::BTreeSet; mod util; mod msg { rosrust::rosmsg_include!(rosgraph_msgs / Log); } #[test] fn can_read_log_from_rosout() { let _roscore = util::run_roscore_for(util::Language::None, util::Feature::Log); rosrust::init("rosout_agg_listener"); let (...
rosrust::ros_debug!("debug message"); rosrust::ros_info!("info message"); rosrust::ros_warn!("warn message"); rosrust::ros_err!("err message"); rosrust::ros_fatal!("fatal message"); rate.sleep(); } panic!("Failed to receive data on /rosout_agg"); }
{ return; }
conditional_block
can_read_log_from_rosout.rs
use crossbeam::channel::unbounded; use std::collections::BTreeSet; mod util; mod msg { rosrust::rosmsg_include!(rosgraph_msgs / Log); } #[test] fn can_read_log_from_rosout() { let _roscore = util::run_roscore_for(util::Language::None, util::Feature::Log); rosrust::init("rosout_agg_listener"); let (...
expected_messages.insert((16, "fatal message".to_owned())); for _ in 0..10 { for item in rx.try_iter() { println!("Received message at level {}: {}", item.0, item.1); expected_messages.remove(&item); } if expected_messages.is_empty() { return; ...
random_line_split
can_read_log_from_rosout.rs
use crossbeam::channel::unbounded; use std::collections::BTreeSet; mod util; mod msg { rosrust::rosmsg_include!(rosgraph_msgs / Log); } #[test] fn can_read_log_from_rosout()
{ let _roscore = util::run_roscore_for(util::Language::None, util::Feature::Log); rosrust::init("rosout_agg_listener"); let (tx, rx) = unbounded(); let _subscriber = rosrust::subscribe::<msg::rosgraph_msgs::Log, _>("/rosout_agg", 100, move |data| { tx.send((data.level, data.msg))....
identifier_body
origin.rs
extern crate regex; use std::fmt; use std::str::FromStr; use std::string::ToString; use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; use regex::Regex; use super::{ NetType, AddrType }; use super::{ ProtocolVersion, SessionVersion }; use error::Error; // o=<username> <sess-id> <sess-version> <nettype> <addrtype> <unicas...
}
{ let re = match Regex::new(r"(\S+)\s(\S+)\s(\d+)\s(IN)\s(IP\d)\s(\d+\.\d+\.\d+\.\d+)") { Ok(re) => re, Err(e) => { println!("[Regex] {:?}", e); return Err(Error::Origin); } }; let cap = re.captures(s).unwrap(); let use...
identifier_body
origin.rs
extern crate regex; use std::fmt; use std::str::FromStr; use std::string::ToString; use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; use regex::Regex; use super::{ NetType, AddrType }; use super::{ ProtocolVersion, SessionVersion }; use error::Error; // o=<username> <sess-id> <sess-version> <nettype> <addrtype> <unicas...
}; let cap = re.captures(s).unwrap(); let username = match cap.at(1) { Some(username) => username.to_string(), None => return Err(Error::SessionName) }; let session_id = match cap.at(2) { Some(session_id) => session_id.to_string(), ...
Ok(re) => re, Err(e) => { println!("[Regex] {:?}", e); return Err(Error::Origin); }
random_line_split
origin.rs
extern crate regex; use std::fmt; use std::str::FromStr; use std::string::ToString; use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; use regex::Regex; use super::{ NetType, AddrType }; use super::{ ProtocolVersion, SessionVersion }; use error::Error; // o=<username> <sess-id> <sess-version> <nettype> <addrtype> <unicas...
(&self) -> String { let origin = "o=".to_string() + self.username.as_ref() + " " + self.session_id.as_ref() + " " + self.session_version.to_string().as_ref() + " " + self.nettype.to_string().as_ref() + " " + self.a...
to_string
identifier_name
regie.py
from .base import BaseInterface import eventlet from watchdog.observers import Observer from watchdog.events import PatternMatchingEventHandler from flask import Flask, render_template, session, request, send_from_directory from flask_socketio import SocketIO, emit, join_room, leave_room, close_room, rooms, disconnect ...
order["data"] = { 'topic': 'leds/all', 'data': b["light"].split('light ')[1] } elif b["light"].startswith('preset'): order["data"] = { ...
# LIGHT if b["light"] and b["light"] != '...': order = { 'peer': peerName, 'synchro': True, 'event': 'esp'} if b["light"].startswith('light'):
random_line_split
regie.py
from .base import BaseInterface import eventlet from watchdog.observers import Observer from watchdog.events import PatternMatchingEventHandler from flask import Flask, render_template, session, request, send_from_directory from flask_socketio import SocketIO, emit, join_room, leave_room, close_room, rooms, disconnect ...
(self, hplayer, port, datapath): super(RegieInterface, self).__init__(hplayer, "Regie") self._port = port self._datapath = datapath self._server = None # HTTP receiver THREAD def listen(self): # Advertize on ZeroConf zeroconf = Zeroconf() ...
__init__
identifier_name
regie.py
from .base import BaseInterface import eventlet from watchdog.observers import Observer from watchdog.events import PatternMatchingEventHandler from flask import Flask, render_template, session, request, send_from_directory from flask_socketio import SocketIO, emit, join_room, leave_room, close_room, rooms, disconnect ...
else: args[0].update({'type': event}) self.sendBuffer.put( ('peer', args[0]) ) # !!! TODO: stop zyre monitoring when every client are disconnected @socketio.on('connect') def client_connect(): self.regieinterface.log('New Remote Regie c...
print(ev, args[0]['data'][1]) self.sendBuffer.put( ('data', {'sequence': args[0]['data'][1]}) )
conditional_block
regie.py
from .base import BaseInterface import eventlet from watchdog.observers import Observer from watchdog.events import PatternMatchingEventHandler from flask import Flask, render_template, session, request, send_from_directory from flask_socketio import SocketIO, emit, join_room, leave_room, close_room, rooms, disconnect ...
# # Threaded HTTP Server # class ThreadedHTTPServer(object): def __init__(self, regieinterface, port): self.regieinterface = regieinterface interface_path = os.path.dirname(os.path.realpath(__file__)) if os.path.isdir(REGIE_PATH1): www_path = os.path.join...
self.log("PLAYSEQ") try: # self.log('PLAYSEQ', seqIndex, sceneIndex, boxes) orderz = [] boxes = [b for b in self._project["project"][0][sceneIndex]["allMedias"] if b["y"] == seqIndex] for b in boxes: peerName = self._project["pool"][ b["x"...
identifier_body
purchase_invoice.js
// Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors // License: GNU General Public License v3. See license.txt frappe.provide("erpnext.accounts"); {% include 'erpnext/public/js/controllers/buying.js' %}; erpnext.accounts.PurchaseInvoice = erpnext.buying.BuyingController.extend({ setup: function(doc...
setters: { supplier: me.frm.doc.supplier || undefined, }, get_query_filters: { docstatus: 1, status: ["not in", ["Closed", "Completed"]], company: me.frm.doc.company, is_return: 0 } }) }, __("Get items from")); } this.frm.toggle_reqd("supplier_warehouse", thi...
target: me.frm, date_field: "posting_date",
random_line_split
purchase_invoice.js
// Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors // License: GNU General Public License v3. See license.txt frappe.provide("erpnext.accounts"); {% include 'erpnext/public/js/controllers/buying.js' %}; erpnext.accounts.PurchaseInvoice = erpnext.buying.BuyingController.extend({ setup: function(doc...
oc) { var parent_fields = ['due_date', 'is_opening', 'advances_section', 'from_date', 'to_date']; if(cint(doc.is_paid) == 1) { hide_field(parent_fields); } else { for (var i in parent_fields) { var docfield = frappe.meta.docfield_map[doc.doctype][parent_fields[i]]; if(!docfield.hidden) unhide_field(parent...
de_fields(d
identifier_name
purchase_invoice.js
// Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors // License: GNU General Public License v3. See license.txt frappe.provide("erpnext.accounts"); {% include 'erpnext/public/js/controllers/buying.js' %}; erpnext.accounts.PurchaseInvoice = erpnext.buying.BuyingController.extend({ setup: function(doc...
cur_frm.cscript.update_stock = function(doc, dt, dn) { hide_fields(doc, dt, dn); this.frm.fields_dict.items.grid.toggle_reqd("item_code", doc.update_stock? true: false) } cur_frm.fields_dict.cash_bank_account.get_query = function(doc) { return { filters: [ ["Account", "account_type", "in", ["Cash", "Bank"]], ...
var parent_fields = ['due_date', 'is_opening', 'advances_section', 'from_date', 'to_date']; if(cint(doc.is_paid) == 1) { hide_field(parent_fields); } else { for (var i in parent_fields) { var docfield = frappe.meta.docfield_map[doc.doctype][parent_fields[i]]; if(!docfield.hidden) unhide_field(parent_field...
identifier_body
purchase_invoice.js
// Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors // License: GNU General Public License v3. See license.txt frappe.provide("erpnext.accounts"); {% include 'erpnext/public/js/controllers/buying.js' %}; erpnext.accounts.PurchaseInvoice = erpnext.buying.BuyingController.extend({ setup: function(doc...
}, onload: function() { this._super(); if(!this.frm.doc.__islocal) { // show credit_to in print format if(!this.frm.doc.supplier && this.frm.doc.credit_to) { this.frm.set_df_property("credit_to", "print_hide", 0); } } }, refresh: function(doc) { const me = this; this._super(); hide_fiel...
{ this.frm.set_indicator_formatter('item_code', function(doc) { return (doc.qty<=doc.received_qty) ? "green" : "orange"; }); }
conditional_block
app.ts
import {routes, ng, model, notify, http, BaseModel, Collection, Behaviours} from 'entcore' import { forumExtensions } from './extensions'; import { forumController } from './controller' routes.define(function($routeProvider){ $routeProvider .when('/view/:categoryId', { action: 'goToCategory' ...
}); }; Behaviours.applicationsBehaviours.forum.namespace.Category.prototype.save = function(callback){ if(this._id){ this.saveModifications(callback); } else{ this.createCategory(function(){ (model as any).categories.sync(); if (typeof callback === 'function') { callback(); } }); ...
{ callback(); }
conditional_block
app.ts
import {routes, ng, model, notify, http, BaseModel, Collection, Behaviours} from 'entcore' import { forumExtensions } from './extensions'; import { forumController } from './controller' routes.define(function($routeProvider){ $routeProvider .when('/view/:categoryId', { action: 'goToCategory' ...
} }.bind(this)); }, removeSelection: function(callback){ var counter = this.selection().length; this.selection().forEach(function(item){ http().delete('/forum/category/' + item._id).done(function(){ counter = counter - 1; if (counter === 0) { (model as any).categories.sync(); ...
random_line_split
test_static.py
import unittest from cStringIO import StringIO from ..backends import static # There aren't many tests here because it turns out to be way more convenient to # use test_serializer for the majority of cases class TestStatic(unittest.TestCase): def compile(self, input_text, input_data): return static.com...
(self): data = """key: if a == 1.5: value_1 value_2 key_1: other_value """ manifest = self.compile(data, {"a": 1.5}) self.assertFalse(manifest.is_empty) self.assertEquals(manifest.root, manifest) self.assertTrue(manifest.has_key("key_1")) self.assertFalse(manifest.ha...
test_api
identifier_name
test_static.py
import unittest from cStringIO import StringIO from ..backends import static # There aren't many tests here because it turns out to be way more convenient to # use test_serializer for the majority of cases class TestStatic(unittest.TestCase): def compile(self, input_text, input_data): return static.com...
def test_get_4(self): data = """key: if not a: value_1 value_2 """ manifest = self.compile(data, {"a": True}) self.assertEquals(manifest.get("key"), "value_2") manifest = self.compile(data, {"a": False}) self.assertEquals(manifest.get("key"), "value_1") def test_a...
data = """key: if a == "1": value_1 if a[0] == "ab"[0]: value_2 """ manifest = self.compile(data, {"a": "1"}) self.assertEquals(manifest.get("key"), "value_1") manifest = self.compile(data, {"a": "ac"}) self.assertEquals(manifest.get("key"), "value_2")
identifier_body
test_static.py
import unittest from cStringIO import StringIO from ..backends import static # There aren't many tests here because it turns out to be way more convenient to # use test_serializer for the majority of cases class TestStatic(unittest.TestCase): def compile(self, input_text, input_data): return static.com...
""" manifest = self.compile(data, {"a": "1"}) self.assertEquals(manifest.get("key"), "value_1") manifest = self.compile(data, {"a": "ac"}) self.assertEquals(manifest.get("key"), "value_2") def test_get_4(self): data = """key: if not a: value_1 value_2 """ manife...
if a[0] == "ab"[0]: value_2
random_line_split
070-E-ClimbingStairs.py
# You are climbing a stair case. It takes n steps to reach to the top. # # Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? # # Note: Given n will be a positive integer. # # Example 1: # # Input: 2 # Output: 2 # Explanation: There are two ways to climb to the top. # 1. ...
# Explanation: There are three ways to climb to the top. # 1. 1 step + 1 step + 1 step # 2. 1 step + 2 steps # 3. 2 steps + 1 step class Solution(object): def climbStairs(self, n): """ :type n: int :rtype: int """ table = [1, 2] i = 2 while i < n: ...
# # Input: 3 # Output: 3
random_line_split
070-E-ClimbingStairs.py
# You are climbing a stair case. It takes n steps to reach to the top. # # Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? # # Note: Given n will be a positive integer. # # Example 1: # # Input: 2 # Output: 2 # Explanation: There are two ways to climb to the top. # 1. ...
return table[n-1] # Note: # Generate two trees one with 1 step and other with 2 step and add both
table.append(table[i-1] + table[i-2]) i += 1
conditional_block
070-E-ClimbingStairs.py
# You are climbing a stair case. It takes n steps to reach to the top. # # Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? # # Note: Given n will be a positive integer. # # Example 1: # # Input: 2 # Output: 2 # Explanation: There are two ways to climb to the top. # 1. ...
(self, n): """ :type n: int :rtype: int """ table = [1, 2] i = 2 while i < n: table.append(table[i-1] + table[i-2]) i += 1 return table[n-1] # Note: # Generate two trees one with 1 step and other with 2 step and add both
climbStairs
identifier_name
070-E-ClimbingStairs.py
# You are climbing a stair case. It takes n steps to reach to the top. # # Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? # # Note: Given n will be a positive integer. # # Example 1: # # Input: 2 # Output: 2 # Explanation: There are two ways to climb to the top. # 1. ...
# Note: # Generate two trees one with 1 step and other with 2 step and add both
""" :type n: int :rtype: int """ table = [1, 2] i = 2 while i < n: table.append(table[i-1] + table[i-2]) i += 1 return table[n-1]
identifier_body
functions.rs
/* * MIT License * * Copyright (c) 2016 Johnathan Fercher * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy...
}
random_line_split
functions.rs
/* * MIT License * * Copyright (c) 2016 Johnathan Fercher * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy...
// receives two u8 and prints the bigger, without any return fn print_max(a: u8, b: u8) -> () { let mut low; if a > b { low = a; }else{ low = b; } println!("{}", low); } fn main() { println!("{}", return_max(10, 50)); print_max(10, 50); }
{ if a > b { a }else{ b } }
identifier_body
functions.rs
/* * MIT License * * Copyright (c) 2016 Johnathan Fercher * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy...
else{ low = b; } println!("{}", low); } fn main() { println!("{}", return_max(10, 50)); print_max(10, 50); }
{ low = a; }
conditional_block
functions.rs
/* * MIT License * * Copyright (c) 2016 Johnathan Fercher * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy...
(a: u8, b: u8) -> u8 { if a > b { a }else{ b } } // receives two u8 and prints the bigger, without any return fn print_max(a: u8, b: u8) -> () { let mut low; if a > b { low = a; }else{ low = b; } println!("{}", low); } fn main() { println!("{}", retu...
return_max
identifier_name
memory.js
'use strict'; var client = require('../http-client'); var extend = require('extend'); var http = require('http'); module.exports = function(dependencies) { var graceperiod = dependencies('graceperiod'); var logger = dependencies('logger'); return function(req, res, options) { var target = options.endpoin...
callback(error, response); }); } function onComplete(err, result) { logger.debug('Task has been completed'); if (err) { logger.error('Error while sending request to remote service', err); } if (result) { logger.info('Remote service response status code', ...
{ error = {error: {code: response.statusCode, message: http.STATUS_CODES[response.statusCode], details: response.statusMessage}}; logger.error('Error from remote service : ', response.body); if (options.onError) { return options.onError(response, body, req, res, callback.bind(n...
conditional_block
memory.js
'use strict'; var client = require('../http-client'); var extend = require('extend'); var http = require('http'); module.exports = function(dependencies) { var graceperiod = dependencies('graceperiod'); var logger = dependencies('logger'); return function(req, res, options) { var target = options.endpoin...
(err, result) { logger.debug('Task has been completed'); if (err) { logger.error('Error while sending request to remote service', err); } if (result) { logger.info('Remote service response status code', result.statusCode); } } function onCancel() { logger.inf...
onComplete
identifier_name
memory.js
'use strict'; var client = require('../http-client'); var extend = require('extend'); var http = require('http'); module.exports = function(dependencies) { var graceperiod = dependencies('graceperiod'); var logger = dependencies('logger'); return function(req, res, options) { var target = options.endpoin...
graceperiod.create(forwardRequest, delay, context, onComplete, onCancel).then(function(task) { logger.info('Grace Task %s has been created for %s', task.id, target); res.set('X-ESN-Task-Id', task.id); return res.status(202).json({id: task.id}); }, function(err) { logger.error('Error wh...
{ logger.info('Task has been aborted'); }
identifier_body
memory.js
'use strict'; var client = require('../http-client'); var extend = require('extend'); var http = require('http'); module.exports = function(dependencies) { var graceperiod = dependencies('graceperiod'); var logger = dependencies('logger');
var target = options.endpoint + '/' + options.path + req.url; var delay = options.graceperiod; var context = { user: req.user._id }; function forwardRequest(callback) { var requestOptions = { method: req.method, url: target, headers: extend({}, req.headers, { ESN...
return function(req, res, options) {
random_line_split
issue-11881.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
// ... } fn encode_json<'a, T: Encodable<json::Encoder<'a>, std::io::IoError>>(val: &T, wr: &'a mut SeekableMemWriter) { let mut encoder = json::Encoder::new(wr); val.encode(&mut encoder); } fn encode_rbml<'a, ...
random_line_split
issue-11881.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
{ baz: bool, } #[deriving(Encodable)] struct Bar { froboz: uint, } enum WireProtocol { JSON, RBML, // ... } fn encode_json<'a, T: Encodable<json::Encoder<'a>, std::io::IoError>>(val: &T, wr: &'a mut Seekabl...
Foo
identifier_name
deferred.py
# -*- coding: utf-8 -*- import copy from django.core.exceptions import ImproperlyConfigured from django.db.models.base import ModelBase from django.db import models from django.utils import six from django.utils.functional import SimpleLazyObject, _super, empty from shop import settings as shop_settings class Deferre...
attrs.setdefault('Meta', Meta) if not hasattr(attrs['Meta'], 'app_label') and not getattr(attrs['Meta'], 'abstract', False): attrs['Meta'].app_label = Meta.app_label attrs.setdefault('__module__', getattr(bases[-1], '__module__')) Model = super(ForeignKeyBuilder, cls).__new...
app_label = shop_settings.APP_LABEL
identifier_body
deferred.py
# -*- coding: utf-8 -*- import copy from django.core.exceptions import ImproperlyConfigured from django.db.models.base import ModelBase from django.db import models from django.utils import six from django.utils.functional import SimpleLazyObject, _super, empty from shop import settings as shop_settings class Deferre...
(DeferredRelatedField): """ Use this class to specify many-to-many keys in abstract classes. They will be converted into a real ``ManyToManyField`` whenever a real model class is derived from a given abstract class. """ MaterializedField = models.ManyToManyField class ForeignKeyBuilder(ModelBase):...
ManyToManyField
identifier_name
deferred.py
# -*- coding: utf-8 -*- import copy from django.core.exceptions import ImproperlyConfigured from django.db.models.base import ModelBase from django.db import models from django.utils import six from django.utils.functional import SimpleLazyObject, _super, empty from shop import settings as shop_settings class Deferre...
if self._wrapped is empty: self._setup() return self._wrapped(*args, **kwargs) def __deepcopy__(self, memo): if self._wrapped is empty: # We have to use SimpleLazyObject, not self.__class__, because the latter is proxied. result = MaterializedModel(self._...
def _setup(self): self._wrapped = getattr(self._base_model, '_materialized_model') def __call__(self, *args, **kwargs): # calls the constructor of the materialized model
random_line_split
deferred.py
# -*- coding: utf-8 -*- import copy from django.core.exceptions import ImproperlyConfigured from django.db.models.base import ModelBase from django.db import models from django.utils import six from django.utils.functional import SimpleLazyObject, _super, empty from shop import settings as shop_settings class Deferre...
ForeignKeyBuilder.process_pending_mappings(Model, basename) # search for deferred foreign fields in our Model for attrname in dir(Model): try: member = getattr(Model, attrname) except AttributeError: continue if not isinst...
if basename in cls._materialized_models: if Model.__name__ != cls._materialized_models[basename]: raise AssertionError("Both Model classes '%s' and '%s' inherited from abstract" "base class %s, which is disallowed in this configuration." % ...
conditional_block
macro-doc-escapes.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
fn main() { }
random_line_split
macro-doc-escapes.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
() { }
main
identifier_name
macro-doc-escapes.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
{ }
identifier_body
signpdf.py
#!/usr/bin/env python import os import time import argparse import tempfile import PyPDF2 import datetime from reportlab.pdfgen import canvas parser = argparse.ArgumentParser("Add signatures to PDF files") parser.add_argument("pdf", help="The pdf file to annotate") parser.add_argument("signature", help="The signature...
if __name__ == "__main__": main()
sign_pdf(parser.parse_args())
identifier_body
signpdf.py
#!/usr/bin/env python import os import time import argparse import tempfile import PyPDF2 import datetime from reportlab.pdfgen import canvas parser = argparse.ArgumentParser("Add signatures to PDF files") parser.add_argument("pdf", help="The pdf file to annotate") parser.add_argument("signature", help="The signature...
if sig_tmp_filename: os.remove(sig_tmp_filename) def main(): sign_pdf(parser.parse_args()) if __name__ == "__main__": main()
if handle: handle.close()
conditional_block
signpdf.py
#!/usr/bin/env python import os import time import argparse import tempfile import PyPDF2 import datetime from reportlab.pdfgen import canvas parser = argparse.ArgumentParser("Add signatures to PDF files") parser.add_argument("pdf", help="The pdf file to annotate") parser.add_argument("signature", help="The signature...
(args): #TODO: use a gui or something.... for now, just trial-and-error the coords page_num, x1, y1, width, height = [int(a) for a in args.coords.split("x")] page_num -= 1 output_filename = args.output or "{}_signed{}".format( *os.path.splitext(args.pdf) ) pdf_fh = open(args.pdf, 'rb')...
sign_pdf
identifier_name
signpdf.py
#!/usr/bin/env python import os import time import argparse import tempfile import PyPDF2 import datetime from reportlab.pdfgen import canvas parser = argparse.ArgumentParser("Add signatures to PDF files") parser.add_argument("pdf", help="The pdf file to annotate") parser.add_argument("signature", help="The signature...
if __name__ == "__main__": main()
def main(): sign_pdf(parser.parse_args())
random_line_split
mod.rs
//! The SMTP transport sends emails using the SMTP protocol. //! //! This SMTP client follows [RFC //! 5321](https://tools.ietf.org/html/rfc5321), and is designed to efficiently send emails from an //! application to a relay email server, as it relies as much as possible on the relay server //! for sanity and RFC compl...
() -> Self { Self { server: "localhost".to_string(), port: SMTP_PORT, hello_name: ClientId::default(), credentials: None, authentication: DEFAULT_MECHANISMS.into(), timeout: Some(DEFAULT_TIMEOUT), tls: Tls::None, } }...
default
identifier_name
mod.rs
//! The SMTP transport sends emails using the SMTP protocol. //! //! This SMTP client follows [RFC //! 5321](https://tools.ietf.org/html/rfc5321), and is designed to efficiently send emails from an //! application to a relay email server, as it relies as much as possible on the relay server //! for sanity and RFC compl...
//! * Fast: supports connection reuse and pooling //! //! This client is designed to send emails to a relay server, and should *not* be used to send //! emails directly to the destination server. //! //! The relay server can be the local email server, a specific host or a third-party service. //! //! #### Simple exampl...
//! It is designed to be: //! //! * Secured: connections are encrypted by default //! * Modern: unicode support for email contents and sender/recipient addresses when compatible
random_line_split
io.py
# -*- coding: utf-8 -*- from __future__ import print_function from __future__ import unicode_literals import sys from terminaltables import SingleTable def _to_utf8(message): try: return message.encode('utf-8') except UnicodeDecodeError: return message def _print_message(stream, *component...
"""Prompts the user to select an option in the `selection` list.""" while True: id_ = collect_single_input(prompt) if id_ == 'q': return None try: id_ = int(id_) - 1 if id_ < 0: continue return selection[id_] except ...
def collect_input(prompt, selection):
random_line_split
io.py
# -*- coding: utf-8 -*- from __future__ import print_function from __future__ import unicode_literals import sys from terminaltables import SingleTable def _to_utf8(message): try: return message.encode('utf-8') except UnicodeDecodeError: return message def _print_message(stream, *component...
# @see: http://pueblo.sourceforge.net/doc/manual/ansi_color_codes.html U_ERROR = add_color('[error]', 'red') U_WARNING = add_color('[warn]', 'yellow') U_INFO = add_color('==>', 'blue') U_OK = add_color('OK ✓', 'green')
"""Prompts the user to select an option in the `selection` list.""" while True: id_ = collect_single_input(prompt) if id_ == 'q': return None try: id_ = int(id_) - 1 if id_ < 0: continue return selection[id_] except (Val...
identifier_body
io.py
# -*- coding: utf-8 -*- from __future__ import print_function from __future__ import unicode_literals import sys from terminaltables import SingleTable def _to_utf8(message): try: return message.encode('utf-8') except UnicodeDecodeError: return message def _print_message(stream, *component...
# @see: http://pueblo.sourceforge.net/doc/manual/ansi_color_codes.html U_ERROR = add_color('[error]', 'red') U_WARNING = add_color('[warn]', 'yellow') U_INFO = add_color('==>', 'blue') U_OK = add_color('OK ✓', 'green')
id_ = collect_single_input(prompt) if id_ == 'q': return None try: id_ = int(id_) - 1 if id_ < 0: continue return selection[id_] except (ValueError, TypeError, IndexError): continue
conditional_block
io.py
# -*- coding: utf-8 -*- from __future__ import print_function from __future__ import unicode_literals import sys from terminaltables import SingleTable def _to_utf8(message): try: return message.encode('utf-8') except UnicodeDecodeError: return message def
(stream, *components): message = ' '.join(map(unicode, components)) return print(message, file=stream) def err(message): _print_message(sys.stderr, U_ERROR, message) def warn(message): _print_message(sys.stderr, U_WARNING, message) def info(message): _print_message(sys.stdout, U_INFO, message)...
_print_message
identifier_name
rec-align-u64.rs
// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
} pub fn main() { unsafe { let x = Outer {c8: 22, t: Inner {c64: 44}}; let y = format!("{:?}", x); println!("align inner = {:?}", rusti::min_align_of::<Inner>()); println!("size outer = {:?}", mem::size_of::<Outer>()); println!("y = {:?}", y); // per clang/gcc the...
#[cfg(any(target_arch = "arm", target_arch = "aarch64"))] pub mod m { pub fn align() -> uint { 8 } pub fn size() -> uint { 16 } }
random_line_split
rec-align-u64.rs
// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
() -> uint { 8 } pub fn size() -> uint { 16 } } } #[cfg(target_os = "android")] mod m { #[cfg(any(target_arch = "arm", target_arch = "aarch64"))] pub mod m { pub fn align() -> uint { 8 } pub fn size() -> uint { 16 } } } pub fn main() { unsafe { let x = Outer {c8: 22...
align
identifier_name
rec-align-u64.rs
// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
pub fn size() -> uint { 16 } } } #[cfg(target_os = "bitrig")] mod m { #[cfg(target_arch = "x86_64")] pub mod m { pub fn align() -> uint { 8 } pub fn size() -> uint { 16 } } } #[cfg(target_os = "windows")] mod m { #[cfg(target_arch = "x86")] pub mod m { pub fn a...
{ 8 }
identifier_body
elrte.jp.js
/** * Japanese translation * @author Tomoaki Yoshida <info@yoshida-studio.jp> * @version 2010-09-18 */ (function($) { elRTE.prototype.i18Messages.jp = { '_translator' : 'Tomoaki Yoshida &lt;info@yoshida-studio.jp&gt;', '_translation' : 'Japanese translation', 'Editor' : 'エディター', 'Source' : 'ソース', // Panel...
'Delete link' : 'リンク削除', 'Bookmark' : 'アンカー挿入/編集', 'Image' : 'イメージ', 'Table' : 'テーブル', 'Delete table' : 'テーブル削除', 'Insert row before' : '前に行を挿入', 'Insert row after' : '後ろに行を挿入', 'Delete row' : '行を削除', 'Insert co...
'Block element (DIV)' : 'ブロック要素 (DIV)', 'Link' : 'リンク',
random_line_split
easy.rs
use std::sync::{Once, ONCE_INIT}; use std::c_vec::CVec; use std::{io,mem}; use std::collections::HashMap; use libc::{c_void,c_int,c_long,c_double,size_t}; use super::{consts,err,info,opt}; use super::err::ErrCode; use http::body::Body; use http::{header,Response}; type CURL = c_void; pub type ProgressCb<'a> = |uint, u...
() { // Schedule curl to be cleaned up after we're done with this whole process static mut INIT: Once = ONCE_INIT; unsafe { INIT.doit(|| ::std::rt::at_exit(proc() curl_global_cleanup())) } } impl Drop for Easy { fn drop(&mut self) { unsafe { curl_easy_cleanup(self.curl) } } } /...
global_init
identifier_name
easy.rs
use std::sync::{Once, ONCE_INIT}; use std::c_vec::CVec; use std::{io,mem}; use std::collections::HashMap; use libc::{c_void,c_int,c_long,c_double,size_t}; use super::{consts,err,info,opt}; use super::err::ErrCode; use http::body::Body; use http::{header,Response}; type CURL = c_void; pub type ProgressCb<'a> = |uint, u...
pub extern "C" fn curl_header_fn(p: *mut u8, size: size_t, nmemb: size_t, resp: &mut ResponseBuilder) -> size_t { // TODO: Skip the first call (it seems to be the status line) let vec = unsafe { CVec::new(p, (size * nmemb) as uint) }; match header::parse(vec.as_slice()) { Some((name, val)) => { ...
{ if !resp.is_null() { let builder: &mut ResponseBuilder = unsafe { mem::transmute(resp) }; let chunk = unsafe { CVec::new(p, (size * nmemb) as uint) }; builder.body.push_all(chunk.as_slice()); } size * nmemb }
identifier_body
easy.rs
use std::sync::{Once, ONCE_INIT}; use std::c_vec::CVec; use std::{io,mem}; use std::collections::HashMap; use libc::{c_void,c_int,c_long,c_double,size_t}; use super::{consts,err,info,opt}; use super::err::ErrCode; use http::body::Body; use http::{header,Response}; type CURL = c_void; pub type ProgressCb<'a> = |uint, u...
return Err(res); } Ok(v) } } #[inline] fn global_init() { // Schedule curl to be cleaned up after we're done with this whole process static mut INIT: Once = ONCE_INIT; unsafe { INIT.doit(|| ::std::rt::at_exit(proc() curl_global_cleanup())) } } impl Drop for Eas...
if !res.is_success() {
random_line_split
webostv.py
""" Support for interface with an LG webOS Smart TV. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/media_player.webostv/ """ import logging import asyncio from datetime import timedelta from urllib.parse import urlparse import voluptuous as vol import...
# Try to pair. try: client.register() except PyLGTVPairException: _LOGGER.warning( "Connected to LG webOS TV %s but not paired", host) return except (OSError, ConnectionClosed, TypeError, ...
client = WebOsClient(host, config) if not client.is_registered(): if host in _CONFIGURING:
random_line_split
webostv.py
""" Support for interface with an LG webOS Smart TV. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/media_player.webostv/ """ import logging import asyncio from datetime import timedelta from urllib.parse import urlparse import voluptuous as vol import...
else: self._state = STATE_OFF self._current_source = None self._current_source_id = None if self._state is not STATE_OFF: self._muted = self._client.get_muted() self._volume = self._client.get_volume() ...
self._state = STATE_PLAYING
conditional_block
webostv.py
""" Support for interface with an LG webOS Smart TV. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/media_player.webostv/ """ import logging import asyncio from datetime import timedelta from urllib.parse import urlparse import voluptuous as vol import...
@property def media_image_url(self): """Image url of current playing media.""" if self._current_source_id in self._app_list: icon = self._app_list[self._current_source_id]['largeIcon'] if not icon.startswith('http'): icon = self._app_list[self._current_s...
"""Content type of current playing media.""" return MEDIA_TYPE_CHANNEL
identifier_body
webostv.py
""" Support for interface with an LG webOS Smart TV. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/media_player.webostv/ """ import logging import asyncio from datetime import timedelta from urllib.parse import urlparse import voluptuous as vol import...
(self): """Return the current input source.""" return self._current_source @property def source_list(self): """List of available input sources.""" return sorted(self._source_list.keys()) @property def media_content_type(self): """Content type of current playing ...
source
identifier_name
term.rs
use std::fmt; use super::Field; use byteorder::{BigEndian, ByteOrder}; use common; use schema::Facet; use std::str; use DateTime; /// Size (in bytes) of the buffer of a int field. const INT_TERM_LEN: usize = 4 + 8; /// Term represents the value that the token can take. /// /// It actually wraps a `Vec<u8>`. #[derive...
/// Builds a term given a field, and a string value /// /// Assuming the term has a field id of 2, and a text value of "abc", /// the Term will have 4 bytes. /// The first byte is 2, and the three following bytes are the utf-8 /// representation of "abc". pub fn from_field_text(field: Fiel...
{ let bytes = facet.encoded_str().as_bytes(); let buffer = Vec::with_capacity(4 + bytes.len()); let mut term = Term(buffer); term.set_field(field); term.set_bytes(bytes); term }
identifier_body
term.rs
use std::fmt; use super::Field; use byteorder::{BigEndian, ByteOrder}; use common; use schema::Facet; use std::str; use DateTime; /// Size (in bytes) of the buffer of a int field. const INT_TERM_LEN: usize = 4 + 8; /// Term represents the value that the token can take. /// /// It actually wraps a `Vec<u8>`. #[derive...
} /// Returns the `u64` value stored in a term. /// /// # Panics /// ... or returns an invalid value /// if the term is not a `u64` field. pub fn get_u64(&self) -> u64 { BigEndian::read_u64(&self.0.as_ref()[4..]) } /// Returns the `i64` value stored in a term. /// /...
random_line_split
term.rs
use std::fmt; use super::Field; use byteorder::{BigEndian, ByteOrder}; use common; use schema::Facet; use std::str; use DateTime; /// Size (in bytes) of the buffer of a int field. const INT_TERM_LEN: usize = 4 + 8; /// Term represents the value that the token can take. /// /// It actually wraps a `Vec<u8>`. #[derive...
BigEndian::write_u32(&mut self.0[0..4], field.0); } /// Sets a u64 value in the term. /// /// U64 are serialized using (8-byte) BigEndian /// representation. /// The use of BigEndian has the benefit of preserving /// the natural order of the values. pub fn set_u64(&mut self, va...
{ self.0.resize(4, 0u8); }
conditional_block
term.rs
use std::fmt; use super::Field; use byteorder::{BigEndian, ByteOrder}; use common; use schema::Facet; use std::str; use DateTime; /// Size (in bytes) of the buffer of a int field. const INT_TERM_LEN: usize = 4 + 8; /// Term represents the value that the token can take. /// /// It actually wraps a `Vec<u8>`. #[derive...
(&mut self, val: i64) { self.set_u64(common::i64_to_u64(val)); } fn set_bytes(&mut self, bytes: &[u8]) { self.0.resize(4, 0u8); self.0.extend(bytes); } pub(crate) fn from_field_bytes(field: Field, bytes: &[u8]) -> Term { let mut term = Term::for_field(field); te...
set_i64
identifier_name
cadastro.ts
import { Component } from '@angular/core'; import { IonicPage, NavController, NavParams, ToastController, Events } from 'ionic-angular'; import { AppPreferences } from '@ionic-native/app-preferences'; import { Cliente } from '../../models/cliente'; import { EnderecoPage } from '../endereco/endereco'; import { Link } f...
@IonicPage() @Component({ selector: 'page-cadastro', templateUrl: 'cadastro.html', }) export class CadastroPage { public data: any; public link: Link; nome: string = ''; email: string = ''; senha: string = ''; cliente: Cliente; constructor(private toastCtrl: ToastController, public navCtrl: NavCont...
* See http://ionicframework.com/docs/components/#navigation for more info * on Ionic pages and navigation. */
random_line_split