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
test_document.py
from mock import patch, Mock from nose.tools import istest from unittest import TestCase from structominer import Document, Field class DocumentTests(TestCase): @istest def creating_document_object_with_string_should_automatically_parse(self): html = '<html></html>' with patch('structom...
@istest def document_should_only_parse_fields_with_auto_parse_attributes(self): html = '<html></html>' class Doc(Document): one = Mock(Field, _field_counter=1, auto_parse=True) two = Mock(Field, _field_counter=2, auto_parse=False) doc = Doc(html) self.a...
class Doc(Document): three = Mock(Field, _field_counter=3) two = Mock(Field, _field_counter=2) one = Mock(Field, _field_counter=1) doc = Doc() self.assertEquals([field._field_counter for field in doc._fields.values()], [1, 2, 3])
identifier_body
wsgi.py
""" WSGI config for skeleton project. This module contains the WSGI application used by Django's development server and any production WSGI deployments. It should expose a module-level variable named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover this application via the ``WSGI_APPLICATION``...
# file. This includes Django's development server, if the WSGI_APPLICATION # setting points here. from django.core.wsgi import get_wsgi_application application = get_wsgi_application() # Apply WSGI middleware here. # from helloworld.wsgi import HelloWorldApplication # application = HelloWorldApplication(application)
random_line_split
gulpfile.js
'use strict' let gulp = require("gulp"); let sourcemaps = require("gulp-sourcemaps"); let babel = require("gulp-babel"); let watch = require('gulp-watch'); let changed = require('gulp-changed');
gulp.task("default", ['es6']); gulp.task("sourcemaps", function() { return gulp.src("src/**/*.js") .pipe(sourcemaps.init()) .pipe(babel()) .pipe(sourcemaps.write("./maps")) .pipe(gulp.dest("build")); }); gulp.task("es6-js", function() { return gulp.src(["src/**/*.js", "tests/**/*.js"]) .pipe(changed("bu...
let nodemon = require('gulp-nodemon'); let plumber = require('gulp-plumber'); let path = require('path'); let demon;
random_line_split
browserUtils.ts
/* * Power BI Visualizations * * Copyright (c) Microsoft Corporation * All rights reserved. * MIT License * * 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 restrict...
/** * Get the current version of IE * @returns The version of Internet Explorer or a 0 (indicating the use of another browser). */ export function getInternetExplorerVersion(): number { var retValue = 0; if (navigator.appName === 'Microsoft Int...
|| userAgent.indexOf('trident') > -1 || userAgent.indexOf('edge') > -1; }
random_line_split
browserUtils.ts
/* * Power BI Visualizations * * Copyright (c) Microsoft Corporation * All rights reserved. * MIT License * * 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 restrict...
/** * Get the current version of IE * @returns The version of Internet Explorer or a 0 (indicating the use of another browser). */ export function getInternetExplorerVersion(): number { var retValue = 0; if (navigator.appName === 'Microsoft Inte...
let userAgent = window.navigator.userAgent.toLowerCase(); return userAgent.indexOf('msie') > -1 || userAgent.indexOf('trident') > -1 || userAgent.indexOf('edge') > -1; }
identifier_body
browserUtils.ts
/* * Power BI Visualizations * * Copyright (c) Microsoft Corporation * All rights reserved. * MIT License * * 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 restrict...
: number { var retValue = 0; if (navigator.appName === 'Microsoft Internet Explorer' || window.navigator.userAgent.indexOf('MSIE') >= 0) { var re = new RegExp('MSIE ([0-9]{1,}[\\.0-9]{0,})'); var result = re.exec(window.navigator.userAgent); if (re...
tInternetExplorerVersion()
identifier_name
browserUtils.ts
/* * Power BI Visualizations * * Copyright (c) Microsoft Corporation * All rights reserved. * MIT License * * 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 restrict...
return retValue; } export function isFirefox(): boolean { return navigator.userAgent.toLowerCase().indexOf('firefox') > -1; } } }
var re = new RegExp('MSIE ([0-9]{1,}[\\.0-9]{0,})'); var result = re.exec(window.navigator.userAgent); if (result) { retValue = parseFloat(result[1]); } }
conditional_block
path_recognizer.ts
import { RegExp, RegExpWrapper, RegExpMatcherWrapper, StringWrapper, isPresent, isBlank } from 'angular2/src/facade/lang'; import {BaseException, WrappedException} from 'angular2/src/facade/exceptions'; import {Map, MapWrapper, StringMapWrapper} from 'angular2/src/facade/collection'; import {Url, RootUrl, ...
return {urlPath, urlParams, allParams, auxiliary, nextSegment}; } generate(params: {[key: string]: any}): {[key: string]: any} { var paramTokens = new TouchMap(params); var path = []; for (var i = 0; i < this._segments.length; i++) { let segment = this._segments[i]; if (!(segment in...
{ allParams = positionalParams; auxiliary = []; urlParams = []; }
conditional_block
path_recognizer.ts
import { RegExp, RegExpWrapper, RegExpMatcherWrapper, StringWrapper, isPresent, isBlank } from 'angular2/src/facade/lang'; import {BaseException, WrappedException} from 'angular2/src/facade/exceptions'; import {Map, MapWrapper, StringMapWrapper} from 'angular2/src/facade/collection'; import {Url, RootUrl, ...
implements Segment { name: string = ''; constructor(public path: string) {} match(path: string): boolean { return path == this.path; } generate(params: TouchMap): string { return this.path; } } class DynamicSegment implements Segment { constructor(public name: string) {} match(path: string): boolean { ret...
StaticSegment
identifier_name
path_recognizer.ts
import { RegExp, RegExpWrapper, RegExpMatcherWrapper, StringWrapper, isPresent, isBlank } from 'angular2/src/facade/lang'; import {BaseException, WrappedException} from 'angular2/src/facade/exceptions'; import {Map, MapWrapper, StringMapWrapper} from 'angular2/src/facade/collection'; import {Url, RootUrl, ...
} class StaticSegment implements Segment { name: string = ''; constructor(public path: string) {} match(path: string): boolean { return path == this.path; } generate(params: TouchMap): string { return this.path; } } class DynamicSegment implements Segment { constructor(public name: string) {} match(path:...
{ return true; }
identifier_body
path_recognizer.ts
import { RegExp, RegExpWrapper, RegExpMatcherWrapper, StringWrapper,
import {Url, RootUrl, serializeParams} from './url_parser'; class TouchMap { map: {[key: string]: string} = {}; keys: {[key: string]: boolean} = {}; constructor(map: {[key: string]: any}) { if (isPresent(map)) { StringMapWrapper.forEach(map, (value, key) => { this.map[key] = isPresent(value) ...
isPresent, isBlank } from 'angular2/src/facade/lang'; import {BaseException, WrappedException} from 'angular2/src/facade/exceptions'; import {Map, MapWrapper, StringMapWrapper} from 'angular2/src/facade/collection';
random_line_split
config.py
issues=[ dict(name='Habit',number=5,season='Winter 2012', description='commit to a change, experience it, and record'), dict(name='Interview', number=4, season='Autumn 2011', description="this is your opportunity to inhabit another's mind"),
description='what are you looking forward to leaving?') ] siteroot='/Users/adam/open review quarterly/source/' infodir='/Users/adam/open review quarterly/info' skip_issues_before=5 illustration_tag='=== Illustration ===' illustration_tag_sized="=== Illustration width: 50% ==="
dict(name= 'Digital Presence', number= 3, season= 'Summer 2011', description='what does your digital self look like?'), dict(name= 'Adventure', number=2, season= 'Spring 2011', description='take an adventure and write about it.'), dict(name= 'Unplugging', number=1, season= 'Winter 2011',
random_line_split
main.rs
extern mod extra; use std::io::buffered::BufferedStream; use std::io::net::addrinfo::get_host_addresses; use std::io::net::ip::{IpAddr, SocketAddr}; use std::io::net::tcp::TcpStream; use std::os::args; use extra::json; use extra::json::{Json, ToJson}; use extra::treemap::TreeMap; trait Protocol { fn msg_type(&self...
{ msgType: ~str, data: Json } impl Protocol for Msg { fn msg_type(&self) -> ~str { self.msgType.clone() } fn json_data(&self) -> Json { self.data.clone() } } struct JoinMsg { name: ~str, key: ~str } impl Protocol for JoinMsg { fn msg_type(&self) -> ~str { ~"join" } fn json_data(&self) -> Json { ...
Msg
identifier_name
main.rs
extern mod extra; use std::io::buffered::BufferedStream; use std::io::net::addrinfo::get_host_addresses; use std::io::net::ip::{IpAddr, SocketAddr}; use std::io::net::tcp::TcpStream; use std::os::args; use extra::json; use extra::json::{Json, ToJson}; use extra::treemap::TreeMap; trait Protocol { fn msg_type(&self...
fn main() { match read_config() { None => println("Usage: ./run <host> <port> <botname> <botkey>"), Some(config) => start(config) } }
} }
random_line_split
main.rs
extern mod extra; use std::io::buffered::BufferedStream; use std::io::net::addrinfo::get_host_addresses; use std::io::net::ip::{IpAddr, SocketAddr}; use std::io::net::tcp::TcpStream; use std::os::args; use extra::json; use extra::json::{Json, ToJson}; use extra::treemap::TreeMap; trait Protocol { fn msg_type(&self...
_ => None } } fn handle_msg(msg: ~Msg, stream: &mut BufferedStream<TcpStream>) { match msg.msgType { ~"carPositions" => write_msg(&ThrottleMsg { value: 0.5 }, stream), _ => { match msg.msgType { ~"join" => println("Joined"), ~"gameInit" => println("Race init")...
{ let data = json.find(&~"data").unwrap_or(&json::Null); Some(Msg { msgType: msgType.clone(), data: data.clone() }) }
conditional_block
main.rs
extern mod extra; use std::io::buffered::BufferedStream; use std::io::net::addrinfo::get_host_addresses; use std::io::net::ip::{IpAddr, SocketAddr}; use std::io::net::tcp::TcpStream; use std::os::args; use extra::json; use extra::json::{Json, ToJson}; use extra::treemap::TreeMap; trait Protocol { fn msg_type(&self...
fn json_data(&self) -> Json { json::Number(self.value) } } fn write_msg<T: Protocol>(msg: &T, stream: &mut BufferedStream<TcpStream>) { let mut json = TreeMap::new(); json.insert(~"msgType", msg.msg_type().to_json()); json.insert(~"data", msg.json_data()); write_json(&json::Object(~json), stream); } fn wr...
{ ~"throttle" }
identifier_body
TransformQuery.d.ts
import { SelectionSetNode, FragmentDefinitionNode } from 'graphql'; import { Transform, Request, Result } from '../../Interfaces'; export declare type QueryTransformer = (selectionSet: SelectionSetNode, fragments: Record<string, FragmentDefinitionNode>) => SelectionSetNode; export declare type ResultTransformer = (r...
private readonly fragments; constructor({ path, queryTransformer, resultTransformer, errorPathTransformer, fragments, }: { path: Array<string>; queryTransformer: QueryTransformer; resultTransformer?: ResultTransformer; errorPathTransformer?: ErrorPathTransformer; fr...
private readonly resultTransformer; private readonly errorPathTransformer;
random_line_split
TransformQuery.d.ts
import { SelectionSetNode, FragmentDefinitionNode } from 'graphql'; import { Transform, Request, Result } from '../../Interfaces'; export declare type QueryTransformer = (selectionSet: SelectionSetNode, fragments: Record<string, FragmentDefinitionNode>) => SelectionSetNode; export declare type ResultTransformer = (r...
implements Transform { private readonly path; private readonly queryTransformer; private readonly resultTransformer; private readonly errorPathTransformer; private readonly fragments; constructor({ path, queryTransformer, resultTransformer, errorPathTransformer, fragments, }: { p...
TransformQuery
identifier_name
matplotlib_service.py
from app import db from app.model import DirectionStatistic import random import numpy as np import matplotlib.pyplot as plt from matplotlib.figure import Figure def create_range_figure2(sender_id): fig = Figure() axis = fig.add_subplot(1, 1, 1) xs = range(100) ys = [random.randint(1, 50) for x in xs]...
ax.set_theta_direction(-1) fig.suptitle(f"Range between sender '{sds.sender.name}' and receiver '{sds.receiver.name}'") return fig
sds = db.session.query(DirectionStatistic) \ .filter(DirectionStatistic.sender_id == sender_id) \ .order_by(DirectionStatistic.directions_count.desc()) \ .limit(1) \ .one() fig = Figure() direction_data = sds.direction_data max_range = max([r['max_range'] / 1000.0 for r in ...
identifier_body
matplotlib_service.py
from app import db from app.model import DirectionStatistic import random import numpy as np import matplotlib.pyplot as plt from matplotlib.figure import Figure def create_range_figure2(sender_id): fig = Figure() axis = fig.add_subplot(1, 1, 1) xs = range(100) ys = [random.randint(1, 50) for x in xs]...
(sender_id): sds = db.session.query(DirectionStatistic) \ .filter(DirectionStatistic.sender_id == sender_id) \ .order_by(DirectionStatistic.directions_count.desc()) \ .limit(1) \ .one() fig = Figure() direction_data = sds.direction_data max_range = max([r['max_range'] /...
create_range_figure
identifier_name
matplotlib_service.py
from app import db from app.model import DirectionStatistic import random import numpy as np import matplotlib.pyplot as plt from matplotlib.figure import Figure def create_range_figure2(sender_id): fig = Figure() axis = fig.add_subplot(1, 1, 1) xs = range(100) ys = [random.randint(1, 50) for x in xs]...
return fig def create_range_figure(sender_id): sds = db.session.query(DirectionStatistic) \ .filter(DirectionStatistic.sender_id == sender_id) \ .order_by(DirectionStatistic.directions_count.desc()) \ .limit(1) \ .one() fig = Figure() direction_data = sds.direction_d...
random_line_split
stock_picking_wave.py
# -*- coding: utf-8 -*- ############################################################################## # For copyright and license notices, see __openerp__.py file in root directory ############################################################################## from openerp import models, fields, api, exceptions, _ c...
return True @api.one def button_check_availability(self): pickings = self.picking_ids.filtered(lambda x: x.state == 'confirmed') pickings.action_assign() # The old API is used because the father is updated method context def action_transfer(self, cr, uid, ids, context=None): ...
pickings = picking_obj.search([('wave_id', '=', wave.id), ('state', '=', 'draft')]) pickings.action_assign() wave.state = 'in_progress'
conditional_block
stock_picking_wave.py
# For copyright and license notices, see __openerp__.py file in root directory ############################################################################## from openerp import models, fields, api, exceptions, _ class StockPickingWave(models.Model): _inherit = 'stock.picking.wave' @api.one def _count_c...
# -*- coding: utf-8 -*- ##############################################################################
random_line_split
stock_picking_wave.py
# -*- coding: utf-8 -*- ############################################################################## # For copyright and license notices, see __openerp__.py file in root directory ############################################################################## from openerp import models, fields, api, exceptions, _ c...
@api.multi def done(self): for wave in self: for picking in wave.picking_ids: if picking.state not in ('cancel', 'done'): raise exceptions.Warning(_( 'Some pickings are not transferred. ' 'Please transfer p...
self.ensure_one() cond = self._get_pickings_domain() return {'domain': {'picking_ids': cond}}
identifier_body
stock_picking_wave.py
# -*- coding: utf-8 -*- ############################################################################## # For copyright and license notices, see __openerp__.py file in root directory ############################################################################## from openerp import models, fields, api, exceptions, _ c...
(self): self.num_confirmed = len(self.picking_ids.filtered(lambda x: x.state == 'confirmed')) @api.one def _count_assigned_pickings(self): self.num_assigned = len(self.picking_ids.filtered(lambda x: x.state == ...
_count_confirmed_pickings
identifier_name
viewer.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 #![forbid(unsafe_code)] use crate::{ interfaces::{LeftScreen, RightScreen}, tui::{ text_builder::TextBuilder, tui_interface::{TUIInterface, TUIOutput}, }, }; use tui::{ style::{Color, Style}, text::Sp...
} impl<BytecodeViewer: LeftScreen, SourceViewer: RightScreen<BytecodeViewer>> TUIInterface for Viewer<BytecodeViewer, SourceViewer> { const LEFT_TITLE: &'static str = "Bytecode"; const RIGHT_TITLE: &'static str = "Source Code"; fn on_redraw(&mut self, line_number: u16, column_number: u16) -> TUIOutpu...
{ Self { bytecode_text: bytecode_viewer .backing_string() .split('\n') .map(|x| x.to_string()) .collect(), source_viewer, bytecode_viewer, } }
identifier_body
viewer.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 #![forbid(unsafe_code)] use crate::{ interfaces::{LeftScreen, RightScreen}, tui::{ text_builder::TextBuilder, tui_interface::{TUIInterface, TUIOutput}, }, }; use tui::{ style::{Color, Style}, text::Sp...
{ None => { let mut builder = TextBuilder::new(); builder.add(self.source_viewer.backing_string(), Style::default()); builder.finish() } Some(info) => { let source_context = self.source_viewer.source_for_code_loc...
.get_source_index_for_line(line_number as usize, column_number as usize)
random_line_split
viewer.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 #![forbid(unsafe_code)] use crate::{ interfaces::{LeftScreen, RightScreen}, tui::{ text_builder::TextBuilder, tui_interface::{TUIInterface, TUIOutput}, }, }; use tui::{ style::{Color, Style}, text::Sp...
(&self, line_number: u16) -> u16 { std::cmp::min( line_number, self.bytecode_text.len().checked_sub(1).unwrap() as u16, ) } fn bound_column(&self, line_number: u16, column_number: u16) -> u16 { std::cmp::min( column_number, self.bytecode_t...
bound_line
identifier_name
lib.rs
//! Rustic bindings to [libnotify](https://developer.gnome.org/libnotify/) //! //! ```rust //! extern crate libnotify; //! //! fn main() { //! // Init libnotify //! libnotify::init("myapp").unwrap(); //! // Create a new notification (doesn't show it yet) //! let n = libnotify::Notification::new("Summary...
mod enums; mod functions; mod notification;
random_line_split
config.js
module.exports = { stores: process.env.STORES ? process.env.STORES.split(',') : [ 'elasticsearch', 'postgresql', 'leveldb' ], postgresql: { host: process.env.POSTGRESQL_HOST || 'localhost', port: process.env.POSTGRESQL_PORT || '5432', username: process.env.POSTGRESQL_USER || 'postgres',...
process.env.ELASTICSEARCH_HOST || 'http://localhost:9200' ] }, level: { path: process.env.LEVEL_PATH || '/tmp/level' }, queue: { client: process.env.QUEUE_CLIENT || 'kue', kue: { port: process.env.QUEUE_KUE_PORT ? Number(process.env.QUEUE_KUE_PORT) : 3000 }, rabbitmq: { ...
elasticsearch: { hosts: [
random_line_split
best_fitness.py
# -*- coding: utf-8 -*- # Future from __future__ import absolute_import, division, print_function, \ unicode_literals, with_statement # Standard Library from datetime import datetime # Third Party import matplotlib.pyplot as plt from matplotlib import cm from mpl_toolkits.mplot3d import Axes3D # Load 3d plots ca...
(self, invocation): fitness = invocation.current_result if self.current_best is None or fitness < self.current_best: self.current_best = fitness self.best_fitnesses.append(self.current_best.raw_values) time_delta = datetime.now() - self.start_time self.timestamps.a...
on_result
identifier_name
best_fitness.py
# -*- coding: utf-8 -*- # Future from __future__ import absolute_import, division, print_function, \ unicode_literals, with_statement # Standard Library from datetime import datetime # Third Party import matplotlib.pyplot as plt from matplotlib import cm from mpl_toolkits.mplot3d import Axes3D # Load 3d plots ca...
self.best_fitnesses.append(self.current_best.raw_values) time_delta = datetime.now() - self.start_time self.timestamps.append(time_delta.total_seconds()) def show_fitness_invocations_plot(self): """Show a fitness--invocations plot""" fig = plt.figure() ax = fig.a...
self.current_best = fitness
conditional_block
best_fitness.py
# -*- coding: utf-8 -*- # Future from __future__ import absolute_import, division, print_function, \ unicode_literals, with_statement # Standard Library from datetime import datetime # Third Party import matplotlib.pyplot as plt from matplotlib import cm from mpl_toolkits.mplot3d import Axes3D # Load 3d plots ca...
NUMBER_OF_SAMPLES = 200 COLORMAP = cm.jet REVERSED_COLORMAP = cm.jet_r class VisualizeBestFitnessPlugin(Plugin): """Visualize optimization progess""" def __init__(self): self.best_fitnesses = [] self.timestamps = [] self.start_time = None self.current_best = None se...
random_line_split
best_fitness.py
# -*- coding: utf-8 -*- # Future from __future__ import absolute_import, division, print_function, \ unicode_literals, with_statement # Standard Library from datetime import datetime # Third Party import matplotlib.pyplot as plt from matplotlib import cm from mpl_toolkits.mplot3d import Axes3D # Load 3d plots ca...
def show_fitness_time_plot(self): """Show a fitness--time plot""" fig = plt.figure() ax = fig.add_subplot(111) ax.set_xlabel("Time") ax.set_ylabel(self.get_y_label()) ax.plot(self.timestamps, self.best_fitnesses) plt.show() def get_y_label(self): ...
"""Show a fitness--invocations plot""" fig = plt.figure() ax = fig.add_subplot(111) ax.set_xlabel("Number of Invocations") ax.set_ylabel(self.get_y_label()) ax.plot(self.best_fitnesses) plt.show()
identifier_body
scan.js
/** * @package AdminTools * @copyright Copyright (c)2010-2013 Nicholas K. Dionysopoulos * @license GNU General Public License version 3, or later */ /** @var The AJAX proxy URL */ var admintools_scan_ajax_url_start = ""; var admintools_scan_ajax_url_step = ""; /** @var The callback function to call on error */...
} else { errorCallback(message); } } }; var ajax_object = null; start_scan_timer(); // Damn you, Internet Explorer!!! var randomJunk = new Date().getTime(); url += '&randomJunk='+randomJunk; if(typeof(XHR) == 'undefined') { structure.url = url; ajax_object = new Request(structure); ...
{ admintools_scan_error_callback(message); }
conditional_block
scan.js
/** * @package AdminTools * @copyright Copyright (c)2010-2013 Nicholas K. Dionysopoulos * @license GNU General Public License version 3, or later */ /** @var The AJAX proxy URL */ var admintools_scan_ajax_url_start = ""; var admintools_scan_ajax_url_step = ""; /** @var The callback function to call on error */...
admintools_scan_timerid = window.setInterval('step_scan_timer()', 1000); } function step_scan_timer() { admintools_scan_responseago++; var myText = admintools_scan_msg_ago; document.id('admintools-lastupdate-text').innerHTML = myText.replace('%s',admintools_scan_responseago); } function stop_scan_timer() { if(...
admintools_scan_responseago = 0;
random_line_split
scan.js
/** * @package AdminTools * @copyright Copyright (c)2010-2013 Nicholas K. Dionysopoulos * @license GNU General Public License version 3, or later */ /** @var The AJAX proxy URL */ var admintools_scan_ajax_url_start = ""; var admintools_scan_ajax_url_step = ""; /** @var The callback function to call on error */...
(data) { stop_scan_timer(); if(data.status == false) { // handle failure admintools_scan_error_callback(data.error); } else { if(data.done) { window.location = 'index.php?option=com_admintools&view=scans'; } else { start_scan_timer(); doScanAjax(admintools_scan_ajax_url_step, function(data){ p...
processScanStep
identifier_name
scan.js
/** * @package AdminTools * @copyright Copyright (c)2010-2013 Nicholas K. Dionysopoulos * @license GNU General Public License version 3, or later */ /** @var The AJAX proxy URL */ var admintools_scan_ajax_url_start = ""; var admintools_scan_ajax_url_step = ""; /** @var The callback function to call on error */...
function step_scan_timer() { admintools_scan_responseago++; var myText = admintools_scan_msg_ago; document.id('admintools-lastupdate-text').innerHTML = myText.replace('%s',admintools_scan_responseago); } function stop_scan_timer() { if(admintools_scan_timerid >= 0) { window.clearInterval(admintools_scan_timeri...
{ if(admintools_scan_timerid >= 0) { window.clearInterval(admintools_scan_timerid); } admintools_scan_responseago = 0; admintools_scan_timerid = window.setInterval('step_scan_timer()', 1000); }
identifier_body
2081300.js
engine.eval("load('nashorn:mozilla_compat.js');"); /* This file is part of the OdinMS Maple Story Server Copyright (C) 2008 Patrick Huy <patrick.huy@frz.cc> Matthias Butz <matze@odinms.de> Jan Christian Meyer <vimes@odinms.de> This program is free software: you c...
else { cm.sendOk("Your time has yet to come..."); cm.dispose(); } } else if (status == 1) { if (cm.getJob().equals(MapleJob.RANGER)) { cm.changeJob(MapleJob.BOWMASTER); cm.getChar().gainAp(5); cm.gainItem(2280003,1); cm.teachSkill(3120005,0,10); //bow expert cm.teachSkill(3121...
{ cm.sendNext("You are a strong one."); }
conditional_block
2081300.js
engine.eval("load('nashorn:mozilla_compat.js');"); /* This file is part of the OdinMS Maple Story Server Copyright (C) 2008 Patrick Huy <patrick.huy@frz.cc> Matthias Butz <matze@odinms.de> Jan Christian Meyer <vimes@odinms.de> This program is free software: you c...
if ((cm.getJob().equals(MapleJob.RANGER) || cm.getJob().equals(MapleJob.SNIPER)) && cm.getLevel() >= 120 && cm.getChar().getRemainingSp() <= (cm.getLevel() - 120) * 3) { cm.sendNext("You are a strong one."); } else { cm.sendOk("Your time has yet to come..."); cm.dispose(); } } else i...
{ if (mode == -1) { cm.dispose(); } else { if (mode == 0 && status == 1) { cm.sendOk("Make up your mind and visit me again."); cm.dispose(); return; } if (mode == 1) status++; else status--; if (status == 0) { if (!(cm.getJob().equals(MapleJob.RANGER) || cm.getJob().equals(MapleJob.S...
identifier_body
2081300.js
engine.eval("load('nashorn:mozilla_compat.js');"); /* This file is part of the OdinMS Maple Story Server Copyright (C) 2008 Patrick Huy <patrick.huy@frz.cc> Matthias Butz <matze@odinms.de> Jan Christian Meyer <vimes@odinms.de> This program is free software: you c...
() { status = -1; action(1, 0, 0); } function action(mode, type, selection) { if (mode == -1) { cm.dispose(); } else { if (mode == 0 && status == 1) { cm.sendOk("Make up your mind and visit me again."); cm.dispose(); return; } if (mode == 1) status++; else status--; if (status == 0) { ...
start
identifier_name
2081300.js
engine.eval("load('nashorn:mozilla_compat.js');"); /* This file is part of the OdinMS Maple Story Server Copyright (C) 2008 Patrick Huy <patrick.huy@frz.cc> Matthias Butz <matze@odinms.de> Jan Christian Meyer <vimes@odinms.de> This program is free software: you c...
GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* Floating bowman lady whose name I forget Bowman 4th job advancement Somewhere in Leafre (hell if I know...
but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
random_line_split
graph_placer.py
# Copyright 2018 The TensorFlow Authors. 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 applica...
optimized_graph = tf_optimizer.OptimizeGraph( rewriter_config, metagraph, verbose=verbose, cluster=cluster) optimized_metagraph = meta_graph_pb2.MetaGraphDef() optimized_metagraph.CopyFrom(metagraph) optimized_metagraph.graph_def.CopyFrom(optimized_graph) item = gitem.Item(optimized_metagraph) # Mea...
"""Place the provided metagraph. Args: metagraph: the metagraph to place. cluster: an optional set of hardware resource to optimize the placement for. If none is specified, we'll optimize the placement for the hardware available on the local machine. allotted_time: the maximum amount to time ...
identifier_body
graph_placer.py
# Copyright 2018 The TensorFlow Authors. 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 applica...
original_run_time = hparams.failing_signal if hparams is None: hparams = hierarchical_controller.hierarchical_controller_hparams() # We run with a single child hparams.num_children = 1 with tf_ops.Graph().as_default(): # Place all the nodes of the controller on the CPU. We don't want them to ...
print("Original placement isn't feasible: " + str(e))
conditional_block
graph_placer.py
# Copyright 2018 The TensorFlow Authors. 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 applica...
(metagraph, cluster=None, allotted_time=3600, hparams=None, verbose=False): """Place the provided metagraph. Args: metagraph: the metagraph to place. cluster: an optional set of hardware resource to optimize the placement for. If none is spe...
PlaceGraph
identifier_name
graph_placer.py
# Copyright 2018 The TensorFlow Authors. 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 applica...
from tensorflow.python.grappler import tf_optimizer from tensorflow.python.training import training def PlaceGraph(metagraph, cluster=None, allotted_time=3600, hparams=None, verbose=False): """Place the provided metagraph. Args: metagraph: the metag...
from tensorflow.python.framework import ops as tf_ops from tensorflow.python.grappler import cluster as gcluster from tensorflow.python.grappler import hierarchical_controller from tensorflow.python.grappler import item as gitem
random_line_split
IndexDocBuilder.js
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("va...
subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * Index output builder clas...
{ throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); }
conditional_block
IndexDocBuilder.js
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("va...
* @param {function(html: string, filePath: string)} callback - is called with output. */ _createClass(IndexDocBuilder, [{ key: 'exec', value: function exec(callback) { var ice = this._buildLayoutDoc(); var title = this._getTitle(); ice.load('content', this._buildIndexDoc()); ic...
* execute building output.
random_line_split
IndexDocBuilder.js
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("va...
(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw n...
_possibleConstructorReturn
identifier_name
IndexDocBuilder.js
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("va...
/** * Index output builder class. */ var IndexDocBuilder = function (_DocBuilder) { _inherits(IndexDocBuilder, _DocBuilder); /** * create instance. * @param {Taffy} data - doc object database. * @param {ESDocConfig} config - use config to build output. * @param {CoverageObject} coverage - use cove...
{ if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable...
identifier_body
queueoftwostacks.py
# -*- coding:utf-8; mode:python -*- """ Implements a queue efficiently using only two stacks. """ from helpers import SingleNode from stack import Stack class QueueOf2Stacks: def __init__(self): self.stack_1 = Stack() self.stack_2 = Stack() def enqueue(self, value): self.stack_1.pus...
(): queue = QueueOf2Stacks() print() for i in range(10): queue.enqueue(i) print(i) print("---") for i in range(len(queue)): print(queue.dequeue()) if __name__ == "__main__": main() main()
main
identifier_name
queueoftwostacks.py
# -*- coding:utf-8; mode:python -*- """ Implements a queue efficiently using only two stacks. """
def __init__(self): self.stack_1 = Stack() self.stack_2 = Stack() def enqueue(self, value): self.stack_1.push(value) def dequeue(self): self.transfer_if_necessary() if self.stack_2: return self.stack_2.pop() def peek(self): self.transfer_if...
from helpers import SingleNode from stack import Stack class QueueOf2Stacks:
random_line_split
queueoftwostacks.py
# -*- coding:utf-8; mode:python -*- """ Implements a queue efficiently using only two stacks. """ from helpers import SingleNode from stack import Stack class QueueOf2Stacks: def __init__(self): self.stack_1 = Stack() self.stack_2 = Stack() def enqueue(self, value): self.stack_1.pus...
if __name__ == "__main__": main() main()
print(queue.dequeue())
conditional_block
queueoftwostacks.py
# -*- coding:utf-8; mode:python -*- """ Implements a queue efficiently using only two stacks. """ from helpers import SingleNode from stack import Stack class QueueOf2Stacks: def __init__(self): self.stack_1 = Stack() self.stack_2 = Stack() def enqueue(self, value): self.stack_1.pus...
if __name__ == "__main__": main() main()
queue = QueueOf2Stacks() print() for i in range(10): queue.enqueue(i) print(i) print("---") for i in range(len(queue)): print(queue.dequeue())
identifier_body
problem35.py
# Find primes up to a certain number and output a list of them as strings def primes(top):
prime_list = primes(1000000) # Clear primes with any even number i = 0 while True: try: p = prime_list[i] if p.count('0') != 0: prime_list.pop(i) continue if p.count('2') != 0: prime_list.pop(i) continue if p.count('4') != 0: prime_list.pop(i) continue if p.count('6') != 0: prime_list...
seive = range(2, top+1) for m in range(2, top+1): for n in range(m, top//m+1): p = m*n if p<=top: seive[p-2] = 0 primes = [] for i in range(top-1): if seive[i] != 0: primes.append(str(seive[i])) return primes
identifier_body
problem35.py
# Find primes up to a certain number and output a list of them as strings def primes(top): seive = range(2, top+1) for m in range(2, top+1): for n in range(m, top//m+1): p = m*n if p<=top: seive[p-2] = 0 primes = [] for i in range(top-1): if seive[i] != 0: primes.append(str(seive[i])) return primes prim...
if p.count('4') != 0: prime_list.pop(i) continue if p.count('6') != 0: prime_list.pop(i) continue if p.count('8') != 0: prime_list.pop(i) continue i += 1 except IndexError: break # 2 will have been removed, so add it back prime_list.append('2') # Solve problem circular_primes = [] for p ...
prime_list.pop(i) continue
conditional_block
problem35.py
# Find primes up to a certain number and output a list of them as strings def primes(top): seive = range(2, top+1) for m in range(2, top+1): for n in range(m, top//m+1): p = m*n if p<=top: seive[p-2] = 0 primes = [] for i in range(top-1): if seive[i] != 0: primes.append(str(seive[i])) return primes prim...
i = 0 while True: try: p = prime_list[i] if p.count('0') != 0: prime_list.pop(i) continue if p.count('2') != 0: prime_list.pop(i) continue if p.count('4') != 0: prime_list.pop(i) continue if p.count('6') != 0: prime_list.pop(i) continue if p.count('8') != 0: prime_list.pop(i) ...
# Clear primes with any even number
random_line_split
problem35.py
# Find primes up to a certain number and output a list of them as strings def
(top): seive = range(2, top+1) for m in range(2, top+1): for n in range(m, top//m+1): p = m*n if p<=top: seive[p-2] = 0 primes = [] for i in range(top-1): if seive[i] != 0: primes.append(str(seive[i])) return primes prime_list = primes(1000000) # Clear primes with any even number i = 0 while True: try...
primes
identifier_name
kendo.mobile.navbar.js
/** * Copyright 2015 Telerik AD * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to ...
function toggleTitle(centerElement) { var siblings = centerElement.siblings(), noTitle = !!centerElement.children("ul")[0], showTitle = (!!siblings[0] && $.trim(centerElement.text()) === ""), android = !!(kendo.mobile.application && kendo.mobile.application.element.is("...
{ var items = element.find("[" + kendo.attr("align") + "=" + align + "]"); if (items[0]) { return $('<div class="km-' + align + 'item" />').append(items).prependTo(element); } }
identifier_body
kendo.mobile.navbar.js
/** * Copyright 2015 Telerik AD * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to ...
refresh: function(e) { var view = e.view; this.title(view.options.title); }, destroy: function() { Widget.fn.destroy.call(this); kendo.destroy(this.element); } }); ui.plugin(NavBar); })(window.kendo.jQuery); })(); return wind...
title: function(value) { this.element.find(kendo.roleSelector("view-title")).text(value); toggleTitle(this.centerElement); },
random_line_split
kendo.mobile.navbar.js
/** * Copyright 2015 Telerik AD * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to ...
} function toggleTitle(centerElement) { var siblings = centerElement.siblings(), noTitle = !!centerElement.children("ul")[0], showTitle = (!!siblings[0] && $.trim(centerElement.text()) === ""), android = !!(kendo.mobile.application && kendo.mobile.application.elemen...
{ return $('<div class="km-' + align + 'item" />').append(items).prependTo(element); }
conditional_block
kendo.mobile.navbar.js
/** * Copyright 2015 Telerik AD * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to ...
(align, element) { var items = element.find("[" + kendo.attr("align") + "=" + align + "]"); if (items[0]) { return $('<div class="km-' + align + 'item" />').append(items).prependTo(element); } } function toggleTitle(centerElement) { var siblings = centerElement.sibl...
createContainer
identifier_name
const.py
= "attribute_id" ATTR_ATTRIBUTE_NAME = "attribute_name" ATTR_AVAILABLE = "available" ATTR_CLUSTER_ID = "cluster_id" ATTR_CLUSTER_TYPE = "cluster_type" ATTR_COMMAND_TYPE = "command_type" ATTR_DEVICE_IEEE = "device_ieee" ATTR_DEVICE_TYPE = "device_type" ATTR_ENDPOINTS = "endpoints" ATTR_ENDPOINT_NAMES = "endpoint_names"...
@property def controller(self) -> CALLABLE_T: """Return controller class.""" return self._ctrl_cls @property def description(self) -> str: """Return radio type description.""" return self._desc REPORT_CONFIG_MAX_INT = 900 REPORT_CONFIG_MAX_INT_BATTERY_SAVE = 10800 RE...
"""Init instance.""" self._desc = description self._ctrl_cls = controller_cls
identifier_body
const.py
= "attribute_id" ATTR_ATTRIBUTE_NAME = "attribute_name" ATTR_AVAILABLE = "available" ATTR_CLUSTER_ID = "cluster_id" ATTR_CLUSTER_TYPE = "cluster_type" ATTR_COMMAND_TYPE = "command_type" ATTR_DEVICE_IEEE = "device_ieee" ATTR_DEVICE_TYPE = "device_type" ATTR_ENDPOINTS = "endpoints" ATTR_ENDPOINT_NAMES = "endpoint_names"...
raise ValueError def __init__(self, description: str, controller_cls: CALLABLE_T): """Init instance.""" self._desc = description self._ctrl_cls = controller_cls @property def controller(self) -> CALLABLE_T: """Return controller class.""" return self._ctrl_c...
if radio.description == description: return radio.name
conditional_block
const.py
ATTR_DEVICE_IEEE = "device_ieee" ATTR_DEVICE_TYPE = "device_type" ATTR_ENDPOINTS = "endpoints" ATTR_ENDPOINT_NAMES = "endpoint_names" ATTR_ENDPOINT_ID = "endpoint_id" ATTR_IEEE = "ieee" ATTR_IN_CLUSTERS = "in_clusters" ATTR_LAST_SEEN = "last_seen" ATTR_LEVEL = "level" ATTR_LQI = "lqi" ATTR_MANUFACTURER = "manufacturer"...
SIGNAL_MOVE_LEVEL = "move_level" SIGNAL_REMOVE = "remove" SIGNAL_SET_LEVEL = "set_level"
random_line_split
const.py
= "attribute_id" ATTR_ATTRIBUTE_NAME = "attribute_name" ATTR_AVAILABLE = "available" ATTR_CLUSTER_ID = "cluster_id" ATTR_CLUSTER_TYPE = "cluster_type" ATTR_COMMAND_TYPE = "command_type" ATTR_DEVICE_IEEE = "device_ieee" ATTR_DEVICE_TYPE = "device_type" ATTR_ENDPOINTS = "endpoints" ATTR_ENDPOINT_NAMES = "endpoint_names"...
(self, description: str, controller_cls: CALLABLE_T): """Init instance.""" self._desc = description self._ctrl_cls = controller_cls @property def controller(self) -> CALLABLE_T: """Return controller class.""" return self._ctrl_cls @property def description(self)...
__init__
identifier_name
app.js
/* * #%L * ACS AEM Commons Package * %% * Copyright (C) 2014 Adobe * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unles...
}); }; $scope.saveConfig = function () { $http({ method: 'POST', url: $scope.app.uri + '/config', data: 'enabled=' + $scope.form.enabled || 'false', headers: { 'Content-Type': 'application/x-www-form-urlencoded' } ...
{ NotificationsService.add('error', "Error", "Something went wrong while fetching previous configurations"); }
conditional_block
app.js
/* * #%L * ACS AEM Commons Package * %% * Copyright (C) 2014 Adobe * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unles...
} }). success(function (data, status, headers, config) { if ($scope.form.enabled) { $http({ method: 'POST', url: $scope.app.uri, data: './clientlib-authoring/categories@TypeHint=String[]&./clientlib-autho...
'Content-Type': 'application/x-www-form-urlencoded'
random_line_split
test_task_exceptions.py
from unittest import TestCase from PyProjManCore.task import Task class TestTaskOperationsExceptions(TestCase): """Test Exceptions for Task operations""" def test_append_duplicate_prereq(self): """Test appending duplicate prerequisites to a task, it should be unique"""
root = Task("Root Task") parent = Task("Parent Task") root.append_prerequisite(parent) root.append_prerequisite(parent) self.assertNotEqual(2, len(root.prerequisites)) def test_cyclic_dependency(self): """ Test case of a cyclic dependency, i.e. a Task depends...
random_line_split
test_task_exceptions.py
from unittest import TestCase from PyProjManCore.task import Task class TestTaskOperationsExceptions(TestCase):
root.append_dependant(child) root.append_dependant(child) self.assertNotEqual(2, len(root.dependants))
"""Test Exceptions for Task operations""" def test_append_duplicate_prereq(self): """Test appending duplicate prerequisites to a task, it should be unique""" root = Task("Root Task") parent = Task("Parent Task") root.append_prerequisite(parent) root.append_prerequisite(parent...
identifier_body
test_task_exceptions.py
from unittest import TestCase from PyProjManCore.task import Task class TestTaskOperationsExceptions(TestCase): """Test Exceptions for Task operations""" def test_append_duplicate_prereq(self): """Test appending duplicate prerequisites to a task, it should be unique""" root = Task("Root Task"...
(self): """Test appending duplicate dependants to a task, it should be unique""" root = Task("Root Task") child = Task("Child Task") root.append_dependant(child) root.append_dependant(child) self.assertNotEqual(2, len(root.dependants))
test_append_duplicate_dep
identifier_name
eq.rs
// Copyright 2013 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 ...
} ); let trait_def = TraitDef { cx: cx, span: span, path: Path::new(~["std", "cmp", "Eq"]), additional_bounds: ~[], generics: LifetimeBounds::empty(), methods: ~[ md!("eq", cs_eq), md!("ne", cs_ne) ] }; trait_def.expand(mi...
random_line_split
lib.rs
use binary_podman::{BinaryTrait, PodmanBinary}; use buildpack::{ eyre::Report, libcnb::{ build::{BuildContext, BuildResult, BuildResultBuilder}, detect::{DetectContext, DetectResult, DetectResultBuilder}, generic::{GenericMetadata, GenericPlatform}, Buildpack, Error, Result, ...
() -> &'static str { include_str!("../buildpack.toml") } }
toml
identifier_name
lib.rs
use binary_podman::{BinaryTrait, PodmanBinary}; use buildpack::{ eyre::Report, libcnb::{ build::{BuildContext, BuildResult, BuildResultBuilder}, detect::{DetectContext, DetectResult, DetectResultBuilder}, generic::{GenericMetadata, GenericPlatform}, Buildpack, Error, Result, ...
type Platform = GenericPlatform; type Metadata = GenericMetadata; type Error = Report; fn detect(&self, _context: DetectContext<Self>) -> Result<DetectResult, Self::Error> { if Self::any_exist(&["Dockerfile", "Containerfile"]) { DetectResultBuilder::pass().build() } else { ...
}; pub struct DockerfileBuildpack; impl Buildpack for DockerfileBuildpack {
random_line_split
lib.rs
use binary_podman::{BinaryTrait, PodmanBinary}; use buildpack::{ eyre::Report, libcnb::{ build::{BuildContext, BuildResult, BuildResultBuilder}, detect::{DetectContext, DetectResult, DetectResultBuilder}, generic::{GenericMetadata, GenericPlatform}, Buildpack, Error, Result, ...
else { DetectResultBuilder::fail().build() } } fn build(&self, context: BuildContext<Self>) -> Result<BuildResult, Self::Error> { let tag = tag_for_path(&context.app_dir); PodmanBinary {} .ensure_version_sync(">=1") .map_err(Error::BuildpackError)? ...
{ DetectResultBuilder::pass().build() }
conditional_block
lib.rs
use binary_podman::{BinaryTrait, PodmanBinary}; use buildpack::{ eyre::Report, libcnb::{ build::{BuildContext, BuildResult, BuildResultBuilder}, detect::{DetectContext, DetectResult, DetectResultBuilder}, generic::{GenericMetadata, GenericPlatform}, Buildpack, Error, Result, ...
} impl BuildpackTrait for DockerfileBuildpack { fn toml() -> &'static str { include_str!("../buildpack.toml") } }
{ let tag = tag_for_path(&context.app_dir); PodmanBinary {} .ensure_version_sync(">=1") .map_err(Error::BuildpackError)? .run_sync(&["build", "--tag", &tag, "."]) .map_err(Error::BuildpackError)?; BuildResultBuilder::new().build() }
identifier_body
line_follower.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # # line_follower.py # # Copyright 2011 Manuel Martín Ortiz <mmartinortiz@gmail.com> # # 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 # ...
robot_id = sys.argv[1] if epucks.has_key(robot_id): main(epucks[robot_id]) elif re.match(X, robot_id) != 0: main(robot_id) else: error('You have to indicate the MAC direction of the robot')
rror("Usage: " + sys.argv[0] + " ePuck_ID | MAC Address") sys.exit()
conditional_block
line_follower.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # # line_follower.py # # Copyright 2011 Manuel Martín Ortiz <mmartinortiz@gmail.com> # # 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 # ...
except KeyboardInterrupt: log('Stoping the robot. Bye!') robot.close() sys.exit() except Exception, e: error(e) return 0 if __name__ == '__main__': X = '([a-fA-F0-9]{2}[:|\-]?){6}' if len(sys.argv) < 2: error("Usage: " + sys.argv[0] + " ePuck_ID | MAC Address") sys.exit() robot_id = sys.argv[1] i...
# Switch Off robot.set_led(index, 0) leds_on[index] = 0
random_line_split
line_follower.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # # line_follower.py # # Copyright 2011 Manuel Martín Ortiz <mmartinortiz@gmail.com> # # 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 # ...
log('Conection complete. CTRL+C to stop') log('Library version: ' + robot.version) times_got = [] except Exception, e: error(e) sys.exit(1) try: while True: # Important: when you execute 'step()', al sensors # and actuators are updated. All changes you do on the ePuck # will be effectives af...
lobal_speed = 180 fs_speed = 0.6 threshold = 1000 log('Conecting with ePuck') try: # First, create an ePuck object. # If you want debug information: #~ robot = ePuck(mac, debug = True) # else: robot = ePuck(mac) # Second, connect to it robot.connect() # You can enable various sensors at the sam...
identifier_body
line_follower.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # # line_follower.py # # Copyright 2011 Manuel Martín Ortiz <mmartinortiz@gmail.com> # # 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 # ...
text): """ Show @text in standart output with colors """ blue = '\033[1;34m' off = '\033[1;m' print(''.join((blue, '[Log] ', off, str(text)))) def error(text): red = '\033[1;31m' off = '\033[1;m' print(''.join((red, '[Error] ', off, str(text)))) def main(mac): global_speed = 180 fs_speed = 0.6 th...
og(
identifier_name
standard.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity 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 lat...
pub use rustc_serialize::json::Json; pub use rustc_serialize::base64::FromBase64; pub use rustc_serialize::hex::{FromHex, FromHexError}; pub use heapsize::HeapSizeOf; pub use itertools::Itertools; pub use parking_lot::{Condvar, Mutex, MutexGuard, RwLock, RwLockReadGuard, RwLockWriteGuard};
pub use std::ops::*; pub use std::cmp::*; pub use std::sync::Arc; pub use std::collections::*;
random_line_split
urlbuilder.js
(function(angular) { 'use strict'; angular.module('httpu.urlbuilder', []) .factory('huURLBuilderInterceptor', huURLBuilderInterceptor) .factory('huURLBuilderFactory', huURLBuilderFactory); huURLBuilderInterceptor.$inject = ['$injector', '$q']; function huURLBuilderInterceptor($injector, $q) { ...
return paramsSerializer; ////////////////////////////// /** * From Angular * Please guys! export this! */ function encodeUriQuery(val) { return $window.encodeURIComponent(val) .replace(/%40/gi, '@') .replace(/%3A/gi, ':') .replace(/%24/g, '$') ...
} } huURLBuilderFactory.$inject = ['$window']; function huURLBuilderFactory($window) {
random_line_split
urlbuilder.js
(function(angular) { 'use strict'; angular.module('httpu.urlbuilder', []) .factory('huURLBuilderInterceptor', huURLBuilderInterceptor) .factory('huURLBuilderFactory', huURLBuilderFactory); huURLBuilderInterceptor.$inject = ['$injector', '$q']; function huURLBuilderInterceptor($injector, $q) { ...
} })(window.angular);
{ serializer = serializer || toStringEncode; return function buildUrl(url, params) { if (!params) { return url; } var parts = []; serializer(params, function addKeyValue(key, value) { parts.push(encodeUriQuery(key) + '=' + encodeUriQuery(value)); ...
identifier_body
urlbuilder.js
(function(angular) { 'use strict'; angular.module('httpu.urlbuilder', []) .factory('huURLBuilderInterceptor', huURLBuilderInterceptor) .factory('huURLBuilderFactory', huURLBuilderFactory); huURLBuilderInterceptor.$inject = ['$injector', '$q']; function huURLBuilderInterceptor($injector, $q) { ...
return url; }; } } })(window.angular);
{ url += ((url.indexOf('?') === -1) ? '?' : '&') + parts.join('&'); }
conditional_block
urlbuilder.js
(function(angular) { 'use strict'; angular.module('httpu.urlbuilder', []) .factory('huURLBuilderInterceptor', huURLBuilderInterceptor) .factory('huURLBuilderFactory', huURLBuilderFactory); huURLBuilderInterceptor.$inject = ['$injector', '$q']; function huURLBuilderInterceptor($injector, $q) { ...
($window) { return paramsSerializer; ////////////////////////////// /** * From Angular * Please guys! export this! */ function encodeUriQuery(val) { return $window.encodeURIComponent(val) .replace(/%40/gi, '@') .replace(/%3A/gi, ':') .replace(/%24/g, ...
huURLBuilderFactory
identifier_name
RadioButton.js
ing or unselecting it). */ select : { parameters : { /** * Checks whether the RadioButton is active or not. */ selected : {type : "boolean"} } } }, associations : { /** * Association to controls / IDs which describe this control (see WAI-ARIA attribute aria-described...
{ this.$().toggleClass("sapMRbSel", bSelected); if (bSelected) { this.getDomRef().setAttribute("aria-checked", "true"); this.getDomRef("RB").checked = true; this.getDomRef("RB").setAttribute("checked", "checked"); } else { this.getDomRef().removeAttribute("aria-checked"); // aria-checked=false...
conditional_block
RadioButton.js
radio button belongs to the sapMRbDefaultGroup per default. Default behavior of a radio button in a group is that when one of the radio buttons in a group is selected, all others are unselected. */ groupName : {type : "string", group : "Behavior", defaultValue : 'sapMRbDefaultGroup'}, /** * Specifies th...
return this; }; RadioButton.prototype.onsaphome = function(oEvent) { this._keyboardHandler(KH_NAVIGATION.HOME, true); // mark the event that it is handled by the control oEvent.setMarked(); return this; }; RadioButton.prototype.onsaphomemodifiers = function(oEvent) { this._keyboardHandler(KH_NAVIGAT...
// mark the event that it is handled by the control oEvent.setMarked();
random_line_split
processing.rs
BlockstackOperationType::UserBurnSupport(ref op) => { op.check(burnchain, self).map_err(|e| { warn!( "REJECTED({}) user burn support {} at {},{}: {:?}", op.block_height, &op.txid, op.block_height, op.vtxindex, &e ...
{ match blockstack_op { BlockstackOperationType::LeaderKeyRegister(ref op) => { op.check(burnchain, self).map_err(|e| { warn!( "REJECTED({}) leader key register {} at {},{}: {:?}", op.block_height, &op.txid, op.block...
identifier_body
processing.rs
<MissedBlockCommit>, next_pox_info: Option<RewardCycleInfo>, parent_pox: PoxId, reward_info: Option<&RewardSetInfo>, initial_mining_bonus_ustx: u128, ) -> Result<(BlockSnapshot, BurnchainStateTransition), BurnchainError> { let this_block_height = block_header.block_height; ...
use burnchains::*; use chainstate::burn::db::sortdb::{tests::test_append_snapshot, SortitionDB}; use chainstate::burn::operations::{ leader_block_commit::BURN_BLOCK_MINED_AT_MODULUS, LeaderBlockCommitOp, LeaderKeyRegisterOp, };
random_line_split
processing.rs
_hash = block_header.block_hash.clone(); // make the burn distribution, and in doing so, identify the user burns that we'll keep let state_transition = BurnchainStateTransition::from_block_ops(self, burnchain, parent_snapshot, this_block_ops, missed_commits, burnchain.pox_constants.sunset_end) ...
test_initial_block_reward
identifier_name
configuration.py
# -*- coding: utf-8 -*- # This file is part of Shuup. # # Copyright (c) 2012-2017, Shoop Commerce Ltd. All rights reserved. # # This source code is licensed under the OSL-3.0 license found in the # LICENSE file in the root directory of this source tree. """ API for Shuup's Dynamic Configuration. Idea of the Dynamic Co...
def _get_configuration(shop): """ Get global or shop specific configuration with caching. :param shop: Shop to get configuration for, or None :type shop: shuup.core.models.Shop|None :return: Global or shop specific configuration :rtype: dict """ configuration = cache.get(_get_cache_key(...
:rtype: Any """ return _get_configuration(shop).get(key, default)
random_line_split
configuration.py
# -*- coding: utf-8 -*- # This file is part of Shuup. # # Copyright (c) 2012-2017, Shoop Commerce Ltd. All rights reserved. # # This source code is licensed under the OSL-3.0 license found in the # LICENSE file in the root directory of this source tree. """ API for Shuup's Dynamic Configuration. Idea of the Dynamic Co...
def _get_configuration_from_db(shop): """ Get global or shop specific configuration from database. :param shop: Shop to fetch configuration for, or None :type shop: shuup.core.models.Shop|None :return: Configuration as it was saved in database :rtype: dict """ configuration = {} ...
""" Cache global or shop specific configuration. Global configuration (`shop` is ``None``) is read first, then `shop` based configuration is updated over that. :param shop: Shop to cache configuration for, or None :type shop: shuup.core.models.Shop|None :return: Cached configuration :rtype...
identifier_body
configuration.py
# -*- coding: utf-8 -*- # This file is part of Shuup. # # Copyright (c) 2012-2017, Shoop Commerce Ltd. All rights reserved. # # This source code is licensed under the OSL-3.0 license found in the # LICENSE file in the root directory of this source tree. """ API for Shuup's Dynamic Configuration. Idea of the Dynamic Co...
(shop): """ Cache global or shop specific configuration. Global configuration (`shop` is ``None``) is read first, then `shop` based configuration is updated over that. :param shop: Shop to cache configuration for, or None :type shop: shuup.core.models.Shop|None :return: Cached configuratio...
_cache_shop_configuration
identifier_name
configuration.py
# -*- coding: utf-8 -*- # This file is part of Shuup. # # Copyright (c) 2012-2017, Shoop Commerce Ltd. All rights reserved. # # This source code is licensed under the OSL-3.0 license found in the # LICENSE file in the root directory of this source tree. """ API for Shuup's Dynamic Configuration. Idea of the Dynamic Co...
cache.set(_get_cache_key(shop), configuration) return configuration def _get_configuration_from_db(shop): """ Get global or shop specific configuration from database. :param shop: Shop to fetch configuration for, or None :type shop: shuup.core.models.Shop|None :return: Configuration as i...
configuration.update(_get_configuration_from_db(shop))
conditional_block
siteProcessor.js
import {first, uniq, compact, startsWith} from 'lodash' import cheerio from 'cheerio' import urijs from 'urijs' import {flattenDeepCheerioElements} from 'utils' export function getRelevantTags(htmlText, urlToFetch){ return new Promise((resolve, reject) => { const doc = cheerio.load(htmlText, { ignoreWhit...
resolve({ title: extractTitle(doc) || '', description: extractDescription(doc) || '', imageUrls: extractImages(doc, urlToFetch) }) }) } function extractDescription(doc){ return first(compact([ doc("meta[name='description']").attr('content'), doc("meta[property='og:description']")....
random_line_split
siteProcessor.js
import {first, uniq, compact, startsWith} from 'lodash' import cheerio from 'cheerio' import urijs from 'urijs' import {flattenDeepCheerioElements} from 'utils' export function getRelevantTags(htmlText, urlToFetch){ return new Promise((resolve, reject) => { const doc = cheerio.load(htmlText, { ignoreWhit...
return urijs(imageUrl).absoluteTo(urlToFetch).toString() }) ) }
{ const imageUrls = flattenDeepCheerioElements([ doc("meta[name='image']").attr("content"), doc("meta[property='og:image']").attr("content"), doc("img").map((i, imgNode) => doc(imgNode).attr("src")) ]) return uniq(imageUrls .map(imageUrl => imageUrl.replace('\\', '/')) .map(imageUrl => { ...
identifier_body
siteProcessor.js
import {first, uniq, compact, startsWith} from 'lodash' import cheerio from 'cheerio' import urijs from 'urijs' import {flattenDeepCheerioElements} from 'utils' export function getRelevantTags(htmlText, urlToFetch){ return new Promise((resolve, reject) => { const doc = cheerio.load(htmlText, { ignoreWhit...
if(startsWith(imageUrl, '//')){ const urlToFetchProtocol = urijs(urlToFetch).protocol() return urijs(imageUrl).protocol(urlToFetchProtocol).toString() } return urijs(imageUrl).absoluteTo(urlToFetch).toString() }) ) }
{ return imageUrl }
conditional_block
siteProcessor.js
import {first, uniq, compact, startsWith} from 'lodash' import cheerio from 'cheerio' import urijs from 'urijs' import {flattenDeepCheerioElements} from 'utils' export function getRelevantTags(htmlText, urlToFetch){ return new Promise((resolve, reject) => { const doc = cheerio.load(htmlText, { ignoreWhit...
(doc) { return first(compact([ doc("meta[name='title']").attr('content'), doc("meta[property='og:title']").attr('content'), doc('title').text(), ])) } function extractImages(doc, urlToFetch) { const imageUrls = flattenDeepCheerioElements([ doc("meta[name='image']").attr("content"), doc("meta[...
extractTitle
identifier_name
marFileLockedStageFailurePartialSvc_win.js
/* Any copyright is dedicated to the Public Domain. * http://creativecommons.org/publicdomain/zero/1.0/ */ /* File locked partial MAR file staged patch apply failure test */ const STATE_AFTER_STAGE = STATE_PENDING; function run_test()
/** * Called after the call to setupUpdaterTest finishes. */ function setupUpdaterTestFinished() { runHelperLockFile(gTestFiles[2]); } /** * Called after the call to waitForHelperSleep finishes. */ function waitForHelperSleepFinished() { stageUpdate(); } /** * Called after the call to stageUpdate finishes....
{ if (!setupTestCommon()) { return; } gTestFiles = gTestFilesPartialSuccess; gTestDirs = gTestDirsPartialSuccess; setTestFilesAndDirsForFailure(); setupUpdaterTest(FILE_PARTIAL_MAR, false); }
identifier_body
marFileLockedStageFailurePartialSvc_win.js
/* Any copyright is dedicated to the Public Domain. * http://creativecommons.org/publicdomain/zero/1.0/ */ /* File locked partial MAR file staged patch apply failure test */ const STATE_AFTER_STAGE = STATE_PENDING; function run_test() { if (!setupTestCommon()) { return; } gTestFiles = gTestFilesPartialSu...
() { runHelperLockFile(gTestFiles[2]); } /** * Called after the call to waitForHelperSleep finishes. */ function waitForHelperSleepFinished() { stageUpdate(); } /** * Called after the call to stageUpdate finishes. */ function stageUpdateFinished() { checkPostUpdateRunningFile(false); // Files aren't check...
setupUpdaterTestFinished
identifier_name