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 |
|---|---|---|---|---|
content.rs | #![stable]
use libc;
use std;
/// Opaque struct which holds a reference to the underlying Clutter object.
#[repr(C)]
pub struct ContentRef {
opaque: *mut libc::c_void
}
/// Delegate for painting the content of an actor
///
/// Content is an interface to implement types responsible for painting the
/// content of a... | (&mut self) {
unsafe {
clutter_content_invalidate(self.as_content());
}
}
}
impl Content for ContentRef {
fn as_content(&self) -> *mut libc::c_void {
return self.opaque;
}
}
extern {
fn clutter_content_get_preferred_size(self_value: *mut libc::c_void, width: *mut f32, height: *mut f32) -> i3... | invalidate | identifier_name |
content.rs | #![stable]
use libc;
use std;
/// Opaque struct which holds a reference to the underlying Clutter object.
#[repr(C)]
pub struct ContentRef {
opaque: *mut libc::c_void
}
/// Delegate for painting the content of an actor
///
/// Content is an interface to implement types responsible for painting the
/// content of a... |
/// Invalidates a Content.
///
/// This function should be called by Content implementations when they change
/// the way the content should be painted regardless of the actor state.
///
/// _Since 1.10_
fn invalidate(&mut self) {
unsafe {
clutter_content_invalidate(self.as_content());
}
... | {
unsafe {
let mut width:f32 = std::intrinsics::init();
let mut height:f32 = std::intrinsics::init();
let foreign_result = clutter_content_get_preferred_size(self.as_content(), &mut width, &mut height);
return (foreign_result != 0, width, height);
}
} | identifier_body |
issue-643-inner-struct.rs | #![allow(
dead_code,
non_snake_case,
non_camel_case_types,
non_upper_case_globals
)]
#[repr(C)]
#[derive(Default)]
pub struct __IncompleteArrayField<T>(::std::marker::PhantomData<T>, [T; 0]);
impl<T> __IncompleteArrayField<T> {
#[inline]
pub const fn new() -> Self {
__IncompleteArrayFie... | (&self, fmt: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
fmt.write_str("__IncompleteArrayField")
}
}
#[repr(C)]
#[derive(Debug)]
pub struct rte_ring {
pub memzone: *mut rte_memzone,
pub prod: rte_ring_prod,
pub cons: rte_ring_cons,
pub ring: __IncompleteArrayField<*mut ::std::os:... | fmt | identifier_name |
issue-643-inner-struct.rs | #![allow(
dead_code,
non_snake_case,
non_camel_case_types,
non_upper_case_globals
)]
#[repr(C)]
#[derive(Default)]
pub struct __IncompleteArrayField<T>(::std::marker::PhantomData<T>, [T; 0]);
impl<T> __IncompleteArrayField<T> {
#[inline]
pub const fn new() -> Self {
__IncompleteArrayFie... | &(*(::std::ptr::null::<rte_ring_cons>())).sc_dequeue as *const _
as usize
},
0usize,
concat!(
"Offset of field: ",
stringify!(rte_ring_cons),
"::",
stringify!(sc_dequeue)
)
);
}
#[test]
fn bindgen_test_layout... | );
assert_eq!(
unsafe { | random_line_split |
test_auto_MotionCorrection.py | # AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT
from nipype.testing import assert_equal
from nipype.interfaces.broccoli.preprocess import MotionCorrection
def test_MotionCorrection_inputs():
| platform=dict(argstr='-platform %d',
),
quiet=dict(argstr='-quiet',
),
referencevolume=dict(argstr='-referencevolume %s',
),
terminal_output=dict(nohash=True,
),
verbose=dict(argstr='-verbose',
),
)
inputs = MotionCorrection.input_spec()
for key, metadata in input_ma... | input_map = dict(args=dict(argstr='%s',
),
device=dict(argstr='-device %d',
),
environ=dict(nohash=True,
usedefault=True,
),
ignore_exception=dict(nohash=True,
usedefault=True,
),
in_file=dict(argstr='%s',
copyfile=False,
mandatory=True,
position=0,
),
iterati... | identifier_body |
test_auto_MotionCorrection.py | # AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT
from nipype.testing import assert_equal
from nipype.interfaces.broccoli.preprocess import MotionCorrection
def test_MotionCorrection_inputs():
input_map = dict(args=dict(argstr='%s',
),
device=dict(argstr='-device %d',
),
environ=dict(nohash=Tru... |
def test_MotionCorrection_outputs():
output_map = dict(motioncorrected_file=dict(),
parameters_file=dict(),
)
outputs = MotionCorrection.output_spec()
for key, metadata in output_map.items():
for metakey, value in metadata.items():
yield assert_equal, getattr(outputs.traits()[... | yield assert_equal, getattr(inputs.traits()[key], metakey), value | conditional_block |
test_auto_MotionCorrection.py | # AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT
from nipype.testing import assert_equal
from nipype.interfaces.broccoli.preprocess import MotionCorrection
def | ():
input_map = dict(args=dict(argstr='%s',
),
device=dict(argstr='-device %d',
),
environ=dict(nohash=True,
usedefault=True,
),
ignore_exception=dict(nohash=True,
usedefault=True,
),
in_file=dict(argstr='%s',
copyfile=False,
mandatory=True,
position=0,
),
... | test_MotionCorrection_inputs | identifier_name |
test_auto_MotionCorrection.py | # AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT
from nipype.testing import assert_equal
from nipype.interfaces.broccoli.preprocess import MotionCorrection
def test_MotionCorrection_inputs():
input_map = dict(args=dict(argstr='%s',
),
device=dict(argstr='-device %d',
),
environ=dict(nohash=Tru... | in_file=dict(argstr='%s',
copyfile=False,
mandatory=True,
position=0,
),
iterations=dict(argstr='-iterations %d',
),
output=dict(argstr='-output %s',
),
output_type=dict(),
platform=dict(argstr='-platform %d',
),
quiet=dict(argstr='-quiet',
),
referencevolume=... | usedefault=True,
),
ignore_exception=dict(nohash=True,
usedefault=True,
), | random_line_split |
http-status-type.ts |
export function | (statusCode: number) {
//tslint:disable-next-line:no-magic-numbers
return Math.floor(statusCode / 100);
}
export const HTTP_STATUS_TYPE_INFO = 1;
export const HTTP_STATUS_TYPE_SUCCESS = 2;
export const HTTP_STATUS_TYPE_REDIRECTION = 3;
export const HTTP_STATUS_TYPE_CLIENT_ERROR = 4;
export const HTTP_STATUS_TY... | httpStatusType | identifier_name |
http-status-type.ts | export function httpStatusType(statusCode: number) {
//tslint:disable-next-line:no-magic-numbers
return Math.floor(statusCode / 100);
}
export const HTTP_STATUS_TYPE_INFO = 1;
export const HTTP_STATUS_TYPE_SUCCESS = 2;
export const HTTP_STATUS_TYPE_REDIRECTION = 3;
export const HTTP_STATUS_TYPE_CLIENT_ERROR = ... | export const HTTP_STATUS_OK = 200;
export const HTTP_STATUS_PARTIAL_CONTENT = 206;
export const HTTP_STATUS_ERROR = 400;
export const HTTP_STATUS_NOT_LOGGED_IN = 401;
export const HTTP_STATUS_UNAUTHORIZED = 403;
export const HTTP_STATUS_NOT_FOUND = 404;
export const HTTP_STATUS_WRONG_RANGE = 416;
export const HTTP_STA... | export const HTTP_STATUS_TYPE_SERVER_ERROR = 5;
| random_line_split |
http-status-type.ts |
export function httpStatusType(statusCode: number) |
export const HTTP_STATUS_TYPE_INFO = 1;
export const HTTP_STATUS_TYPE_SUCCESS = 2;
export const HTTP_STATUS_TYPE_REDIRECTION = 3;
export const HTTP_STATUS_TYPE_CLIENT_ERROR = 4;
export const HTTP_STATUS_TYPE_SERVER_ERROR = 5;
export const HTTP_STATUS_OK = 200;
export const HTTP_STATUS_PARTIAL_CONTENT = 206;
export ... | {
//tslint:disable-next-line:no-magic-numbers
return Math.floor(statusCode / 100);
} | identifier_body |
sysInfo.py | # (c) Copyright 2008-2015 Synapse Wireless, Inc.
"""System Info IDs - used in 'getInfo()' and 'getStat()' calls"""
# Types
SI_TYPE_VENDOR = 0
SI_TYPE_RADIO = 1
SI_TYPE_CPU = 2
SI_TYPE_PLATFORM = 3
SI_TYPE_BUILD = 4
SI_TYPE_VERSION_MAJOR = ... | SI_BUILD_DEBUG = 0
SI_BUILD_RELEASE = 1
# Encryptions
SI_NO_ENCRYPTION = 0
SI_AES128_ENCRYPTION = 1
SI_SNAP_ENCRYPTION = 2
# getStat() Enumerations
STAT_DS_NULL_TX_BUFFERS = 0
STAT_DS_UART0_RX_BUFFERS = 1
STAT_DS_UART0_TX_BUFFERS = 2
STAT_DS_UART1_RX_BUFFERS ... | SI_PLATFORM_ATmega128RFR2_PFM = 26
SI_PLATFORM_SM220UF1_PFM = 27
SI_PLATFORM_ATmega1284RFR2_PFM = 28
# Builds | random_line_split |
baseWibjects.py | # -*- coding: utf-8 -*-
# Copyright (C) 2012, Almar Klein
#
# Visvis is distributed under the terms of the (new) BSD License.
# The full license can be found in 'license.txt'.
""" Module baseWibjects
Defines the Box class and the DraggableBox class.
"""
import OpenGL.GL as gl
from visvis.core import Wibject
from v... |
return locals()
@misc.PropWithDraw
def edgeWidth():
""" Get/Set the edge width of the wibject.
"""
def fget(self):
return self._edgeWidth
def fset(self, value):
self._edgeWidth = float(value)
return locals()
def ... | self._edgeColor = misc.getColor(value, 'setting edgeColor') | identifier_body |
baseWibjects.py | # -*- coding: utf-8 -*-
# Copyright (C) 2012, Almar Klein
#
# Visvis is distributed under the terms of the (new) BSD License.
# The full license can be found in 'license.txt'.
""" Module baseWibjects
Defines the Box class and the DraggableBox class.
"""
import OpenGL.GL as gl
from visvis.core import Wibject
from v... | gl.glColor(0,0,0,1)
gl.glPointSize(1)
gl.glDisable(gl.GL_POINT_SMOOTH)
# Draw dots
if len(self._dots):
gl.glEnableClientState(gl.GL_VERTEX_ARRAY)
gl.glVertexPointerf(self._dots.data)
gl.glDrawArrays(gl.GL_POINTS... | conditional_block | |
baseWibjects.py | # -*- coding: utf-8 -*-
# Copyright (C) 2012, Almar Klein
#
# Visvis is distributed under the terms of the (new) BSD License.
# The full license can be found in 'license.txt'.
""" Module baseWibjects
Defines the Box class and the DraggableBox class.
"""
import OpenGL.GL as gl
from visvis.core import Wibject
from v... | self.position.w += event.absx - self._dragStartPos[0]
self.position.h += event.absy - self._dragStartPos[1]
event.owner.Draw()
else: # dragging
self.position.x += event.absx - self._dragStartPos[0]
self.position.y += event.absy - self._dragStartPos[1]
... | def _DragOnMove(self, event):
if not self._dragStartPos:
return
elif self._dragResizing: | random_line_split |
baseWibjects.py | # -*- coding: utf-8 -*-
# Copyright (C) 2012, Almar Klein
#
# Visvis is distributed under the terms of the (new) BSD License.
# The full license can be found in 'license.txt'.
""" Module baseWibjects
Defines the Box class and the DraggableBox class.
"""
import OpenGL.GL as gl
from visvis.core import Wibject
from v... | (self, value):
self._edgeWidth = float(value)
return locals()
def _GetBgcolorToDraw(self):
""" Can be overloaded to indicate mouse over in buttons.
"""
return self._bgcolor
def OnDraw(self, fast=False):
# get dimensions ... | fset | identifier_name |
sheriff_unittest.py | # Copyright (C) 2010 Google Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the f... | --- Begin comment ---
http://trac.webkit.org/changeset/4321 might have broken Foo and Bar
--- End comment ---
MOCK bug comment: bug_id=1234, cc=['watcher@example.com']
--- Begin comment ---
http://trac.webkit.org/changeset/4321 might have broken Foo and Bar
The following tests are not passing:
mock-test-1
--- End comm... | def test_post_blame_comment_on_bug(self):
def run():
sheriff = Sheriff(MockTool(), MockSheriffBot())
builders = [
Builder("Foo", None),
Builder("Bar", None),
]
commit_info = Mock()
commit_info.bug_id = lambda: None
... | identifier_body |
sheriff_unittest.py | # Copyright (C) 2010 Google Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the f... | --- End comment ---
MOCK bug comment: bug_id=1234, cc=['watcher@example.com']
--- Begin comment ---
http://trac.webkit.org/changeset/4321 might have broken Foo and Bar
The following tests are not passing:
mock-test-1
--- End comment ---
MOCK bug comment: bug_id=1234, cc=['watcher@example.com']
--- Begin comment ---
h... | http://trac.webkit.org/changeset/4321 might have broken Foo and Bar | random_line_split |
sheriff_unittest.py | # Copyright (C) 2010 Google Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the f... | (object):
name = "mock-sheriff-bot"
watchers = [
"watcher@example.com",
]
def run_webkit_patch(self, args):
return "Created bug https://bugs.webkit.org/show_bug.cgi?id=36936\n"
class SheriffTest(unittest.TestCase):
def test_post_blame_comment_on_bug(self):
def run():
... | MockSheriffBot | identifier_name |
upperair_soundings.py | # Copyright (c) 2016,2017 MetPy Developers.
# Distributed under the terms of the BSD 3-Clause License.
# SPDX-License-Identifier: BSD-3-Clause
"""
===========================
Upper Air Sounding Tutorial
===========================
Upper air analysis is a staple of many synoptic and mesoscale analysis
problems. In this... | skiprows=5, usecols=[0, 1, 2, 3, 6, 7], names=col_names)
df['u_wind'], df['v_wind'] = mpcalc.get_wind_components(df['speed'],
np.deg2rad(df['direction']))
# Drop any rows with all NaN values for T, Td, winds
df = df.dropna(subset=('temperature',... | df = pd.read_fwf(get_test_data('nov11_sounding.txt', as_file_obj=False), | random_line_split |
EncoderUserModesComponent.py | # http://remotescripts.blogspot.com
"""
Track Control User Modes component originally designed for use with the APC40.
Copyright (C) 2010 Hanz Petrov <hanz.petrov@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
the Fre... | self._encoder_device_modes = encoder_device_modes
self._encoder_eq_modes = encoder_eq_modes
self._mode_index = 0
self._modes_buttons = []
self._user_buttons = []
self._last_mode = 0
def disconnect(self):
ModeSelectorComponent.disconnect(self)
self._p... | self._bank_buttons = bank_buttons
self._mixer = mixer
self._device = device | random_line_split |
EncoderUserModesComponent.py | # http://remotescripts.blogspot.com
"""
Track Control User Modes component originally designed for use with the APC40.
Copyright (C) 2010 Hanz Petrov <hanz.petrov@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
the Fre... | (self):
pass
def set_mode(self, mode):
assert isinstance(mode, int)
assert (mode in range(self.number_of_modes()))
if (self._mode_index != mode):
self._last_mode = self._mode_index # keep track of previous mode, to allow conditional actions
self._mode_index =... | on_enabled_changed | identifier_name |
EncoderUserModesComponent.py | # http://remotescripts.blogspot.com
"""
Track Control User Modes component originally designed for use with the APC40.
Copyright (C) 2010 Hanz Petrov <hanz.petrov@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
the Fre... |
def _set_modes(self):
if self.is_enabled():
assert (self._mode_index in range(self.number_of_modes()))
for index in range(len(self._modes_buttons)):
if (index <= self._mode_index):
self._modes_buttons[index].turn_on()
else:
... | self.set_mode(self._modes_buttons.index(sender)) | conditional_block |
EncoderUserModesComponent.py | # http://remotescripts.blogspot.com
"""
Track Control User Modes component originally designed for use with the APC40.
Copyright (C) 2010 Hanz Petrov <hanz.petrov@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
the Fre... |
def _mode_value(self, value, sender):
assert (len(self._modes_buttons) > 0)
assert isinstance(value, int)
assert isinstance(sender, ButtonElement)
assert (self._modes_buttons.count(sender) == 1)
if ((value is not 0) or (not sender.is_momentary())):
self.set_mod... | pass | identifier_body |
control.js | /*
* Copyright (C) 2014 rafa
*
* 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 2
* of the License, or (at your option) any later version.
*
* This program is distributed ... |
productoControl.prototype.new = function (place, objParams, oModel, oView) {
var thisObject = this;
$(place).empty();
$(place).append(oView.getPanel("Alta de " + this.clase, oView.getEmptyForm()));
//id must not be enabled
$('#id').val('0').attr("disabled", true);
if (objParams) {
//sop... | oView.loadFormValues(oDocumentoModel.getCachedOne(), oDocumentoModel.getCachedFieldNames());
}; | random_line_split |
control.js | /*
* Copyright (C) 2014 rafa
*
* 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 2
* of the License, or (at your option) any later version.
*
* This program is distributed ... |
oView.doEventsLoading();
//$('#submitForm').unbind('click');
//$('#submitForm').click(function () {
oView.okValidation(function (e) {
resultado = oModel.setOne({json: JSON.stringify(oView.getFormValues())});
oView.doResultOperationNotifyToUser(place, resultado["... | {
//soporte de claves ajenas
var selector = objParams["systemfilter"].replace('id_', 'obj_');
$('#' + selector + "_id").val(objParams["systemfiltervalue"]).attr("disabled", true);
$('#' + selector + "_button").attr("disabled", true).hide();
var oModelo = "o" + objParams["systemfi... | conditional_block |
agency.js | /*!
* Start Bootstrap - Agency Bootstrap Theme (http://startbootstrap.com)
* Code licensed under the Apache License v2.0. | // jQuery for page scrolling feature - requires jQuery Easing plugin
$(function() {
$('a.page-scroll').bind('click', function(event) {
var $anchor = $(this);
$('html, body').stop().animate({
scrollTop: $($anchor.attr('href')).offset().top
}, 1500, 'easeInOutExpo');
event.... | * For details, see http://www.apache.org/licenses/LICENSE-2.0.
*/
| random_line_split |
agency.js | /*!
* Start Bootstrap - Agency Bootstrap Theme (http://startbootstrap.com)
* Code licensed under the Apache License v2.0.
* For details, see http://www.apache.org/licenses/LICENSE-2.0.
*/
// jQuery for page scrolling feature - requires jQuery Easing plugin
$(function() {
$('a.page-scroll').bind('click', functi... |
});
}); | {
element.css('background-color', '#9a0000');
} | conditional_block |
js_FxzL6y_vG1Dd9B-MsolHGVlVoN_lbUIGopU6FCDDV9U.js | true or false, depending on whether this constraint is satisfied.
*/
checkConstraints: function(value, selector, state) {
// Normalize the last parameter. If it's non-numeric, we treat it either as
// a selector (in case there isn't one yet) or as a trigger/state.
if (typeof state !== 'string' || (/[0... | compare | identifier_name | |
js_FxzL6y_vG1Dd9B-MsolHGVlVoN_lbUIGopU6FCDDV9U.js |
});
$('> li:first', tab_list).addClass('first');
$('> li:last', tab_list).addClass('last');
if (!tab_focus) {
// If the current URL has a fragment and one of the tabs contains an
// element that matches the URL fragment, activate that tab.
if (window.location.hash && $... | {
tab_focus = $(this);
} | conditional_block | |
js_FxzL6y_vG1Dd9B-MsolHGVlVoN_lbUIGopU6FCDDV9U.js | non-numeric
* strings, a lookup for the actual value of that selector's state is
* performed. This parameter is not a State object but a pristine state
* string.
*
* @return
* true or false, depending on whether this constraint is satisfied.
*/
checkConstraints: function(value, selector,... | {
return typeof a === 'undefined' ? b : (typeof b === 'undefined' ? a : a && b);
} | identifier_body | |
js_FxzL6y_vG1Dd9B-MsolHGVlVoN_lbUIGopU6FCDDV9U.js | the form's #states array fail to match string values
// returned from jQuery's val().
return (typeof value === 'string') ? compare(reference.toString(), value) : compare(reference, value);
}
};
states.Dependent.prototype = {
/**
* Initializes one of the elements this dependent depends on.
*
* @pa... | if (trigger.hasOwnProperty(event)) { | random_line_split | |
animation.js | /* animation.js */
Janice._Animation = {};
Janice._Animation.staticm = {};
Janice._Animation.method = {};
Janice._Animation.staticm.decomposeVersion = function(versionNumber) {
var major = Math.floor(versionNumber)
var minor = parseInt(('' + (versionNumber - major)).substr(2));
return {
major: m... |
return animation;
}; | random_line_split | |
incident.py | from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import *
import logging |
class Incident(ecwb.WrapperBase):
props = {"loc": ecwb.WrapperBase.Access.RO, # geojson representation of the point
"ts": ecwb.WrapperBase.Access.RO, # timestamp representation of the point
"stress": ecwb.WrapperBase.Access.RO, # stress level (0 = no stress, 100 = max stress)
... | import emission.core.wrapper.wrapperbase as ecwb | random_line_split |
incident.py | from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import *
import logging
import emission.core.wrapper.wrapperbase as ecwb
class | (ecwb.WrapperBase):
props = {"loc": ecwb.WrapperBase.Access.RO, # geojson representation of the point
"ts": ecwb.WrapperBase.Access.RO, # timestamp representation of the point
"stress": ecwb.WrapperBase.Access.RO, # stress level (0 = no stress, 100 = max stress)
"local_... | Incident | identifier_name |
incident.py | from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import *
import logging
import emission.core.wrapper.wrapperbase as ecwb
class Incide... | props = {"loc": ecwb.WrapperBase.Access.RO, # geojson representation of the point
"ts": ecwb.WrapperBase.Access.RO, # timestamp representation of the point
"stress": ecwb.WrapperBase.Access.RO, # stress level (0 = no stress, 100 = max stress)
"local_dt": ecwb.WrapperBase.Ac... | identifier_body | |
dictionary-settings.js | var __windowDictionary = {
selectedGrammar: [],
selectedLanguage: "",
initialize: {
C: false,
Python: false
}
}
$(function() {
function updateTips( t ) {
tips
.text( t )
.addClass( "ui-state-highlight" );
setTimeout(function() {
tips.removeClass( "ui-state-highlight", 1500 );
... | }
}
if (found) {
i--;
funcList.splice(i, 1);
funcSelList.splice(j, 1);
}
}
var functionTree = [];
var funcList = dictionary.pages.findWordsByKeywords([__windowDictionary.selectedLanguage + "-language"]);
for (var i = 0; i < funcList.length; i++) {
var cFunc = diction... | break;
| random_line_split |
dictionary-settings.js | var __windowDictionary = {
selectedGrammar: [],
selectedLanguage: "",
initialize: {
C: false,
Python: false
}
}
$(function() {
function updateTips( t ) {
tips
.text( t )
.addClass( "ui-state-highlight" );
setTimeout(function() {
tips.removeClass( "ui-state-highlight", 1500 );
... |
$("#dictionaryFunctionList").fancytree("getTree").reload(functionTree);
});
$("#functionCode").val("");
/*editAreaLoader.init({
id: "functionCode"
,start_highlight: true
,word_wrap: true
,language: "en"
,syntax: "python"
});
editAreaLoader.setValue("functionCode", "");*/
}); | {
var cFunc = dictionary.pages.word[funcList[i].index];
var rType = cFunc.returnType == 0 ? "void" : cFunc.returnType;
var func = {title: cFunc.name + " : " + rType, folder: false, key: funcList[i].index, children: []};
functionTree.push(func);
} | conditional_block |
dictionary-settings.js | var __windowDictionary = {
selectedGrammar: [],
selectedLanguage: "",
initialize: {
C: false,
Python: false
}
}
$(function() {
function | ( t ) {
tips
.text( t )
.addClass( "ui-state-highlight" );
setTimeout(function() {
tips.removeClass( "ui-state-highlight", 1500 );
setTimeout(function(){
tips.html("All form fields are required.");
}, 1500)
}, 500 );
}
function checkLength( o, n, min, max ) {
if ( o.val().leng... | updateTips | identifier_name |
dictionary-settings.js | var __windowDictionary = {
selectedGrammar: [],
selectedLanguage: "",
initialize: {
C: false,
Python: false
}
}
$(function() {
function updateTips( t ) {
tips
.text( t )
.addClass( "ui-state-highlight" );
setTimeout(function() {
tips.removeClass( "ui-state-highlight", 1500 );
... |
function checkRegexp( o, regexp, n ) {
if ( !( regexp.test( o.val() ) ) ) {
o.addClass( "ui-state-error" );
updateTips( n );
return false;
} else {
return true;
}
}
function checkLengthNum( o, n, min, max ) {
if ( o.val().length > max || o.val().length < min ) {
o.addClass( "u... | {
if ( o.val().length > max || o.val().length < min ) {
o.addClass( "ui-state-error" );
updateTips( "Length of " + n + " must be between " +
min + " and " + max + "." );
return false;
} else {
return true;
}
} | identifier_body |
challenge36.rs | use std::net::{Shutdown, TcpListener, TcpStream};
use std::sync::mpsc::{channel, Sender};
use std::thread;
use srp::client::Client;
use srp::server::ClientHandler;
use srp::server::Server;
use crate::errors::*;
#[allow(clippy::type_complexity)]
pub fn start_server<T: ClientHandler>(
mut server: T,
port: u16,... | (port: u16, tx: &Sender<u8>) -> Result<()> {
// Ugly hack for shutting down the server
tx.send(1)?;
let stream = TcpStream::connect(("localhost", port)).map_err(|err| AnnotatedError {
message: "client failed to connect".to_string(),
error: err.into(),
})?;
stream.shutdown(Shutdown:... | shutdown_server | identifier_name |
challenge36.rs | use std::net::{Shutdown, TcpListener, TcpStream};
use std::sync::mpsc::{channel, Sender};
use std::thread;
use srp::client::Client;
use srp::server::ClientHandler;
use srp::server::Server;
use crate::errors::*;
#[allow(clippy::type_complexity)]
pub fn start_server<T: ClientHandler>(
mut server: T,
port: u16,... |
pub fn connect_and_execute(port: u16, action: impl Fn(&mut TcpStream) -> Result<()>) -> Result<()> {
let mut stream = TcpStream::connect(("localhost", port)).map_err(|err| AnnotatedError {
message: "client failed to connect".to_string(),
error: err.into(),
})?;
action(&mut stream)?;
s... | {
// Ugly hack for shutting down the server
tx.send(1)?;
let stream = TcpStream::connect(("localhost", port)).map_err(|err| AnnotatedError {
message: "client failed to connect".to_string(),
error: err.into(),
})?;
stream.shutdown(Shutdown::Both)?;
Ok(())
} | identifier_body |
challenge36.rs | use std::net::{Shutdown, TcpListener, TcpStream};
use std::sync::mpsc::{channel, Sender};
use std::thread;
use srp::client::Client;
use srp::server::ClientHandler;
use srp::server::Server;
use crate::errors::*;
#[allow(clippy::type_complexity)]
pub fn start_server<T: ClientHandler>(
mut server: T,
port: u16,... | pub fn run() -> Result<()> {
let port: u16 = 8080;
let (tx, join_handle) = start_server(Server::default(), port)?;
let user_name = b"foo";
let password = b"baz";
let client = Client::new(user_name.to_vec(), password.to_vec());
connect_and_execute(port, |stream| client.register(stream))?;
c... | }
| random_line_split |
default.ts | /// <reference path="typings/winjs/winjs.d.ts" />
/// <reference path="typings/jquery/jquery.d.ts" />
/// <reference path="typings/patches.d.ts" />
/// <reference path="typings/jetzt/jetzt.d.ts" />
/// <reference path="jetztInit.ts" />
declare var readability: any;
(() => {
"use strict";
HTMLElement.prototype.remo... | return doShareWithUri(shareOperation);
} else {
var el = document.createElement("div");
el.innerHTML = htmlFragment;
var text = el.textContent;
display(text, true);
}
});
}
function doShare(shareOperation: Windows.ApplicationModel.DataTransfer.ShareTarget.Sha... | function doShareWithHtml(shareOperation: Windows.ApplicationModel.DataTransfer.ShareTarget.ShareOperation): Windows.Foundation.IPromise<any> {
return shareOperation.data.getHtmlFormatAsync().then(htmlFormat=> {
var htmlFragment = Windows.ApplicationModel.DataTransfer.HtmlFormatHelper.getStaticFragment(htmlF... | random_line_split |
default.ts | /// <reference path="typings/winjs/winjs.d.ts" />
/// <reference path="typings/jquery/jquery.d.ts" />
/// <reference path="typings/patches.d.ts" />
/// <reference path="typings/jetzt/jetzt.d.ts" />
/// <reference path="jetztInit.ts" />
declare var readability: any;
(() => {
"use strict";
HTMLElement.prototype.remo... | function doShareWithHtml(shareOperation: Windows.ApplicationModel.DataTransfer.ShareTarget.ShareOperation): Windows.Foundation.IPromise<any> {
return shareOperation.data.getHtmlFormatAsync().then(htmlFormat=> {
var htmlFragment = Windows.ApplicationModel.DataTransfer.HtmlFormatHelper.getStaticFragment(htmlF... | return shareOperation.data.getUriAsync()
.then(uri => getArticleFromUri(uri.absoluteUri))
.then(articleText => {
display(articleText, true);
shareOperation.reportDataRetrieved();
}, e => shareOperation.reportError("An error ocurred when trying to go to the internet to get your arti... | identifier_body |
default.ts | /// <reference path="typings/winjs/winjs.d.ts" />
/// <reference path="typings/jquery/jquery.d.ts" />
/// <reference path="typings/patches.d.ts" />
/// <reference path="typings/jetzt/jetzt.d.ts" />
/// <reference path="jetztInit.ts" />
declare var readability: any;
(() => {
"use strict";
HTMLElement.prototype.remo... | hareOperation: Windows.ApplicationModel.DataTransfer.ShareTarget.ShareOperation): Windows.Foundation.IPromise<any> {
return shareOperation.data.getHtmlFormatAsync().then(htmlFormat=> {
var htmlFragment = Windows.ApplicationModel.DataTransfer.HtmlFormatHelper.getStaticFragment(htmlFormat);
if (htmlFragme... | ShareWithHtml(s | identifier_name |
index.ts | /// <reference types="jquery"/>
Mousetrap
.bind('4', function() { console.log('4'); })
.bind("?", function() { console.log('show shortcuts!'); })
.bind('esc', function() { console.log('escape'); }, 'keyup');
// combinations
Mousetrap.bind('command+shift+K', function() { console.log('command shift k'); });... | else {
// internet explorer
e.returnValue = false;
}
});
Mousetrap.unbind('?');
Mousetrap.trigger('esc');
Mousetrap.trigger('esc', 'keyup');
// Test that custom keycodes can be added.
Mousetrap.addKeycodes({ 144: 'numlock' });
Mousetrap.bind('numlock', function() { console.log('numlock'); });
M... | {
e.preventDefault();
} | conditional_block |
index.ts | /// <reference types="jquery"/>
Mousetrap
.bind('4', function() { console.log('4'); })
.bind("?", function() { console.log('show shortcuts!'); })
.bind('esc', function() { console.log('escape'); }, 'keyup');
// combinations
Mousetrap.bind('command+shift+K', function() { console.log('command shift k'); });... | // Test that the factory method works as well.
Mousetrap(element).bind('mod+s', function(){ console.log('Factory Saved'); });
// Test that union types are accepted.
const unionTypeKeys: string | string[] = ['a', 'b', 'c'];
Mousetrap(element).bind(unionTypeKeys, function() { console.log('Union type test') });
Mousetra... | var documentInstance = new Mousetrap();
documentInstance.bind('mod+s', function () { console.log('documentInstance Saved'); });
| random_line_split |
update.js | /*
* Copyright (c) 2014
*
* This file is licensed under the Affero General Public License version 3
* or later.
*
* See the COPYING-README file.
*
*/
(function() {
OC.Update = {
_started : false,
/**
* Start the upgrade process.
*
* @param $el progress list element
*/
start: function($el, o... | .append('<br />')
.append(t('core', 'The update was successful. There were warnings.'))
.appendTo($el);
var message = t('core', 'Please reload the page.');
$('<span>').append('<br />').append(message).append('<br />').appendTo($el);
} else {
// FIXME: use product name
$('<span>... | .appendTo($el);
});
updateEventSource.listen('done', function() {
if (hasWarnings) {
$('<span>').addClass('bold') | random_line_split |
update.js | /*
* Copyright (c) 2014
*
* This file is licensed under the Affero General Public License version 3
* or later.
*
* See the COPYING-README file.
*
*/
(function() {
OC.Update = {
_started : false,
/**
* Start the upgrade process.
*
* @param $el progress list element
*/
start: function($el, o... | else {
// FIXME: use product name
$('<span>').addClass('bold')
.append('<br />')
.append(t('core', 'The update was successful. Redirecting you to ownCloud now.'))
.appendTo($el);
setTimeout(function () {
OC.redirect(OC.webroot);
}, 3000);
}
});
},
addMessage: fun... | {
$('<span>').addClass('bold')
.append('<br />')
.append(t('core', 'The update was successful. There were warnings.'))
.appendTo($el);
var message = t('core', 'Please reload the page.');
$('<span>').append('<br />').append(message).append('<br />').appendTo($el);
} | conditional_block |
publications.js | Meteor.publish("avatars", function () {
//Meteor._sleepForMs(2000);
return Avatars.find();
});
Meteor.publish("posts", function () {
//Meteor._sleepForMs(2000);
return Posts.find({
$or: [
{ hidden: {$ne: true} },
{ author: this.userId }
]
});
});
Meteor.publish("post", function (id) {
check(id, String... | }); | random_line_split | |
index.ts | // Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... | () {
// check that the client instance can be created
const transcoderServiceClient = new TranscoderServiceClient();
doStuffWithTranscoderServiceClient(transcoderServiceClient);
}
main();
| main | identifier_name |
index.ts | // Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... |
function main() {
// check that the client instance can be created
const transcoderServiceClient = new TranscoderServiceClient();
doStuffWithTranscoderServiceClient(transcoderServiceClient);
}
main();
| {
client.close();
} | identifier_body |
index.ts | // Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... |
// check that the client class type name can be used
function doStuffWithTranscoderServiceClient(client: TranscoderServiceClient) {
client.close();
}
function main() {
// check that the client instance can be created
const transcoderServiceClient = new TranscoderServiceClient();
doStuffWithTranscoderServiceCl... | // ** This file is automatically generated by gapic-generator-typescript. **
// ** https://github.com/googleapis/gapic-generator-typescript **
// ** All changes to this file may be overwritten. **
import {TranscoderServiceClient} from '@google-cloud/video-transcoder'; | random_line_split |
app.js | import {
injectDeps
} from 'react-simple-di';
export default class App {
constructor(context) {
if (!context) {
const message = `Context is required when creating a new app.`;
throw new Error(message);
}
this.context = context;
this.actions = {};
this._routeFns = [];
}
_bindCo... | }
const actions = module.actions || {};
this.actions = {
...this.actions,
...actions
};
if (module.load) {
if (typeof module.load !== 'function') {
const message = `module.load should be a function`;
throw new Error(message);
}
// This module has no a... | {
this._checkForInit();
if (!module) {
const message = `Should provide a module to load.`;
throw new Error(message);
}
if (module.__loaded) {
const message = `This module is already loaded.`;
throw new Error(message);
}
if (module.routes) {
if (typeof module.rout... | identifier_body |
app.js | import {
injectDeps
} from 'react-simple-di';
export default class App {
constructor(context) {
if (!context) {
const message = `Context is required when creating a new app.`;
throw new Error(message);
}
this.context = context;
this.actions = {};
this._routeFns = [];
}
_bindCo... | () {
this._checkForInit();
for (const routeFn of this._routeFns) {
const inject = comp => {
return injectDeps(this.context, this.actions)(comp);
};
routeFn(inject, this.context, this.actions);
}
this._routeFns = [];
this.__initialized = true;
}
_checkForInit() {
... | init | identifier_name |
app.js | import {
injectDeps
} from 'react-simple-di';
export default class App {
constructor(context) {
if (!context) {
const message = `Context is required when creating a new app.`;
throw new Error(message);
}
this.context = context;
this.actions = {};
this._routeFns = [];
}
_bindCo... | }
module.__loaded = true;
}
init() {
this._checkForInit();
for (const routeFn of this._routeFns) {
const inject = comp => {
return injectDeps(this.context, this.actions)(comp);
};
routeFn(inject, this.context, this.actions);
}
this._routeFns = [];
this.__in... | // This module has no access to the actions loaded after this module.
const boundedActions = this._bindContext(this.actions);
module.load(this.context, boundedActions); | random_line_split |
app.js | import {
injectDeps
} from 'react-simple-di';
export default class App {
constructor(context) {
if (!context) {
const message = `Context is required when creating a new app.`;
throw new Error(message);
}
this.context = context;
this.actions = {};
this._routeFns = [];
}
_bindCo... |
module.__loaded = true;
}
init() {
this._checkForInit();
for (const routeFn of this._routeFns) {
const inject = comp => {
return injectDeps(this.context, this.actions)(comp);
};
routeFn(inject, this.context, this.actions);
}
this._routeFns = [];
this.__initial... | {
if (typeof module.load !== 'function') {
const message = `module.load should be a function`;
throw new Error(message);
}
// This module has no access to the actions loaded after this module.
const boundedActions = this._bindContext(this.actions);
module.load(this.context... | conditional_block |
class_path.py | # PyJVM (pyjvm.org) Java Virtual Machine implemented in pure Python
# Copyright (C) 2014 Andrew Romanenco (andrew@romanenco.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
# the Free Software Foundation, either version ... |
return (lookup_paths, jars, rt)
def read_from_jar(jar, dict_data):
'''Read file list from a jar'''
if not zipfile.is_zipfile(jar):
raise Exception("Not a jar file: %s" % jar)
with zipfile.ZipFile(jar, "r") as j:
for name in j.namelist():
if name.endswith(".class"): # at ... | p = p.strip()
path = os.path.join(current, p)
if not os.path.exists(path):
raise Exception("Wrong class path entry: %s (path not found %s)",
p, path)
if os.path.isdir(path):
lookup_paths.append(path)
else:
if zipfile.is_zipf... | conditional_block |
class_path.py | # PyJVM (pyjvm.org) Java Virtual Machine implemented in pure Python
# Copyright (C) 2014 Andrew Romanenco (andrew@romanenco.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
# the Free Software Foundation, either version ... | (jar, dict_data):
'''Read file list from a jar'''
if not zipfile.is_zipfile(jar):
raise Exception("Not a jar file: %s" % jar)
with zipfile.ZipFile(jar, "r") as j:
for name in j.namelist():
if name.endswith(".class"): # at some point save all files
dict_data[name]... | read_from_jar | identifier_name |
class_path.py | # PyJVM (pyjvm.org) Java Virtual Machine implemented in pure Python
# Copyright (C) 2014 Andrew Romanenco (andrew@romanenco.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
# the Free Software Foundation, either version ... | local_path = os.path.dirname(os.path.realpath(__file__))
RT_JAR = os.path.join(local_path, "../rt/rt.jar")
if not os.path.isfile(RT_JAR):
JAVA_HOME = os.environ.get('JAVA_HOME')
if JAVA_HOME is None:
raise Exception("JAVA_HOME is not set")
if not os.path.isdir(JAVA_HOME):... | # content of rt.jar
rt = {}
# first check local rt.jar | random_line_split |
class_path.py | # PyJVM (pyjvm.org) Java Virtual Machine implemented in pure Python
# Copyright (C) 2014 Andrew Romanenco (andrew@romanenco.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
# the Free Software Foundation, either version ... | '''Read file list from a jar'''
if not zipfile.is_zipfile(jar):
raise Exception("Not a jar file: %s" % jar)
with zipfile.ZipFile(jar, "r") as j:
for name in j.namelist():
if name.endswith(".class"): # at some point save all files
dict_data[name] = jar | identifier_body | |
bmp180.py | import pyb
from struct import unpack as unp
# BMP180 default address
BMP180_I2CADDR = 0x77
# Operating Modes
BMP180_ULTRALOWPOWER = 0
BMP180_STANDARD = 1
BMP180_HIGHRES = 2
BMP180_ULTRAHIGHRES = 3
# BMP180 Registers
BMP180_CAL_AC1 = 0xAA
BMP180_CAL_AC2 = 0xAC
BMP180_... |
def read_raw_temp(self):
"""Reads the raw (uncompensated) temperature from the sensor."""
self._write_byte(BMP180_CONTROL, BMP180_READTEMPCMD)
pyb.udelay(4500)
raw = self._read_s16(BMP180_TEMPDATA)
return raw
def read_raw_pressure(self):
"""Reads the raw (uncom... | "load calibration"
self.cal_AC1 = self._read_s16(BMP180_CAL_AC1)
self.cal_AC2 = self._read_s16(BMP180_CAL_AC2)
self.cal_AC3 = self._read_s16(BMP180_CAL_AC3)
self.cal_AC4 = self._read_u16(BMP180_CAL_AC4)
self.cal_AC5 = self._read_u16(BMP180_CAL_AC5)
self.cal_AC6 = self._re... | identifier_body |
bmp180.py | import pyb
from struct import unpack as unp
# BMP180 default address
BMP180_I2CADDR = 0x77
# Operating Modes
BMP180_ULTRALOWPOWER = 0
BMP180_STANDARD = 1
BMP180_HIGHRES = 2
BMP180_ULTRAHIGHRES = 3
# BMP180 Registers
BMP180_CAL_AC1 = 0xAA
BMP180_CAL_AC2 = 0xAC
BMP180_... |
return result
def _read_u24(self, cmd):
result = self._bus.mem_read(3,self._address,cmd)
#print(result)
return (result[0]<<16)+(result[1]<<8)+result[2]
def _write_byte(self, cmd, val):
self._bus.mem_write(val, self._address, cmd)
def _load_calibration(self):
... | result -= (1<<16) | conditional_block |
bmp180.py | import pyb
from struct import unpack as unp
# BMP180 default address
BMP180_I2CADDR = 0x77
# Operating Modes
BMP180_ULTRALOWPOWER = 0
BMP180_STANDARD = 1
BMP180_HIGHRES = 2
BMP180_ULTRAHIGHRES = 3
# BMP180 Registers
BMP180_CAL_AC1 = 0xAA
BMP180_CAL_AC2 = 0xAC
BMP180_... | ():
def __init__(self, bus=1, address=BMP180_I2CADDR, mode=BMP180_STANDARD):
self._mode = mode
self._address = address
self._bus = pyb.I2C(bus, pyb.I2C.MASTER)
# Load calibration values
self._load_calibration()
def _read_byte(self, cmd):
return self._bus.mem_read(... | BMP180 | identifier_name |
bmp180.py | import pyb
from struct import unpack as unp
# BMP180 default address
BMP180_I2CADDR = 0x77
# Operating Modes
BMP180_ULTRALOWPOWER = 0
BMP180_STANDARD = 1
BMP180_HIGHRES = 2
BMP180_ULTRAHIGHRES = 3
# BMP180 Registers
BMP180_CAL_AC1 = 0xAA
BMP180_CAL_AC2 = 0xAC
BMP180_... | def read_altitude(self, sealevel_pa = 101325.0):
"""Calculates the altitude in meters."""
#Calculation taken straight from section 3.6 of the datasheet
pressure = float(self.read_pressure())
altitude = 44330.0 * (1.0 - pow(pressure / sealevel_pa, (1.0 /5.255)))
return altitud... | X1 = (X1 * 3038) >> 16
X2 = (-7357 * p) >> 16
p = p + ((X1 + X2 + 3791) >> 4)
return p
| random_line_split |
x2search4porn.py | # -*- coding: utf-8 -*-
from Plugins.Extensions.MediaPortal.plugin import _
from Plugins.Extensions.MediaPortal.resources.imports import *
from Plugins.Extensions.MediaPortal.resources.keyboardext import VirtualKeyBoardExt
CONFIG = "/usr/lib/enigma2/python/Plugins/Extensions/MediaPortal/additions/additions.xml"
clas... | def keyCancel(self):
if self.keyLocked:
return
self.genreliste.sort(key=lambda t : t[0].lower())
fobj_out = open(config.mediaportal.watchlistpath.value+"mp_2s4p","w")
x = len(self.genreliste)
if x > 0:
for c in range(x):
writeback = self.genreliste[c][0].rstrip()+"\n"
fobj_out.write(writeback)
... | self.keyLocked:
return
self.SearchEdit()
| identifier_body |
x2search4porn.py | # -*- coding: utf-8 -*-
from Plugins.Extensions.MediaPortal.plugin import _
from Plugins.Extensions.MediaPortal.resources.imports import *
from Plugins.Extensions.MediaPortal.resources.keyboardext import VirtualKeyBoardExt
CONFIG = "/usr/lib/enigma2/python/Plugins/Extensions/MediaPortal/additions/additions.xml"
clas... | PScreen):
def __init__(self, session, suchString):
self.suchString = suchString
self.plugin_path = mp_globals.pluginPath
self.skin_path = mp_globals.pluginPath + mp_globals.skinsPath
path = "%s/%s/defaultGenreScreen.xml" % (self.skin_path, config.mediaportal.skin.value)
if not fileExists(path):
path = s... | SearchForPornBrowse(M | identifier_name |
x2search4porn.py | # -*- coding: utf-8 -*-
from Plugins.Extensions.MediaPortal.plugin import _
from Plugins.Extensions.MediaPortal.resources.imports import *
from Plugins.Extensions.MediaPortal.resources.keyboardext import VirtualKeyBoardExt
CONFIG = "/usr/lib/enigma2/python/Plugins/Extensions/MediaPortal/additions/additions.xml"
clas... |
self['title'] = Label("2Search4Porn")
self['ContentTitle'] = Label("Select Site")
self['name'] = Label(_("Selection:"))
self.keyLocked = True
self.pornscreen = None
self.genreliste = []
self.ml = MenuList([], enableWrapAround=True, content=eListboxPythonMultiContent)
self['liste'] = self.ml
self.onL... | "down" : self.keyDown,
"right" : self.keyRight,
"left" : self.keyLeft
}, -1) | random_line_split |
x2search4porn.py | # -*- coding: utf-8 -*-
from Plugins.Extensions.MediaPortal.plugin import _
from Plugins.Extensions.MediaPortal.resources.imports import *
from Plugins.Extensions.MediaPortal.resources.keyboardext import VirtualKeyBoardExt
CONFIG = "/usr/lib/enigma2/python/Plugins/Extensions/MediaPortal/additions/additions.xml"
clas... | if len(self.genreliste) > 0:
self.genreliste.pop(self['liste'].getSelectedIndex())
self.ml.setList(map(self._defaultlistcenter, self.genreliste))
def keyGreen(self):
if self.keyLocked:
return
self.SearchAdd()
def keyYellow(self):
if self.keyLocked:
return
self.SearchEdit()
def keyCancel(self)... | turn
| conditional_block |
HttpServer.js | "use strict";
| var express = require('express');
var less = require('less-middleware');
function HttpServer(port, staticServedPath, logRequest) {
this.port = port;
this.staticServedPath = staticServedPath;
this.logRequest = (typeof logRequest === "undefined") ? true : logRequest;
}
HttpServer.prototype.start = function(fn) {
... | random_line_split | |
HttpServer.js | "use strict";
var express = require('express');
var less = require('less-middleware');
function HttpServer(port, staticServedPath, logRequest) |
HttpServer.prototype.start = function(fn) {
console.log("Starting server");
var self = this;
var app = express();
self.app = app;
if(self.logRequest) {
app.use(function (req, res, next) {
console.log(req.method, req.url);
next();
});
}
app.use('/', express.static(self.staticServed... | {
this.port = port;
this.staticServedPath = staticServedPath;
this.logRequest = (typeof logRequest === "undefined") ? true : logRequest;
} | identifier_body |
HttpServer.js | "use strict";
var express = require('express');
var less = require('less-middleware');
function | (port, staticServedPath, logRequest) {
this.port = port;
this.staticServedPath = staticServedPath;
this.logRequest = (typeof logRequest === "undefined") ? true : logRequest;
}
HttpServer.prototype.start = function(fn) {
console.log("Starting server");
var self = this;
var app = express();
self.app = app... | HttpServer | identifier_name |
xor2.py | # -*- coding: utf-8 -*-
"""
Created on Thu Apr 21 22:48:37 2016
@author: burger
"""
import numpy as np
from matplotlib import pyplot as plt
def sigma(x, a=1, b=0):
return 1/(1+np.exp(-(a*x+b)))
x = np.asarray([[0.0, .1], [0, 1], [.9, .05], [.9, .95]])
markers = 'v<>^'
a = .5*np.ones((2,))
proj = np.dot(x, a)... | c = (a + b)/2
m = (proj_y[3] - proj_y[0])/(proj_x[3] - proj_x[0])
X = np.mean(proj_x) + proj_line
Y = np.mean(proj_y) + m*proj_line
plt.figure()
plt.hold(True)
ms = 10
for i in range(len(x)):
plt.plot(x[i, 0], x[i, 1], 'g'+markers[i], MarkerSize=ms)
plt.plot(proj[i], proj[i], 'b'+markers[i], MarkerSize=ms)... | b = (x[1] + x[2])/2 | random_line_split |
xor2.py | # -*- coding: utf-8 -*-
"""
Created on Thu Apr 21 22:48:37 2016
@author: burger
"""
import numpy as np
from matplotlib import pyplot as plt
def | (x, a=1, b=0):
return 1/(1+np.exp(-(a*x+b)))
x = np.asarray([[0.0, .1], [0, 1], [.9, .05], [.9, .95]])
markers = 'v<>^'
a = .5*np.ones((2,))
proj = np.dot(x, a)
def trafo(x, y):
return sigma(x, 2, -2), sigma(y, 5, 0)
proj_line = np.arange(-50, 50, .02)
proj_transformed_x, proj_transformed_y = trafo(proj_... | sigma | identifier_name |
xor2.py | # -*- coding: utf-8 -*-
"""
Created on Thu Apr 21 22:48:37 2016
@author: burger
"""
import numpy as np
from matplotlib import pyplot as plt
def sigma(x, a=1, b=0):
return 1/(1+np.exp(-(a*x+b)))
x = np.asarray([[0.0, .1], [0, 1], [.9, .05], [.9, .95]])
markers = 'v<>^'
a = .5*np.ones((2,))
proj = np.dot(x, a)... |
dots = 3
plt.plot(proj_line, proj_line, 'k.', MarkerSize=dots)
plt.plot(proj_transformed_x, proj_transformed_y, 'r.', MarkerSize=dots)
plt.plot(X, Y, 'k')
for x in proj_line[::4]:
a, b = trafo(proj_line, x*np.ones_like(proj_line))
plt.plot(a, b, 'k')
a, b = trafo(x*np.ones_like(proj_line), proj_line)
... | plt.plot(x[i, 0], x[i, 1], 'g'+markers[i], MarkerSize=ms)
plt.plot(proj[i], proj[i], 'b'+markers[i], MarkerSize=ms)
plt.plot(proj_x[i], proj_y[i], 'r'+markers[i], MarkerSize=ms) | conditional_block |
xor2.py | # -*- coding: utf-8 -*-
"""
Created on Thu Apr 21 22:48:37 2016
@author: burger
"""
import numpy as np
from matplotlib import pyplot as plt
def sigma(x, a=1, b=0):
return 1/(1+np.exp(-(a*x+b)))
x = np.asarray([[0.0, .1], [0, 1], [.9, .05], [.9, .95]])
markers = 'v<>^'
a = .5*np.ones((2,))
proj = np.dot(x, a)... |
proj_line = np.arange(-50, 50, .02)
proj_transformed_x, proj_transformed_y = trafo(proj_line, proj_line)
proj_x, proj_y = trafo(proj, proj)
a = (x[0] + x[3])/2
b = (x[1] + x[2])/2
c = (a + b)/2
m = (proj_y[3] - proj_y[0])/(proj_x[3] - proj_x[0])
X = np.mean(proj_x) + proj_line
Y = np.mean(proj_y) + m*proj_line
... | return sigma(x, 2, -2), sigma(y, 5, 0) | identifier_body |
example.local_settings.py | """
Wheel will try to read configurations from environment variables
so you dont need this local_settings.py file if you have env vars.
1. You can set as a file
export WHEEL_SETTINGS='/path/to/settings.py'
2. You can set individual values
export WHEEL_MONGODB_DB="wheel_db"
export WHEEL_MONGODB_HOST='localhost'
expo... | # coding: utf-8
| random_line_split | |
context.directive.js | /*!
* Copyright 2019 Hitachi Vantara. 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 appli... | ($document) {
return {
restrict: "A",
link: function (scope, element, attrs) {
var contextMenu = angular.element(document.querySelector('#' + attrs.context));
element.bind('contextmenu', function (event) {
scope.$apply(function () {
event.stopPropagation();
... | context | identifier_name |
context.directive.js | /*!
* Copyright 2019 Hitachi Vantara. 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 appli... | });
}
});
}
};
}
return {
name: "context",
options: ["$document", context]
};
}); | random_line_split | |
context.directive.js | /*!
* Copyright 2019 Hitachi Vantara. 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 appli... | });
});
angular.element($document).bind('click', function (event) {
contextMenu.css({
'display': 'none'
});
});
angular.element($document).bind('keydown', function (event) {
if (event.keyCode === 27) {
contextMenu.css({
... | {
return {
restrict: "A",
link: function (scope, element, attrs) {
var contextMenu = angular.element(document.querySelector('#' + attrs.context));
element.bind('contextmenu', function (event) {
scope.$apply(function () {
event.stopPropagation();
event.pr... | identifier_body |
context.directive.js | /*!
* Copyright 2019 Hitachi Vantara. 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 appli... |
});
}
};
}
return {
name: "context",
options: ["$document", context]
};
});
| {
contextMenu.css({
'display': 'none'
});
} | conditional_block |
bullet.js | var GameOpts = require('./game_opts');
//Constructor
var Bullet = function(x,y,color){
var GameOpts = {
screenW : 800,
screenH : 600
};
//this.canvas = document.getElementById("canvas");
//this.ctx = canvas.getContext("2d");
this.rectangle = {x:x,y:y,w:10,h:25};
this.speed = 25;
this... | else {
this.reset();
}
} else{
//return;
}
return {s: this.state, x: this.rectangle.x, y: this.rectangle.y};
}
Bullet.prototype.setState = function(data){
this.state = data.s;
this.rectangle.x = data.x;
this.rectangle.y = data.y;
}
module.exports = Bullet;
| {
this.moveY(this.speed);
//ctx.fillStyle = this.color;
//ctx.fillRect(this.getX(),this.getY(),this.getW(),this.getH());
} | conditional_block |
bullet.js | var GameOpts = require('./game_opts');
//Constructor
var Bullet = function(x,y,color){
var GameOpts = {
screenW : 800,
screenH : 600
};
//this.canvas = document.getElementById("canvas");
//this.ctx = canvas.getContext("2d");
this.rectangle = {x:x,y:y,w:10,h:25};
this.speed = 25;
this... | }
};
Bullet.prototype.getState = function(){
if (this.state == 1) {
if (this.getY() < GameOpts.screenH && this.getY() > 0) {
this.moveY(this.speed);
//ctx.fillStyle = this.color;
//ctx.fillRect(this.getX(),this.getY(),this.getW(),this.getH());
} else {
this.reset();
}
} else{
//re... | random_line_split | |
coapserver.py | import asyncio
import json
import aiocoap.resource as resource
import aiocoap
from pyWL.database import Station, Line
from pyWL.realtime import Departures
import json_serializer
class DepartureResource(resource.ObservableResource):
def __init__(self):
super().__init__()
self.notify()
def not... | if stations:
payload = str([s['name'] for s in stations])
for station in stations:
if station['name'] == station_name:
stations = [station]
if len(stations) == 1:
station = stations[0]
dep = Departures(stati... | random_line_split | |
coapserver.py | import asyncio
import json
import aiocoap.resource as resource
import aiocoap
from pyWL.database import Station, Line
from pyWL.realtime import Departures
import json_serializer
class DepartureResource(resource.ObservableResource):
def | (self):
super().__init__()
self.notify()
def notify(self):
self.updated_state()
# Notify all observers every minute
asyncio.get_event_loop().call_later(30, self.notify)
@asyncio.coroutine
def render_post(self, request):
station_name = request.payload.decode(... | __init__ | identifier_name |
coapserver.py | import asyncio
import json
import aiocoap.resource as resource
import aiocoap
from pyWL.database import Station, Line
from pyWL.realtime import Departures
import json_serializer
class DepartureResource(resource.ObservableResource):
| if stations:
payload = str([s['name'] for s in stations])
for station in stations:
if station['name'] == station_name:
stations = [station]
if len(stations) == 1:
station = stations[0]
dep = Departures(stati... | def __init__(self):
super().__init__()
self.notify()
def notify(self):
self.updated_state()
# Notify all observers every minute
asyncio.get_event_loop().call_later(30, self.notify)
@asyncio.coroutine
def render_post(self, request):
station_name = request.pay... | identifier_body |
coapserver.py | import asyncio
import json
import aiocoap.resource as resource
import aiocoap
from pyWL.database import Station, Line
from pyWL.realtime import Departures
import json_serializer
class DepartureResource(resource.ObservableResource):
def __init__(self):
super().__init__()
self.notify()
def not... |
else:
return aiocoap.Message(code=aiocoap.NOT_FOUND, payload='Station not found'.encode('ascii'))
response = aiocoap.Message(code=aiocoap.CONTENT, payload=payload.encode('UTF-8'))
response.opt.content_format = aiocoap.numbers.media_types_rev['application/json']
return respo... | station = stations[0]
dep = Departures(station.get_stops())
dep.refresh()
payload = json.dumps(dep, ensure_ascii=False, default=json_serializer.default) | conditional_block |
bars.py | #!/usr/bin/python
# $Id:$
import random
import sys
from pyglet.gl import *
from pyglet import clock
from pyglet import font
from pyglet import graphics
from pyglet import window
BARS = 100
if len(sys.argv) > 1:
BARS = int(sys.argv[1])
MIN_BAR_LENGTH = 4
MAX_BAR_LENGTH = 100
BAR_SEGMENT_HEIGHT = 10
UPDATE_PERIOD... |
stats_text = font.Text(font.load('', 12, bold=True), '',
x=win.width, y=0,
halign='right')
def update_stats(dt):
np = len(bars)
usage = bars[0].domain.allocator.get_usage()
fragmentation = bars[0].domain.allocator.get_fragmentation()
blocks = len(bars[0... | for bar in bars:
old_length = bar.count
length = random.randint(MIN_BAR_LENGTH, MAX_BAR_LENGTH)
bar.resize(length)
vertices = bar.vertices
# Update new vertices (overwrite old degenerate)
for i in range((old_length - 1) * 2, length * 2):
if i & 1: # y
... | identifier_body |
bars.py | #!/usr/bin/python
# $Id:$
import random
import sys
from pyglet.gl import *
from pyglet import clock
from pyglet import font
from pyglet import graphics
from pyglet import window
BARS = 100
if len(sys.argv) > 1:
BARS = int(sys.argv[1])
MIN_BAR_LENGTH = 4
MAX_BAR_LENGTH = 100
BAR_SEGMENT_HEIGHT = 10
UPDATE_PERIOD... |
stats_text = font.Text(font.load('', 12, bold=True), '',
x=win.width, y=0,
halign='right')
def update_stats(dt):
np = len(bars)
usage = bars[0].domain.allocator.get_usage()
fragmentation = bars[0].domain.allocator.get_fragmentation()
blocks = len(bars[0].... | random_line_split | |
bars.py | #!/usr/bin/python
# $Id:$
import random
import sys
from pyglet.gl import *
from pyglet import clock
from pyglet import font
from pyglet import graphics
from pyglet import window
BARS = 100
if len(sys.argv) > 1:
BARS = int(sys.argv[1])
MIN_BAR_LENGTH = 4
MAX_BAR_LENGTH = 100
BAR_SEGMENT_HEIGHT = 10
UPDATE_PERIOD... |
def update_bars():
for bar in bars:
old_length = bar.count
length = random.randint(MIN_BAR_LENGTH, MAX_BAR_LENGTH)
bar.resize(length)
vertices = bar.vertices
# Update new vertices (overwrite old degenerate)
for i in range((old_length - 1) * 2, length * 2):
... | position = [i * width, 0, # degenerate
i * width, 0,
(i + 1) * width, 0,
(i + 1) * width, 0 # degenerate
]
color = colors[i % len(colors)] * 4
bar = batch.add(4, GL_TRIANGLE_STRIP, None,
('v2f/dyna... | conditional_block |
bars.py | #!/usr/bin/python
# $Id:$
import random
import sys
from pyglet.gl import *
from pyglet import clock
from pyglet import font
from pyglet import graphics
from pyglet import window
BARS = 100
if len(sys.argv) > 1:
BARS = int(sys.argv[1])
MIN_BAR_LENGTH = 4
MAX_BAR_LENGTH = 100
BAR_SEGMENT_HEIGHT = 10
UPDATE_PERIOD... | ():
width = win.width / float(BARS)
for i in range(BARS):
position = [i * width, 0, # degenerate
i * width, 0,
(i + 1) * width, 0,
(i + 1) * width, 0 # degenerate
]
color = colors[i % len(colors)] * 4
bar ... | create_bars | identifier_name |
dynamicControls.ts | /* tslint:disable:no-console */
import * as WebSocket from 'ws';
import * as faker from 'faker';
import {
delay,
GameClient,
IButtonData,
IControlData,
IParticipant,
setWebSocket,
} from '../lib';
if (process.argv.length < 4) {
console.log('Usage gameClient.exe <token> <versionId>');
... |
// Now we open the connection passing in our authentication details and an experienceId.
client.open({
authToken: process.argv[2],
versionId: parseInt(process.argv[3], 10),
})
.then(() => {
/* Pull in the scenes stored on the server
* then call ready so our controls show up.
* then call loop() to ... | {
const scene = client.state.getScene('default');
scene.createControls(makeControls(5))
.then(() => delay(delayTime))
.then(() => scene.deleteAllControls())
.then(() => delay(delayTime))
.then(() => loop());
} | identifier_body |
dynamicControls.ts | /* tslint:disable:no-console */
import * as WebSocket from 'ws';
import * as faker from 'faker';
import {
delay,
GameClient,
IButtonData,
IControlData,
IParticipant,
setWebSocket,
} from '../lib';
if (process.argv.length < 4) {
console.log('Usage gameClient.exe <token> <versionId>');
... | return controls;
}
const delayTime = 2000;
/* Loop creates 5 controls and adds them to the default scene.
* It then waits delayTime milliseconds and then deletes them,
* before calling itself again.
*/
function loop() {
const scene = client.state.getScene('default');
scene.createControls(makeControls(5))... | },
],
},
);
} | random_line_split |
dynamicControls.ts | /* tslint:disable:no-console */
import * as WebSocket from 'ws';
import * as faker from 'faker';
import {
delay,
GameClient,
IButtonData,
IControlData,
IParticipant,
setWebSocket,
} from '../lib';
if (process.argv.length < 4) |
// We need to tell the interactive client what type of websocket we are using.
setWebSocket(WebSocket);
// As we're on the Streamer's side we need a "GameClient" instance
const client = new GameClient();
// Log when we're connected to interactive
client.on('open', () => console.log('Connected to interactive'));
// ... | {
console.log('Usage gameClient.exe <token> <versionId>');
process.exit();
} | conditional_block |
dynamicControls.ts | /* tslint:disable:no-console */
import * as WebSocket from 'ws';
import * as faker from 'faker';
import {
delay,
GameClient,
IButtonData,
IControlData,
IParticipant,
setWebSocket,
} from '../lib';
if (process.argv.length < 4) {
console.log('Usage gameClient.exe <token> <versionId>');
... | (amount: number): IControlData[] {
const controls: IButtonData[] = [];
const size = 10;
for (let i = 0; i < amount; i++) {
controls.push({
controlID: `${i}`,
kind: 'button',
text: faker.name.firstName(),
cost: 1,
position: [
... | makeControls | identifier_name |
index.js | 'use strict';
const fs = require('fs');
const path = require('path');
const Router = require('koa-router');
const apiRouter = require('./api');
const ask = require('../lib/ask');
const config = require('config');
const indexFilePath = path.resolve(__dirname, '..', 'views', 'index.html');
const router = new ... |
}
module.exports = router; | {
return `<script type="text/javascript" src="/js/simple-require.js"></script>
<script type="text/javascript" src="/js/index.js"></script>`;
} | conditional_block |
index.js | 'use strict';
const fs = require('fs');
const path = require('path');
const Router = require('koa-router');
const apiRouter = require('./api');
const ask = require('../lib/ask');
| const indexFilePath = path.resolve(__dirname, '..', 'views', 'index.html');
const router = new Router();
const apiAddress = config.port ?
`//${config.path}:${config.port}/api` : `//${config.path}/api`;
router.use('/api', apiRouter.routes(), apiRouter.allowedMethods());
router.get('/*', index);
const appScri... | const config = require('config');
| random_line_split |
index.js | 'use strict';
const fs = require('fs');
const path = require('path');
const Router = require('koa-router');
const apiRouter = require('./api');
const ask = require('../lib/ask');
const config = require('config');
const indexFilePath = path.resolve(__dirname, '..', 'views', 'index.html');
const router = new ... | (ctx) {
if (indexFileContents === null) {
let indexFile = await ask(fs, 'readFile', indexFilePath);
indexFileContents = new Function ('state', `return \`${indexFile}\``)({
apiAddress,
appScripts
});
}
ctx.body = indexFileContents;
}
function getStartScripts() {
if (process.... | index | identifier_name |
index.js | 'use strict';
const fs = require('fs');
const path = require('path');
const Router = require('koa-router');
const apiRouter = require('./api');
const ask = require('../lib/ask');
const config = require('config');
const indexFilePath = path.resolve(__dirname, '..', 'views', 'index.html');
const router = new ... |
function getStartScripts() {
if (process.env.NODE_ENV === 'production') {
return `<script type="text/javascript" src="/js/app.bundle.js"></script>`;
} else {
return `<script type="text/javascript" src="/js/simple-require.js"></script>
<script type="text/javascript" src="/js/index.js"></script>`;
... | {
if (indexFileContents === null) {
let indexFile = await ask(fs, 'readFile', indexFilePath);
indexFileContents = new Function ('state', `return \`${indexFile}\``)({
apiAddress,
appScripts
});
}
ctx.body = indexFileContents;
} | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.