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 |
|---|---|---|---|---|
utf8.ts | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may... |
return (input = '') => toUint8Array(_Buffer.from(input, 'utf8'));
})(typeof TextEncoder !== 'undefined' ? TextEncoder : TextEncoderPolyfill);
| {
const encoder = new TextEncoder();
return encoder.encode.bind(encoder);
} | conditional_block |
lib.rs | // Copyright 2018 TiKV Project Authors. Licensed under Apache-2.0.
#![feature(test)]
extern crate test;
#[macro_use]
extern crate slog_global;
pub mod encryption;
mod kv_generator;
mod logging;
mod macros;
mod runner;
mod security;
use rand::Rng;
use std::sync::atomic::{AtomicU16, Ordering};
use std::{env, thread};... |
if env::var("LOG_FILE").is_ok() {
logging::init_log_for_test();
}
}
if env::var("PANIC_ABORT").is_ok() {
// Panics as aborts, it's helpful for debugging,
// but also stops tests immediately.
tikv_util::set_panic_hook(true, "./");
}
tikv_util::check_... | {
// We use backtrace in tests to record suspicious problems. And loading backtrace
// the first time can take several seconds. Spawning a thread and load it ahead
// of time to avoid causing timeout.
thread::Builder::new()
.name(tikv_util::thd_name!("backtrace-loader"))
.spawn(::backtra... | identifier_body |
lib.rs | // Copyright 2018 TiKV Project Authors. Licensed under Apache-2.0.
#![feature(test)]
extern crate test;
#[macro_use]
extern crate slog_global;
pub mod encryption;
mod kv_generator;
mod logging;
mod macros;
mod runner;
mod security;
use rand::Rng;
use std::sync::atomic::{AtomicU16, Ordering};
use std::{env, thread};... | () {
// We use backtrace in tests to record suspicious problems. And loading backtrace
// the first time can take several seconds. Spawning a thread and load it ahead
// of time to avoid causing timeout.
thread::Builder::new()
.name(tikv_util::thd_name!("backtrace-loader"))
.spawn(::back... | setup_for_ci | identifier_name |
lib.rs | // Copyright 2018 TiKV Project Authors. Licensed under Apache-2.0.
#![feature(test)]
| #[macro_use]
extern crate slog_global;
pub mod encryption;
mod kv_generator;
mod logging;
mod macros;
mod runner;
mod security;
use rand::Rng;
use std::sync::atomic::{AtomicU16, Ordering};
use std::{env, thread};
pub use crate::encryption::*;
pub use crate::kv_generator::*;
pub use crate::logging::*;
pub use crate::... | extern crate test; | random_line_split |
gui5.py | """Tables, Widgets, and Groups!
An example of tables and most of the included widgets.
"""
import pygame
from pygame.locals import *
# the following line is not needed if pgu is installed
import sys; sys.path.insert(0, "..")
from pgu import gui
# Load an alternate theme to show how it is done. You can also
# speci... | ():
print("Input received")
w = gui.Input(value='Cuzco',size=8)
w.connect("activate", cb)
c.td(w,colspan=3)
c.tr()
c.td(gui.Label("Slider"))
c.td(gui.HSlider(value=23,min=0,max=100,size=20,width=120),colspan=3)
c.tr()
c.td(gui.Label("Keysym"))
c.td(gui.Keysym(),colspan=3)
c.tr()
c.td(gui.Label("Text Area"), cols... | cb | identifier_name |
gui5.py | """Tables, Widgets, and Groups!
An example of tables and most of the included widgets.
"""
import pygame
from pygame.locals import *
# the following line is not needed if pgu is installed
import sys; sys.path.insert(0, "..")
from pgu import gui
# Load an alternate theme to show how it is done. You can also
# speci... |
w = gui.Input(value='Cuzco',size=8)
w.connect("activate", cb)
c.td(w,colspan=3)
c.tr()
c.td(gui.Label("Slider"))
c.td(gui.HSlider(value=23,min=0,max=100,size=20,width=120),colspan=3)
c.tr()
c.td(gui.Label("Keysym"))
c.td(gui.Keysym(),colspan=3)
c.tr()
c.td(gui.Label("Text Area"), colspan=4, align=-1)
c.tr()
c.td(g... | print("Input received") | identifier_body |
gui5.py | """Tables, Widgets, and Groups!
An example of tables and most of the included widgets.
"""
import pygame
from pygame.locals import *
# the following line is not needed if pgu is installed
import sys; sys.path.insert(0, "..") |
# Load an alternate theme to show how it is done. You can also
# specify a path (absolute or relative) to your own custom theme:
#
# app = gui.Desktop(theme=gui.Theme("path/to/theme"))
#
app = gui.Desktop()
app.connect(gui.QUIT,app.quit,None)
##The table code is entered much like HTML.
##::
c = gui.Table()
c.tr(... |
from pgu import gui | random_line_split |
gulpfile.js | /**
* Created by kusamao_abe on 2015/11/17.
*/
var gulp = require( 'gulp' ),
jade = require( 'gulp-jade' ),
scss = require( 'gulp-sass' ),
browser = require( 'browser-sync' ), | plumber = require( 'gulp-plumber' ),
data = require( 'gulp-data' );
var PLEASE_OPTION = {
'autoprefixer': { 'browsers': [ 'last 2 versions', 'ie >= 8', 'Android >= 4' ] },
'minifier': false,
'filters': false,
'rem': [ '10px' ]
};
var dataStream = function () {
return require( './data.json'... | please = require( 'gulp-pleeease' ), | random_line_split |
test_update_order_lines_partner.py | import ddt
from django.core.management import call_command
from django.core.management.base import CommandError
from mock import patch
from oscar.core.loading import get_model
from ecommerce.extensions.test.factories import create_order
from ecommerce.tests.factories import PartnerFactory
from ecommerce.tests.testcase... | self.assertNotEqual(order_line.partner_name, new_partner.name) | random_line_split | |
test_update_order_lines_partner.py |
import ddt
from django.core.management import call_command
from django.core.management.base import CommandError
from mock import patch
from oscar.core.loading import get_model
from ecommerce.extensions.test.factories import create_order
from ecommerce.tests.factories import PartnerFactory
from ecommerce.tests.testca... | (self, error_msg, *args):
"""Helper to call command and assert error log."""
with self.assertRaisesRegex(CommandError, error_msg):
call_command('update_order_lines_partner', *args)
def test_partner_required(self):
"""Test that command raises partner required error."""
er... | assert_error_log | identifier_name |
test_update_order_lines_partner.py |
import ddt
from django.core.management import call_command
from django.core.management.base import CommandError
from mock import patch
from oscar.core.loading import get_model
from ecommerce.extensions.test.factories import create_order
from ecommerce.tests.factories import PartnerFactory
from ecommerce.tests.testca... | self.assertNotEqual(order_line.partner, new_partner)
self.assertNotEqual(order_line.partner_name, new_partner.name) | conditional_block | |
test_update_order_lines_partner.py |
import ddt
from django.core.management import call_command
from django.core.management.base import CommandError
from mock import patch
from oscar.core.loading import get_model
from ecommerce.extensions.test.factories import create_order
from ecommerce.tests.factories import PartnerFactory
from ecommerce.tests.testca... |
def test_partner_required(self):
"""Test that command raises partner required error."""
err_msg = 'Error: the following arguments are required: --partner'
self.assert_error_log(
err_msg,
'sku12345'
)
def test_partner_does_not_exist(self):
"""Tes... | """Helper to call command and assert error log."""
with self.assertRaisesRegex(CommandError, error_msg):
call_command('update_order_lines_partner', *args) | identifier_body |
Signum.Entities.Printing.ts | //////////////////////////////////
//Auto-generated. Do NOT modify!//
//////////////////////////////////
import { MessageKey, QueryKey, Type, EnumType, registerSymbol } from '../../Signum.React/Scripts/Reflection'
import * as Entities from '../../Signum.React/Scripts/Signum.Entities'
import * as Processes from '... |
export module PrintLineOperation {
export const CreateTest : Entities.ConstructSymbol_Simple<PrintLineEntity> = registerSymbol("Operation", "PrintLineOperation.CreateTest");
export const SaveTest : Entities.ExecuteSymbol<PrintLineEntity> = registerSymbol("Operation", "PrintLineOperation.SaveTest");
export co... | package: Entities.Lite<PrintPackageEntity> | null;
printedOn: string /*DateTime*/ | null;
referred: Entities.Lite<Entities.Entity> | null;
state: PrintLineState;
}
| random_line_split |
manager.py | """
Custom manager for HelpEntry objects.
"""
from django.db import models
from src.utils import logger, utils | class HelpEntryManager(models.Manager):
"""
This HelpEntryManager implements methods for searching
and manipulating HelpEntries directly from the database.
These methods will all return database objects
(or QuerySets) directly.
Evennia-specific:
find_topicmatch
find_apropos
find_to... | __all__ = ("HelpEntryManager",)
| random_line_split |
manager.py | """
Custom manager for HelpEntry objects.
"""
from django.db import models
from src.utils import logger, utils
__all__ = ("HelpEntryManager",)
class HelpEntryManager(models.Manager):
"""
This HelpEntryManager implements methods for searching
and manipulating HelpEntries directly from the database.
Th... | (self):
"""
Return all topics.
"""
return self.all()
def get_all_categories(self, pobject):
"""
Return all defined category names with at least one
topic in them.
"""
return list(set(topic.help_category for topic in self.all()))
def all_t... | get_all_topics | identifier_name |
manager.py | """
Custom manager for HelpEntry objects.
"""
from django.db import models
from src.utils import logger, utils
__all__ = ("HelpEntryManager",)
class HelpEntryManager(models.Manager):
"""
This HelpEntryManager implements methods for searching
and manipulating HelpEntries directly from the database.
Th... |
else:
return self.filter(db_key__iexact=ostring)
| return self.filter(db_key__iexact=ostring,
db_help_category__iexact=help_category) | conditional_block |
manager.py | """
Custom manager for HelpEntry objects.
"""
from django.db import models
from src.utils import logger, utils
__all__ = ("HelpEntryManager",)
class HelpEntryManager(models.Manager):
"""
This HelpEntryManager implements methods for searching
and manipulating HelpEntries directly from the database.
Th... | """
Retrieve a search entry object.
ostring - the help topic to look for
category - limit the search to a particular help topic
"""
ostring = ostring.strip().lower()
if help_category:
return self.filter(db_key__iexact=ostring,
d... | identifier_body | |
thermostat.js | var Thermostat = function() {
this.targetTemperature = 20;
this.maxTempOn = 25;
this.maxTempOff = 32;
this.minTemp = 10;
this.powerSave = true;
this.increment = 1;
this.defaultTemperature = 20;
};
Thermostat.prototype.temperature = function() {
return this.targetTemperature; |
Thermostat.prototype.up = function() {
if (this.powerSave === true && this.targetTemperature === this.maxTempOn) {
this.targetTemperature = this.maxTempOn
} else if (this.powerSave === false && this.targetTemperature === this.maxTempOff) {
this.targetTemperature = this.maxTempOff
} else {
this.target... | }; | random_line_split |
thermostat.js | var Thermostat = function() {
this.targetTemperature = 20;
this.maxTempOn = 25;
this.maxTempOff = 32;
this.minTemp = 10;
this.powerSave = true;
this.increment = 1;
this.defaultTemperature = 20;
};
Thermostat.prototype.temperature = function() {
return this.targetTemperature;
};
Thermostat.prototy... |
};
Thermostat.prototype.down = function() {
if (this.targetTemperature > this.minTemp) {
this.targetTemperature--;
};
};
Thermostat.prototype.powerSave = function() {
return this.powerSave;
};
Thermostat.prototype.powerSaveOff = function() {
this.powerSave = false;
};
Thermostat.prototype.powerSaveOn =... | {
this.targetTemperature++;
} | conditional_block |
to_bytes.rs | use bytes::{Buf, BufMut, Bytes};
use super::HttpBody;
/// Concatenate the buffers from a body into a single `Bytes` asynchronously.
///
/// This may require copying the data into a single buffer. If you don't need
/// a contiguous buffer, prefer the [`aggregate`](crate::body::aggregate())
/// function.
///
/// # Note... | vec.put(second);
while let Some(buf) = body.data().await {
vec.put(buf?);
}
Ok(vec.into())
}
| {
futures_util::pin_mut!(body);
// If there's only 1 chunk, we can just return Buf::to_bytes()
let mut first = if let Some(buf) = body.data().await {
buf?
} else {
return Ok(Bytes::new());
};
let second = if let Some(buf) = body.data().await {
buf?
} else {
... | identifier_body |
to_bytes.rs | use bytes::{Buf, BufMut, Bytes};
use super::HttpBody;
/// Concatenate the buffers from a body into a single `Bytes` asynchronously.
///
/// This may require copying the data into a single buffer. If you don't need
/// a contiguous buffer, prefer the [`aggregate`](crate::body::aggregate())
/// function.
///
/// # Note... | /// let body_bytes = hyper::body::to_bytes(response.into_body()).await?;
/// println!("body: {:?}", body_bytes);
/// }
///
/// # Ok(())
/// # }
/// ```
pub async fn to_bytes<T>(body: T) -> Result<Bytes, T::Error>
where
T: HttpBody,
{
futures_util::pin_mut!(body);
// If there's only 1 chunk, we can ... | ///
/// if response_content_length < MAX_ALLOWED_RESPONSE_SIZE { | random_line_split |
to_bytes.rs | use bytes::{Buf, BufMut, Bytes};
use super::HttpBody;
/// Concatenate the buffers from a body into a single `Bytes` asynchronously.
///
/// This may require copying the data into a single buffer. If you don't need
/// a contiguous buffer, prefer the [`aggregate`](crate::body::aggregate())
/// function.
///
/// # Note... | else {
return Ok(Bytes::new());
};
let second = if let Some(buf) = body.data().await {
buf?
} else {
return Ok(first.copy_to_bytes(first.remaining()));
};
// With more than 1 buf, we gotta flatten into a Vec first.
let cap = first.remaining() + second.remaining() + bod... | {
buf?
} | conditional_block |
to_bytes.rs | use bytes::{Buf, BufMut, Bytes};
use super::HttpBody;
/// Concatenate the buffers from a body into a single `Bytes` asynchronously.
///
/// This may require copying the data into a single buffer. If you don't need
/// a contiguous buffer, prefer the [`aggregate`](crate::body::aggregate())
/// function.
///
/// # Note... | <T>(body: T) -> Result<Bytes, T::Error>
where
T: HttpBody,
{
futures_util::pin_mut!(body);
// If there's only 1 chunk, we can just return Buf::to_bytes()
let mut first = if let Some(buf) = body.data().await {
buf?
} else {
return Ok(Bytes::new());
};
let second = if let Som... | to_bytes | identifier_name |
RefillAmmo.ts | /*
* 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/.
*
* @Author: Mehuge (mehuge@sorcerer.co.uk)
* @Date: 2017-04-12 20:01:27
* @Last Modified by: Mehuge (mehuge@so... | import RefillAmmo from '../../../components/RefillAmmo';
export default {
position: {
x: {
anchor: 9,
offset: 10,
},
y: {
anchor: 9,
offset: 40,
},
size: {
width: 120,
height: 35,
},
scale: 1,
opacity: 1,
visibility: true,
zOrder: 99,
la... |
import { LayoutMode, Edge } from '../../../components/HUDDrag'; | random_line_split |
main.rs | Rng>,
controllers: Vec<Box<Controller<World<cell::ShapeCell>,Event<(PlayerId,WorldId),WorldId>>>>,
request_receiver: sync::mpsc::Receiver<Request<PlayerId,WorldId>>,
connection: online::ConnectionType,
paused: bool,
key_map: ::game::data::input::key::KeyMap,
key_down: HashMap<Key,f64>,
}
impl App{
fn update(&mu... | if let hash_map::Entry::Vacant(entry) = self.key_down.entry(key){
entry.insert(mapping.repeat_delay);
request_sender.send(Request::PlayerInput{input: mapping.input,player: mapping.player}).unwrap();
}
}
}}
}
fn on_key_release(&mut self,key: Key){
if let hash_map::Entry::Occupied(entry) = sel... | },
Key::Home => {if let Some(player) = self.game_state.data.players.get_mut(0 as usize){player.pos.y = 0;};},
//Other keys, check key bindings
key => if let Some(mapping) = self.key_map.get(&key){ | random_line_split |
main.rs | Rng>,
controllers: Vec<Box<Controller<World<cell::ShapeCell>,Event<(PlayerId,WorldId),WorldId>>>>,
request_receiver: sync::mpsc::Receiver<Request<PlayerId,WorldId>>,
connection: online::ConnectionType,
paused: bool,
key_map: ::game::data::input::key::KeyMap,
key_down: HashMap<Key,f64>,
}
impl App{
fn update(&mu... |
}
}
//Input
while let Ok(request) = self.request_receiver.try_recv(){match request{
Request::PlayerInput{input,player: pid} => {
if let Some(player) = self.game_state.data.players.get_mut(pid as usize){
if let Some(&mut(ref mut world,false)) = self.game_state.data.worlds.get_mut(player.world as u... | {
f64::NAN//TODO: If the mapping doesn't exist, it will never be removed
} | conditional_block |
main.rs | {
gl: GlGraphics,
game_state: game::State<World<cell::ShapeCell>,rand::StdRng>,
controllers: Vec<Box<Controller<World<cell::ShapeCell>,Event<(PlayerId,WorldId),WorldId>>>>,
request_receiver: sync::mpsc::Receiver<Request<PlayerId,WorldId>>,
connection: online::ConnectionType,
paused: bool,
key_map: ::game::data::... | App | identifier_name | |
main.rs | Rng>,
controllers: Vec<Box<Controller<World<cell::ShapeCell>,Event<(PlayerId,WorldId),WorldId>>>>,
request_receiver: sync::mpsc::Receiver<Request<PlayerId,WorldId>>,
connection: online::ConnectionType,
paused: bool,
key_map: ::game::data::input::key::KeyMap,
key_down: HashMap<Key,f64>,
}
impl App{
fn update(&mu... | }
}
//Input
while let Ok(request) = self.request_receiver.try_recv(){match request{
Request::PlayerInput{input,player: pid} => {
if let Some(player) = self.game_state.data.players.get_mut(pid as usize){
if let Some(&mut(ref mut world,false)) = self.game_state.data.worlds.get_mut(player.world as us... | {
//Controllers
if !self.paused{
for mut controller in self.controllers.iter_mut(){
controller.update(args,&self.game_state.data);
}
}
//Key repeat
for (key,time_left) in self.key_down.iter_mut(){
while{
*time_left-= args.dt;
*time_left <= 0.0
}{
*time_left = if let Some(mapping) ... | identifier_body |
markdown.js | /**
* The reveal.js markdown plugin. Handles parsing of
* markdown inside of presentations as well as loading
* of external markdown documents.
*/
(function(){
if( typeof marked === 'undefined' ) {
throw 'The reveal.js Markdown plugin requires marked to be loaded';
}
if( typeof hljs !== 'undefined... |
xhr.onreadystatechange = function() {
if( xhr.readyState === 4 ) {
if ( xhr.status >= 200 && xhr.status < 300 ) {
section.outerHTML = slidifyMarkdown( xhr.responseText, {
separator: section.getAttribute( 'data-separator' ),
verticalSeparator: section.getAttribute( 'data-ve... | {
var sections = document.querySelectorAll( '[data-markdown]'),
section;
for( var i = 0, len = sections.length; i < len; i++ ) {
section = sections[i];
if( section.getAttribute( 'data-markdown' ).length ) {
var xhr = new XMLHttpRequest(),
url = section.getAttribute( 'data-markdown... | identifier_body |
markdown.js | /**
* The reveal.js markdown plugin. Handles parsing of
* markdown inside of presentations as well as loading
* of external markdown documents.
*/
(function(){
if( typeof marked === 'undefined' ) {
throw 'The reveal.js Markdown plugin requires marked to be loaded';
}
if( typeof hljs !== 'undefined... |
return markdownSections;
}
function loadExternalMarkdown() {
var sections = document.querySelectorAll( '[data-markdown]'),
section;
for( var i = 0, len = sections.length; i < len; i++ ) {
section = sections[i];
if( section.getAttribute( 'data-markdown' ).length ) {
var xhr... | {
// vertical
if( sectionStack[i].propertyIsEnumerable( length ) && typeof sectionStack[i].splice === 'function' ) {
markdownSections += '<section '+ options.attributes +'>' +
'<section data-markdown>' + sectionStack[i].map( createMarkdownSlide ).join( '</section><section data-markdown>' ) + '<... | conditional_block |
markdown.js | /**
* The reveal.js markdown plugin. Handles parsing of
* markdown inside of presentations as well as loading
* of external markdown documents.
*/
(function(){
if( typeof marked === 'undefined' ) {
throw 'The reveal.js Markdown plugin requires marked to be loaded';
}
if( typeof hljs !== 'undefined... | ( section ) {
var template = section.querySelector( 'script' );
// strip leading whitespace so it isn't evaluated as code
var text = ( template || section ).textContent;
var leadingWs = text.match( /^\n?(\s*)/ )[1].length,
leadingTabs = text.match( /^\n?(\t*)/ )[1].length;
if( leadingTabs > 0... | getMarkdownFromSlide | identifier_name |
markdown.js | /**
* The reveal.js markdown plugin. Handles parsing of
* markdown inside of presentations as well as loading
* of external markdown documents.
*/
(function(){
if( typeof marked === 'undefined' ) {
throw 'The reveal.js Markdown plugin requires marked to be loaded';
}
if( typeof hljs !== 'undefined... | notes = noteMatch[1].trim();
}
slide = {
content: content,
notes: notes || ''
};
if( isHorizontal && wasHorizontal ) {
// add to horizontal stack
sectionStack.push( slide );
}
else {
// add to vertical stack
sectionStack[sectionStack.length-1].push( slide );... |
if( noteMatch.length === 2 ) {
content = noteMatch[0];
| random_line_split |
codehilite.py | import logging
import re
from markdown.extensions.codehilite import CodeHilite
from markdown.extensions.codehilite import CodeHiliteExtension
from markdown.preprocessors import Preprocessor
from markdown.treeprocessors import Treeprocessor
from wiki.core.markdown import add_to_registry
logger = logging.getLogger(__na... |
class WikiCodeHiliteExtension(CodeHiliteExtension):
"""
markdown.extensions.codehilite cannot configure container tags but forces
code to be in <table></table>, so we had to overwrite some of the code
because it's hard to extend...
"""
def extendMarkdown(self, md):
"""Add HilitePostp... | if len(block) == 1 and block[0].tag == "code":
html = highlight(block[0].text, self.config, self.markdown.tab_length)
placeholder = self.markdown.htmlStash.store(html)
# Clear codeblock in etree instance
block.clear()
# Change to p element ... | conditional_block |
codehilite.py | import logging
import re
from markdown.extensions.codehilite import CodeHilite
from markdown.extensions.codehilite import CodeHiliteExtension
from markdown.preprocessors import Preprocessor
from markdown.treeprocessors import Treeprocessor
from wiki.core.markdown import add_to_registry
logger = logging.getLogger(__na... | super().__init__(md)
self.checked_for_codehilite = False
self.codehilite_conf = {}
def run(self, lines):
"""Match and store Fenced Code Blocks in the HtmlStash."""
text = "\n".join(lines)
while 1:
m = self.FENCED_BLOCK_RE.search(text)
if m:
... | """
This is a replacement of markdown.extensions.fenced_code which will
directly and without configuration options invoke the vanilla CodeHilite
extension.
"""
FENCED_BLOCK_RE = re.compile(
r"""
(?P<fence>^(?:~{3,}|`{3,}))[ ]* # Opening ``` or ~~~
(\{?\.?(?P<lang>[a-zA-Z0-9_+-]*))?[... | identifier_body |
codehilite.py | import logging
import re
from markdown.extensions.codehilite import CodeHilite
from markdown.extensions.codehilite import CodeHiliteExtension
from markdown.preprocessors import Preprocessor
from markdown.treeprocessors import Treeprocessor
from wiki.core.markdown import add_to_registry
logger = logging.getLogger(__na... | guess_lang=config["guess_lang"],
css_class=config["css_class"],
style=config["pygments_style"],
noclasses=config["noclasses"],
tab_length=tab_length,
use_pygments=config["use_pygments"],
lang=lang,
)
html = code.hilite()
html = """<div class="codehilit... | random_line_split | |
codehilite.py | import logging
import re
from markdown.extensions.codehilite import CodeHilite
from markdown.extensions.codehilite import CodeHiliteExtension
from markdown.preprocessors import Preprocessor
from markdown.treeprocessors import Treeprocessor
from wiki.core.markdown import add_to_registry
logger = logging.getLogger(__na... | (*args, **kwargs):
"""Return an instance of the extension."""
return WikiCodeHiliteExtension(*args, **kwargs)
| makeExtension | identifier_name |
RapidBreachResponseEradicationTasksCountWidget.py | import demistomock as demisto # noqa: F401
from CommonServerPython import * # noqa: F401
ORANGE_HTML_STYLE = "'color:#EF9700;font-size:48px;padding: 60px; text-align:center;padding-left: 70px'>"
GREEN_HTML_STYLE = "'color:#1DB846;font-size:48px;padding: 60px; text-align:center;padding-left: 70px'>"
GREY_HTML_STYLE =... |
if __name__ in ["__main__", "builtin", "builtins"]:
main()
| incident = demisto.incidents()
query = incident[0].get('CustomFields', {}).get('eradicationtaskcount', 0)
if not query:
html = f"<div style={GREY_HTML_STYLE}{0}</div>"
elif int(query) == 0:
html = f"<div style={ORANGE_HTML_STYLE}{str(query)}</div>"
else:
html = f"<div style={GRE... | identifier_body |
RapidBreachResponseEradicationTasksCountWidget.py | import demistomock as demisto # noqa: F401
from CommonServerPython import * # noqa: F401
ORANGE_HTML_STYLE = "'color:#EF9700;font-size:48px;padding: 60px; text-align:center;padding-left: 70px'>"
GREEN_HTML_STYLE = "'color:#1DB846;font-size:48px;padding: 60px; text-align:center;padding-left: 70px'>"
GREY_HTML_STYLE =... | ():
incident = demisto.incidents()
query = incident[0].get('CustomFields', {}).get('eradicationtaskcount', 0)
if not query:
html = f"<div style={GREY_HTML_STYLE}{0}</div>"
elif int(query) == 0:
html = f"<div style={ORANGE_HTML_STYLE}{str(query)}</div>"
else:
html = f"<div st... | main | identifier_name |
RapidBreachResponseEradicationTasksCountWidget.py | import demistomock as demisto # noqa: F401
from CommonServerPython import * # noqa: F401
ORANGE_HTML_STYLE = "'color:#EF9700;font-size:48px;padding: 60px; text-align:center;padding-left: 70px'>"
GREEN_HTML_STYLE = "'color:#1DB846;font-size:48px;padding: 60px; text-align:center;padding-left: 70px'>"
GREY_HTML_STYLE =... | if __name__ in ["__main__", "builtin", "builtins"]:
main() | random_line_split | |
RapidBreachResponseEradicationTasksCountWidget.py | import demistomock as demisto # noqa: F401
from CommonServerPython import * # noqa: F401
ORANGE_HTML_STYLE = "'color:#EF9700;font-size:48px;padding: 60px; text-align:center;padding-left: 70px'>"
GREEN_HTML_STYLE = "'color:#1DB846;font-size:48px;padding: 60px; text-align:center;padding-left: 70px'>"
GREY_HTML_STYLE =... |
demisto.results({
'ContentsFormat': formats['html'],
'Type': entryTypes['note'],
'Contents': html
})
if __name__ in ["__main__", "builtin", "builtins"]:
main()
| html = f"<div style={GREEN_HTML_STYLE}{str(query)}</div>" | conditional_block |
types.rs | use core::fmt;
use core::ops::*;
pub use kernel::mm::{PhysAddrConv, MappedAddrConv, VirtAddrConv};
#[derive(Eq, PartialEq, Ord, PartialOrd, Clone, Copy, Debug, Default)]
pub struct PhysAddr(pub usize);
#[derive(Eq, PartialEq, Ord, PartialOrd, Clone, Copy, Debug, Default)]
pub struct MappedAddr(pub usize);
#[derive(... | else {
PhysAddr(self.0)
}
}
}
impl MappedAddrConv for MappedAddr {
fn to_phys(&self) -> PhysAddr {
if self >= &PHYSMAP {
PhysAddr(self.0 - PHYSMAP.0)
} else {
PhysAddr(self.0)
}
}
} | {
PhysAddr(self.0 - VIRT.0)
} | conditional_block |
types.rs | use core::fmt;
use core::ops::*;
pub use kernel::mm::{PhysAddrConv, MappedAddrConv, VirtAddrConv};
#[derive(Eq, PartialEq, Ord, PartialOrd, Clone, Copy, Debug, Default)]
pub struct PhysAddr(pub usize);
#[derive(Eq, PartialEq, Ord, PartialOrd, Clone, Copy, Debug, Default)]
pub struct MappedAddr(pub usize);
#[derive(... | (pub usize);
enable_unsigned_ops!(PhysAddr);
enable_unsigned_ops!(MappedAddr);
enable_unsigned_ops!(VirtAddr);
const VIRT : VirtAddr = VirtAddr(0xFFFFFF0000000000);
const PHYSMAP : MappedAddr = MappedAddr(0xFFFF800000000000);
impl PhysAddrConv for PhysAddr {
fn to_mapped(&self) -> MappedAddr {
if self.0 ... | VirtAddr | identifier_name |
types.rs | use core::fmt;
use core::ops::*;
pub use kernel::mm::{PhysAddrConv, MappedAddrConv, VirtAddrConv};
#[derive(Eq, PartialEq, Ord, PartialOrd, Clone, Copy, Debug, Default)]
pub struct PhysAddr(pub usize);
#[derive(Eq, PartialEq, Ord, PartialOrd, Clone, Copy, Debug, Default)]
pub struct MappedAddr(pub usize);
#[derive(... | impl MappedAddrConv for MappedAddr {
fn to_phys(&self) -> PhysAddr {
if self >= &PHYSMAP {
PhysAddr(self.0 - PHYSMAP.0)
} else {
PhysAddr(self.0)
}
}
} | }
}
| random_line_split |
receive.py | from django.db import models
from django.utils import timezone
from edc_base.model.models import BaseUuidModel
from simple_history.models import HistoricalRecords as AuditTrail
from getresults_patient.models import Patient
from .receive_identifier import ReceiveIdentifier
class ReceiveBaseFieldsMixin(models.Model):... |
super(Receive, self).save(*args, **kwargs)
class Meta:
app_label = 'getresults_receive'
db_table = 'getresults_receive'
unique_together = (('patient', 'collection_datetime', 'specimen_type'), )
| self.specimen_reference = '{}-{}'.format(
self.collection_datetime.strftime('%Y-%m-%d %H:%M'), self.specimen_type) | conditional_block |
receive.py | from django.db import models
from django.utils import timezone
from edc_base.model.models import BaseUuidModel
from simple_history.models import HistoricalRecords as AuditTrail
from getresults_patient.models import Patient
from .receive_identifier import ReceiveIdentifier
class ReceiveBaseFieldsMixin(models.Model):... | def save(self, *args, **kwargs):
if not self.id and not self.receive_identifier:
self.receive_identifier = ReceiveIdentifier().identifier
if not self.specimen_reference:
self.specimen_reference = '{}-{}'.format(
self.collection_datetime.strftime('%Y-%m-%d %H:%... | random_line_split | |
receive.py | from django.db import models
from django.utils import timezone
from edc_base.model.models import BaseUuidModel
from simple_history.models import HistoricalRecords as AuditTrail
from getresults_patient.models import Patient
from .receive_identifier import ReceiveIdentifier
class ReceiveBaseFieldsMixin(models.Model):... |
def save(self, *args, **kwargs):
if not self.id and not self.receive_identifier:
self.receive_identifier = ReceiveIdentifier().identifier
if not self.specimen_reference:
self.specimen_reference = '{}-{}'.format(
self.collection_datetime.strftime('%Y-%m-%d %H... | return '{}: {}'.format(
self.receive_identifier, self.receive_datetime.strftime('%Y-%m-%d %H:%M')) | identifier_body |
receive.py | from django.db import models
from django.utils import timezone
from edc_base.model.models import BaseUuidModel
from simple_history.models import HistoricalRecords as AuditTrail
from getresults_patient.models import Patient
from .receive_identifier import ReceiveIdentifier
class ReceiveBaseFieldsMixin(models.Model):... | (self, *args, **kwargs):
if not self.id and not self.receive_identifier:
self.receive_identifier = ReceiveIdentifier().identifier
if not self.specimen_reference:
self.specimen_reference = '{}-{}'.format(
self.collection_datetime.strftime('%Y-%m-%d %H:%M'), self.sp... | save | identifier_name |
loggingFunctions.py | #!/usr/bin/env python
|
import logging
import tempfile
import os
def initialize_logging():
"""
Set up the screen and file logging.
:return: The log filename
"""
# set up DEBUG logging to file, INFO logging to STDERR
log_file = os.path.join(tempfile.gettempdir(), 'spfy.log')
formatter = logging.Formatter(
... | """
Set up the logging
""" | random_line_split |
loggingFunctions.py | #!/usr/bin/env python
"""
Set up the logging
"""
import logging
import tempfile
import os
def | ():
"""
Set up the screen and file logging.
:return: The log filename
"""
# set up DEBUG logging to file, INFO logging to STDERR
log_file = os.path.join(tempfile.gettempdir(), 'spfy.log')
formatter = logging.Formatter(
'%(asctime)s %(name)-12s %(levelname)-8s %(message)s')
# s... | initialize_logging | identifier_name |
loggingFunctions.py | #!/usr/bin/env python
"""
Set up the logging
"""
import logging
import tempfile
import os
def initialize_logging():
| console.setLevel(logging.INFO)
# add the handler to the root logger
logging.getLogger('').addHandler(console)
return log_file
| """
Set up the screen and file logging.
:return: The log filename
"""
# set up DEBUG logging to file, INFO logging to STDERR
log_file = os.path.join(tempfile.gettempdir(), 'spfy.log')
formatter = logging.Formatter(
'%(asctime)s %(name)-12s %(levelname)-8s %(message)s')
# set up lo... | identifier_body |
ErrorsField.tsx | import { useTheme, PropTypes } from '@material-ui/core';
import FormControl from '@material-ui/core/FormControl';
import FormHelperText, {
FormHelperTextProps,
} from '@material-ui/core/FormHelperText';
import React from 'react';
import { Override, filterDOMProps, useForm } from 'uniforms';
export type ErrorsFieldPr... | }
>;
function ErrorsField({
children,
fullWidth,
margin,
variant,
...props
}: ErrorsFieldProps) {
const theme = useTheme();
const themeProps = theme.props?.MuiFormControl;
const { error, schema } = useForm();
return !error && !children ? null : (
<FormControl
error={!!error}
fullWi... | variant?: 'standard' | 'outlined' | 'filled'; | random_line_split |
dialog.ts | // SPDX-FileCopyrightText: 2018-2020 The Manyverse Authors
//
// SPDX-License-Identifier: MPL-2.0
import {Stream} from 'xstream';
import {Image} from 'react-native-image-crop-picker';
import {DialogSource} from '../../drivers/dialogs';
import {t} from '../../drivers/localization';
import {Palette} from '../../global-s... | (actions: Actions, dialogSource: DialogSource) {
return {
updateContentWarning$: actions.openContentWarning$
.map(() =>
dialogSource.prompt(
t('compose.dialogs.content_warning.title'),
t('compose.dialogs.content_warning.description'),
{
...Palette.dialogColo... | dialog | identifier_name |
dialog.ts | // SPDX-FileCopyrightText: 2018-2020 The Manyverse Authors
//
// SPDX-License-Identifier: MPL-2.0
import {Stream} from 'xstream';
import {Image} from 'react-native-image-crop-picker';
import {DialogSource} from '../../drivers/dialogs';
import {t} from '../../drivers/localization';
import {Palette} from '../../global-s... | dialogSource
.prompt(
t('compose.dialogs.image_caption.title'),
t('compose.dialogs.image_caption.description'),
{
...Palette.dialogColors,
positiveColor: Palette.textDialogStrong,
positiveText: t('call_to_action.done'),
... | {
return {
updateContentWarning$: actions.openContentWarning$
.map(() =>
dialogSource.prompt(
t('compose.dialogs.content_warning.title'),
t('compose.dialogs.content_warning.description'),
{
...Palette.dialogColors,
positiveText: t('call_to_action... | identifier_body |
dialog.ts | // SPDX-FileCopyrightText: 2018-2020 The Manyverse Authors
//
// SPDX-License-Identifier: MPL-2.0
import {Stream} from 'xstream';
import {Image} from 'react-native-image-crop-picker';
import {DialogSource} from '../../drivers/dialogs';
import {t} from '../../drivers/localization';
import {Palette} from '../../global-s... | {
...Palette.dialogColors,
positiveText: t('call_to_action.done'),
negativeText: t('call_to_action.cancel'),
},
),
)
.flatten()
.filter((res) => res.action === 'actionPositive')
.map((res) => (res as any).text as string),
addPi... | random_line_split | |
actions.test.js | import expect from 'expect';
import * as actions from '../actions';
import {
LOAD_DATA_INITIATION,
LOAD_DATA_SUCCESS,
LOAD_DATA_FAILURE,
CLEAR_DATA_ERROR,
} from '../constants';
// Testing actions is as easy as validating that the actions are dispatched
// The way you think they are being dispatched.
// Just t... | type: LOAD_DATA_SUCCESS,
data,
};
expect(
actions.loadDataSuccess(data)
).toEqual(expectedAction);
});
it('should dispatch an action with an error describing a failure to load data', () => {
const error = {
message: 'An error occured',
};
const expectedAction = {
... | it('should dispatch an action to successfully finish loading', () => {
const data = {
items: [],
};
const expectedAction = { | random_line_split |
catalog.rs | // Copyright 2017 Google 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... | path, err);
Vec::new()
}
}
})
.collect::<Vec<_>>();
PluginCatalog::new(&plugins)
}
pub fn new(plugins: &[PluginDescription]) -> Self {
let mut items = HashMap::with_capacity(pl... | Ok(plugins) => plugins,
Err(err) => {
eprintln!("error loading plugins from {:?}, error:\n{:?}", | random_line_split |
catalog.rs | // Copyright 2017 Google 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... | (&'a self) -> Box<Iterator<Item=&'a PluginDescription> + 'a> {
Box::new(self.items.values())
}
/// Returns an iterator over all plugin names in the catalog,
/// in arbitrary order.
pub fn iter_names(&'a self) -> Box<Iterator<Item=&'a PluginName> + 'a> {
Box::new(self.items.keys())
}
... | iter | identifier_name |
catalog.rs | // Copyright 2017 Google 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... |
pub fn new(plugins: &[PluginDescription]) -> Self {
let mut items = HashMap::with_capacity(plugins.len());
for plugin in plugins {
if items.contains_key(&plugin.name) {
eprintln!("Duplicate plugin name.\n 1: {:?}\n 2: {:?}",
plugin, items.get(... | {
let plugins = paths.iter()
.flat_map(|path| {
match load_plugins(path) {
Ok(plugins) => plugins,
Err(err) => {
eprintln!("error loading plugins from {:?}, error:\n{:?}",
path, err);
... | identifier_body |
catalog.rs | // Copyright 2017 Google 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... |
items.insert(plugin.name.to_owned(), plugin.to_owned());
}
PluginCatalog { items }
}
/// Returns an iterator over all plugins in the catalog, in arbitrary order.
pub fn iter(&'a self) -> Box<Iterator<Item=&'a PluginDescription> + 'a> {
Box::new(self.items.values())
}... | {
eprintln!("Duplicate plugin name.\n 1: {:?}\n 2: {:?}",
plugin, items.get(&plugin.name));
continue
} | conditional_block |
20_Sherlock_And_Anagrams.py | # https://www.hackerrank.com/challenges/sherlock-and-anagrams
def nCr(n, r):
# To cancel the (n-r)! part of (n)! with the highest
# value possible. (n)! / (n-r)! == (n)*(n-1)*(...)*(n-r+1)
r = min(r, n-r)
# nC1 or nCn is 1.
if r == 0: return 1
# nCr is...
# (n)! / ((n-r)! * r!)
# ((n)! ... | # character.
for i in range(len(s)):
word = s[i]
# Add single char substring to the counter.
c[word] += 1
for j in range(i + 1, len(s)):
word += s[j]
# Add sorted substring to the counter.
c["".join(sorted(word))] += 1
# For values in the c... | c = Counter()
# Generate all possible substrings starting at each | random_line_split |
20_Sherlock_And_Anagrams.py | # https://www.hackerrank.com/challenges/sherlock-and-anagrams
def nCr(n, r):
# To cancel the (n-r)! part of (n)! with the highest
# value possible. (n)! / (n-r)! == (n)*(n-1)*(...)*(n-r+1)
r = min(r, n-r)
# nC1 or nCn is 1.
if r == 0: return 1
# nCr is...
# (n)! / ((n-r)! * r!)
# ((n)! ... |
# For values in the counter, if its greater or equal
# than 2, then the amount of anagramatic pairs is
# nCr(count, 2). The sum of all these will be the
# total of pairs.
print sum([nCr(val, 2) for val in c.values() if val >= 2])
| word = s[i]
# Add single char substring to the counter.
c[word] += 1
for j in range(i + 1, len(s)):
word += s[j]
# Add sorted substring to the counter.
c["".join(sorted(word))] += 1 | conditional_block |
20_Sherlock_And_Anagrams.py | # https://www.hackerrank.com/challenges/sherlock-and-anagrams
def | (n, r):
# To cancel the (n-r)! part of (n)! with the highest
# value possible. (n)! / (n-r)! == (n)*(n-1)*(...)*(n-r+1)
r = min(r, n-r)
# nC1 or nCn is 1.
if r == 0: return 1
# nCr is...
# (n)! / ((n-r)! * r!)
# ((n)! / (n-r)!) * 1/r!
# n*(n-1)*...(n-r+1) * 1/r!
num = reduce(lam... | nCr | identifier_name |
20_Sherlock_And_Anagrams.py | # https://www.hackerrank.com/challenges/sherlock-and-anagrams
def nCr(n, r):
# To cancel the (n-r)! part of (n)! with the highest
# value possible. (n)! / (n-r)! == (n)*(n-1)*(...)*(n-r+1)
|
from collections import Counter
t = int(raw_input())
for _ in xrange(t):
s = raw_input()
c = Counter()
# Generate all possible substrings starting at each
# character.
for i in range(len(s)):
word = s[i]
# Add single char substring to the counter.
c[word] += 1
for j... | r = min(r, n-r)
# nC1 or nCn is 1.
if r == 0: return 1
# nCr is...
# (n)! / ((n-r)! * r!)
# ((n)! / (n-r)!) * 1/r!
# n*(n-1)*...(n-r+1) * 1/r!
num = reduce(lambda x, y: x*y, xrange(n, n-r, -1))
den = reduce(lambda x, y: x*y, xrange(1, r+1))
return num/den | identifier_body |
config.py | import os
class Config(object):
SPOTIPY_REDIRECT_URI = os.environ['SPOTIPY_REDIRECT_URI']
SPOTIPY_CLIENT_ID = os.environ['SPOTIPY_CLIENT_ID']
SPOTIPY_CLIENT_SECRET = os.environ['SPOTIPY_CLIENT_SECRET']
SPOTIFY_ACCESS_SCOPE = 'playlist-modify-public playlist-modify-private playlist-read-private user-lib... |
# TRACKS_PER_ARTIST #
# Number of tracks per artist to add to the playlist.
# I recommend 5 or less. Max is 10.
TRACKS_PER_ARTIST = 3
# COLLATE #
# By default, the playlist will be ordered like:
# - ARTIST A TRACK 1
# - ARTIST A TRACK 2
# - ARTIST A TRACK 3
# - ARTIST A TRACK 4... | random_line_split | |
config.py | import os
class | (object):
SPOTIPY_REDIRECT_URI = os.environ['SPOTIPY_REDIRECT_URI']
SPOTIPY_CLIENT_ID = os.environ['SPOTIPY_CLIENT_ID']
SPOTIPY_CLIENT_SECRET = os.environ['SPOTIPY_CLIENT_SECRET']
SPOTIFY_ACCESS_SCOPE = 'playlist-modify-public playlist-modify-private playlist-read-private user-library-read'
#######... | Config | identifier_name |
config.py | import os
class Config(object):
| # - ARTIST A TRACK 5
# - ARTIST B TRACK 1
# - ARTIST B TRACK 2
# - ARTIST B TRACK 3
# ...
# if COLLATE is set to True, it will instead be ordered like so:
# - ARTIST A TRACK 1
# - ARTIST B TRACK 1
# - ARTIST C TRACK 1
# ...
# - ARTIST Z TRACK 1
# - ARTIST A TRACK 2
#... | SPOTIPY_REDIRECT_URI = os.environ['SPOTIPY_REDIRECT_URI']
SPOTIPY_CLIENT_ID = os.environ['SPOTIPY_CLIENT_ID']
SPOTIPY_CLIENT_SECRET = os.environ['SPOTIPY_CLIENT_SECRET']
SPOTIFY_ACCESS_SCOPE = 'playlist-modify-public playlist-modify-private playlist-read-private user-library-read'
###########
# Opt... | identifier_body |
ARDORCryptoService.ts | @Service('ardorCryptoService')
@Inject('$window', 'user')
class ARDORCryptoService {
private nxtCrypto;
constructor(private $window: angular.IWindowService,
private user: UserService) {
this.nxtCrypto = $window.heatlibs.nxtCrypto;
}
/* Sets the seed to this wallet */
unlock(seedOrPrivateKey: any): ... | })
})
promises.push(promise)
});
Promise.all(promises).then(() => resolve(true))
if (accountAssets.length === 0)
resolve(true)
})
})
} else {
resolve(false)
}
... | {
let userAccount = wallet.addresses[0].accountId;
return new Promise((resolve, reject) => {
let ardorBlockExplorerService: ArdorBlockExplorerService = heat.$inject.get('ardorBlockExplorerService')
ardorBlockExplorerService.getTransactions(userAccount, 0, 10).then(transactions => {
if (trans... | identifier_body |
ARDORCryptoService.ts | @Service('ardorCryptoService')
@Inject('$window', 'user')
class ARDORCryptoService {
private nxtCrypto;
constructor(private $window: angular.IWindowService,
private user: UserService) {
this.nxtCrypto = $window.heatlibs.nxtCrypto;
}
/* Sets the seed to this wallet */
unlock(seedOrPrivateKey: any): ... | wallet.addresses[0].tokensBalances.push({
symbol: assetInfo?assetInfo.name:'',
name: assetInfo?assetInfo.name:'',
decimals: assetInfo.decimals,
balance: utils.formatQNT(asset.unconfirmedQuantityQNT,assetInfo.decimals),
... | ardorBlockExplorerService.getAccountAssets(userAccount).then(accountAssets => {
wallet.addresses[0].tokensBalances = []
let promises = []
accountAssets.forEach(asset => {
let promise = ardorBlockExplorerService.getAssetInfo(asset.asset).then(assetInf... | random_line_split |
ARDORCryptoService.ts | @Service('ardorCryptoService')
@Inject('$window', 'user')
class ARDORCryptoService {
private nxtCrypto;
constructor(private $window: angular.IWindowService,
private user: UserService) {
this.nxtCrypto = $window.heatlibs.nxtCrypto;
}
/* Sets the seed to this wallet */
unlock(seedOrPrivateKey: any): ... | (wallet: WalletType) {
let userAccount = wallet.addresses[0].accountId;
return new Promise((resolve, reject) => {
let ardorBlockExplorerService: ArdorBlockExplorerService = heat.$inject.get('ardorBlockExplorerService')
ardorBlockExplorerService.getTransactions(userAccount, 0, 10).then(transactions =... | refreshAdressBalances | identifier_name |
ARDORCryptoService.ts | @Service('ardorCryptoService')
@Inject('$window', 'user')
class ARDORCryptoService {
private nxtCrypto;
constructor(private $window: angular.IWindowService,
private user: UserService) {
this.nxtCrypto = $window.heatlibs.nxtCrypto;
}
/* Sets the seed to this wallet */
unlock(seedOrPrivateKey: any): ... | Promise.all(promises).then(() => resolve(true))
if (accountAssets.length === 0)
resolve(true)
})
})
}
else {
resolve(false)
}
})
})
}
} | {
ardorBlockExplorerService.getBalance(userAccount).then(balance => {
wallet.addresses[0].balance = new Big(utils.convertToQNTf(balance)).toFixed(8);
wallet.addresses[0].inUse = true;
ardorBlockExplorerService.getAccountAssets(userAccount).then(accountAssets => {
... | conditional_block |
lib.rs | //! The command-line tool works in the following order: | //!
//! 1. [`RemoteMounts::load`](struct.RemoteMounts.html#method.load) is called to load the contents
//! of `/etc/mtab` into an internal struct.
//! 2. [`RemoteMounts::into_current_dir`](struct.RemoteMounts.html#method.into_current_dir) is
//! called to convert the above into a [`Location`](enum.Location.html).... | random_line_split | |
bulletHell.js | "use strict";
BulletHell.prototype = new Minigame();
BulletHell.prototype.constructor = BulletHell;
function BulletHell (pGameEngine) {
this.gameEngine = pGameEngine;
this.gameId = 'bh';
// [TODO] enum
// 0 = ongoing, 1 = won, -1 = lost
this.outcome = 0;
this.score = 0;
this.bulletHellMusic;
this.gameT... |
else if(this.counter < 0)
{
this.gameTimer--;
this.gameTimerTitle.destroy();
if(this.gameTimer > 0)
{
this.gameTimerTitle = this.gameEngine.add.text(900, 30, this.gameTimer, this.gameTimerStyle);
}
else
{
this.outcome = 1;
}
}
};
BulletHell.prototype.update = function() {
//Player gets hit b... | {
this.counterTitle = this.gameEngine.add.text(this.gameEngine.world.centerX, this.gameEngine.world.centerY, this.counter, this.counterStyle);
} | conditional_block |
bulletHell.js | "use strict";
BulletHell.prototype = new Minigame();
BulletHell.prototype.constructor = BulletHell;
function BulletHell (pGameEngine) {
this.gameEngine = pGameEngine;
this.gameId = 'bh';
// [TODO] enum
// 0 = ongoing, 1 = won, -1 = lost
this.outcome = 0;
this.score = 0;
this.bulletHellMusic;
this.gameT... | this.counter = 3;
this.gameTimer = 5;
this.counterStyle = {font: "70px ChickenButt", fill:"#fff", align:"center" };
for(var i=0; i < this.turrets.length; i++){
this.turrets[i].destroy();
}
this.bullets.destroy();
this.gameStarted = false;
} | this.dragObj.destroy();
this.counterTitle.destroy();
this.gameTimerTitle.destroy();
this.timer.destroy(); | random_line_split |
bulletHell.js | "use strict";
BulletHell.prototype = new Minigame();
BulletHell.prototype.constructor = BulletHell;
function BulletHell (pGameEngine) {
this.gameEngine = pGameEngine;
this.gameId = 'bh';
// [TODO] enum
// 0 = ongoing, 1 = won, -1 = lost
this.outcome = 0;
this.score = 0;
this.bulletHellMusic;
this.gameT... |
if(this.counter <= 0){
for(var i=0; i < this.turrets.length; i++){
this.turrets[i].fire(this);
}
}
};
BulletHell.prototype.onDragStart = function(sprite, pointer){
this.timer = this.gameEngine.time.create(false);
this.timer.loop(1000, this.countdown, this);
this.timer.start();
};
BulletHell.prototype.on... | {
this.dragObj.kill();
this.outcome = -1;
} | identifier_body |
bulletHell.js | "use strict";
BulletHell.prototype = new Minigame();
BulletHell.prototype.constructor = BulletHell;
function BulletHell (pGameEngine) {
this.gameEngine = pGameEngine;
this.gameId = 'bh';
// [TODO] enum
// 0 = ongoing, 1 = won, -1 = lost
this.outcome = 0;
this.score = 0;
this.bulletHellMusic;
this.gameT... | (player, bullet){
this.dragObj.kill();
this.outcome = -1;
}
if(this.counter <= 0){
for(var i=0; i < this.turrets.length; i++){
this.turrets[i].fire(this);
}
}
};
BulletHell.prototype.onDragStart = function(sprite, pointer){
this.timer = this.gameEngine.time.create(false);
this.timer.loop(1000, this.co... | killPlayer | identifier_name |
exp_quat_func.py |
import rospy
import sys
from math import *
import numpy as np
from tf2_msgs.msg import TFMessage
from geometry_msgs.msg import Transform, Vector3
import kin_func_skeleton as kfs
def quaternion_to_exp(rot):
"""
Converts a quaternion vector in 3D to its corresponding omega and theta.
This uses the quaternio... |
def compute_gab(g0a,g0b):
"""
Creates a rigid body transform g_{ab} the converts between frame A and B
given the coordinate frame A,B in relation to the origin
Args:
g0a - (4,4) ndarray : the rigid body transform from the origin to frame A
g0b - (4,4) ndarray : the rigid body transfor... | """
Creates a rigid body transform using omega, theta, and the translation component.
g = [R,p; 0,1], where R = exp(omega * theta), p = trans
Args:
omega - (3,) ndarray : the axis you want to rotate about
theta - scalar value
trans - (3,) ndarray or 3x1 array: the translation component of t... | identifier_body |
exp_quat_func.py |
import rospy
import sys
from math import *
import numpy as np
from tf2_msgs.msg import TFMessage
from geometry_msgs.msg import Transform, Vector3
import kin_func_skeleton as kfs
def quaternion_to_exp(rot):
"""
Converts a quaternion vector in 3D to its corresponding omega and theta.
This uses the quaternio... |
if __name__ == "__main__":
print('Testing...')
#Test quaternion_to_exp()
arg1 = np.array([1.0, 2, 3, 0.1])
func_args = (arg1,)
ret_desired = (np.array([1.005, 2.0101, 3.0151]), 2.94125)
array_func_test_two_outputs(quaternion_to_exp, func_args, ret_desired)
#Test create_rbt()
... | print('[PASS] ' + func_name.__name__ + '() returned the argument %d value!' % i) | conditional_block |
exp_quat_func.py |
import rospy
import sys
from math import *
import numpy as np
from tf2_msgs.msg import TFMessage
from geometry_msgs.msg import Transform, Vector3
import kin_func_skeleton as kfs | def quaternion_to_exp(rot):
"""
Converts a quaternion vector in 3D to its corresponding omega and theta.
This uses the quaternion -> exponential coordinate equation given in Lab 6
Args:
rot - a (4,) nd array or 4x1 array: the quaternion vector (\vec{q}, q_o)
Returns:
omega - (3,) n... | random_line_split | |
exp_quat_func.py |
import rospy
import sys
from math import *
import numpy as np
from tf2_msgs.msg import TFMessage
from geometry_msgs.msg import Transform, Vector3
import kin_func_skeleton as kfs
def quaternion_to_exp(rot):
"""
Converts a quaternion vector in 3D to its corresponding omega and theta.
This uses the quaternio... | (R):
"""
Given a rotation matrix R, finds the omega and theta such that R = exp(omega * theta)
Args:
R - (3,3) ndarray : the rotational component of the rigid body transform
Returns:
omega - (3,) ndarray : the axis you want to rotate about
theta - scalar value
"""
#YOUR COD... | find_omega_theta | identifier_name |
cliente.py | '''
Created on 20/02/2009
@author: Chuidiang
Ejemplo de cliente de socket.
Establece conexion con el servidor, envia "hola", recibe y escribe la
respuesta, espera 2 segundos, envia "adios", recibe y escribe la respuesta
y cierrra la conexion
'''
import socket
#import time
if __name__ == '__main__':
# Se establece ... |
# Se envia "hola"
#s.send("hola")
# Se recibe la respuesta y se escribe en pantalla
#datos = s.recv(1000)
#print datos
#
## Espera de 2 segundos
#time.sleep(2)
#
## Se envia "adios"
#s.send("adios")
#
## Se espera respuesta, se escribe en pantalla y se cierra la
... | b = raw_input(">. ")
#print type(b)
if (b != ''):
b = int(b)
if (b <= 255) & (b >= 0):
s.send(str(b))
elif (b == 666):
cond = False
s.send(str(b))
s.close()
print "nojoda"
... | conditional_block |
cliente.py | '''
Created on 20/02/2009
@author: Chuidiang
Ejemplo de cliente de socket.
Establece conexion con el servidor, envia "hola", recibe y escribe la
respuesta, espera 2 segundos, envia "adios", recibe y escribe la respuesta
y cierrra la conexion
'''
import socket
#import time
if __name__ == '__main__':
# Se establece ... | ## Se espera respuesta, se escribe en pantalla y se cierra la
## conexion
#datos = s.recv(1000)
#print datos
#s.close() | # | random_line_split |
macs2_wrapper.py | shutil, glob, os, os.path, gzip
from galaxy import eggs
import json
CHUNK_SIZE = 1024
#==========================================================================================
#functions
#==========================================================================================
def gunzip_cat_glob_path( glob_path,... | out.write( '\t'.join( fields ) )
out.close()
#==========================================================================================
#main
#==========================================================================================
def main():
#take in options file and output file names
opt... | out = open( interval_file, 'wb' )
if header:
out.write( '#%s\n' % header )
wrote_header = False
#From macs readme: Coordinates in XLS is 1-based which is different with BED format.
for line in open( xls_file ):
#keep all existing comment lines
if line.startswith( '#' ):
... | identifier_body |
macs2_wrapper.py | , glob, os, os.path, gzip
from galaxy import eggs
import json
CHUNK_SIZE = 1024
#==========================================================================================
#functions
#==========================================================================================
def gunzip_cat_glob_path( glob_path, target... |
out.close()
#==========================================================================================
#main
#==========================================================================================
def main():
#take in options file and output file names
options = json.load( open( sys.argv[1] ) )
o... | fields = line.split( '\t' )
if len( fields ) > 1:
fields[1] = str( int( fields[1] ) - 1 )
out.write( '\t'.join( fields ) ) | conditional_block |
macs2_wrapper.py | , glob, os, os.path, gzip
from galaxy import eggs
import json
CHUNK_SIZE = 1024
#==========================================================================================
#functions
#==========================================================================================
def gunzip_cat_glob_path( glob_path, target... | ( xls_file, interval_file, header = None ):
out = open( interval_file, 'wb' )
if header:
out.write( '#%s\n' % header )
wrote_header = False
#From macs readme: Coordinates in XLS is 1-based which is different with BED format.
for line in open( xls_file ):
#keep all existing comment li... | xls_to_interval | identifier_name |
macs2_wrapper.py | UNK_SIZE = 1024
#==========================================================================================
#functions
#==========================================================================================
def gunzip_cat_glob_path( glob_path, target_filename, delete = False ):
out = open( target_filename, 'wb... | #move files generated by bdgcmp command
if (options['command'] == "bdgcmp"):
created_bdgcmp_file = os.path.join (tmp_dir, "bdgcmp_out.bdg" ) | random_line_split | |
add_parameterized_profile.py | # IfcOpenShell - IFC toolkit and geometry engine
# Copyright (C) 2021 Dion Moult <dion@thinkmoult.com>
#
# This file is part of IfcOpenShell.
#
# IfcOpenShell is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundat... |
def execute(self):
return self.file.create_entity(self.settings["ifc_class"])
| self.file = file
self.settings = {"ifc_class": None}
for key, value in settings.items():
self.settings[key] = value | identifier_body |
add_parameterized_profile.py | # IfcOpenShell - IFC toolkit and geometry engine
# Copyright (C) 2021 Dion Moult <dion@thinkmoult.com>
#
# This file is part of IfcOpenShell.
#
# IfcOpenShell is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundat... | :
def __init__(self, file, **settings):
self.file = file
self.settings = {"ifc_class": None}
for key, value in settings.items():
self.settings[key] = value
def execute(self):
return self.file.create_entity(self.settings["ifc_class"])
| Usecase | identifier_name |
add_parameterized_profile.py | # IfcOpenShell - IFC toolkit and geometry engine
# Copyright (C) 2021 Dion Moult <dion@thinkmoult.com>
#
# This file is part of IfcOpenShell.
#
# IfcOpenShell is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundat... |
class Usecase:
def __init__(self, file, **settings):
self.file = file
self.settings = {"ifc_class": None}
for key, value in settings.items():
self.settings[key] = value
def execute(self):
return self.file.create_entity(self.settings["ifc_class"]) | #
# You should have received a copy of the GNU Lesser General Public License
# along with IfcOpenShell. If not, see <http://www.gnu.org/licenses/>. | random_line_split |
add_parameterized_profile.py | # IfcOpenShell - IFC toolkit and geometry engine
# Copyright (C) 2021 Dion Moult <dion@thinkmoult.com>
#
# This file is part of IfcOpenShell.
#
# IfcOpenShell is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundat... |
def execute(self):
return self.file.create_entity(self.settings["ifc_class"])
| self.settings[key] = value | conditional_block |
linkify-string.js | /*
* Copyright (c) 2016 SoapBox Innovations Inc.
*
* 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, modify, m... |
var _opts$resolve = opts.resolve(token);
var formatted = _opts$resolve.formatted;
var formattedHref = _opts$resolve.formattedHref;
var tagName = _opts$resolve.tagName;
var className = _opts$resolve.className;
var target = _opts$resolve.target;
var attributes = _opts$resolve.attributes;
... | {
result.push(escapeText(token.toString()));
continue;
} | conditional_block |
linkify-string.js | /*
* Copyright (c) 2016 SoapBox Innovations Inc.
*
* 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, modify, m... |
var link = '<' + tagName + ' href="' + escapeAttr(formattedHref) + '"';
if (className) {
link += ' class="' + escapeAttr(className) + '"';
}
if (target) {
link += ' target="' + escapeAttr(target) + '"';
}
if (attributes) {
link += ' ' + attributesToString(attributes);
}
... | var target = _opts$resolve.target;
var attributes = _opts$resolve.attributes;
| random_line_split |
linkify-string.js | /*
* Copyright (c) 2016 SoapBox Innovations Inc.
*
* 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, modify, m... | (attributes) {
if (!attributes) {
return '';
}
var result = [];
for (var attr in attributes) {
var val = attributes[attr] + '';
result.push(attr + '="' + escapeAttr(val) + '"');
}
return result.join(' ');
}
function linkifyStr(str) {
var opts = arguments.length <= 1 || arguments[1... | attributesToString | identifier_name |
linkify-string.js | /*
* Copyright (c) 2016 SoapBox Innovations Inc.
*
* 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, modify, m... |
function attributesToString(attributes) {
if (!attributes) {
return '';
}
var result = [];
for (var attr in attributes) {
var val = attributes[attr] + '';
result.push(attr + '="' + escapeAttr(val) + '"');
}
return result.join(' ');
}
function linkifyStr(str) {
var opts = argum... | {
return href.replace(/"/g, '"');
} | identifier_body |
movie4kis.py | # -*- coding: utf-8 -*-
'''
fantastic Add-on
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This pro... | self.search_link = '/search/%s/feed/rss2/'
def movie(self, imdb, title, localtitle, aliases, year):
try:
url = {'imdb': imdb, 'title': title, 'year': year}
url = urllib.urlencode(url)
return url
except:
return
def sources(self, url, hostD... | self.priority = 1
self.language = ['en']
self.domains = ['movie4k.is']
self.base_link = 'http://movie4k.is' | random_line_split |
movie4kis.py | # -*- coding: utf-8 -*-
'''
fantastic Add-on
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This pro... | (self, imdb, title, localtitle, aliases, year):
try:
url = {'imdb': imdb, 'title': title, 'year': year}
url = urllib.urlencode(url)
return url
except:
return
def sources(self, url, hostDict, hostprDict):
try:
sources = []
... | movie | identifier_name |
movie4kis.py | # -*- coding: utf-8 -*-
'''
fantastic Add-on
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This pro... |
except:
pass
return sources
except:
return sources
def resolve(self, url):
return url
| l = client.parseDOM(u, 'div', {'class': 'movieplay'})[0]
l = client.parseDOM(u, 'iframe', ret='data-lazy-src')[0]
quality, info = source_utils.get_release_quality(name, l)
info = ' | '.join(info)
url = l
... | conditional_block |
movie4kis.py | # -*- coding: utf-8 -*-
'''
fantastic Add-on
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This pro... |
data = urlparse.parse_qs(url)
data = dict([(i, data[i][0]) if data[i] else (i, '') for i in data])
title = data['tvshowtitle'] if 'tvshowtitle' in data else data['title']
hdlr = 'S%02dE%02d' % (int(data['season']), int(data['episode'])) if 'tvshowtitle' in data else dat... | def __init__(self):
self.priority = 1
self.language = ['en']
self.domains = ['movie4k.is']
self.base_link = 'http://movie4k.is'
self.search_link = '/search/%s/feed/rss2/'
def movie(self, imdb, title, localtitle, aliases, year):
try:
url = {'imdb': imdb, '... | identifier_body |
mod.rs | /**
* Flow - Realtime log analyzer
* Copyright (C) 2016 Daniel Mircea
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later ve... |
pub mod frame;
pub mod content;
pub mod navigation;
pub mod menu;
pub mod search;
pub mod input;
pub mod event;
pub mod readline;
pub mod color;
pub mod printer;
pub mod highlighter;
pub mod rendered_line; | * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ | random_line_split |
color.py | #!/usr/bin/env python3
#
# mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
# Copyright (C)2013-2022 The MMGen Project <mmgen@tuta.io>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Softwa... | exec(f'{_c} = lambda s: s') | conditional_block | |
color.py | #!/usr/bin/env python3
#
# mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
# Copyright (C)2013-2022 The MMGen Project <mmgen@tuta.io>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Softwa... |
def init_color(num_colors='auto'):
assert num_colors in ('auto',8,16,256,0)
import mmgen.color as self
if num_colors == 'auto':
import os
t = os.getenv('TERM')
num_colors = 256 if (t and t.endswith('256color')) or get_terminfo_colors() == 256 else 16
reset = '\033[0m'
if num_colors == 0:
ncc = (lambda... | from subprocess import run,PIPE
cmd = ['infocmp','-0']
if term:
cmd.append(term)
try:
cmdout = run(cmd,stdout=PIPE,check=True).stdout.decode()
except:
return None
else:
s = [e.split('#')[1] for e in cmdout.split(',') if e.startswith('colors')][0]
from .util import is_hex_str
if s.isdecimal():
retur... | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.