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 |
|---|---|---|---|---|
labelsTable.tsx | import * as React from "react";
import { Link } from 'react-router-dom'
import { useQuery } from 'react-query';
import { firstBy } from 'thenby';
import { fetchRules } from '../../../utils/evidence/ruleAPIs';
import { DataTable, Spinner } from '../../../../Shared/index';
import { getCheckIcon } from '../../../helpers/... | return formattedRows.sort(firstBy('state_for_sort').thenBy('id'));
}
if(!rulesData) {
return(
<div className="loading-spinner-container">
<Spinner />
</div>
);
}
const dataTableFields = [
{ name: "Rule ID", attribute:"id", width: "70px" },
{ name: "Descriptive Label", ... | {
if(!(rulesData && rulesData.rules && rulesData.rules.length)) {
return [];
}
const formattedRows = rulesData.rules.map(rule => {
const { name, id, state, optimal, label } = rule;
const ruleLink = (
<Link className="data-link" to={{ pathname: `/activities/${activityId}/semantic-la... | identifier_body |
labelsTable.tsx | import * as React from "react";
import { Link } from 'react-router-dom' | import { fetchRules } from '../../../utils/evidence/ruleAPIs';
import { DataTable, Spinner } from '../../../../Shared/index';
import { getCheckIcon } from '../../../helpers/evidence/renderHelpers';
import { AUTO_ML } from '../../../../../constants/evidence';
const LabelsTable = ({ activityId, prompt }) => {
const {... | import { useQuery } from 'react-query';
import { firstBy } from 'thenby';
| random_line_split |
labelsTable.tsx | import * as React from "react";
import { Link } from 'react-router-dom'
import { useQuery } from 'react-query';
import { firstBy } from 'thenby';
import { fetchRules } from '../../../utils/evidence/ruleAPIs';
import { DataTable, Spinner } from '../../../../Shared/index';
import { getCheckIcon } from '../../../helpers/... | () {
if(!(rulesData && rulesData.rules && rulesData.rules.length)) {
return [];
}
const formattedRows = rulesData.rules.map(rule => {
const { name, id, state, optimal, label } = rule;
const ruleLink = (
<Link className="data-link" to={{ pathname: `/activities/${activityId}/semantic... | getFormattedRows | identifier_name |
radiowatchframe.py | import wx
import sys
import os
import time
import threading
import math
import pynotify
import pygame.mixer | from pprzlink.ivy import IvyMessagesInterface
WIDTH = 150
HEIGHT = 40
UPDATE_INTERVAL = 250
class RadioWatchFrame(wx.Frame):
def message_recv(self, ac_id, msg):
if msg.name == "ROTORCRAFT_STATUS":
self.rc_status = int(msg['rc_status'])
if self.rc_status != 0 and not self.alertChannel.... |
sys.path.append(os.getenv("PAPARAZZI_HOME") + "/sw/ext/pprzlink/lib/v1.0/python")
| random_line_split |
radiowatchframe.py | import wx
import sys
import os
import time
import threading
import math
import pynotify
import pygame.mixer
sys.path.append(os.getenv("PAPARAZZI_HOME") + "/sw/ext/pprzlink/lib/v1.0/python")
from pprzlink.ivy import IvyMessagesInterface
WIDTH = 150
HEIGHT = 40
UPDATE_INTERVAL = 250
class RadioWatchFrame(wx.Frame):... |
def rclink_alert(self):
self.alertChannel.queue(self.alertSound)
self.notification.show()
time.sleep(5)
def setFont(self, control):
font = control.GetFont()
size = font.GetPointSize()
font.SetPointSize(size * 1.4)
control.SetFont(font)
def __init__... | self.rc_statusText.SetLabel(["OK", "LOST", "REALLY LOST"][self.rc_status])
self.update_timer.Restart(UPDATE_INTERVAL) | identifier_body |
radiowatchframe.py | import wx
import sys
import os
import time
import threading
import math
import pynotify
import pygame.mixer
sys.path.append(os.getenv("PAPARAZZI_HOME") + "/sw/ext/pprzlink/lib/v1.0/python")
from pprzlink.ivy import IvyMessagesInterface
WIDTH = 150
HEIGHT = 40
UPDATE_INTERVAL = 250
class RadioWatchFrame(wx.Frame):... | (self, control):
font = control.GetFont()
size = font.GetPointSize()
font.SetPointSize(size * 1.4)
control.SetFont(font)
def __init__(self):
wx.Frame.__init__(self, id=-1, parent=None, name=u'RCWatchFrame',
size=wx.Size(WIDTH, HEIGHT), title=u'RC St... | setFont | identifier_name |
radiowatchframe.py | import wx
import sys
import os
import time
import threading
import math
import pynotify
import pygame.mixer
sys.path.append(os.getenv("PAPARAZZI_HOME") + "/sw/ext/pprzlink/lib/v1.0/python")
from pprzlink.ivy import IvyMessagesInterface
WIDTH = 150
HEIGHT = 40
UPDATE_INTERVAL = 250
class RadioWatchFrame(wx.Frame):... |
if self.rc_status != 0 and not self.alertChannel.get_busy():
self.warn_timer = wx.CallLater(5, self.rclink_alert)
# else:
# self.notification.close()
def gui_update(self):
self.rc_statusText.SetLabel(["OK", "LOST", "REALLY LOST"][self.rc_status])
self.up... | self.rc_status = int(msg['rc_status']) | conditional_block |
signrawtransactions.py | TEtiFrA']
inputs = [
# Valid pay-to-pubkey scripts
{'txid': '9b907ef1e3c26fc71fe4a4b3580bc75264112f95050014157059c736f0202e71', 'vout': 0,
'scriptPubKey': '76a91460baa0f494b38ce3c940dea67f3804dc52d1fb9488ac'},
{'txid': '83a4f6a6b73660e13ee6cb3c6063fa3759c50c9b75... | assert not rawTxSigned['errors'][0]['witness']
# Now test signing failure for transaction with input witnesses
p2wpkh_raw_tx = "01000000000102fff7f7881a8099afa6940d42d1e7f6362bec38171ea3edf433541db4e4ad969f00000000494830450221008b9d1dc26ba6a9cb62127b02742fa9d754cd3bebf337f7a55d114c8e5cdd30be022... | random_line_split | |
signrawtransactions.py | (self):
"""Create and sign a valid raw transaction with one input.
Expected results:
1) The transaction has a complete set of signatures
2) No script verification error occurred"""
privKeys = ['cUeKHd5orzT3mz8P9pxyREHfsWtVfgsfDjiZZBcjUBAaGk1BTj7N', 'cVKpPfVKSJxKqVpE9awvXNWuLHCa... | successful_signing_test | identifier_name | |
signrawtransactions.py | TEtiFrA']
inputs = [
# Valid pay-to-pubkey scripts
{'txid': '9b907ef1e3c26fc71fe4a4b3580bc75264112f95050014157059c736f0202e71', 'vout': 0,
'scriptPubKey': '76a91460baa0f494b38ce3c940dea67f3804dc52d1fb9488ac'},
{'txid': '83a4f6a6b73660e13ee6cb3c6063fa3759c50c9b75... |
# Make sure decoderawtransaction throws if there is extra data
assert_raises_rpc_error(-22, "TX decode failed", self.nodes[0].decoderawtransaction, rawTx + "00")
rawTxSigned = self.nodes[0].signrawtransaction(rawTx, scripts, privKeys)
# 3) The transaction has no complete set of signa... | assert_equal(decodedRawTx["vin"][i]["txid"], inp["txid"])
assert_equal(decodedRawTx["vin"][i]["vout"], inp["vout"]) | conditional_block |
signrawtransactions.py |
outputs = {'mpLQjfK79b7CCV4VMJWEWAj5Mpx8Up5zxB': 0.1}
rawTx = self.nodes[0].createrawtransaction(inputs, outputs)
rawTxSigned = self.nodes[0].signrawtransaction(rawTx, inputs, privKeys)
# 1) The transaction has a complete set of signatures
assert 'complete' in rawTxSigned
... | def set_test_params(self):
self.setup_clean_chain = True
self.num_nodes = 1
def successful_signing_test(self):
"""Create and sign a valid raw transaction with one input.
Expected results:
1) The transaction has a complete set of signatures
2) No script verification... | identifier_body | |
classcrossbow_1_1infinio_1_1_rpc_response.js | var classcrossbow_1_1infinio_1_1_rpc_response =
[
[ "RpcResponse", "classcrossbow_1_1infinio_1_1_rpc_response.html#a5aff1389291798073171aebf69d744dd", null ],
[ "~RpcResponse", "classcrossbow_1_1infinio_1_1_rpc_response.html#aea474873966add062795e7294e5f45b1", null ],
[ "complete", "classcrossbow_1_1infinio... | ]; | random_line_split | |
icon_set.rs | // This file was generated by gir (https://github.com/gtk-rs/gir)
// from gir-files (https://github.com/gtk-rs/gir-files)
// DO NOT EDIT
use IconSource;
use StyleContext;
#[cfg(any(feature = "v3_10", feature = "dox"))]
use cairo;
use ffi;
#[cfg(any(feature = "v3_10", feature = "dox"))]
use gdk;
use gdk_pixbuf;
use gli... |
#[cfg_attr(feature = "v3_10", deprecated)]
pub fn copy(&self) -> Option<IconSet> {
unsafe {
from_glib_full(ffi::gtk_icon_set_copy(self.to_glib_none().0))
}
}
#[cfg_attr(feature = "v3_10", deprecated)]
pub fn get_sizes(&self) -> Vec<i32> {
unsafe {
l... | {
unsafe {
ffi::gtk_icon_set_add_source(self.to_glib_none().0, source.to_glib_none().0);
}
} | identifier_body |
icon_set.rs | // This file was generated by gir (https://github.com/gtk-rs/gir)
// from gir-files (https://github.com/gtk-rs/gir-files)
// DO NOT EDIT
use IconSource;
use StyleContext;
#[cfg(any(feature = "v3_10", feature = "dox"))]
use cairo;
use ffi;
#[cfg(any(feature = "v3_10", feature = "dox"))]
use gdk;
use gdk_pixbuf;
use gli... | (&self) -> Vec<i32> {
unsafe {
let mut sizes = ptr::null_mut();
let mut n_sizes = mem::uninitialized();
ffi::gtk_icon_set_get_sizes(self.to_glib_none().0, &mut sizes, &mut n_sizes);
FromGlibContainer::from_glib_full_num(sizes, n_sizes as usize)
}
}
... | get_sizes | identifier_name |
icon_set.rs | // This file was generated by gir (https://github.com/gtk-rs/gir)
// from gir-files (https://github.com/gtk-rs/gir-files)
// DO NOT EDIT
use IconSource;
use StyleContext;
#[cfg(any(feature = "v3_10", feature = "dox"))]
use cairo;
use ffi;
#[cfg(any(feature = "v3_10", feature = "dox"))]
use gdk;
use gdk_pixbuf;
use gli... | pub struct IconSet(Shared<ffi::GtkIconSet>);
match fn {
ref => |ptr| ffi::gtk_icon_set_ref(ptr),
unref => |ptr| ffi::gtk_icon_set_unref(ptr),
get_type => || ffi::gtk_icon_set_get_type(),
}
}
impl IconSet {
#[cfg_attr(feature = "v3_10", deprecated)]
pub fn new() -> IconSet {... | random_line_split | |
AccelerometerProxy.js | /*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); y... | * under the License.
*
*/
(function (win) {
var cordova = require('cordova'),
Acceleration = require('cordova-plugin-device-motion.Acceleration'),
accelerometerCallback = null;
module.exports = {
start: function (successCallback, errorCallback) {
if (accelerometerCallbac... | * Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations | random_line_split |
AccelerometerProxy.js | /*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); y... |
accelerometerCallback = function (motion) {
successCallback({
x: motion.accelerationIncludingGravity.x,
y: motion.accelerationIncludingGravity.y,
z: motion.accelerationIncludingGravity.z,
timestamp: new Date().... | {
win.removeEventListener("devicemotion", accelerometerCallback, true);
} | conditional_block |
table-remove-column.js | var Notifier = require('../../../components/notifier/notifier');
var errorParser = require('../../../helpers/error-parser');
module.exports = function (opts) {
if (!opts.columnModel) |
var columnModel = opts.columnModel;
var successCallback = opts.onSuccess;
var errorCallback = opts.onError;
var notification = Notifier.addNotification({
status: 'loading',
info: _t('components.table.columns.destroy.loading', { columnName: columnModel.get('name') }),
closable: false
});
colum... | { throw new Error('columnModel is required'); } | conditional_block |
table-remove-column.js | var Notifier = require('../../../components/notifier/notifier');
var errorParser = require('../../../helpers/error-parser');
module.exports = function (opts) {
if (!opts.columnModel) { throw new Error('columnModel is required'); }
var columnModel = opts.columnModel;
var successCallback = opts.onSuccess;
var e... | });
}
});
}; | random_line_split | |
islamic.js | define(
"dojo/cldr/nls/bs/islamic", //begin v1.x content
{
"dateFormatItem-yM": "MM.y.",
"dateFormatItem-yyyyMMMEd": "E, dd. MMM y. G",
"dateFormatItem-MMMEd": "E, dd. MMM",
"dateFormatItem-hms": "hh:mm:ss a",
"dateFormatItem-MMM": "LLL",
"dateFormatItem-y": "y.", | "dateFormatItem-yMMM": "MMM y.",
"eraAbbr": [
"AH"
],
"dateFormat-long": "dd. MMMM y. G",
"dateFormatItem-Hm": "HH:mm",
"dateFormat-medium": "dd.MM.y. G",
"dateFormatItem-Hms": "HH:mm:ss",
"dateFormatItem-ms": "mm:ss",
"dateFormatItem-yyyyMd": "dd.MM.y. G",
"dateFormatItem-yyyyMMMd": "dd. MMM y. G",
"dateF... | "dateFormatItem-yyyy": "y. G",
"dateFormatItem-Ed": "E, dd.", | random_line_split |
lexer.rs | use lex::lexeme::Lexeme;
/***
* Structure Lexer
* -> Lexical Analyzer structure used to tokenize given source code
*/
#[allow(dead_code)]
pub struct Lexer<'a>{
index: usize,
errors: u32,
code: String,
whitespaces: String,
terminals: Vec<&'a str>,
lexemes: Vec<Lexeme>
}
#[allow(dead_code)]
im... | else {
self.errors += 1;
println!("Syntax Error at {} : {}.", self.index, self.code.len());
}
}
}
if self.errors > 0 {
println!("Total Errors : {}", self.errors);
} else {
println!("Build Successful!");
... | {
lexemes.push(self.identifier());
} | conditional_block |
lexer.rs | use lex::lexeme::Lexeme;
/***
* Structure Lexer
* -> Lexical Analyzer structure used to tokenize given source code
*/
#[allow(dead_code)]
pub struct Lexer<'a>{
index: usize,
errors: u32,
code: String,
whitespaces: String,
terminals: Vec<&'a str>,
lexemes: Vec<Lexeme>
}
#[allow(dead_code)]
im... | (&mut self) -> Lexeme {
let mut varname = String::new();
if self.getc().is_alphabetic() {
varname.push(self.getc());
self.index += 1;
while self.getc().is_alphanumeric() {
varname.push(self.getc());
self.index += 1;
}
... | identifier | identifier_name |
lexer.rs | use lex::lexeme::Lexeme;
/***
* Structure Lexer
* -> Lexical Analyzer structure used to tokenize given source code
*/
#[allow(dead_code)]
pub struct Lexer<'a>{
index: usize,
errors: u32,
code: String,
whitespaces: String,
terminals: Vec<&'a str>,
lexemes: Vec<Lexeme>
}
#[allow(dead_code)]
im... |
// returns current character
fn getc(&self) -> char {
self.code.chars().nth(self.index).unwrap()
}
// skips whitespaces
fn skip(&mut self) {
while self.whitespaces.contains(self.getc()) {
self.index += 1;
}
}
// returns part of remaining slice
fn peek... | {
self.errors
} | identifier_body |
lexer.rs | use lex::lexeme::Lexeme;
/***
* Structure Lexer
* -> Lexical Analyzer structure used to tokenize given source code
*/
#[allow(dead_code)]
pub struct Lexer<'a>{
index: usize,
errors: u32,
code: String,
whitespaces: String,
terminals: Vec<&'a str>,
lexemes: Vec<Lexeme>
}
#[allow(dead_code)]
im... | } else if self.getc() == '\"' {
lexemes.push(self.string());
} else if self.getc().is_alphabetic() {
lexemes.push(self.identifier());
} else {
self.errors += 1;
println!("Syntax Error at {} : ... | if !construct {
if self.getc().is_numeric() {
lexemes.push(self.number()); | random_line_split |
__init__.py | def get (request, query):
import badge
import archived
from ..issuers.library.badges import library
from ..issuers.library.programs.mit.badges import scratch
badges = [
badge.get(request, query)['badge'],
archived.get(request, query)['badge'],
library.get(request, query)['ba... | required_fields = ('name', 'slug', 'earnerDescription', 'consumerDescription',
'criteriaUrl', 'unique', 'image', 'type',) | return missing
| random_line_split |
__init__.py | def | (request, query):
import badge
import archived
from ..issuers.library.badges import library
from ..issuers.library.programs.mit.badges import scratch
badges = [
badge.get(request, query)['badge'],
archived.get(request, query)['badge'],
library.get(request, query)['badge'],
... | get | identifier_name |
__init__.py | def get (request, query):
|
def post (request, query):
badge = request['data']
errors = validateBadge(badge)
if len(errors):
return ({
'message': 'Could not validate required fields',
'code': 'ValidationError',
'details': [{'field': field, 'value': ''} for field in errors]
}, 400... | import badge
import archived
from ..issuers.library.badges import library
from ..issuers.library.programs.mit.badges import scratch
badges = [
badge.get(request, query)['badge'],
archived.get(request, query)['badge'],
library.get(request, query)['badge'],
scratch.get(req... | identifier_body |
__init__.py | def get (request, query):
import badge
import archived
from ..issuers.library.badges import library
from ..issuers.library.programs.mit.badges import scratch
badges = [
badge.get(request, query)['badge'],
archived.get(request, query)['badge'],
library.get(request, query)['ba... |
return missing
required_fields = ('name', 'slug', 'earnerDescription', 'consumerDescription',
'criteriaUrl', 'unique', 'image', 'type',)
| missing.append(field) | conditional_block |
blob.rs | /// either File-based or Memory-based
Sliced(Dom<Blob>, RelativePos),
}
impl BlobImpl {
/// Construct memory-backed BlobImpl
#[allow(unrooted_must_root)]
pub fn new_from_bytes(bytes: Vec<u8>) -> BlobImpl {
BlobImpl::Memory(bytes)
}
/// Construct file-backed BlobImpl from File ID
... | size: size,
})
}
}
// https://w3c.github.io/FileAPI/#blob
#[dom_struct]
pub struct Blob {
reflector_: Reflector,
#[ignore_malloc_size_of = "No clear owner"]
blob_impl: DomRefCell<BlobImpl>,
/// content-type string
type_string: String,
}
impl Blob {
#[allow(unrooted_must... | cache: DomRefCell::new(None), | random_line_split |
blob.rs | Ok(s.clone()),
BlobImpl::Sliced(ref parent, ref rel_pos) => parent.get_bytes().map(|v| {
let range = rel_pos.to_abs_range(v.len());
v.index(range).to_vec()
}),
}
}
/// Get a copy of the type_string
pub fn type_string(&self) -> String {
... | {
if is_ascii_printable(s) {
let s_lower = s.to_ascii_lowercase();
// match s_lower.parse() as Result<Mime, ()> {
// Ok(_) => s_lower,
// Err(_) => "".to_string()
s_lower
} else {
"".to_string()
}
} | identifier_body | |
blob.rs | ::new(),
Some(blobparts) => match blob_parts_to_bytes(blobparts) {
Ok(bytes) => bytes,
Err(_) => return Err(Error::InvalidCharacter),
},
};
Ok(Blob::new(
global,
BlobImpl::new_from_bytes(bytes),
blobPropertyBag.... | Slice | identifier_name | |
Targets-dbg.js | /*!
* UI development toolkit for HTML5 (OpenUI5)
* (c) Copyright 2009-2016 SAP SE or an SAP affiliate company.
* Licensed under the Apache License, Version 2.0 - see LICENSE.txt.
*/
sap.ui.define([], function() {
"use strict";
/**
* Provide methods for sap.m.routing.Targets in sync mode
* @private
* @exper... |
this._oTargetHandler.navigate({
viewLevel: iViewLevel,
navigationIdentifier: sName
});
return oReturnValue;
},
/**
* @private
*/
_displaySingleTarget: function (sName) {
var oTarget = this.getTarget(sName);
if (oTarget) {
this._oLastDisplayedTarget = oTarget;
}
return ... | {
iViewLevel = this._getViewLevel(this._oLastDisplayedTarget);
sName = this._oLastDisplayedTarget._oOptions.name;
} | conditional_block |
Targets-dbg.js | /*!
* UI development toolkit for HTML5 (OpenUI5)
* (c) Copyright 2009-2016 SAP SE or an SAP affiliate company.
* Licensed under the Apache License, Version 2.0 - see LICENSE.txt.
*/
sap.ui.define([], function() {
"use strict";
/**
* Provide methods for sap.m.routing.Targets in sync mode
* @private
* @exper... | sName = this._oLastDisplayedTarget._oOptions.name;
}
this._oTargetHandler.navigate({
viewLevel: iViewLevel,
navigationIdentifier: sName
});
return oReturnValue;
},
/**
* @private
*/
_displaySingleTarget: function (sName) {
var oTarget = this.getTarget(sName);
if (oTarget) {... |
// maybe a wrong name was provided then there is no last displayed target
if (this._oLastDisplayedTarget) {
iViewLevel = this._getViewLevel(this._oLastDisplayedTarget); | random_line_split |
vue-focus.common.js | 'use strict';
var Vue = require('vue');
var Vue__default = 'default' in Vue ? Vue['default'] : Vue;
// @NOTE: We have to use Vue.nextTick because the element might not be
// present at the time model changes, but will be in the next batch.
// But because we use Vue.nextTick, the directive may already be... |
};
this.blur = function() {
if (self.bound === true) {
self.el.blur();
}
};
},
update: function(value) {
if (value) {
Vue__default.nextTick(this.focus);
} else {
Vue__default.nextTick(this.blur);
}
},
unbind: function() {
this.bound = false;
},
}... | {
self.el.focus();
} | conditional_block |
vue-focus.common.js | 'use strict';
var Vue = require('vue');
var Vue__default = 'default' in Vue ? Vue['default'] : Vue;
// @NOTE: We have to use Vue.nextTick because the element might not be
// present at the time model changes, but will be in the next batch.
// But because we use Vue.nextTick, the directive may already be... | } else {
if (process.env.NODE_ENV !== 'production') {
Vue.util.warn(
this.name + '="' +
this.expression + '" expects a boolean value, ' +
'got ' + JSON.stringify(value)
);
}
}
},
unbind: function() {
Vue.util.off(this.el, 'focus', this.focusHand... | Vue__default.nextTick(this.focus);
} else if (value === false) {
Vue__default.nextTick(this.blur); | random_line_split |
socket-io-connection.js | /**
* @author Phuluong
* December 27, 2015
*/
/** Exports **/
module.exports = new SocketIOConnection();
/** Imports **/
var event = require(__dir + "/core/app/event");
/** Classes **/
function SocketIOConnection() {
this.messageListeners = [];
this.connectionListeners = [];
this.io = require("socket.io... |
}
}
function onConnectionEvent(type, session) {
// Fire event
event.fire("connection.socketio." + type, session);
// Remove from sessions
if (type === "disconnect") {
this.sessionManager.destroy(session);
}
// Pass event to listeners
f... | {
socket.on(namespace, function (data) {
self.messageListeners[namespace](data, session);
});
} | conditional_block |
socket-io-connection.js | /**
* @author Phuluong
* December 27, 2015
*/
/** Exports **/
module.exports = new SocketIOConnection();
/** Imports **/
var event = require(__dir + "/core/app/event");
/** Classes **/
function SocketIOConnection() {
this.messageListeners = [];
this.connectionListeners = [];
this.io = require("socket.io... | (type, session) {
// Fire event
event.fire("connection.socketio." + type, session);
// Remove from sessions
if (type === "disconnect") {
this.sessionManager.destroy(session);
}
// Pass event to listeners
for (var i = 0; i < this.connectionListeners.len... | onConnectionEvent | identifier_name |
socket-io-connection.js | /**
* @author Phuluong
* December 27, 2015
*/
/** Exports **/
module.exports = new SocketIOConnection();
/** Imports **/
var event = require(__dir + "/core/app/event");
/** Classes **/
function SocketIOConnection() {
this.messageListeners = [];
this.connectionListeners = [];
this.io = require("socket.io... | var self = this;
this.sessionManager = sessionManager;
socketIO = self.io(httpServer.getServer());
socketIO.sockets.on("connection", function (socket) {
// Initialize session
var session = self.sessionManager.initSocketIOSession(socket);
// Fire connec... | for (var i = 0; i < users.length; i++) {
users[i].socket.emit(type, message);
}
};
this.listen = function (httpServer, sessionManager) { | random_line_split |
socket-io-connection.js | /**
* @author Phuluong
* December 27, 2015
*/
/** Exports **/
module.exports = new SocketIOConnection();
/** Imports **/
var event = require(__dir + "/core/app/event");
/** Classes **/
function SocketIOConnection() | this.sendMessage = function (toUserId, type, message, ignoredClientSession) {
var users = this.sessionManager.getUserSessions(toUserId);
for (var i = 0; i < users.length; i++) {
if (ignoredClientSession != null && users[i].socket === ignoredClientSession.socket) {
continu... | {
this.messageListeners = [];
this.connectionListeners = [];
this.io = require("socket.io");
/**
* Add A messsage listener
* @param {interface[onClientMessage]} listener
* @returns {bool}
*/
this.addMessageListener = function (namespace, listener) {
this.messageListeners[... | identifier_body |
ins.js | /**
* $Id$
*
* @author Moxiecode - based on work by Andrew Tetlaw
* @copyright Copyright © 2004-2007, Moxiecode Systems AB, All rights reserved.
*/
function preinit() {
// Initialize
tinyMCE.setWindowArg('mce_windowresize', false);
}
function init() {
tinyMCEPopup.resizeToInnerSize();
SXE.initE... | for (var i=0; i<elementArray.length; i++) {
var elm = elementArray[i];
setElementAttribs(elm);
}
}
} else {
setElementAttribs(elm);
}
tinyMCE.triggerNodeChange();
tinyMCEPopup.execCommand('mceEndUndoLevel');
tinyMCEPopup.close();
}
function removeIns() {
SXE.removeElement('ins');
... | random_line_split | |
ins.js | /**
* $Id$
*
* @author Moxiecode - based on work by Andrew Tetlaw
* @copyright Copyright © 2004-2007, Moxiecode Systems AB, All rights reserved.
*/
function preinit() {
// Initialize
tinyMCE.setWindowArg('mce_windowresize', false);
}
function init() {
tinyMCEPopup.resizeToInnerSize();
SXE.init... | else {
setElementAttribs(elm);
}
tinyMCE.triggerNodeChange();
tinyMCEPopup.execCommand('mceEndUndoLevel');
tinyMCEPopup.close();
}
function removeIns() {
SXE.removeElement('ins');
tinyMCEPopup.close();
} |
var s = SXE.inst.selection.getSelectedHTML();
if(s.length > 0) {
tinyMCEPopup.execCommand('mceInsertContent', false, '<ins id="#sxe_temp_ins#">' + s + '</ins>');
var elementArray = tinyMCE.getElementsByAttributeValue(SXE.inst.getBody(), 'ins', 'id', '#sxe_temp_ins#');
for (var i=0; i<elementArray.len... | conditional_block |
ins.js | /**
* $Id$
*
* @author Moxiecode - based on work by Andrew Tetlaw
* @copyright Copyright © 2004-2007, Moxiecode Systems AB, All rights reserved.
*/
function preinit() {
// Initialize
tinyMCE.setWindowArg('mce_windowresize', false);
}
function init() {
tinyMCEPopup.resizeToInnerSize();
SXE.init... | elm) {
setAllCommonAttribs(elm);
setAttrib(elm, 'datetime');
setAttrib(elm, 'cite');
}
function insertIns() {
var elm = tinyMCE.getParentElement(SXE.focusElement, 'ins');
tinyMCEPopup.execCommand('mceBeginUndoLevel');
if (elm == null) {
var s = SXE.inst.selection.getSelectedHTML();
if(s.length > 0... | etElementAttribs( | identifier_name |
ins.js | /**
* $Id$
*
* @author Moxiecode - based on work by Andrew Tetlaw
* @copyright Copyright © 2004-2007, Moxiecode Systems AB, All rights reserved.
*/
function preinit() {
// Initialize
tinyMCE.setWindowArg('mce_windowresize', false);
}
function init() {
tinyMCEPopup.resizeToInnerSize();
SXE.init... |
SXE.removeElement('ins');
tinyMCEPopup.close();
} | identifier_body | |
__init__.py | """
Provides functionality to emulate keyboard presses on host machine.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/keyboard/ | from homeassistant.const import (
SERVICE_MEDIA_NEXT_TRACK, SERVICE_MEDIA_PLAY_PAUSE,
SERVICE_MEDIA_PREVIOUS_TRACK, SERVICE_VOLUME_DOWN, SERVICE_VOLUME_MUTE,
SERVICE_VOLUME_UP)
REQUIREMENTS = ['pyuserinput==0.1.11']
DOMAIN = 'keyboard'
TAP_KEY_SCHEMA = vol.Schema({})
def setup(hass, config):
"""Lis... | """
import voluptuous as vol
| random_line_split |
__init__.py | """
Provides functionality to emulate keyboard presses on host machine.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/keyboard/
"""
import voluptuous as vol
from homeassistant.const import (
SERVICE_MEDIA_NEXT_TRACK, SERVICE_MEDIA_PLAY_PAUSE,
... | (hass, config):
"""Listen for keyboard events."""
import pykeyboard # pylint: disable=import-error
keyboard = pykeyboard.PyKeyboard()
keyboard.special_key_assignment()
hass.services.register(DOMAIN, SERVICE_VOLUME_UP,
lambda service:
keyboard.... | setup | identifier_name |
__init__.py | """
Provides functionality to emulate keyboard presses on host machine.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/keyboard/
"""
import voluptuous as vol
from homeassistant.const import (
SERVICE_MEDIA_NEXT_TRACK, SERVICE_MEDIA_PLAY_PAUSE,
... |
hass.services.register(DOMAIN, SERVICE_MEDIA_PLAY_PAUSE,
lambda service:
keyboard.tap_key(keyboard.media_play_pause_key),
schema=TAP_KEY_SCHEMA)
hass.services.register(DOMAIN, SERVICE_MEDIA_NEXT_TRACK,
... | """Listen for keyboard events."""
import pykeyboard # pylint: disable=import-error
keyboard = pykeyboard.PyKeyboard()
keyboard.special_key_assignment()
hass.services.register(DOMAIN, SERVICE_VOLUME_UP,
lambda service:
keyboard.tap_key(keyboard.vol... | identifier_body |
issue-19190.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | ;
pub struct Bar;
impl Foo {
pub fn foo(&self) {}
}
impl Deref for Bar {
type Target = Foo;
fn deref(&self) -> &Foo { loop {} }
}
// @has issue_19190/struct.Bar.html
// @has - '//*[@id="method.foo"]' 'fn foo(&self)'
| Foo | identifier_name |
issue-19190.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | // option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::ops::Deref;
pub struct Foo;
pub struct Bar;
impl Foo {
pub fn foo(&self) {}
}
impl Deref for Bar {
type Target = Foo;
fn deref(&self) -> &Foo { loop {} }
}
// @has issue_19190/struct.Bar.html
/... | random_line_split | |
index.js | /*!
* http-errors
* Copyright(c) 2014 Jonathan Ong
* Copyright(c) 2016 Douglas Christopher Wilson
* MIT Licensed
*/
'use strict'
/**
* Module dependencies.
* @private
*/
var deprecate = require('depd')('http-errors')
var setPrototypeOf = require('setprototypeof')
var statuses = require('statuses')
var inheri... | {
return str.split(' ').map(function (token) {
return token.slice(0, 1).toUpperCase() + token.slice(1)
}).join('').replace(/[^ _0-9a-z]/gi, '')
} | identifier_body | |
index.js | /*!
* http-errors
* Copyright(c) 2014 Jonathan Ong
* Copyright(c) 2016 Douglas Christopher Wilson
* MIT Licensed
*/
'use strict'
/**
* Module dependencies.
* @private
*/
var deprecate = require('depd')('http-errors')
var setPrototypeOf = require('setprototypeof')
var statuses = require('statuses')
var inheri... | (str) {
return str.split(' ').map(function (token) {
return token.slice(0, 1).toUpperCase() + token.slice(1)
}).join('').replace(/[^ _0-9a-z]/gi, '')
}
| toIdentifier | identifier_name |
index.js | /*!
* http-errors
* Copyright(c) 2014 Jonathan Ong
* Copyright(c) 2016 Douglas Christopher Wilson
* MIT Licensed
*/
'use strict'
/**
* Module dependencies.
* @private
*/
var deprecate = require('depd')('http-errors')
var setPrototypeOf = require('setprototypeof')
var statuses = require('statuses')
var inheri... |
switch (typeof arg) {
case 'string':
msg = arg
break
case 'number':
status = arg
if (i !== 0) {
deprecate('non-first-argument status code; replace with createError(' + arg + ', ...)')
}
break
case 'object':
props = arg
brea... | {
err = arg
status = err.status || err.statusCode || status
continue
} | conditional_block |
index.js | /*!
* http-errors
* Copyright(c) 2014 Jonathan Ong
* Copyright(c) 2016 Douglas Christopher Wilson
* MIT Licensed
*/
'use strict'
/**
* Module dependencies.
* @private
*/
var deprecate = require('depd')('http-errors')
var setPrototypeOf = require('setprototypeof')
var statuses = require('statuses')
var inheri... | exports[code] = CodeError
exports[name] = CodeError
}
})
// backwards-compatibility
exports["I'mateapot"] = deprecate.function(exports.ImATeapot,
'"I\'mateapot"; use "ImATeapot" instead')
}
/**
* Convert a string of words to a JavaScript identifier.
* @private
*/
function toIdentifier (s... | }
if (CodeError) {
// export the constructor | random_line_split |
barchartDirective.js | /**
* @ngdoc directive
* @name barchart
* @module angular-graphael
* @description
* Creates a bar chart.
* @link http://g.raphaeljs.com/reference.html#Paper.barchart
*/
angular.module('angular-graphael').directive('barchart', function ($window, mapData) {
'use strict';
return {
restrict: 'E',
... | }); | random_line_split | |
__init__.py | import sys
import traceback
import logging
import time
import inspect
def run_resilient(function, function_args=[], function_kwargs={}, tolerated_errors=(Exception,), log_prefix='Something failed, tolerating error and retrying: ', retries=5, delay=True, critical=False, initial_delay_time=0.1, delay_multiplier = 2.0):
... |
except Exception:
# We've recieved an error we didn't anticipate. This is bad.
# Depending on the error we the developers should either fix something, or, if we want to tolerate it,
# add it to our tolerated_errors.
# Those things require human judgement, so w... | logging.error('Critical action failed.')
raise error | conditional_block |
__init__.py | import sys
import traceback
import logging
import time
import inspect
def run_resilient(function, function_args=[], function_kwargs={}, tolerated_errors=(Exception,), log_prefix='Something failed, tolerating error and retrying: ', retries=5, delay=True, critical=False, initial_delay_time=0.1, delay_multiplier = 2.0):
... | (log_prefix):
"""Warn about an exception with a lower priority message, with a text prefix and the error type"""
exc_type, exc_value, exc_traceback = sys.exc_info()
lines = traceback.format_exception(exc_type, exc_value, exc_traceback)
traceback_text = lines[2]
logging.info(log_p... | show_exception_info | identifier_name |
__init__.py | import sys
import traceback
import logging
import time
import inspect
def run_resilient(function, function_args=[], function_kwargs={}, tolerated_errors=(Exception,), log_prefix='Something failed, tolerating error and retrying: ', retries=5, delay=True, critical=False, initial_delay_time=0.1, delay_multiplier = 2.0):
... | # "Exceptions should typically be derived from the Exception class, either directly or indirectly."
logging.exception("Bad mannered exception. Class was: %s Value was: %s Source file: %s", typ.__name__, str(value), inspect.getsourcefile(typ))
raise | except:
typ, value, unused = sys.exc_info()
# We've received an exception that isn't even an Exception subclass!
# This is bad manners - see http://docs.python.org/tutorial/errors.html: | random_line_split |
__init__.py | import sys
import traceback
import logging
import time
import inspect
def run_resilient(function, function_args=[], function_kwargs={}, tolerated_errors=(Exception,), log_prefix='Something failed, tolerating error and retrying: ', retries=5, delay=True, critical=False, initial_delay_time=0.1, delay_multiplier = 2.0):
... | show_exception_info(log_prefix)
if delay:
time.sleep(delay_time)
delay_time = delay_time * delay_multiplier
else:
delay_time = 0
logging.info('We have %d tries left. Delaying for %.2f seconds and... | """Run the function with function_args and function_kwargs. Warn if it excepts, and retry. If retries are exhausted,
log that, and if it's critical, properly throw the exception """
def show_exception_info(log_prefix):
"""Warn about an exception with a lower priority message, with a text prefix an... | identifier_body |
console.rs | use core;
use x86::io::outb;
use ::console::{Color, ConsoleCore};
const VGA_TEXT_BASE: *mut u16 = 0xB8000 as *mut u16;
// TODO: Read this from BIOS instead
const VGA_BASE_PORT: u16 = 0x3d4;
pub struct ConsoleCoreImpl {
x: usize,
y: usize,
fg: Color,
bg: Color,
show_cursor: bool,
}
impl ConsoleC... |
fn advance_cursor(&mut self) {
if self.x == self.width() - 1 {
self.advance_line();
} else {
self.x += 1;
self.update_hw_cursor();
}
}
fn advance_line(&mut self) {
let width = self.width();
let height = self.height();
asser... | {
self.show_cursor = v;
} | identifier_body |
console.rs | use core;
use x86::io::outb;
use ::console::{Color, ConsoleCore};
const VGA_TEXT_BASE: *mut u16 = 0xB8000 as *mut u16;
// TODO: Read this from BIOS instead
const VGA_BASE_PORT: u16 = 0x3d4;
pub struct ConsoleCoreImpl {
x: usize,
y: usize,
fg: Color,
bg: Color,
show_cursor: bool,
}
impl ConsoleC... | (&mut self, ch: u8) {
let color = self.fg as u16 | ((self.bg as u16) << 4);
unsafe {
let addr = VGA_TEXT_BASE.offset((self.y * self.width() + self.x) as isize);
core::intrinsics::volatile_store(addr, ch as u16 | (color << 8));
}
}
fn show_cursor(&mut self, v: bool... | set_char | identifier_name |
console.rs | use core;
use x86::io::outb;
use ::console::{Color, ConsoleCore};
const VGA_TEXT_BASE: *mut u16 = 0xB8000 as *mut u16;
// TODO: Read this from BIOS instead
const VGA_BASE_PORT: u16 = 0x3d4;
pub struct ConsoleCoreImpl {
x: usize,
y: usize,
fg: Color,
bg: Color,
show_cursor: bool,
}
impl ConsoleC... | let addr = VGA_TEXT_BASE.offset((width * (height - 1) + x) as isize);
core::intrinsics::volatile_store(addr, b' ' as u16 | (color << 8));
}
}
} else {
self.y += 1;
}
self.x = 0;
self.update_hw_cursor();
... | random_line_split | |
console.rs | use core;
use x86::io::outb;
use ::console::{Color, ConsoleCore};
const VGA_TEXT_BASE: *mut u16 = 0xB8000 as *mut u16;
// TODO: Read this from BIOS instead
const VGA_BASE_PORT: u16 = 0x3d4;
pub struct ConsoleCoreImpl {
x: usize,
y: usize,
fg: Color,
bg: Color,
show_cursor: bool,
}
impl ConsoleC... | else {
self.y += 1;
}
self.x = 0;
self.update_hw_cursor();
}
fn width(&self) -> usize {
80
}
fn height(&self) -> usize {
25
}
fn cursor(&self) -> (usize, usize) {
(self.x, self.y)
}
}
| {
unsafe {
core::intrinsics::volatile_copy_memory(VGA_TEXT_BASE, VGA_TEXT_BASE.offset(width as isize), width * (height - 1));
}
let color = (self.bg as u16) << 4;
for x in 0..width {
unsafe {
let addr = VGA_TEXT_BASE.of... | conditional_block |
package.py | # Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class Pngwriter(CMakePackage):
"""PNGwriter is a very easy to use open source graphics library t... | depends_on('libpng')
depends_on('zlib')
depends_on('freetype')
def cmake_args(self):
spec = self.spec
args = []
if spec.satisfies('@0.7.0:'):
args += ['-DPNGwriter_USE_FREETYPE:BOOL=ON']
return args | random_line_split | |
package.py | # Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class Pngwriter(CMakePackage):
|
depends_on('libpng')
depends_on('zlib')
depends_on('freetype')
def cmake_args(self):
spec = self.spec
args = []
if spec.satisfies('@0.7.0:'):
args += ['-DPNGwriter_USE_FREETYPE:BOOL=ON']
return args
| """PNGwriter is a very easy to use open source graphics library that uses
PNG as its output format. The interface has been designed to be as simple
and intuitive as possible. It supports plotting and reading pixels in the
RGB (red, green, blue), HSV (hue, saturation, value/brightness) and CMYK
(cyan, ma... | identifier_body |
package.py | # Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class Pngwriter(CMakePackage):
"""PNGwriter is a very easy to use open source graphics library t... | (self):
spec = self.spec
args = []
if spec.satisfies('@0.7.0:'):
args += ['-DPNGwriter_USE_FREETYPE:BOOL=ON']
return args
| cmake_args | identifier_name |
package.py | # Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class Pngwriter(CMakePackage):
"""PNGwriter is a very easy to use open source graphics library t... |
return args
| args += ['-DPNGwriter_USE_FREETYPE:BOOL=ON'] | conditional_block |
ModalManager.jest.tsx | import { LoginForm } from "v2/Components/Authentication/Desktop/LoginForm"
import { ModalType } from "v2/Components/Authentication/Types"
import { mount, ReactWrapper } from "enzyme"
import React from "react"
import { Intent, ContextModule } from "@artsy/cohesion"
import {
ModalManager,
ModalManagerProps,
} from "... | manager.handleTypeChange("signup")
expect(manager.state.currentType).toEqual("signup")
expect(manager.state.switchedForms).toEqual(true)
expect(manager.state.options.mode).toEqual("signup")
})
it("returns the right subtitle", () => {
const wrapper = getWrapper()
const manager = wrapper.ins... | intent: Intent.login,
contextModule: ContextModule.header,
})
| random_line_split |
prime.py | #!/usr/bin/python3
from ctypes import *
import random
import logging
import log
logger = logging.getLogger('test.prime')
__all__ = ['isPrime', 'getRandPrime', 'inv']
libgmp = CDLL('libgmp.so.10')
class _mpz_t(Structure):
_fields_ = [('_mp_alloc', c_int), ('_mp_size', c_int), ('_mp_d', POINTER(c_ulong))]
def _... | elif v == 1:
return 1
pp, vv = p, v
a, b = divmod(pp, vv)
l1=[1,0]
l2 = [0, 1]
l3 = list(map(lambda x: x[0] - a * x[1], zip(l1, l2)))
while b != 1:
pp, vv = vv, b
a, b = divmod(pp, vv)
l1 = l2
l2 = l3
l3 = list(map(lambda x: x[0] - a * x[1], zi... | if v == 0:
raise ValueError('v should not be zero in inv') | random_line_split |
prime.py | #!/usr/bin/python3
from ctypes import *
import random
import logging
import log
logger = logging.getLogger('test.prime')
__all__ = ['isPrime', 'getRandPrime', 'inv']
libgmp = CDLL('libgmp.so.10')
class _mpz_t(Structure):
_fields_ = [('_mp_alloc', c_int), ('_mp_size', c_int), ('_mp_d', POINTER(c_ulong))]
def _... |
def _mpz_probab_prime_p(p, reps):
return libgmp.__gmpz_probab_prime_p(pointer(p), reps)
def isPrime(n):
"""Test if n is a prime."""
if type(n) != int:
raise ValueError('type error, n should be int type')
v = _mpz_t()
_mpz_init_set_str(v, bytes(str(n), encoding = 'ascii'), 10)
if _mpz_... | libgmp.__gmpz_init_set_str(pointer(p), s, base) | identifier_body |
prime.py | #!/usr/bin/python3
from ctypes import *
import random
import logging
import log
logger = logging.getLogger('test.prime')
__all__ = ['isPrime', 'getRandPrime', 'inv']
libgmp = CDLL('libgmp.so.10')
class _mpz_t(Structure):
_fields_ = [('_mp_alloc', c_int), ('_mp_size', c_int), ('_mp_d', POINTER(c_ulong))]
def _... |
#define y, y**2 = 5, get solution in Fp(y) filed
t = [b, 1]
y2 = (b * b - a) % p
q = (p + 1) >> 1
ret = [1, 0]
while q != 0:
if q & 0x01 != 0:
ret = [(ret[0] * t[0] + y2 * ret[1] * t[1]) % p, (ret[0] * t[1] + ret[1] * t[0]) % p]
t = [(t[0] * t[0] + y2 * t[1] * t[1]) ... | break | conditional_block |
prime.py | #!/usr/bin/python3
from ctypes import *
import random
import logging
import log
logger = logging.getLogger('test.prime')
__all__ = ['isPrime', 'getRandPrime', 'inv']
libgmp = CDLL('libgmp.so.10')
class _mpz_t(Structure):
_fields_ = [('_mp_alloc', c_int), ('_mp_size', c_int), ('_mp_d', POINTER(c_ulong))]
def _... | (n):
"""Test if n is a prime."""
if type(n) != int:
raise ValueError('type error, n should be int type')
v = _mpz_t()
_mpz_init_set_str(v, bytes(str(n), encoding = 'ascii'), 10)
if _mpz_probab_prime_p(v, 50) == 0:
return False
else:
return True
def getRandPrime(bits = 10... | isPrime | identifier_name |
gnugo_analysis.py | ",es)
previous_move=new_child
if current_color in ('w','W'):
current_color='b'
else:
current_color='w'
else:
gnugo.undo()
#one_move.add_comment_text(additional_comments)
log("Creating the influence map")
black_influence=gnugo.get_gnugo_initial_influence_black()
blac... | clear_selection | identifier_name | |
gnugo_analysis.py | "):
log("gnugo plays white")
top_moves=gnugo.gnugo_top_moves_white()
answer=gnugo.play_white()
else:
log("gnugo plays black")
top_moves=gnugo.gnugo_top_moves_black()
answer=gnugo.play_black()
log("====","Gnugo answer:",answer)
node_set(one_move,"CBM",answer)
log("==== Gnugo top moves")
f... |
if black_influence_points!=[]:
node_set(one_move,"IBM",black_influence_points) #IBM: influence black map
if black_territories_points!=[]:
node_set(one_move,"TBM",black_territories_points) #TBM: territories black map
if white_influence_points!=[]:
node_set(one_move,"IWM",white_influence_points) ... | for j in range(self.size):
if black_influence[i][j]==-3:
black_territories_points.append([i,j])
if white_influence[i][j]==3:
white_territories_points.append([i,j])
if black_influence[i][j]==-2:
black_influence_points.append([i,j])
if white_influence[i][j]==2:
white_influence_poi... | conditional_block |
gnugo_analysis.py | "):
log("gnugo plays white")
top_moves=gnugo.gnugo_top_moves_white()
answer=gnugo.play_white()
else:
log("gnugo plays black")
top_moves=gnugo.gnugo_top_moves_black()
answer=gnugo.play_black()
log("====","Gnugo answer:",answer)
node_set(one_move,"CBM",answer)
log("==== Gnugo top moves")
f... |
def get_gnugo_experimental_score(self,color):
self.write("experimental_score "+color)
answer=self.readline().strip()
return answer[2:]
class GnuGoSettings(BotProfiles):
def __init__(self,parent,bot="GnuGo"):
Frame.__init__(self,parent)
self.parent=parent
self.bot=bot
self.profiles=get_bot_profiles... | self.write("top_moves_white")
answer=self.readline()[:-1]
try:
answer=answer.split(" ")[1:-1]
except:
raise GRPException("GRPException in get_gnugo_top_moves_white()")
answers_list=[]
for value in answer:
try:
float(value)
except:
answers_list.append(value)
return answers_list | identifier_body |
gnugo_analysis.py | "):
log("gnugo plays white")
top_moves=gnugo.gnugo_top_moves_white()
answer=gnugo.play_white()
else:
log("gnugo plays black")
top_moves=gnugo.gnugo_top_moves_black()
answer=gnugo.play_black()
log("====","Gnugo answer:",answer)
node_set(one_move,"CBM",answer)
log("==== Gnugo top moves")
f... |
log("Creating the influence map")
black_influence=gnugo.get_gnugo_initial_influence_black()
black_territories_points=[]
black_influence_points=[]
white_influence=gnugo.get_gnugo_initial_influence_white()
white_territories_points=[]
white_influence_points=[]
for i in range(self.size):
for j in rang... | else:
gnugo.undo()
#one_move.add_comment_text(additional_comments) | random_line_split |
pytest_store.py | """Storage for pytest objects during test runs
The objects in the module will change during the course of a test run,
so they have been stashed into the 'store' namespace
Usage:
# imported directly (store is pytest.store)
from cfme.fixtures.pytest_store import store
store.config, store.pluginmanager, sto... |
class FlexibleTerminalReporter(TerminalReporter):
"""A TerminalReporter stand-in that pretends to work even without a py.test config."""
def __init__(self, config=None, file=None):
if config:
# If we have a config, nothing more needs to be done
return TerminalReporter.__init__(... | random_line_split | |
pytest_store.py | """Storage for pytest objects during test runs
The objects in the module will change during the course of a test run,
so they have been stashed into the 'store' namespace
Usage:
# imported directly (store is pytest.store)
from cfme.fixtures.pytest_store import store
store.config, store.pluginmanager, sto... |
# Without a config, pretend to be a TerminalReporter
# hook-related functions (logreport, collection, etc) will be outrigt broken,
# but the line writers should still be usable
if file is None:
file = sys.stdout
self._tw = self.writer = TerminalWriter(file)
... | return TerminalReporter.__init__(self, config, file) | conditional_block |
pytest_store.py | """Storage for pytest objects during test runs
The objects in the module will change during the course of a test run,
so they have been stashed into the 'store' namespace
Usage:
# imported directly (store is pytest.store)
from cfme.fixtures.pytest_store import store
store.config, store.pluginmanager, sto... |
@property
def fixturemanager(self):
# "publicize" the fixturemanager
return self.session and self.session._fixturemanager
@property
def capturemanager(self):
return self._maybe_get_plugin('capturemanager')
@property
def pluginmanager(self):
# Expose this direc... | return self.session is not None | identifier_body |
pytest_store.py | """Storage for pytest objects during test runs
The objects in the module will change during the course of a test run,
so they have been stashed into the 'store' namespace
Usage:
# imported directly (store is pytest.store)
from cfme.fixtures.pytest_store import store
store.config, store.pluginmanager, sto... | ():
# Expose the pytest store as pytest.store
return {'store': store}
def pytest_plugin_registered(manager):
# config will be set at the second call to this hook
if store.config is None:
store.config = manager.getplugin('pytestconfig')
def pytest_sessionstart(session):
store.session = se... | pytest_namespace | identifier_name |
_dealer_footer.js | var args = arguments[0] || {};
// function goNav(event){
// alert("footer");
// }
/** For footer More options**/
//$.more.addEventListener('click', expandMoreMenu);
function expandMoreMenu(e){
if(expandMoreMenu.__isExecuting) {
return;
} | Ti.App.Properties.setString('module', 'dealer_more');
}else{
$.subfooter.animate({bottom:0,duration:500}, function(){ expandMoreMenu.__isExecuting = false;});
$.more.image = "/images/icons/icon-more.png";
Ti.App.Properties.setString('module', 'dealer_more');
e.source.mod = 'more';
}
} | expandMoreMenu.__isExecuting = true;
if(e.source.mod == 'more'){
$.subfooter.animate({bottom:70,duration:500}, function(){ expandMoreMenu.__isExecuting = false;});
$.more.image = "/images/icons/icon-more-active.png";
e.source.mod = 'more_active'; | random_line_split |
_dealer_footer.js | var args = arguments[0] || {};
// function goNav(event){
// alert("footer");
// }
/** For footer More options**/
//$.more.addEventListener('click', expandMoreMenu);
function expandMoreMenu(e) | {
if(expandMoreMenu.__isExecuting) {
return;
}
expandMoreMenu.__isExecuting = true;
if(e.source.mod == 'more'){
$.subfooter.animate({bottom:70,duration:500}, function(){ expandMoreMenu.__isExecuting = false;});
$.more.image = "/images/icons/icon-more-active.png";
e.source.mod = 'more_active';
... | identifier_body | |
_dealer_footer.js | var args = arguments[0] || {};
// function goNav(event){
// alert("footer");
// }
/** For footer More options**/
//$.more.addEventListener('click', expandMoreMenu);
function expandMoreMenu(e){
if(expandMoreMenu.__isExecuting) {
return;
}
expandMoreMenu.__isExecuting = true;
if(e.source.mod == 'mor... |
}
| {
$.subfooter.animate({bottom:0,duration:500}, function(){ expandMoreMenu.__isExecuting = false;});
$.more.image = "/images/icons/icon-more.png";
Ti.App.Properties.setString('module', 'dealer_more');
e.source.mod = 'more';
} | conditional_block |
_dealer_footer.js | var args = arguments[0] || {};
// function goNav(event){
// alert("footer");
// }
/** For footer More options**/
//$.more.addEventListener('click', expandMoreMenu);
function | (e){
if(expandMoreMenu.__isExecuting) {
return;
}
expandMoreMenu.__isExecuting = true;
if(e.source.mod == 'more'){
$.subfooter.animate({bottom:70,duration:500}, function(){ expandMoreMenu.__isExecuting = false;});
$.more.image = "/images/icons/icon-more-active.png";
e.source.mod = 'more_active';... | expandMoreMenu | identifier_name |
status.rs |
#[derive(Debug, Eq, PartialEq)]
pub enum StatusCode {
OK = 0,
OutOfMemory = 1,
KeyError = 2,
TypeError = 3,
Invalid = 4,
IOError = 5,
UnknownError = 9,
NotImplemented = 10,
}
pub struct | {
code: StatusCode,
posix_code: i16,
message: String
}
impl ArrowError {
pub fn out_of_memory(message: &'static str) -> ArrowError {
ArrowError::new(StatusCode::OutOfMemory, message, -1)
}
pub fn key_error(message: &'static str) -> ArrowError {
ArrowError::new(StatusCode::KeyError, message, -1)
... | ArrowError | identifier_name |
status.rs |
#[derive(Debug, Eq, PartialEq)]
pub enum StatusCode {
OK = 0,
OutOfMemory = 1,
KeyError = 2,
TypeError = 3,
Invalid = 4,
IOError = 5,
UnknownError = 9,
NotImplemented = 10,
}
pub struct ArrowError {
code: StatusCode,
posix_code: i16,
message: String
}
impl ArrowError {
pub fn out_of_memory(m... |
} | {
&self.message
} | identifier_body |
status.rs | #[derive(Debug, Eq, PartialEq)]
pub enum StatusCode {
OK = 0,
OutOfMemory = 1,
KeyError = 2,
TypeError = 3,
Invalid = 4,
IOError = 5,
UnknownError = 9, |
pub struct ArrowError {
code: StatusCode,
posix_code: i16,
message: String
}
impl ArrowError {
pub fn out_of_memory(message: &'static str) -> ArrowError {
ArrowError::new(StatusCode::OutOfMemory, message, -1)
}
pub fn key_error(message: &'static str) -> ArrowError {
ArrowError::new(StatusCode::Ke... | NotImplemented = 10,
} | random_line_split |
e2ee.ts | littleEndian;
const textEncoder = new TextEncoder();
const textDecoder = new TextDecoder();
// VP8 のみ
// TODO(nakai): VP9 / AV1 も将来的に対応も考える
const unencryptedBytes = {
// I フレーム
key: 10,
// 非 I フレーム
delta: 3,
// オーディオ
undefined: 1,
};
function getCount(connectionId: string): number {
return countMap.get... | const currentSelfDeriveKey = selfDeriveKeyMap.get("latest");
if (currentSelfDeriveKey) {
if (currentSelfDeriveKey["keyId"] < keyId) {
const nextSelfDeriveKey = { connectionId, keyId, deriveKey };
selfDeriveKeyMap.set("latest", nextSelfDeriveKey);
}
} else {
const nextSelfDeriveKey = { conne... | ionId: string, keyId: number, deriveKey: CryptoKey): void {
| conditional_block |
e2ee.ts | littleEndian;
const textEncoder = new TextEncoder();
const textDecoder = new TextDecoder();
// VP8 のみ
// TODO(nakai): VP9 / AV1 も将来的に対応も考える
const unencryptedBytes = {
// I フレーム
key: 10,
// 非 I フレーム
delta: 3,
// オーディオ
undefined: 1,
};
function getCount(connectionId: string): number {
return countMap.get... |
async function encryptFunction(encodedFrame: Chunk, controller: TransformStreamDefaultController): Promise<void> {
const { connectionId, keyId, deriveKey } = getLatestSelfDeriveKey();
if (!deriveKey) {
return;
}
const currentCount = getCount(connectionId);
// count が 32 bit 以上の場合は停止する
if (currentCoun... | } | random_line_split |
e2ee.ts | Endian;
const textEncoder = new TextEncoder();
const textDecoder = new TextDecoder();
// VP8 のみ
// TODO(nakai): VP9 / AV1 も将来的に対応も考える
const unencryptedBytes = {
// I フレーム
key: 10,
// 非 I フレーム
delta: 3,
// オーディオ
undefined: 1,
};
function getCount(connectionId: string): number {
return countMap.get(conne... | ngth);
frameAdd.set(connectionIdData, header.byteLength + sframeHeader.byteLength);
return frameAdd;
}
async function encryptFunction(encodedFrame: Chunk, controller: TransformStreamDefaultController): Promise<void> {
const { connectionId, keyId, deriveKey } = getLatestSelfDeriveKey();
if (!deriveKey) {
re... | der.byteLength + sframeHeader.byteLength + connectionIdData.byteLength);
frameAdd.set(header, 0);
frameAdd.set(sframeHeader, header.byteLe | identifier_body |
e2ee.ts | littleEndian;
const textEncoder = new TextEncoder();
const textDecoder = new TextDecoder();
// VP8 のみ
// TODO(nakai): VP9 / AV1 も将来的に対応も考える
const unencryptedBytes = {
// I フレーム
key: 10,
// 非 I フレーム
delta: 3,
// オーディオ
undefined: 1,
};
function getCount(connectionId: string): number {
return countMap.get... | t("latest");
if (currentSelfDeriveKey) {
if (currentSelfDeriveKey["keyId"] < keyId) {
const nextSelfDeriveKey = { connectionId, keyId, deriveKey };
selfDeriveKeyMap.set("latest", nextSelfDeriveKey);
}
} else {
const nextSelfDeriveKey = { connectionId, keyId, deriveKey };
selfDeriveKeyMap... | fDeriveKeyMap.ge | identifier_name |
shuf.rs | #![crate_name = "shuf"]
/*
* This file is part of the uutils coreutils package.
*
* (c) Arcterus <arcterus@mail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#![feature(macro_rules)]
extern crate getopts;
extern crate lib... | {
RngFile(rand::reader::ReaderRng<io::File>),
RngDefault(rand::TaskRng),
}
impl WrappedRng {
fn next_u32(&mut self) -> u32 {
match self {
&WrappedRng::RngFile(ref mut r) => r.next_u32(),
&WrappedRng::RngDefault(ref mut r) => r.next_u32(),
}
}
}
fn shuf_lines(mu... | WrappedRng | identifier_name |
shuf.rs | #![crate_name = "shuf"]
/*
* This file is part of the uutils coreutils package.
*
* (c) Arcterus <arcterus@mail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#![feature(macro_rules)]
extern crate getopts;
extern crate lib... | Ok(range_inclusive(begin, end))
}
} | }; | random_line_split |
urls.py | """optboard URL Configuration | The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import... | random_line_split | |
topology.rs | //! Types and traits for handling the layers topology.
use std::ops::Range;
/// Common interface for topology of neuron organizations.
///
/// This trait is used to make the mapping between the inputs indexes to
/// their location in a topology of layer.
pub trait Topology {
/// Type of the iterator over neighbor... | )
)
}
fn radius<I: IntoIterator<Item=usize>>(&self, center: usize, nodes: I) -> f64 {
nodes.into_iter()
.map(|i| if i > center { i - center } else { center -i })
.fold(0, |m, i| if i > m { i } else { m })
as f64
}
fn surface(r: f64) -> f64 { 2.0*r... | { i + radius } | conditional_block |
topology.rs | //! Types and traits for handling the layers topology.
use std::ops::Range;
/// Common interface for topology of neuron organizations.
///
/// This trait is used to make the mapping between the inputs indexes to
/// their location in a topology of layer.
pub trait Topology {
/// Type of the iterator over neighbor... | let oldx = self.point.0;
self.point.0 += 1.0;
Some((oldx + self.y_offset) as usize)
}
}
impl TwoDimensions {
/// Create a new `TwoDimension` topology.
///
/// It represents a line of `width*height` inputs, with indexes
/// ranging from `0` to `width*height-1` included.
p... | self.point = (self.center.0 - dx, new_y)
}
self.y_offset += self.width;
self.max_x = self.center.0 + dx;
} | random_line_split |
topology.rs | //! Types and traits for handling the layers topology.
use std::ops::Range;
/// Common interface for topology of neuron organizations.
///
/// This trait is used to make the mapping between the inputs indexes to
/// their location in a topology of layer.
pub trait Topology {
/// Type of the iterator over neighbor... | (b: &mut Bencher) {
b.iter(|| {
let t = TwoDimensions::new(64, 32);
t.neighbors(256, 42.5).count()
});
}
} | neigh_iter_2d | identifier_name |
schema.ts | import {RawType} from '../src/types/schema'
export const imageType: RawType = {
type: 'image',
name: 'blockImage',
}
export const someObject: RawType = {
type: 'object',
name: 'someObject',
fields: [{type: 'string', name: 'color'}],
}
export const blockType: RawType = {
type: 'block',
name: 'block',
... | type: 'array',
name: 'body',
of: [blockType, someObject],
} | random_line_split | |
logger.service.ts | import { Injectable } from '@angular/core';
@Injectable()
export class LoggerService {
private logLevels: any = {
'ERROR' : 0,
'WARN': 1,// bin '01' Only MESSAGE lines
'INFO': 2, // bin '10' -- Only Info, Warn & Error Messages
'DEBUG': 4, // bin '100' -- Only DEBUG+ INFO + WARN + ERROR lines
... |
}
get logLevel() {
return this._logLevel
}
}
| {
throw new Error(`Invalid logLevel: ${l}, use one of: ${Object.keys(this.logLevels)}`)
} | conditional_block |
logger.service.ts | import { Injectable } from '@angular/core';
@Injectable()
export class LoggerService {
private logLevels: any = {
'ERROR' : 0,
'WARN': 1,// bin '01' Only MESSAGE lines
'INFO': 2, // bin '10' -- Only Info, Warn & Error Messages
'DEBUG': 4, // bin '100' -- Only DEBUG+ INFO + WARN + ERROR lines
... | }
} | random_line_split | |
logger.service.ts | import { Injectable } from '@angular/core';
@Injectable()
export class LoggerService {
private logLevels: any = {
'ERROR' : 0,
'WARN': 1,// bin '01' Only MESSAGE lines
'INFO': 2, // bin '10' -- Only Info, Warn & Error Messages
'DEBUG': 4, // bin '100' -- Only DEBUG+ INFO + WARN + ERROR lines
... |
private _l(level: string): boolean {
// this is a bitwise and so we print the log if its of certain type
return ((this.logLevels[this._logLevel] & this.logLevels[level]) === this.logLevels[level])
}
error(opts: any) {
this._l('ERROR') && console.error(opts)
}
info(opts: any) {
this._l('INFO... | { } | identifier_body |
logger.service.ts | import { Injectable } from '@angular/core';
@Injectable()
export class LoggerService {
private logLevels: any = {
'ERROR' : 0,
'WARN': 1,// bin '01' Only MESSAGE lines
'INFO': 2, // bin '10' -- Only Info, Warn & Error Messages
'DEBUG': 4, // bin '100' -- Only DEBUG+ INFO + WARN + ERROR lines
... | (opts: any) {
this._l('ERROR') && console.error(opts)
}
info(opts: any) {
this._l('INFO') && console.info(opts)
}
warn(opts: any) {
this._l('WARN') && console.warn(opts)
}
debug(opts: any) {
this._l('DEBUG') && console.debug(opts)
}
trace(opts: any) {
this._l('TRACE') && console.debu... | error | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.