file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
datalake_samples_access_control_recursive_async.py | # coding: utf-8
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------... | loop = asyncio.get_event_loop()
loop.run_until_complete(run()) | conditional_block | |
datalake_samples_access_control_recursive_async.py | # coding: utf-8
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------... | (directory_client, num_child_files):
import itertools
async def create_file():
# generate a random name
file_name = str(uuid.uuid4()).replace('-', '')
file_client = directory_client.get_file_client(file_name)
await file_client.create_file()
futures = [asyncio.ensure_future(... | create_child_files | identifier_name |
datalake_samples_access_control_recursive_async.py | # coding: utf-8
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------... |
futures = [asyncio.ensure_future(create_file()) for _ in itertools.repeat(None, num_child_files)]
await asyncio.wait(futures)
print("Created {} files under the directory '{}'.".format(num_child_files, directory_client.path_name))
async def run():
account_name = os.getenv('STORAGE_ACCOUNT_NAME', "")
... | file_name = str(uuid.uuid4()).replace('-', '')
file_client = directory_client.get_file_client(file_name)
await file_client.create_file() | identifier_body |
datalake_samples_access_control_recursive_async.py | # coding: utf-8
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------... |
# create the filesystem
filesystem_client = await service_client.create_file_system(file_system=fs_name)
# invoke the sample code
try:
await recursive_access_control_sample(filesystem_client)
finally:
# clean up the demo filesystem
await file... | # generate a random name for testing purpose
fs_name = "testfs{}".format(random.randint(1, 1000))
print("Generating a test filesystem named '{}'.".format(fs_name)) | random_line_split |
puntata.rs | use crate::die::Die;
use std::{collections::HashSet, fmt};
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub struct Puntata {
value: Die,
count: i32,
}
impl Puntata {
pub fn new(count: i32, value: i32) -> Self {
Puntata {
value: Die::new(value),
count,
}
}
pu... | (total_dices: i32, p: Puntata, is_palifico: bool) -> Vec<Puntata> {
let mut v = (p.count..total_dices)
.flat_map(|v| {
let px = p.with_count(v);
least_gt_puntate(px, is_palifico)
})
.collect::<HashSet<_>>();
if !is_palifico || p.is_lama() {
for i in p.cou... | all_gt_puntate | identifier_name |
puntata.rs | use crate::die::Die;
use std::{collections::HashSet, fmt};
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub struct Puntata {
value: Die,
count: i32,
}
impl Puntata {
pub fn new(count: i32, value: i32) -> Self {
Puntata {
value: Die::new(value),
count,
}
}
pu... |
v.into_iter().collect()
} | v.insert(p); | random_line_split |
puntata.rs | use crate::die::Die;
use std::{collections::HashSet, fmt};
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub struct Puntata {
value: Die,
count: i32,
}
impl Puntata {
pub fn new(count: i32, value: i32) -> Self {
Puntata {
value: Die::new(value),
count,
}
}
pu... | else {
puntate.push(Puntata::new_lama(p.count + 1));
for i in 2..7 {
puntate.push(Puntata::new(p.count * 2 + 1, i));
}
}
if is_palifico {
puntate.retain(|pv| pv.value == p.value)
}
puntate
}
pub fn all_gt_puntate(total_dices: i32, p: Puntata, is_palifico:... | {
for i in (p.value.get_value() + 1)..7 {
puntate.push(Puntata::new(p.count, i));
}
for i in 2..7 {
puntate.push(Puntata::new(p.count + 1, i));
}
puntate.push(Puntata::new_lama((p.count + 1) / 2));
} | conditional_block |
puntata.rs | use crate::die::Die;
use std::{collections::HashSet, fmt};
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub struct Puntata {
value: Die,
count: i32,
}
impl Puntata {
pub fn new(count: i32, value: i32) -> Self {
Puntata {
value: Die::new(value),
count,
}
}
pu... |
pub fn get_value(self) -> i32 {
self.value.get_value()
}
pub fn get_count(self) -> i32 {
self.count
}
pub fn is_lama(self) -> bool {
self.value.is_lama()
}
pub fn with_count(self, count: i32) -> Self {
Puntata {
value: Die::new(self.value.get_... | {
Puntata {
value: Die::new_lama(),
count,
}
} | identifier_body |
webviewElement.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... |
this._webContents = this.webview.getWebContents();
return this._webContents;
}
}
type OnBeforeRequestDelegate = (details: OnBeforeRequestListenerDetails) => Promise<Response | undefined>;
type OnHeadersReceivedDelegate = (details: OnHeadersReceivedListenerDetails) => { cancel: boolean; } | undefined;
class Webv... | {
return this._webContents;
} | conditional_block |
webviewElement.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | }
private setIgnoreMenuShortcutsForWebview(webview: WebviewTagHandle, value: boolean) {
if (this.shouldToggleMenuShortcutsEnablement) {
const contents = webview.webContents;
if (!contents?.isDestroyed()) {
contents?.setIgnoreMenuShortcuts(value);
}
}
}
}
export class ElectronWebviewBasedWebview ex... |
private setIgnoreMenuShortcuts(value: boolean) {
for (const webview of this._webviews) {
this.setIgnoreMenuShortcutsForWebview(webview, value);
} | random_line_split |
webviewElement.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | () {
this.element?.cut();
}
public undo() {
this.element?.undo();
}
public redo() {
this.element?.redo();
}
protected on<T = unknown>(channel: WebviewMessageChannels | string, handler: (data: T) => void): IDisposable {
if (!this.element) {
return Disposable.None;
}
return addDisposableListener(t... | cut | identifier_name |
test_securecookies.py | #coding: utf-8
import unittest
import bottle
from bottle import tob, touni
class TestSecureCookies(unittest.TestCase):
def setUp(self):
self.data = dict(a=5, b=touni('υηι¢σ∂є'), c=[1,2,3,4,tob('bytestring')])
self.key = tob('secret')
def testDeEncode(self):
cookie = bottle.cookie_enco... | pairs = self.get_pairs()
self.set_pairs([(k+'xxx', v) for (k, v) in pairs])
result = bottle.request.get_cookie('key', secret=self.secret)
self.assertEqual(None, result)
if __name__ == '__main__': #pragma: no cover
unittest.main() |
def testWrongKey(self):
bottle.response.set_cookie('key', self.data, secret=self.secret) | random_line_split |
test_securecookies.py | #coding: utf-8
import unittest
import bottle
from bottle import tob, touni
class TestSecureCookies(unittest.TestCase):
def setUp(self):
self.data = dict(a=5, b=touni('υηι¢σ∂є'), c=[1,2,3,4,tob('bytestring')])
self.key = tob('secret')
def testDeEncode(self):
cookie = bottle.cookie_enco... | own(self):
bottle.app.pop()
def get_pairs(self):
for k, v in bottle.response.headerlist:
if k == 'Set-Cookie':
key, value = v.split(';')[0].split('=', 1)
yield key.lower().strip(), value.strip()
def set_pairs(self, pairs):
header = ','.jo... | a = dict(a=5, b=touni('υηι¢σ∂є'), c=[1,2,3,4,tob('bytestring')])
self.secret = tob('secret')
bottle.app.push()
bottle.response.bind()
def tear_d | identifier_body |
test_securecookies.py | #coding: utf-8
import unittest
import bottle
from bottle import tob, touni
class TestSecureCookies(unittest.TestCase):
def setUp(self):
self.data = dict(a=5, b=touni('υηι¢σ∂є'), c=[1,2,3,4,tob('bytestring')])
self.key = tob('secret')
def testDeEncode(self):
cookie = bottle.cookie_enco... | bottle.app.pop()
def get_pairs(self):
for k, v in bottle.response.headerlist:
if k == 'Set-Cookie':
key, value = v.split(';')[0].split('=', 1)
yield key.lower().strip(), value.strip()
def set_pairs(self, pairs):
header = ','.join(['%s=%s' % (k, v... | identifier_name | |
test_securecookies.py | #coding: utf-8
import unittest
import bottle
from bottle import tob, touni
class TestSecureCookies(unittest.TestCase):
def setUp(self):
self.data = dict(a=5, b=touni('υηι¢σ∂є'), c=[1,2,3,4,tob('bytestring')])
self.key = tob('secret')
def testDeEncode(self):
cookie = bottle.cookie_enco... | t_pairs(self, pairs):
header = ','.join(['%s=%s' % (k, v) for k, v in pairs])
bottle.request.bind({'HTTP_COOKIE': header})
def testValid(self):
bottle.response.set_cookie('key', self.data, secret=self.secret)
pairs = self.get_pairs()
self.set_pairs(pairs)
result = bo... | plit(';')[0].split('=', 1)
yield key.lower().strip(), value.strip()
def se | conditional_block |
settings_base.py | """private_base will be populated from puppet and placed in this directory"""
import logging
import os
import dj_database_url
from lib.settings_base import (
CACHE_PREFIX, ES_INDEXES, KNOWN_PROXIES, LOGGING, CSP_SCRIPT_SRC,
CSP_FRAME_SRC)
from .. import splitstrip
import private_base as private
ENGAGE_ROBO... | ADDONS_PATH = private.NETAPP_STORAGE_ROOT + '/files'
PERF_THRESHOLD = 20
SPIDERMONKEY = '/usr/bin/tracemonkey'
# Remove DetectMobileMiddleware from middleware in production.
detect = 'mobility.middleware.DetectMobileMiddleware'
csp = 'csp.middleware.CSPMiddleware'
RESPONSYS_ID = private.RESPONSYS_ID
CRONJOB_LOCK_... | RECAPTCHA_PUBLIC_KEY)
TMP_PATH = os.path.join(NETAPP_STORAGE, 'tmp')
PACKAGER_PATH = os.path.join(TMP_PATH, 'packager')
| random_line_split |
htmldataelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::HTMLDataElementBinding;
use dom::bindings::js::Root;
use dom::document::Docu... |
}
| {
let element = HTMLDataElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLDataElementBinding::Wrap)
} | identifier_body |
htmldataelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::HTMLDataElementBinding;
use dom::bindings::js::Root;
use dom::document::Docu... | (localName: DOMString,
prefix: Option<DOMString>,
document: &Document) -> HTMLDataElement {
HTMLDataElement {
htmlelement: HTMLElement::new_inherited(localName, prefix, document)
}
}
#[allow(unrooted_must_root)]
pub fn new(localName: DOM... | new_inherited | identifier_name |
htmldataelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::HTMLDataElementBinding;
use dom::bindings::js::Root;
use dom::document::Docu... | htmlelement: HTMLElement
}
impl HTMLDataElement {
fn new_inherited(localName: DOMString,
prefix: Option<DOMString>,
document: &Document) -> HTMLDataElement {
HTMLDataElement {
htmlelement: HTMLElement::new_inherited(localName, prefix, document)
... | pub struct HTMLDataElement { | random_line_split |
get.js | JsonRecordApp.contorller(getCtrl, ['$scope', '$http', function($scope, $http){
var testArray = new Array();
var errorChar = 1;
for (var i = 10001; i < 10101; i++) {
var query = jQuery.ajax({
url: jsonUrl + jsonName + i + ".json",
type: "GET",
async: false,
dataType: 'json',
succe... |
// $http.get(jsonUrl + jsonName + i + ".json").then(function(data){
// testArray.push(data.data);
// $scope.jsonData = testArray;
// console.log(testArray);
// }).catch(function(){
// errorChar = 0;
// });
}
var testJson ={
"id" : 100010,
"Name" : "testsName"
}
// ... | { break;} | conditional_block |
get.js | JsonRecordApp.contorller(getCtrl, ['$scope', '$http', function($scope, $http){
var testArray = new Array();
var errorChar = 1;
for (var i = 10001; i < 10101; i++) {
var query = jQuery.ajax({
url: jsonUrl + jsonName + i + ".json",
type: "GET",
async: false,
dataType: 'json',
succe... | contentType: "application/json",
async: false,
dataType: 'json',
success: function(result){
console.log(result);
}
})
}]); | random_line_split | |
usage.js | /*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
* Changes may cause incorrect behavior and will be lost if the code is
* regenerated.
*/
'... | serializedName: 'name',
type: {
name: 'Composite',
className: 'UsageName'
}
}
}
}
};
}
}
module.exports = Usage; | name: {
required: true, | random_line_split |
usage.js | /*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
* Changes may cause incorrect behavior and will be lost if the code is
* regenerated.
*/
'... | {
/**
* Create a Usage.
* @member {string} [id] Resource identifier.
* @member {number} currentValue The current value of the usage.
* @member {number} limit The limit of usage.
* @member {object} name The name of the type of usage.
* @member {string} [name.value] A string describing the resource n... | Usage | identifier_name |
indexOf.js | /**
* Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
* Build: `lodash modularize exports="amd" -o ./compat/`
* Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
* Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
* Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigat... |
return indexOf;
});
| {
if (typeof fromIndex == 'number') {
var length = array ? array.length : 0;
fromIndex = (fromIndex < 0 ? nativeMax(0, length + fromIndex) : fromIndex || 0);
} else if (fromIndex) {
var index = sortedIndex(array, value);
return array[index] === value ? index : -1;
}
return baseIn... | identifier_body |
indexOf.js | /**
* Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
* Build: `lodash modularize exports="amd" -o ./compat/`
* Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
* Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
* Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigat... | (array, value, fromIndex) {
if (typeof fromIndex == 'number') {
var length = array ? array.length : 0;
fromIndex = (fromIndex < 0 ? nativeMax(0, length + fromIndex) : fromIndex || 0);
} else if (fromIndex) {
var index = sortedIndex(array, value);
return array[index] === value ? index : -... | indexOf | identifier_name |
indexOf.js | /**
* Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
* Build: `lodash modularize exports="amd" -o ./compat/`
* Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
* Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
* Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigat... | * @category Arrays
* @param {Array} array The array to search.
* @param {*} value The value to search for.
* @param {boolean|number} [fromIndex=0] The index to search from or `true`
* to perform a binary search on a sorted array.
* @returns {number} Returns the index of the matched value or `-1`.
... | * strict equality for comparisons, i.e. `===`. If the array is already sorted
* providing `true` for `fromIndex` will run a faster binary search.
*
* @static
* @memberOf _ | random_line_split |
transport.rs | use std::io::{self, Read, Write};
use std::net::{Shutdown, SocketAddr};
use std::time::Duration;
use std::u32;
use byteorder::{BigEndian, ByteOrder};
use bytes::{BufMut, Bytes, BytesMut, IntoBuf};
use futures::{Async, Future, Poll};
use prost::{decode_length_delimiter, length_delimiter_len, Message};
use tokio::net::{... | (duration: Duration) -> u32 {
let millis = duration
.as_secs()
.saturating_mul(1000)
.saturating_add(u64::from(duration.subsec_nanos()) / 1_000_000);
if millis > u64::from(u32::MAX) {
u32::MAX
} else {
millis as u32
}
}
| duration_to_ms | identifier_name |
transport.rs | use std::io::{self, Read, Write};
use std::net::{Shutdown, SocketAddr};
use std::time::Duration;
use std::u32;
use byteorder::{BigEndian, ByteOrder};
use bytes::{BufMut, Bytes, BytesMut, IntoBuf};
use futures::{Async, Future, Poll};
use prost::{decode_length_delimiter, length_delimiter_len, Message};
use tokio::net::{... |
/// Flushes bytes from send buffer to the stream.
///
/// Based on tokio-io's [`FramedWrite`][1].
/// [1]: https://github.com/tokio-rs/tokio-io/blob/0.1.3/src/framed_write.rs#L202-L225
///
/// An error return indicates a fatal error.
fn poll_flush(&mut self) -> Result<Async<()>, io::Error>... | {
self.recv_buf.reserve(at_least);
while at_least > 0 {
let n = unsafe {
let n = try_nb!(self.stream.read(self.recv_buf.bytes_mut()));
self.recv_buf.advance_mut(n);
n
};
at_least = at_least.saturating_sub(n);
... | identifier_body |
transport.rs | use std::io::{self, Read, Write};
use std::net::{Shutdown, SocketAddr};
use std::time::Duration;
use std::u32;
use byteorder::{BigEndian, ByteOrder};
use bytes::{BufMut, Bytes, BytesMut, IntoBuf};
use futures::{Async, Future, Poll};
use prost::{decode_length_delimiter, length_delimiter_len, Message};
use tokio::net::{... | service: &str,
method: &str,
required_feature_flags: &[u32],
body: &RequestBody,
timeout: Option<Duration>,
) -> Result<(), Error> {
let result = || -> Result<(), Error> {
// Set the header fields.
self.request_header.call_id = call_id;
... | call_id: i32, | random_line_split |
frontmatterparser.py | #!/usr/bin/env python
__author__ = "Dulip Withanage"
__email__ = "dulip.withanage@gmail.com"
import re
import string
import sys
import operator
import globals as gv
import os
import subprocess
import shutil
#from django.utils.encoding import smart_str
class FrontMatterParser:
def __init__(self, gv):
self.gv =... | (self, filestring):
# this works for perception-monospace, equations tables, laddering, neoliberalism, snowball, valuechain, sodium
name = re.findall(r'(\n|<p>|<bold>|<italic>)(([A-Za-z\-\.]+)\*?\s){2,5}(&|and|et|und)\s(([A-Za-z\-\.]+)\*?\s?){2,5}(</p>|</bold>|</italic>|\n)',filestring)
if len(name) == 0:
# t... | parse_authors | identifier_name |
frontmatterparser.py | #!/usr/bin/env python
__author__ = "Dulip Withanage"
__email__ = "dulip.withanage@gmail.com"
import re
import string
import sys
import operator
import globals as gv
import os
import subprocess
import shutil
#from django.utils.encoding import smart_str
class FrontMatterParser:
def __init__(self, gv):
self.gv =... |
#title0 = ''.join(title[0])
title_first= ''.join(title[0])
#remove <> tags
titleString = re.sub(r'<(.*)>','',re.sub(r'</(.*)>','',title_first))
return titleString
def get_file_text(self, filename):
f = open(filename)
text= f.read()
f.close()
return text
def update_tmp_file(self):
shutil.copy2... | title2 = re.findall(r'(\n|<p>|<bold>|<italic>)(([A-Za-z\-\.]+)((:|,)?\s)){1,20}([A-Za-z\-\.]+)?\??(</p>|</bold>|</italic>|\n)',filestring)
title = title2 | conditional_block |
frontmatterparser.py | #!/usr/bin/env python
__author__ = "Dulip Withanage"
__email__ = "dulip.withanage@gmail.com"
import re
import string
import sys
import operator
import globals as gv
import os
import subprocess
import shutil
#from django.utils.encoding import smart_str
class FrontMatterParser:
def __init__(self, gv):
self.gv =... | def write_output(self, text):
out = open(self.gv.NLM_FILE_PATH,'w')
out.write(text)
out.close()
def run(self):
text = self.get_file_text(self.gv.NLM_TEMP_FILE_PATH)
#self.parse_authors(text)
self.parse_title(text)
self.write_output(text)
self.update_tmp_file() | random_line_split | |
frontmatterparser.py | #!/usr/bin/env python
__author__ = "Dulip Withanage"
__email__ = "dulip.withanage@gmail.com"
import re
import string
import sys
import operator
import globals as gv
import os
import subprocess
import shutil
#from django.utils.encoding import smart_str
class FrontMatterParser:
def __init__(self, gv):
self.gv =... |
def get_file_text(self, filename):
f = open(filename)
text= f.read()
f.close()
return text
def update_tmp_file(self):
shutil.copy2(self.gv.NLM_FILE_PATH,self.gv.NLM_TEMP_FILE_PATH)
def write_output(self, text):
out = open(self.gv.NLM_FILE_PATH,'w')
out.write(text)
out.close()
def run(self):
... | title = re.findall(r'(\n|<p>|<bold>|<italic>)(([A-Za-z\-\.]+)(,?\s)){1,20}([A-Za-z\-\.]+)?:(</p>|</bold>|</italic>|\n)(.|\s)*?(\n|<p>|<bold>|<italic>)(([A-Za-z\-\.]+)((:|,)?\s)){1,20}([A-Za-z\-\.]+)?\??(</p>|</bold>|</italic>|\n)',filestring)
if len(title) == 0:
# this works for antiseptics, eeg_comicsans, entrepr... | identifier_body |
calendarfetcher.js | /* Magic Mirror
* Node Helper: Calendar - CalendarFetcher
*
* By Michael Teeuw http://michaelteeuw.nl
* MIT Licensed.
*/
var ical = require("./vendor/ical.js");
var moment = require("moment");
var CalendarFetcher = function(url, reloadInterval, excludedEvents, maximumEntries, maximumNumberOfDays, auth) {
var se... |
//console.log(newEvents);
events = newEvents.slice(0, maximumEntries);
self.broadcastEvents();
scheduleTimer();
});
};
/* scheduleTimer()
* Schedule the timer for the next update.
*/
var scheduleTimer = function() {
//console.log('Schedule update timer.');
clearTimeout(reloadTimer);
reloa... | }); | random_line_split |
calendarfetcher.js | /* Magic Mirror
* Node Helper: Calendar - CalendarFetcher
*
* By Michael Teeuw http://michaelteeuw.nl
* MIT Licensed.
*/
var ical = require("./vendor/ical.js");
var moment = require("moment");
var CalendarFetcher = function(url, reloadInterval, excludedEvents, maximumEntries, maximumNumberOfDays, auth) {
var se... |
// If additional advanced filtering is added in, this section
// must remain last as we overwrite the filter object with the
// filterBy string
if (filter.caseSensitive) {
filter = filter.filterBy;
testTitle = title;
} else if (useRegex) {
filter = filter.fil... | {
useRegex = filter.regex;
} | conditional_block |
application.js | // This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, or any plugin's
// vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisa... | () {
var numbers = new Set();
scroll = 0;
for (i = 1; i < 19; i++) {
$("#q" + i).css("border", "2px solid white");
for (j = 1; j < 5; j++) {
name = "q" + i + "a" + j;
if ($("input[name='" + name + "']:checked").length == 0) {
numbers.add(i);
$("#q" + i).css("border", "2px solid red");
... | validate_form | identifier_name |
application.js | // This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, or any plugin's
// vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisa... |
if ([39].indexOf(e.keyCode) > -1) { //right
e.preventDefault();
window.scrollBy(50, 0);
}
if([40].indexOf(e.keyCode) > -1) { //down
e.preventDefault();
window.scrollBy(0, 50);
}
}, false);
})
});
| { //up
e.preventDefault();
window.scrollBy(0, -50);
} | conditional_block |
application.js | // This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, or any plugin's
// vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisa... |
// Prevents arrow keys from moving radio button
$(document).on('click', 'input[type=radio]', function() {
document.addEventListener("keydown", function (e) {
if ([37].indexOf(e.keyCode) > -1) { // left
e.preventDefault();
window.scrollBy(-50, -0);
}
if ([38].indexOf(e.keyCode) > -1) { ... | {
var numbers = new Set();
scroll = 0;
for (i = 1; i < 19; i++) {
$("#q" + i).css("border", "2px solid white");
for (j = 1; j < 5; j++) {
name = "q" + i + "a" + j;
if ($("input[name='" + name + "']:checked").length == 0) {
numbers.add(i);
$("#q" + i).css("border", "2px solid red");
if... | identifier_body |
application.js | // This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, or any plugin's
// vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisa... | e.preventDefault();
window.scrollBy(50, 0);
}
if([40].indexOf(e.keyCode) > -1) { //down
e.preventDefault();
window.scrollBy(0, 50);
}
}, false);
})
}); | window.scrollBy(0, -50);
}
if ([39].indexOf(e.keyCode) > -1) { //right | random_line_split |
authored-state.tsx | import * as React from "react";
import { useState, useEffect, useRef } from "react";
interface Props {
id: string;
name: string;
authoredState: string;
}
const prettyAuthoredState = (authoredState: string) => {
try {
const json = JSON.parse(authoredState);
return JSON.stringify(json, null, 2);
} cat... |
};
const renderEditMode = () => {
const style: React.CSSProperties = {width: "98%", height: "200px", border: "1px solid #aaa", outline: "none"};
return (
<textarea ref={textareaRef} onChange={handleEditChange} id={id} name={name} style={style}>
{prettyState}
</textarea>
);
};
... | {
// this is only here to check if the JSON is valid, the text area is not a controlled component
setAuthoredState(textareaRef.current.value);
} | conditional_block |
authored-state.tsx | import * as React from "react";
import { useState, useEffect, useRef } from "react";
interface Props {
id: string;
name: string;
authoredState: string;
}
const prettyAuthoredState = (authoredState: string) => {
try {
const json = JSON.parse(authoredState);
return JSON.stringify(json, null, 2);
} cat... |
return {isValidJSON, setAuthoredState};
};
export const AuthoredState: React.FC<Props> = ({id, name, authoredState}) => {
const [edit, setEdit] = useState(false);
const {isValidJSON, setAuthoredState} = useValidateAuthoredState(authoredState);
const prettyState = prettyAuthoredState(authoredState);
const te... | setIsValidJSON(true);
} catch (e) {
setIsValidJSON(false);
}
}, [authoredState]); | random_line_split |
helper_objects.rs | //! Defines some structs, enums, and constants mainly useful for passing information around
//! over the FFI and over threads.
use std::collections::HashMap;
use std::sync::Mutex;
use libc::{c_char, c_void, uint64_t, c_double, c_int};
use futures::sync::mpsc::UnboundedSender;
use futures::Stream;
use futures::stream:... | {
pub command: ServerCommand,
pub payload: *mut c_void,
}
pub struct FXCMNative {
pub settings_hash: HashMap<String, String>,
pub server_environment: *mut c_void,
pub raw_rx: Option<BoxStream<(u64, BrokerResult), ()>>,
pub tickstream_obj: Mutex<Tickstream>,
}
// TODO: Move to Util
#[derive(De... | ClientMessage | identifier_name |
helper_objects.rs | //! Defines some structs, enums, and constants mainly useful for passing information around
//! over the FFI and over threads.
use std::collections::HashMap;
use std::sync::Mutex;
use libc::{c_char, c_void, uint64_t, c_double, c_int};
use futures::sync::mpsc::UnboundedSender;
use futures::Stream;
use futures::stream:... | impl CSymbolTick {
/// Converts a CSymbolTick into a Tick given the amount of decimal places precision.
pub fn to_tick(&self, decimals: usize) -> Tick {
let multiplier = 10usize.pow(decimals as u32) as f64;
let bid_pips = self.bid * multiplier;
let ask_pips = self.ask * multiplier;
... | pub bid: c_double,
pub ask: c_double,
}
| random_line_split |
invoke_shellcodemsil.py | import re
from lib.common import helpers
class Module:
def | (self, mainMenu, params=[]):
self.info = {
'Name': 'Invoke-ShellcodeMSIL',
'Author': ['@mattifestation'],
'Description': ('Execute shellcode within the context of the running PowerShell '
'process without making any Win32 function calls. Warning... | __init__ | identifier_name |
invoke_shellcodemsil.py | import re
from lib.common import helpers
class Module:
def __init__(self, mainMenu, params=[]):
self.info = {
'Name': 'Invoke-ShellcodeMSIL',
'Author': ['@mattifestation'],
'Description': ('Execute shellcode within the context of the running PowerShell '
... |
def generate(self, obfuscate=False, obfuscationCommand=""):
# read in the common module source code
moduleSource = self.mainMenu.installPath + "/data/module_source/code_execution/Invoke-ShellcodeMSIL.ps1"
if obfuscate:
helpers.obfuscate_module(moduleSource=moduleSourc... | option, value = param
if option in self.options:
self.options[option]['Value'] = value | conditional_block |
invoke_shellcodemsil.py | import re
from lib.common import helpers
class Module:
def __init__(self, mainMenu, params=[]):
self.info = {
'Name': 'Invoke-ShellcodeMSIL',
'Author': ['@mattifestation'],
'Description': ('Execute shellcode within the context of the running PowerShell '
... | }
# save off a copy of the mainMenu object to access external functionality
# like listeners/agent handlers/etc.
self.mainMenu = mainMenu
for param in params:
# parameter format is [Name, Value]
option, value = param
if option in se... | random_line_split | |
invoke_shellcodemsil.py | import re
from lib.common import helpers
class Module:
| def __init__(self, mainMenu, params=[]):
self.info = {
'Name': 'Invoke-ShellcodeMSIL',
'Author': ['@mattifestation'],
'Description': ('Execute shellcode within the context of the running PowerShell '
'process without making any Win32 function ca... | identifier_body | |
day17.py | #!/usr/bin/env python3
"""
http://adventofcode.com/day/17
Part 1
------
The elves bought too much eggnog again - 150 liters this time. To
fit it all into your refrigerator, you'll need to move it into
smaller containers. You take an inventory of the capacities of
the available containers.
For example, suppose you hav... | ():
containers = list()
with open(INFILE) as f:
for line in f:
containers.append(int(line.strip()))
# Part 1
p1count = 0
for s in range(len(containers)):
for c in combinations(containers, s):
if sum(c) == 150:
p1count += 1
# Part 2
p2... | main | identifier_name |
day17.py | #!/usr/bin/env python3
"""
http://adventofcode.com/day/17
Part 1
------
The elves bought too much eggnog again - 150 liters this time. To
fit it all into your refrigerator, you'll need to move it into
smaller containers. You take an inventory of the capacities of
the available containers.
For example, suppose you hav... | main() | conditional_block | |
day17.py | #!/usr/bin/env python3
"""
http://adventofcode.com/day/17
Part 1
------
The elves bought too much eggnog again - 150 liters this time. To
fit it all into your refrigerator, you'll need to move it into
smaller containers. You take an inventory of the capacities of
the available containers.
For example, suppose you hav... |
if __name__ == '__main__':
main()
| containers = list()
with open(INFILE) as f:
for line in f:
containers.append(int(line.strip()))
# Part 1
p1count = 0
for s in range(len(containers)):
for c in combinations(containers, s):
if sum(c) == 150:
p1count += 1
# Part 2
p2sizes = ... | identifier_body |
day17.py | #!/usr/bin/env python3
"""
http://adventofcode.com/day/17
Part 1
------
The elves bought too much eggnog again - 150 liters this time. To
fit it all into your refrigerator, you'll need to move it into
smaller containers. You take an inventory of the capacities of
the available containers.
For example, suppose you hav... |
if __name__ == '__main__':
main() | print(msg.format(p2sizes[p2min]))
| random_line_split |
agent.py | # -*- encoding: utf-8 -*-
# Copyright (c) 2015 b<>com
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... | `NN_CONFIG_UPDATES` environment variable as nanoconfig uses it to
access the nanoconfig service
"""
# NN_CONFIG_SERVICE:
nn_config_service = os.environ.get("NN_CONFIG_SERVICE")
if not self.nanoconfig_service_endpoint and not nn_config_service:
raise ValueError... | self.socket.connect(self.publisher_endpoint)
LOG.info("[Agent] Ready for pushing to Publisher node")
def set_nanoconfig_endpoints(self):
"""This methods sets both the `NN_CONFIG_SERVICE` and | random_line_split |
agent.py | # -*- encoding: utf-8 -*-
# Copyright (c) 2015 b<>com
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... |
def stop(self):
self.socket.close()
super(Agent, self).stop()
LOG.debug("[Agent] Stopped")
def update(self, notifier, data):
LOG.debug("[Agent] Updated by: %s", notifier)
LOG.debug("[Agent] Preparing to send message %s", msgpack.loads(data))
try:
LO... | self.setup_socket()
super(Agent, self).run() | identifier_body |
agent.py | # -*- encoding: utf-8 -*-
# Copyright (c) 2015 b<>com
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... |
if self.nanoconfig_service_endpoint:
os.environ["NN_CONFIG_SERVICE"] = self.nanoconfig_service_endpoint
else:
self.nanoconfig_service_endpoint = nn_config_service
# NN_CONFIG_UPDATES
nn_config_updates = os.environ.get("NN_CONFIG_UPDATES")
if not self.nan... | raise ValueError(
"Invalid configuration! No NN_CONFIG_SERVICE set. You need to "
"configure your `nanoconfig_service_endpoint`.") | conditional_block |
agent.py | # -*- encoding: utf-8 -*-
# Copyright (c) 2015 b<>com
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... | (self):
self.socket.close()
super(Agent, self).stop()
LOG.debug("[Agent] Stopped")
def update(self, notifier, data):
LOG.debug("[Agent] Updated by: %s", notifier)
LOG.debug("[Agent] Preparing to send message %s", msgpack.loads(data))
try:
LOG.debug("[Agen... | stop | identifier_name |
test_hierarchy_control.py | #!/usr/bin/env python
# Copyright (c) 2015, Robot Control and Pattern Recognition Group,
# Institute of Control and Computation Engineering
# Warsaw University of Technology
#
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the ... |
# rospy.sleep(0.01)
if __name__ == '__main__':
rospy.init_node('test_hierarchy_control')
task = TestHierarchyControl()
rospy.sleep(0.5)
task.spin()
| """
"""
def __init__(self):
self.pub_marker = velmautils.MarkerPublisher()
def spin(self):
simulation = True
rospack = rospkg.RosPack()
env_file=rospack.get_path('velma_scripts') + '/data/jar/cabinet_test.env.xml'
srdf_path=rospack.get_path('velma_description') + '/r... | identifier_body |
test_hierarchy_control.py | #!/usr/bin/env python
# Copyright (c) 2015, Robot Control and Pattern Recognition Group,
# Institute of Control and Computation Engineering
# Warsaw University of Technology
#
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the ... |
# print Jcol.shape
# print "Jcol"
# print Jcol
Jcol_pinv = np.linalg.pinv(Jcol)
# Jcol_pinv = Jcol.transpose()
# print "Jcol_pinv"
# print Jcol_pinv
# Ncol1 = ident... | if Jcol1[0, q_idx] < 0.000000001 or not q_idx in affected_dof:#l1_parent:
Jcol1[0, q_idx] = 0.0
if Jcol2[0, q_idx] < 0.000000001 or not q_idx in affected_dof:#l2_parent:
Jcol2[0, q_idx] = 0.0
Jcol[0, q_idx] = Jcol1[0... | conditional_block |
test_hierarchy_control.py | #!/usr/bin/env python
# Copyright (c) 2015, Robot Control and Pattern Recognition Group,
# Institute of Control and Computation Engineering
# Warsaw University of Technology
#
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the ... | :
"""
"""
def __init__(self):
self.pub_marker = velmautils.MarkerPublisher()
def spin(self):
simulation = True
rospack = rospkg.RosPack()
env_file=rospack.get_path('velma_scripts') + '/data/jar/cabinet_test.env.xml'
srdf_path=rospack.get_path('velma_description')... | TestHierarchyControl | identifier_name |
test_hierarchy_control.py | #!/usr/bin/env python
# Copyright (c) 2015, Robot Control and Pattern Recognition Group,
# Institute of Control and Computation Engineering
# Warsaw University of Technology
#
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the ... | # print "Jcol * Jcol_pinv", Jcol * Jcol_pinv
# print "a_des", a_des
omega_col += d_omega
# print "depth", depth
# raw_input(".")
# print "omega_col", omega_col
# print dx_HAND_ref
omega_... | # print "Jcol", Jcol
# print "Jcol_pinv", Jcol_pinv
# print "Jcol_pinv * Jcol", Jcol_pinv * Jcol | random_line_split |
predicates.py | # -*- coding: utf-8 -*-
#
# Copyright 2014-2021 BigML
#
# 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 ... | predicate.get('term')))
def to_rule(self, fields, label='name'):
""" Builds rule string from a predicates list
"""
return " and ".join([predicate.to_rule(fields, label=label) for
predicate in self.predicates
... | random_line_split | |
predicates.py | # -*- coding: utf-8 -*-
#
# Copyright 2014-2021 BigML
#
# 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 ... | (self, fields, label='name'):
""" Builds rule string from a predicates list
"""
return " and ".join([predicate.to_rule(fields, label=label) for
predicate in self.predicates
if not isinstance(predicate, bool)])
def apply(self, input_... | to_rule | identifier_name |
predicates.py | # -*- coding: utf-8 -*-
#
# Copyright 2014-2021 BigML
#
# 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 ... |
def to_rule(self, fields, label='name'):
""" Builds rule string from a predicates list
"""
return " and ".join([predicate.to_rule(fields, label=label) for
predicate in self.predicates
if not isinstance(predicate, bool)])
def a... | self.predicates.append(
Predicate(predicate.get('op'),
predicate.get('field'),
predicate.get('value'),
predicate.get('term'))) | conditional_block |
predicates.py | # -*- coding: utf-8 -*-
#
# Copyright 2014-2021 BigML
#
# 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 ... |
def to_rule(self, fields, label='name'):
""" Builds rule string from a predicates list
"""
return " and ".join([predicate.to_rule(fields, label=label) for
predicate in self.predicates
if not isinstance(predicate, bool)])
def a... | self.predicates = []
for predicate in predicates_list:
if predicate is True:
self.predicates.append(True)
else:
self.predicates.append(
Predicate(predicate.get('op'),
predicate.get('field'),
... | identifier_body |
mod.rs | //! Resource data implementations.
//!
//! This module will eventually contain implementations for the record data
//! for all defined resource record types.
//!
//! The types are named identically to the [`Rtype`] variant they implement.
//! They are grouped into submodules for the RFCs they are defined in. All
//! ty... | }
}
/// Parsed versions of all record data types.
///
/// This module defines or re-exports type aliases for all record data
/// types that use parsed domain names and references to bytes slices where
/// applicable. For convenience, it also includes re-exports for those types
/// that are not in fact generic.
///
... | let mut parser = parser.clone();
let len = parser.remaining();
let data = parser.parse_bytes(len).unwrap();
generic::fmt(data, f)
}
| conditional_block |
mod.rs | //! Resource data implementations.
//!
//! This module will eventually contain implementations for the record data
//! for all defined resource record types.
//!
//! The types are named identically to the [`Rtype`] variant they implement.
//! They are grouped into submodules for the RFCs they are defined in. All
//! ty... | /// Parsed versions of all record data types.
///
/// This module defines or re-exports type aliases for all record data
/// types that use parsed domain names and references to bytes slices where
/// applicable. For convenience, it also includes re-exports for those types
/// that are not in fact generic.
///
/// Use ... | match try!(fmt_master_data(rtype, parser, f)) {
Some(res) => Ok(res),
None => {
let mut parser = parser.clone();
let len = parser.remaining();
let data = parser.parse_bytes(len).unwrap();
generic::fmt(data, f)
}
}
}
| identifier_body |
mod.rs | //! Resource data implementations.
//!
//! This module will eventually contain implementations for the record data
//! for all defined resource record types.
//!
//! The types are named identically to the [`Rtype`] variant they implement.
//! They are grouped into submodules for the RFCs they are defined in. All
//! ty... | type: ::iana::Rtype, parser: &mut ::bits::Parser,
f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
match try!(fmt_master_data(rtype, parser, f)) {
Some(res) => Ok(res),
None => {
let mut parser = parser.clone();
let len = parser.remaining();
... | t_rdata(r | identifier_name |
mod.rs | //! Resource data implementations.
//!
//! This module will eventually contain implementations for the record data
//! for all defined resource record types.
//!
//! The types are named identically to the [`Rtype`] variant they implement.
//! They are grouped into submodules for the RFCs they are defined in. All
//! ty... | // arrow and the name of the type on the right. If the type is generic, use
// the owned version.
//
// The macro creates the re-export of the record data type.
master_types!{
rfc1035::{
A => A,
Cname => Cname<DNameBuf>,
Hinfo => Hinfo<CharStrBuf>,
Mb => Mb<DNameBuf>,
Md => M... | //
// Include all record types that can occur in master files. Place the name of
// the variant (identical to the type name) on the left side of the double | random_line_split |
lib.rs | #![feature(const_fn)]
#![feature(drop_types_in_const)]
#![feature(proc_macro)]
#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate serde_derive;
extern crate serde_json;
extern crate bootstrap_rs as bootstrap;
extern crate fiber;
use fiber::FiberId;
use std::cell::RefCell;
use std::collections::HashMap;... | {
/// Human-readable name for the event.
name: &'static str,
/// Event category.
cat: String,
/// Event phase (i.e. the event type).
ph: &'static str,
/// Timestamp in microseconds.
ts: i64,
/// Process ID for the event.
pid: usize,
/// Thread ID for the event.
tid:... | Event | identifier_name |
lib.rs | #![feature(const_fn)]
#![feature(drop_types_in_const)]
#![feature(proc_macro)]
#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate serde_derive;
extern crate serde_json;
extern crate bootstrap_rs as bootstrap;
extern crate fiber;
use fiber::FiberId;
use std::cell::RefCell;
use std::collections::HashMap;... |
pub fn with_budget(name: &'static str, _budget: Duration) -> Stopwatch {
// TODO: We should actually do something with the budget, right?
Stopwatch::new(name)
}
}
impl Drop for Stopwatch {
fn drop(&mut self) {
with_context(|stack| {
let stopwatch = stack.pop().expect("... | {
push_event(Event {
name: name,
cat: String::new(),
ph: "B",
ts: platform::timestamp(),
tid: platform::thread_id(),
pid: 0, // TODO: Do we care about tracking process ID?
});
with_context(|stack| {
stack.push(S... | identifier_body |
lib.rs | #![feature(const_fn)]
#![feature(drop_types_in_const)]
#![feature(proc_macro)]
#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate serde_derive;
extern crate serde_json;
extern crate bootstrap_rs as bootstrap;
extern crate fiber;
use fiber::FiberId;
use std::cell::RefCell;
use std::collections::HashMap;... | write!(formatter, "{}m {}s {}.{}ms", mins, secs, millis, micros)
} else if secs > 0 {
write!(formatter, "{}s {}.{}ms", secs, millis, micros)
} else {
write!(formatter, "{}.{}ms", millis, micros)
}
}
} | if mins > 0 { | random_line_split |
lib.rs | #![feature(const_fn)]
#![feature(drop_types_in_const)]
#![feature(proc_macro)]
#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate serde_derive;
extern crate serde_json;
extern crate bootstrap_rs as bootstrap;
extern crate fiber;
use fiber::FiberId;
use std::cell::RefCell;
use std::collections::HashMap;... | else {
write!(formatter, "{}.{}ms", millis, micros)
}
}
}
| {
write!(formatter, "{}s {}.{}ms", secs, millis, micros)
} | conditional_block |
ghosthunter-nodependency.js | /**
* ghostHunter - 0.4.0
* Copyright (C) 2014 Jamal Neufeld (jamal@i11u.me)
* MIT Licensed
* @license
*/
(function( $ ) {
/* Include the Lunr library */
var lunr=require('./lunr.min.js');
//This is the main plugin definition
$.fn.ghostHunter = function( options ) {
//Here we use jQuery's extend to set defa... | () {
that.loadAPI();
}
window.setTimeout(miam, 1);
} else {
target.focus(function(){
that.loadAPI();
});
}
target.closest("form").submit(function(e){
e.preventDefault();
that.find(target.val());
});
if( opts.onKeyUp ) {
target.keyup(function() {
that.find(tar... | miam | identifier_name |
ghosthunter-nodependency.js | /**
* ghostHunter - 0.4.0
* Copyright (C) 2014 Jamal Neufeld (jamal@i11u.me)
* MIT Licensed
* @license
*/
(function( $ ) {
/* Include the Lunr library */
var lunr=require('./lunr.min.js');
//This is the main plugin definition
$.fn.ghostHunter = function( options ) {
//Here we use jQuery's extend to set defa... | }
if(this.onComplete) {
this.onComplete(resultsData);
};
},
clear : function(){
$(this.results).empty();
this.target.val("");
},
format : function (t, d) {
return t.replace(/{{([^{}]*)}}/g, function (a, b) {
var r = d[b];
return typeof r === 'string' || typeof r === 'numbe... | var postData = this.blogData[lunrref];
results.append(this.format(this.result_template,postData));
resultsData.push(postData); | random_line_split |
ghosthunter-nodependency.js | /**
* ghostHunter - 0.4.0
* Copyright (C) 2014 Jamal Neufeld (jamal@i11u.me)
* MIT Licensed
* @license
*/
(function( $ ) {
/* Include the Lunr library */
var lunr=require('./lunr.min.js');
//This is the main plugin definition
$.fn.ghostHunter = function( options ) {
//Here we use jQuery's extend to set defa... | ;
if(this.zeroResultsInfo || searchResult.length > 0)
{
if(this.displaySearchInfo) results.append(this.format(this.info_template,{"amount":searchResult.length}));
}
for (var i = 0; i < searchResult.length; i++)
{
var lunrref = searchResult[i].ref;
var postData = this.blogData[lunrref];
... | {
this.before();
} | conditional_block |
ghosthunter-nodependency.js | /**
* ghostHunter - 0.4.0
* Copyright (C) 2014 Jamal Neufeld (jamal@i11u.me)
* MIT Licensed
* @license
*/
(function( $ ) {
/* Include the Lunr library */
var lunr=require('./lunr.min.js');
//This is the main plugin definition
$.fn.ghostHunter = function( options ) {
//Here we use jQuery's extend to set defa... |
window.setTimeout(miam, 1);
} else {
target.focus(function(){
that.loadAPI();
});
}
target.closest("form").submit(function(e){
e.preventDefault();
that.find(target.val());
});
if( opts.onKeyUp ) {
target.keyup(function() {
that.find(target.val());
});
}
},
... | {
that.loadAPI();
} | identifier_body |
main.rs | // Copyright 2015 The Gfx-rs Developers.
//
// 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 ag... | vertex Vertex {
pos: [f32; 2] = "a_Pos",
color: [f32; 3] = "a_Color",
}
pipeline pipe {
vbuf: gfx::VertexBuffer<Vertex> = (),
out: gfx::RenderTarget<ColorFormat> = "Target0",
}
}
const TRIANGLE: [Vertex; 3] = [
Vertex { pos: [ -0.5, -0.5 ], color: [1.0, 0.0, 0.0] },... | pub type ColorFormat = gfx::format::Rgba8;
pub type DepthFormat = gfx::format::DepthStencil;
gfx_defines!{ | random_line_split |
main.rs | // Copyright 2015 The Gfx-rs Developers.
//
// 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 ag... | () {
let builder = glutin::WindowBuilder::new()
.with_title("Triangle example".to_string())
.with_dimensions(1024, 768)
.with_vsync();
let (window, mut device, mut factory, main_color, _main_depth) =
gfx_window_glutin::init::<ColorFormat, DepthFormat>(builder);
let mut encode... | main | identifier_name |
main.rs | // Copyright 2015 The Gfx-rs Developers.
//
// 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 ag... | {
let builder = glutin::WindowBuilder::new()
.with_title("Triangle example".to_string())
.with_dimensions(1024, 768)
.with_vsync();
let (window, mut device, mut factory, main_color, _main_depth) =
gfx_window_glutin::init::<ColorFormat, DepthFormat>(builder);
let mut encoder: ... | identifier_body | |
gamma.rs | use err::ErrMsg;
use RGSLRng;
#[derive(Debug, Clone)]
pub struct Gamma {
a: f64,
b: f64,
}
impl Gamma {
pub fn new(a: f64, b: f64) -> Result<Gamma, ()> {
if a <= 0.0 || b <= 0.0 {
return Err(());
}
Ok(Gamma { a, b })
}
#[inline]
pub fn pdf(&self, x: f64) -... |
#[inline]
fn inverse_cdf(&self, x: f64) -> f64 {
use rgsl::randist::gamma::gamma_Pinv;
if x.is_sign_negative() {
panic!(ErrMsg::PositiveReal.panic_msg_with_arg(&self));
}
gamma_Pinv(x, self.a, self.b)
}
}
| {
use rgsl::randist::gamma::gamma_P;
if x.is_sign_negative() {
panic!(ErrMsg::PositiveReal.panic_msg_with_arg(&self));
}
gamma_P(x, self.a, self.b)
} | identifier_body |
gamma.rs | use err::ErrMsg;
use RGSLRng;
#[derive(Debug, Clone)]
pub struct | {
a: f64,
b: f64,
}
impl Gamma {
pub fn new(a: f64, b: f64) -> Result<Gamma, ()> {
if a <= 0.0 || b <= 0.0 {
return Err(());
}
Ok(Gamma { a, b })
}
#[inline]
pub fn pdf(&self, x: f64) -> f64 {
use rgsl::randist::gamma::gamma_pdf;
gamma_pdf... | Gamma | identifier_name |
gamma.rs | use err::ErrMsg;
use RGSLRng;
#[derive(Debug, Clone)]
pub struct Gamma {
a: f64,
b: f64,
}
impl Gamma {
pub fn new(a: f64, b: f64) -> Result<Gamma, ()> {
if a <= 0.0 || b <= 0.0 {
return Err(());
}
Ok(Gamma { a, b })
}
#[inline]
pub fn pdf(&self, x: f64) -... | use super::{Sample, CDF};
impl Sample for Gamma {
#[inline]
fn sample(&self, rng: &mut RGSLRng) -> f64 {
use rgsl::randist::gamma::gamma;
gamma(rng.get_gen(), self.a, self.b)
}
}
impl CDF for Gamma {
#[inline]
fn cdf(&self, x: f64) -> f64 {
use rgsl::randist::gamma::gamma_... | }
}
| random_line_split |
gamma.rs | use err::ErrMsg;
use RGSLRng;
#[derive(Debug, Clone)]
pub struct Gamma {
a: f64,
b: f64,
}
impl Gamma {
pub fn new(a: f64, b: f64) -> Result<Gamma, ()> {
if a <= 0.0 || b <= 0.0 {
return Err(());
}
Ok(Gamma { a, b })
}
#[inline]
pub fn pdf(&self, x: f64) -... |
gamma_Pinv(x, self.a, self.b)
}
}
| {
panic!(ErrMsg::PositiveReal.panic_msg_with_arg(&self));
} | conditional_block |
remove.ts | import * as vscode from 'vscode';
import * as fs from "fs";
import * as path from "path";
import Helpers from "../shared/helpers";
var projectObj: Object;
var jsonFilePath: string;
// Shows installed packages and gives option to remove them
export function removePackage() {
// Find the path to project.json
j... | else {
vscode.window.showQuickPick(dependenciesList)
.then(item => {
if(item){
// Delete the selected item
deleteItem(item);
}
});
}
}
// Delete the dependency object
function deleteItem(item: string) {
del... | {
Helpers.throwError("You do not have any dependencies on this project.");
} | conditional_block |
remove.ts | import * as vscode from 'vscode';
import * as fs from "fs";
import * as path from "path";
import Helpers from "../shared/helpers";
var projectObj: Object;
var jsonFilePath: string;
// Shows installed packages and gives option to remove them
export function removePackage() {
// Find the path to project.json
j... | () {
fs.readFile(jsonFilePath, { encoding: "utf8" }, (err, data) => {
if (err) {
console.error(err);
Helpers.throwError("Could not read project.json, please try again.");
} else {
// Store content of project.json file
let projectJsonContent: string = d... | readFile | identifier_name |
remove.ts | import * as vscode from 'vscode';
import * as fs from "fs";
import * as path from "path";
import Helpers from "../shared/helpers";
var projectObj: Object;
var jsonFilePath: string;
// Shows installed packages and gives option to remove them
export function removePackage() {
// Find the path to project.json
j... | }
function readFile() {
fs.readFile(jsonFilePath, { encoding: "utf8" }, (err, data) => {
if (err) {
console.error(err);
Helpers.throwError("Could not read project.json, please try again.");
} else {
// Store content of project.json file
let projectJso... | Helpers.throwError("This project does not contain project.json file.");
}
}); | random_line_split |
remove.ts | import * as vscode from 'vscode';
import * as fs from "fs";
import * as path from "path";
import Helpers from "../shared/helpers";
var projectObj: Object;
var jsonFilePath: string;
// Shows installed packages and gives option to remove them
export function removePackage() |
function readFile() {
fs.readFile(jsonFilePath, { encoding: "utf8" }, (err, data) => {
if (err) {
console.error(err);
Helpers.throwError("Could not read project.json, please try again.");
} else {
// Store content of project.json file
let projectJson... | {
// Find the path to project.json
jsonFilePath = path.join(vscode.workspace.rootPath, "/project.json");
// Check if the file exists first
fs.exists(jsonFilePath, exists => {
if (exists) {
readFile();
} else {
Helpers.throwError("This project does not contain pro... | identifier_body |
index.d.ts | // Type definitions for conf 1.1
// Project: https://github.com/sindresorhus/conf
// Definitions by: Sam Verschueren <https://github.com/SamVerschueren>
// BendingBender <https://github.com/BendingBender>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
inte... | <T = any> implements Iterable<[string, T]> {
store: {[key: string]: T};
readonly path: string;
readonly size: number;
constructor(options?: Options<T>);
get(key: string, defaultValue?: T): T;
set(key: string, val: T): void;
set(object: {[key: string]: T}): void;
has(key: string): boolean;
delete(key: strin... | Conf | identifier_name |
index.d.ts | // Type definitions for conf 1.1
// Project: https://github.com/sindresorhus/conf
// Definitions by: Sam Verschueren <https://github.com/SamVerschueren>
// BendingBender <https://github.com/BendingBender>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
inte... | export = Conf; | random_line_split | |
bonus.py | import os
import common_pygame
import random
pygame = common_pygame.pygame
screen = common_pygame.screen
class | ():
def __init__(self, sounds, menu):
self.menu = menu
self.sounds = sounds
self.bonusType = 0
self.bonusAnim = 0
self.font = pygame.font.Font(None, 64)
self.bonusList = list()
self.bonusList.append(self.font.render(
str("plasma gun !"), True, (25... | Bonus | identifier_name |
bonus.py | import os
import common_pygame
import random
pygame = common_pygame.pygame
screen = common_pygame.screen
class Bonus():
def __init__(self, sounds, menu):
|
def ProcessBonus(self, ship):
# if ship.score %200 ==0 and ship.weapon==1 and ship.score>0:
if ship.score > 400 * self.bonuscount and self.score < 400 * self.bonuscount:
self.menu.play_sound(self.sounds["plasmagun.wav"])
ship.setWeapon(2)
self.bonusType = 0
... | self.menu = menu
self.sounds = sounds
self.bonusType = 0
self.bonusAnim = 0
self.font = pygame.font.Font(None, 64)
self.bonusList = list()
self.bonusList.append(self.font.render(
str("plasma gun !"), True, (255, 255, 0)))
self.score = 0
self.bo... | identifier_body |
bonus.py | import os
import common_pygame
import random
pygame = common_pygame.pygame
screen = common_pygame.screen
class Bonus():
def __init__(self, sounds, menu):
self.menu = menu
self.sounds = sounds
self.bonusType = 0
self.bonusAnim = 0
self.font = pygame.font.Font(None, 64)
... | self.bonusAnim = self.bonusAnim - 1
# show bonus for the plasma weapon
if self.bonusType == 0:
screen.blit(self.bonusList[0], (250, 250)) | conditional_block | |
bonus.py | import os
import common_pygame
import random
pygame = common_pygame.pygame
screen = common_pygame.screen
class Bonus():
def __init__(self, sounds, menu):
self.menu = menu
self.sounds = sounds
self.bonusType = 0
self.bonusAnim = 0
self.font = pygame.font.Font(None, 64)
... |
def ProcessBonus(self, ship):
# if ship.score %200 ==0 and ship.weapon==1 and ship.score>0:
if ship.score > 400 * self.bonuscount and self.score < 400 * self.bonuscount:
self.menu.play_sound(self.sounds["plasmagun.wav"])
ship.setWeapon(2)
self.bonusType = 0
... | self.bonuscount = 1 | random_line_split |
test_basics.js | /*
Copyright (c) 2006, Tim Becker 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 conditio... | (elId) {
var e = document.getElementById(elId);
if (e.style.display == "block")
e.style.display = "none";
else
e.style.display = "block";
return false;
}
function debugInfo () {
print ("Browser Infos (<a href=\"#\" onclick=\"toggle(\'debugInfo\')\">+</a>)")
print("<small><div id=\"debugInfo\" s... | toggle | identifier_name |
test_basics.js | /*
Copyright (c) 2006, Tim Becker 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 conditio... |
function toggle(elId) {
var e = document.getElementById(elId);
if (e.style.display == "block")
e.style.display = "none";
else
e.style.display = "block";
return false;
}
function debugInfo () {
print ("Browser Infos (<a href=\"#\" onclick=\"toggle(\'debugInfo\')\">+</a>)")
print("<small><div id... | {
document.writeln(obj);
} | identifier_body |
test_basics.js | /*
Copyright (c) 2006, Tim Becker 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 conditio... |
debugInfo()
} | random_line_split | |
_mod_clickMenu.py | # -*- coding: utf-8 -*-
#----------------------------------------------------------------------------
# Menu for quickly adding waypoints when on move
#----------------------------------------------------------------------------
# Copyright 2007-2008, Oliver White
#
# This program is free software: you can redistribute... |
def drawMapOverlay(self, cr):
"""Draw an overlay on top of the map, showing various information
about position etc."""
# waypoins will be done in another way, so this is disabled for the time being
# (x,y,w,h) = self.get('viewport')
#
# dt = time() - self.lastWaypointAddT... | if message == "addWaypoint":
m = self.m.get("waypoints", None)
if m is not None:
self.lastWaypoint = m.newWaypoint()
self.lastWaypointAddTime = time() | identifier_body |
_mod_clickMenu.py | # -*- coding: utf-8 -*-
#----------------------------------------------------------------------------
# Menu for quickly adding waypoints when on move
#----------------------------------------------------------------------------
# Copyright 2007-2008, Oliver White
#
# This program is free software: you can redistribute... | (self, *args, **kwargs):
RanaModule.__init__(self, *args, **kwargs)
self.lastWaypoint = "(none)"
self.lastWaypointAddTime = 0
self.messageLingerTime = 2
def handleMessage(self, message, messageType, args):
if message == "addWaypoint":
m = self.m.get("waypoints", ... | __init__ | identifier_name |
_mod_clickMenu.py | # -*- coding: utf-8 -*-
#----------------------------------------------------------------------------
# Menu for quickly adding waypoints when on move
#----------------------------------------------------------------------------
# Copyright 2007-2008, Oliver White
#
# This program is free software: you can redistribute... |
def drawMapOverlay(self, cr):
"""Draw an overlay on top of the map, showing various information
about position etc."""
# waypoins will be done in another way, so this is disabled for the time being
# (x,y,w,h) = self.get('viewport')
#
# dt = time() - self.lastWaypointAddT... | self.lastWaypoint = m.newWaypoint()
self.lastWaypointAddTime = time() | conditional_block |
_mod_clickMenu.py | # -*- coding: utf-8 -*-
#----------------------------------------------------------------------------
# Menu for quickly adding waypoints when on move
#----------------------------------------------------------------------------
# Copyright 2007-2008, Oliver White
#
# This program is free software: you can redistribute... | self.lastWaypoint = m.newWaypoint()
self.lastWaypointAddTime = time()
def drawMapOverlay(self, cr):
"""Draw an overlay on top of the map, showing various information
about position etc."""
# waypoins will be done in another way, so this is disabled for the ti... | if message == "addWaypoint":
m = self.m.get("waypoints", None)
if m is not None: | random_line_split |
FloatingLabel.js | import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import { Animated, StyleSheet } from 'react-native';
import { H6 } from '@ui/typography';
import styled from '@ui/styled';
export const LabelText = styled(({ theme }) => ({
color: theme.colors.text.secondary,
backgroundColor: 'transp... | inputRange: [0, 1],
outputRange: [0, -sideScaledWidth],
});
const wrapperStyles = {
transform: [{ scale }, { translateX }, { translateY }],
opacity,
};
return (
<Animated.View
pointerEvents="none"
onLayout={this.handleLayout}
style={[styles.floatLab... | });
const translateX = this.props.animation.interpolate({ | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.