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 |
|---|---|---|---|---|
subscriber_to_roscpp_publisher.rs | use crossbeam::channel::unbounded;
use std::process::Command;
mod util;
mod msg {
rosrust::rosmsg_include!(std_msgs / String);
}
#[test]
fn subscriber_to_roscpp_publisher() {
let _roscore = util::run_roscore_for(util::Language::Cpp, util::Feature::Subscriber);
let _publisher = util::ChildProcessTerminato... | })
.unwrap();
util::test_subscriber(rx, r"hello world (\d+)", true, 20);
assert_eq!(subscriber.publisher_count(), 1);
} | let (tx, rx) = unbounded();
rosrust::init("hello_world_listener");
let subscriber = rosrust::subscribe::<msg::std_msgs::String, _>("chatter", 100, move |data| {
tx.send(data.data).unwrap(); | random_line_split |
subscriber_to_roscpp_publisher.rs | use crossbeam::channel::unbounded;
use std::process::Command;
mod util;
mod msg {
rosrust::rosmsg_include!(std_msgs / String);
}
#[test]
fn | () {
let _roscore = util::run_roscore_for(util::Language::Cpp, util::Feature::Subscriber);
let _publisher = util::ChildProcessTerminator::spawn(
Command::new("rosrun").arg("roscpp_tutorials").arg("talker"),
);
let (tx, rx) = unbounded();
rosrust::init("hello_world_listener");
let subsc... | subscriber_to_roscpp_publisher | identifier_name |
subscriber_to_roscpp_publisher.rs | use crossbeam::channel::unbounded;
use std::process::Command;
mod util;
mod msg {
rosrust::rosmsg_include!(std_msgs / String);
}
#[test]
fn subscriber_to_roscpp_publisher() | {
let _roscore = util::run_roscore_for(util::Language::Cpp, util::Feature::Subscriber);
let _publisher = util::ChildProcessTerminator::spawn(
Command::new("rosrun").arg("roscpp_tutorials").arg("talker"),
);
let (tx, rx) = unbounded();
rosrust::init("hello_world_listener");
let subscrib... | identifier_body | |
fftPerformanceTesting.py |
label):
self.x = lengthx
self.y = lengthy
self.z = lengthz
self.batchsize = batchsize
self.device = device
self.inlayout = inlayout
self.outlayout = outlayout
self.placeness = placeness
self.precision = precision
... |
def expand_range(a_range):
return Range(a_range).expanded
def decode_parameter_problemsize(problemsize):
if not problemsize.count(None):
i = 0
while i < len(problemsize):
problemsize[i] = problemsize[i].split(':')
j = 0
while j < len(problemsize[i]):
... | self.current = self.current + self._stepAmount | identifier_body |
fftPerformanceTesting.py |
label):
self.x = lengthx
self.y = lengthy
self.z = lengthz
self.batchsize = batchsize
self.device = device
self.inlayout = inlayout
self.outlayout = outlayout
self.placeness = placeness
self.precision = precision
... |
elif library == 'cuFFT':
if sys.platform == 'win32':
exe = 'cuFFT-Client.exe'
elif sys.platform == 'linux2':
exe = 'cuFFT-Client'
else:
print 'ERROR: unknown library -- cannot determine executable name'
quit()
return exe
def max_mem_available_in_byt... | if sys.platform == 'win32':
exe = 'clFFT-client-2.5.0.exe'
elif sys.platform == 'linux2':
exe = 'clFFT-client-2.5.0' | conditional_block |
fftPerformanceTesting.py |
label):
self.x = lengthx
self.y = lengthy
self.z = lengthz
self.batchsize = batchsize
self.device = device
self.inlayout = inlayout
self.outlayout = outlayout
self.placeness = placeness
self.precision = precision
... | (exe, device):
arguments = [exe, '-i', device]
deviceInfo = subprocess.check_output(arguments, stderr=subprocess.STDOUT).split(os.linesep)
deviceInfo = itertools.ifilter( lambda x: x.count('MAX_MEM_ALLOC_SIZE'), deviceInfo)
deviceInfo = list(itertools.islice(deviceInfo, None))
maxMemoryAvailabl... | max_mem_available_in_bytes | identifier_name |
fftPerformanceTesting.py | = lengthz
self.batchsize = batchsize
self.device = device
self.inlayout = inlayout
self.outlayout = outlayout
self.placeness = placeness
self.precision = precision
self.label = label
def __str__(self):
return self.x + 'x' + self.y + 'x' + self.z + ':... | self.beta = str(beta)
self.order = order | random_line_split | |
mongodb-indexes.js | /*
* Copyright 2015 OpenCB
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in wr... | db.getCollection('sample').createIndex({"annotationSets.variableSetId": 1})
db.getCollection('sample').createIndex({"annotationSets.annotations.id": 1})
db.getCollection('sample').createIndex({"annotationSets.annotations.value": 1})
db.getCollection('sample').createIndex({"_studyId": 1})
db.getCollection('file').creat... |
db.getCollection('sample').createIndex({"name": 1}) | random_line_split |
.eslintrc.js | module.exports = {
"env": {
"es6": true,
"node": true
},
"globals": {
"expect": true,
"it": true,
"describe": true,
},
"extends": "eslint:recommended",
"parser": "babel-eslint",
"parserOptions": {
"ecmaFeatures": {
"experimentalObjectRest... | ]
}
}; | "error",
"always" | random_line_split |
MainTest.ts | import {
InteractiveWrapper,
InteractiveScene,
InteractiveButton,
InteractiveUser,
InteractiveGroup,
ChatWrapper,
ClientWrapper,
IButton,
IInputEvent,
IButtonInput,
CarinaWrapper
} from "../index";
const config = require("../../config/config.json");
class TestButton extends InteractiveButton {
counter: n... |
onMouseDown(event: IInputEvent<IButtonInput>, participant: InteractiveUser, beamControl: IButton) {
participant.move(this.group);
}
}
const wrapper = new InteractiveWrapper(config.interactiveOauth.access, config.interactiveId);
// wrapper.enableLogging();
const newScene = new InteractiveScene(wrapper, "newScene... | {
super(wrapper, id, text);
this.group = group;
} | identifier_body |
MainTest.ts | import {
InteractiveWrapper,
InteractiveScene,
InteractiveButton,
InteractiveUser,
InteractiveGroup,
ChatWrapper,
ClientWrapper,
IButton,
IInputEvent,
IButtonInput,
CarinaWrapper
} from "../index";
const config = require("../../config/config.json");
class TestButton extends InteractiveButton {
counter: n... | console.log("onResubscribeEvent", data.user.username);
});
carina.onSubscribeEvent.addCallback((data) => {
console.log("onSubscribeEvent", data.user.username);
});
carina.onSubscribeShareEvent.addCallback((data) => {
console.log("onSubscribeShareEvent", data.user.username);
});
carina.onHostEvent.addCallback((dat... | carina.onUnfollowEvent.addCallback((data) => {
console.log("onUnfollowEvent", data.user.username);
});
carina.onResubscribeEvent.addCallback((data) => { | random_line_split |
MainTest.ts | import {
InteractiveWrapper,
InteractiveScene,
InteractiveButton,
InteractiveUser,
InteractiveGroup,
ChatWrapper,
ClientWrapper,
IButton,
IInputEvent,
IButtonInput,
CarinaWrapper
} from "../index";
const config = require("../../config/config.json");
class TestButton extends InteractiveButton {
counter: n... | (event: IInputEvent<IButtonInput>, participant: InteractiveUser, beamControl: IButton) {
participant.move(this.group);
}
}
const wrapper = new InteractiveWrapper(config.interactiveOauth.access, config.interactiveId);
// wrapper.enableLogging();
const newScene = new InteractiveScene(wrapper, "newScene", "newScene")... | onMouseDown | identifier_name |
MainTest.ts | import {
InteractiveWrapper,
InteractiveScene,
InteractiveButton,
InteractiveUser,
InteractiveGroup,
ChatWrapper,
ClientWrapper,
IButton,
IInputEvent,
IButtonInput,
CarinaWrapper
} from "../index";
const config = require("../../config/config.json");
class TestButton extends InteractiveButton {
counter: n... |
});
(async () => {
await wrapper.start();
await chatWrapper.start();
})();
const carina = new CarinaWrapper();
carina.onFollowEvent.addCallback((data) => {
console.log("onFollowEvent", data.user.username);
});
carina.onUnfollowEvent.addCallback((data) => {
console.log("onUnfollowEvent", data.user.username);
})... | {
chatWrapper.sendChatMessage("Yes we are testing");
} | conditional_block |
form.ts | import { computed, inject, provide, reactive, readonly, ref, watch } from "vue";
import { Dialog, Notify } from "quasar";
import { emitComponentEvent } from "./event";
import { useComponentHttp } from "./http";
const SCENE_SUBMIT_CONFIRM = "submit_confirm";
const SCENE_SUBMIT_CANCEL = "submit_cancel";
const SCENE_SUBM... | } | random_line_split | |
form.ts | import { computed, inject, provide, reactive, readonly, ref, watch } from "vue";
import { Dialog, Notify } from "quasar";
import { emitComponentEvent } from "./event";
import { useComponentHttp } from "./http";
const SCENE_SUBMIT_CONFIRM = "submit_confirm";
const SCENE_SUBMIT_CANCEL = "submit_cancel";
const SCENE_SUBM... | (val) => {
updateForm(props.name, val);
if (emit) {
emit("input", val);
}
}
);
watch(
() => form.data[props.name],
(val) => (value.value = val)
);
}
}
const errors = computed(() => {
let errors = [];
Object.ke... | {
const form: any = inject(FORM_PROVIDE_KEY);
const initForm: Function = inject(INIT_FORM_PROVIDE_KEY);
const updateForm: Function = inject(UPDATE_FORM_PROVIDE_KEY);
const resetForm: Function = inject(RESET_FORM_PROVIDE_KEY);
const submitForm: Function = inject(SUBMIT_FORM_PROVIDE_KEY);
const value = ref(p... | identifier_body |
form.ts | import { computed, inject, provide, reactive, readonly, ref, watch } from "vue";
import { Dialog, Notify } from "quasar";
import { emitComponentEvent } from "./event";
import { useComponentHttp } from "./http";
const SCENE_SUBMIT_CONFIRM = "submit_confirm";
const SCENE_SUBMIT_CANCEL = "submit_cancel";
const SCENE_SUBM... | else {
return confirm();
}
};
const submitForm = async () => {
const confirm = async () => {
try {
form.errors = {};
form.processing = true;
const { data } = await http({
url: form.url,
method: form.method,
data: form.data,
});
... | {
Dialog.create({
message: props.messages[SCENE_RESET_CONFIRM],
cancel: true,
})
.onOk(confirm)
.onCancel(cancel)
.onDismiss(cancel);
} | conditional_block |
form.ts | import { computed, inject, provide, reactive, readonly, ref, watch } from "vue";
import { Dialog, Notify } from "quasar";
import { emitComponentEvent } from "./event";
import { useComponentHttp } from "./http";
const SCENE_SUBMIT_CONFIRM = "submit_confirm";
const SCENE_SUBMIT_CANCEL = "submit_cancel";
const SCENE_SUBM... | (props) {
const http = useComponentHttp();
if (useFormCallback) return useFormCallback(props, { http });
const defaultFormData = reactive({});
const form = reactive({
id: props.id,
url: props.url || location.href,
method: props.method || "POST",
processing: false,
errors: {},
data: {},... | makeForm | identifier_name |
waitBatcher.ts | // Copyright 2019-2020 Signal Messenger, LLC
// SPDX-License-Identifier: AGPL-3.0-only
import PQueue from 'p-queue';
import { sleep } from './sleep';
declare global {
interface Window {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
waitBatchers: Array<BatcherType<any>>;
waitForAllWaitB... | item.reject(error);
}
});
}
});
}
function _makeExplodedPromise(): ExplodedPromiseType {
let resolve;
let reject;
const promise = new Promise((resolveParam, rejectParam) => {
resolve = resolveParam;
reject = rejectParam;
});
return { promise... | {
let waitBatcher: BatcherType<ItemType>;
let timeout: NodeJS.Timeout | null;
let items: Array<ItemHolderType<ItemType>> = [];
const queue = new PQueue({ concurrency: 1, timeout: 1000 * 60 * 2 });
function _kickBatchOff() {
const itemsRef = items;
items = [];
queue.add(async () => {
try {
... | identifier_body |
waitBatcher.ts | // Copyright 2019-2020 Signal Messenger, LLC
// SPDX-License-Identifier: AGPL-3.0-only
import PQueue from 'p-queue';
import { sleep } from './sleep';
declare global {
interface Window {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
waitBatchers: Array<BatcherType<any>>;
waitForAllWaitB... |
}
function unregister() {
window.waitBatchers = window.waitBatchers.filter(
item => item !== waitBatcher
);
}
waitBatcher = {
add,
anyPending,
onIdle,
unregister,
};
window.waitBatchers.push(waitBatcher);
return waitBatcher;
}
| {
if (queue.size > 0 || queue.pending > 0) {
// eslint-disable-next-line no-await-in-loop
await queue.onIdle();
}
if (items.length > 0) {
// eslint-disable-next-line no-await-in-loop
await sleep(options.wait * 2);
}
} | conditional_block |
waitBatcher.ts | // Copyright 2019-2020 Signal Messenger, LLC
// SPDX-License-Identifier: AGPL-3.0-only
import PQueue from 'p-queue';
import { sleep } from './sleep';
declare global {
interface Window {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
waitBatchers: Array<BatcherType<any>>;
waitForAllWaitB... | () {
window.waitBatchers = window.waitBatchers.filter(
item => item !== waitBatcher
);
}
waitBatcher = {
add,
anyPending,
onIdle,
unregister,
};
window.waitBatchers.push(waitBatcher);
return waitBatcher;
}
| unregister | identifier_name |
waitBatcher.ts | // Copyright 2019-2020 Signal Messenger, LLC | // SPDX-License-Identifier: AGPL-3.0-only
import PQueue from 'p-queue';
import { sleep } from './sleep';
declare global {
interface Window {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
waitBatchers: Array<BatcherType<any>>;
waitForAllWaitBatchers: () => Promise<unknown>;
}
}
windo... | random_line_split | |
simple.rs | use common::{EmailAddress, AddrError};
/// Performs a dead-simple parse of an email address.
pub fn parse(input: &str) -> Result<EmailAddress, AddrError> {
if input.is_empty() {
return Err(AddrError { msg: "empty string is not valid".to_string() });
}
let parts: Vec<&str> = input.rsplitn(1, '@').c... |
if parts[1].is_empty() {
return Err(AddrError { msg: "empty string is not valid for domain part".to_string() });
}
Ok(EmailAddress {
local: parts[1].to_string(),
domain: parts[0].to_string()
})
}
#[cfg(test)]
mod test {
use super::*;
use common::{EmailAddress};
#... | {
return Err(AddrError { msg: "empty string is not valid for local part".to_string() });
} | conditional_block |
simple.rs | use common::{EmailAddress, AddrError};
/// Performs a dead-simple parse of an email address.
pub fn parse(input: &str) -> Result<EmailAddress, AddrError> {
if input.is_empty() {
return Err(AddrError { msg: "empty string is not valid".to_string() });
}
let parts: Vec<&str> = input.rsplitn(1, '@').c... | if parts[1].is_empty() {
return Err(AddrError { msg: "empty string is not valid for domain part".to_string() });
}
Ok(EmailAddress {
local: parts[1].to_string(),
domain: parts[0].to_string()
})
}
#[cfg(test)]
mod test {
use super::*;
use common::{EmailAddress};
#[t... | return Err(AddrError { msg: "empty string is not valid for local part".to_string() });
}
| random_line_split |
simple.rs | use common::{EmailAddress, AddrError};
/// Performs a dead-simple parse of an email address.
pub fn parse(input: &str) -> Result<EmailAddress, AddrError> |
#[cfg(test)]
mod test {
use super::*;
use common::{EmailAddress};
#[test]
fn test_simple_parse() {
assert_eq!(
parse("someone@example.com").unwrap(),
EmailAddress {
local: "someone".to_string(),
domain: "example.com".to_s... | {
if input.is_empty() {
return Err(AddrError { msg: "empty string is not valid".to_string() });
}
let parts: Vec<&str> = input.rsplitn(1, '@').collect();
if parts[0].is_empty() {
return Err(AddrError { msg: "empty string is not valid for local part".to_string() });
}
if parts[1... | identifier_body |
simple.rs | use common::{EmailAddress, AddrError};
/// Performs a dead-simple parse of an email address.
pub fn parse(input: &str) -> Result<EmailAddress, AddrError> {
if input.is_empty() {
return Err(AddrError { msg: "empty string is not valid".to_string() });
}
let parts: Vec<&str> = input.rsplitn(1, '@').c... | () {
assert_eq!(
parse("someone@example.com").unwrap(),
EmailAddress {
local: "someone".to_string(),
domain: "example.com".to_string()
}
);
}
}
| test_simple_parse | identifier_name |
MenuBarItemStylesExample.py | from muntjac.ui.vertical_layout import VerticalLayout
from muntjac.ui.menu_bar import MenuBar, ICommand
from muntjac.terminal.external_resource import ExternalResource
class MenuBarItemStylesExample(VerticalLayout):
def __init__(self):
super(MenuBarItemStylesExample, self).__init__()
self._menub... | edit.addItem('Undo', menuCommand)
edit.addItem('Redo', menuCommand).setEnabled(False)
edit.addSeparator()
edit.addItem('Cut', menuCommand)
edit.addItem('Copy', menuCommand)
edit.addItem('Paste', menuCommand)
edit.addSeparator()
find = edit.addItem('Find/R... | f.addItem('Save All', menuCommand)
edit = self._menubar.addItem('Edit', None) | random_line_split |
MenuBarItemStylesExample.py |
from muntjac.ui.vertical_layout import VerticalLayout
from muntjac.ui.menu_bar import MenuBar, ICommand
from muntjac.terminal.external_resource import ExternalResource
class MenuBarItemStylesExample(VerticalLayout):
def __init__(self):
| f.addItem('Save', menuCommand)
f.addItem('Save As...', menuCommand)
f.addItem('Save All', menuCommand)
edit = self._menubar.addItem('Edit', None)
edit.addItem('Undo', menuCommand)
edit.addItem('Redo', menuCommand).setEnabled(False)
edit.addSeparator()
edi... | super(MenuBarItemStylesExample, self).__init__()
self._menubar = MenuBar()
menuCommand = MenuCommand(self)
# Save reference to individual items so we can add sub-menu items to
# them
f = self._menubar.addItem('File', None)
newItem = f.addItem('New', None)
f.add... | identifier_body |
MenuBarItemStylesExample.py |
from muntjac.ui.vertical_layout import VerticalLayout
from muntjac.ui.menu_bar import MenuBar, ICommand
from muntjac.terminal.external_resource import ExternalResource
class MenuBarItemStylesExample(VerticalLayout):
def __init__(self):
super(MenuBarItemStylesExample, self).__init__()
self._menu... | (self, c):
self._c = c
def menuSelected(self, selectedItem):
er = ExternalResource('http://www.google.com')
self._c.getWindow().open(er)
class MenuCommand(ICommand):
def __init__(self, c):
self._c = c
def menuSelected(self, selectedItem):
self._c.getWindow().show... | __init__ | identifier_name |
vt.request.spec.ts | let req:VTRequest = new VTRequest();
req.amount = 11;
req.merchantTxnId = "jim1";
req.cardNumber = "4111111111111111";
req.expiryMonth = 10;
req.expiryYear = 2020;
req.zip = "H8P1K1"
let obj:any = req.getJSON();
expect(obj.merchantRefNum).toBe(req.merchantTxnId);
... | import { VTRequest } from "../app/domain/VTRequest";
describe("Unit: VTRequest object", function() {
it("should expect valid VTRequest.getJSON", function() {
| random_line_split | |
NonNCEPModel.py | import time
from bs4 import BeautifulSoup
import sys
if (sys.version_info > (3, 0)):
# Python 3 code in this block
import urllib.request as urllib2
else:
# Python 2 code in this block
import urllib2
import datetime, re, os
class NonNCEPModel:
'''''
Base Class for all Non-NCEP models.
'''''
def __init_... |
def getName(self):
return self.name | return | identifier_body |
NonNCEPModel.py | import time
from bs4 import BeautifulSoup
import sys
if (sys.version_info > (3, 0)):
# Python 3 code in this block
import urllib.request as urllib2
else:
# Python 2 code in this block
import urllib2
import datetime, re, os
class NonNCEPModel:
'''''
Base Class for all Non-NCEP models.
'''''
def __init_... |
def getForecastHourInt(self, filename, noPrefix = False):
fhour = self.getForecastHour(filename, noPrefix)
return int(fhour[1:])
def getForecastHour(self, fileName, noPrefix = False):
return ""
def getLastForecastHour(self):
return "000"
def getRun(self):
return
def getName(self):
... | return self.name | conditional_block |
NonNCEPModel.py | import time
from bs4 import BeautifulSoup
import sys
if (sys.version_info > (3, 0)):
# Python 3 code in this block
import urllib.request as urllib2
else:
# Python 2 code in this block
import urllib2
import datetime, re, os
class NonNCEPModel:
'''''
Base Class for all Non-NCEP models.
'''''
def | (self):
self.modelUrls = ''
self.isNCEPSource = False
return
'''''
Gets the previous forecast hour for a given model, and forecast hour.
'''''
def getPreviousTime(self, model, currentHour):
if currentHour == '000':
return '000'
defaultHours = self.getDefaultHours()
defaultHours... | __init__ | identifier_name |
NonNCEPModel.py | import time
from bs4 import BeautifulSoup
import sys
if (sys.version_info > (3, 0)):
# Python 3 code in this block
import urllib.request as urllib2
else:
# Python 2 code in this block
import urllib2
import datetime, re, os
class NonNCEPModel:
'''''
Base Class for all Non-NCEP models.
'''''
def __init_... | Intialze all of our models hour stamp data to defaults.
'''''
def getDefaultHours(self):
# Default times.
return self.defaultTimes
'''''
Intialze all of our models hour stamp data to defaults.
'''''
def getDefaultHours(self):
# Default times.
modelTimes = self.defaultTimes
return... | self.modelTimes = self.defaultTimes
return
''''' | random_line_split |
scroller.component.ts | import {
Component,
Input,
ElementRef,
Output,
EventEmitter,
Renderer2,
NgZone,
OnInit,
OnDestroy,
HostBinding,
ChangeDetectionStrategy
} from '@angular/core';
import { MouseEvent } from '../../events';
@Component({
selector: 'datatable-scroller',
template: ` <ng-content></ng-content> `,
h... | (offsetY: number): void {
if (this.parentElement) {
this.parentElement.scrollTop = offsetY;
}
}
onScrolled(event: MouseEvent): void {
const dom: Element = <Element>event.currentTarget;
requestAnimationFrame(() => {
this.scrollYPos = dom.scrollTop;
this.scrollXPos = dom.scrollLeft;... | setOffset | identifier_name |
scroller.component.ts | import {
Component,
Input,
ElementRef,
Output,
EventEmitter,
Renderer2,
NgZone,
OnInit,
OnDestroy,
HostBinding,
ChangeDetectionStrategy
} from '@angular/core';
import { MouseEvent } from '../../events';
@Component({
selector: 'datatable-scroller',
template: ` <ng-content></ng-content> `,
h... | direction = 'down';
} else if (this.scrollYPos > this.prevScrollYPos) {
direction = 'up';
}
this.scroll.emit({
direction,
scrollYPos: this.scrollYPos,
scrollXPos: this.scrollXPos
});
this.prevScrollYPos = this.scrollYPos;
this.prevScrollXPos = this.scrollXPos;
}... | let direction: string;
if (this.scrollYPos < this.prevScrollYPos) { | random_line_split |
scroller.component.ts | import {
Component,
Input,
ElementRef,
Output,
EventEmitter,
Renderer2,
NgZone,
OnInit,
OnDestroy,
HostBinding,
ChangeDetectionStrategy
} from '@angular/core';
import { MouseEvent } from '../../events';
@Component({
selector: 'datatable-scroller',
template: ` <ng-content></ng-content> `,
h... | else if (this.scrollYPos > this.prevScrollYPos) {
direction = 'up';
}
this.scroll.emit({
direction,
scrollYPos: this.scrollYPos,
scrollXPos: this.scrollXPos
});
this.prevScrollYPos = this.scrollYPos;
this.prevScrollXPos = this.scrollXPos;
}
}
| {
direction = 'down';
} | conditional_block |
reactquestionrating.tsx | import * as React from 'react';
import {SurveyQuestionElementBase} from "./reactquestionelement";
import {SurveyQuestionCommentItem} from "./reactquestioncomment";
import {QuestionRatingModel} from "../question_rating";
import {ItemValue} from "../itemvalue";
import {ReactQuestionFactory} from "./reactquestionfactory";... |
handleOnChange(event) {
this.question.value = event.target.value;
this.setState({ value: this.question.value });
}
render(): JSX.Element {
if (!this.question) return null;
var values = [];
var minText = this.question.minRateDescription ? this.renderLocString(this.que... | { return this.questionBase as QuestionRatingModel; } | identifier_body |
reactquestionrating.tsx | import * as React from 'react';
import {SurveyQuestionElementBase} from "./reactquestionelement";
import {SurveyQuestionCommentItem} from "./reactquestioncomment";
import {QuestionRatingModel} from "../question_rating";
import {ItemValue} from "../itemvalue";
import {ReactQuestionFactory} from "./reactquestionfactory";... | (): JSX.Element {
if (!this.question) return null;
var values = [];
var minText = this.question.minRateDescription ? this.renderLocString(this.question.locMinRateDescription) : null;
var maxText = this.question.maxRateDescription ? this.renderLocString(this.question.locMaxRateDescription... | render | identifier_name |
reactquestionrating.tsx | import * as React from 'react';
import {SurveyQuestionElementBase} from "./reactquestionelement";
import {SurveyQuestionCommentItem} from "./reactquestioncomment";
import {QuestionRatingModel} from "../question_rating";
import {ItemValue} from "../itemvalue";
import {ReactQuestionFactory} from "./reactquestionfactory";... | }
protected renderItem(key: string, item: ItemValue, minText: JSX.Element, maxText: JSX.Element): JSX.Element {
var isChecked = this.question.value == item.value;
var className = this.css.item;
if (isChecked) className += " active";
var itemText = this.renderLocString(item.locTex... | </div>
); | random_line_split |
lint-uppercase-variables.rs | // Copyright 2012-2014 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-MI... | () {
let Test: usize = 0; //~ ERROR variable `Test` should have a snake case name such as `test`
println!("{}", Test);
let mut f = File::open(&Path::new("something.txt"));
let mut buff = [0u8; 16];
match f.read(&mut buff) {
Ok(cnt) => println!("read this many bytes: {}", cnt),
Err(I... | main | identifier_name |
lint-uppercase-variables.rs | // Copyright 2012-2014 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-MI... | }
test(1);
let _ = Something { X: 0 };
} | Err(IoError{ kind: EndOfFile, .. }) => println!("Got end of file: {:?}", EndOfFile),
//~^ ERROR variable `EndOfFile` should have a snake case name such as `end_of_file`
//~^^ WARN `EndOfFile` is named the same as one of the variants of the type `std::old_io::IoErrorKind` | random_line_split |
index.spec.js | var dotBeautify = require('../index.js');
var fs = require('fs');
var chai = require('chai');
var assert = chai.assert;
var expect = chai.expect;
var setup = 'function start (resp)\
{\
resp.writeHead(200, {"Content-Type": "text/html"\
});\
fs.readFile(filename, "utf8", function(err, data) {\
if (e... |
});
it('Should throw an error upon not passing any directories in', function() {
expect(function() {
dotBeautify.beautify([],{});
}).to.throw(Error);
});
});
| {
return true;
} | conditional_block |
index.spec.js | var dotBeautify = require('../index.js');
var fs = require('fs');
var chai = require('chai');
var assert = chai.assert;
var expect = chai.expect;
var setup = 'function start (resp)\
{\
resp.writeHead(200, {"Content-Type": "text/html"\
});\
fs.readFile(filename, "utf8", function(err, data) {\
if (e... | });
}); | it('Should throw an error upon not passing any directories in', function() {
expect(function() {
dotBeautify.beautify([],{});
}).to.throw(Error); | random_line_split |
piwigo_symlink_local_album.py | import pathlib
import argparse
import os
IMGFORMAT = 'JPG'
if __name__ == '__main__':
| piwigo_album_dir = f'{piwigo_dir}/galleries/{src_album}'
if not os.path.exists(piwigo_album_dir):
sh(f'mkdir -p {piwigo_album_dir}')
sh(f'ln -s {albums_root}/{src_album}/{IMGFORMAT}/{imgfilename} {piwigo_album_dir}')
def is_expected_imgformat(imgfilename):
return imgfil... | parser = argparse.ArgumentParser(description='Symlink a local album directory to the "galleries" subdirectory in a local Piwigo instance.')
parser.add_argument('src_album', type=str, help='Location of album to symlink, relative to ALBUMS_ROOT')
parser.add_argument('piwigo_dir', type=str, help='Location of local... | conditional_block |
piwigo_symlink_local_album.py | import pathlib
import argparse
import os
IMGFORMAT = 'JPG'
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Symlink a local album directory to the "galleries" subdirectory in a local Piwigo instance.')
parser.add_argument('src_album', type=str, help='Location of album to symlink, relat... |
imgs = list(filter(lambda file: is_expected_imgformat(file) and is_in_range(file), os.listdir(f'{albums_root}/{src_album}/{IMGFORMAT}')))
for img in imgs:
symlink_img(img) |
def is_in_range(imgfilename):
imgnum = int(imgfilename.split('.')[0].split('_')[-1])
return minrange <= imgnum <= maxrange | random_line_split |
piwigo_symlink_local_album.py | import pathlib
import argparse
import os
IMGFORMAT = 'JPG'
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Symlink a local album directory to the "galleries" subdirectory in a local Piwigo instance.')
parser.add_argument('src_album', type=str, help='Location of album to symlink, relat... | (imgfilename):
imgnum = int(imgfilename.split('.')[0].split('_')[-1])
return minrange <= imgnum <= maxrange
imgs = list(filter(lambda file: is_expected_imgformat(file) and is_in_range(file), os.listdir(f'{albums_root}/{src_album}/{IMGFORMAT}')))
for img in imgs:
symlink_img(img)
| is_in_range | identifier_name |
piwigo_symlink_local_album.py | import pathlib
import argparse
import os
IMGFORMAT = 'JPG'
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Symlink a local album directory to the "galleries" subdirectory in a local Piwigo instance.')
parser.add_argument('src_album', type=str, help='Location of album to symlink, relat... |
def is_expected_imgformat(imgfilename):
return imgfilename.split('.')[-1].lower() == IMGFORMAT.lower()
def is_in_range(imgfilename):
imgnum = int(imgfilename.split('.')[0].split('_')[-1])
return minrange <= imgnum <= maxrange
imgs = list(filter(lambda file: is_expected_imgformat... | piwigo_album_dir = f'{piwigo_dir}/galleries/{src_album}'
if not os.path.exists(piwigo_album_dir):
sh(f'mkdir -p {piwigo_album_dir}')
sh(f'ln -s {albums_root}/{src_album}/{IMGFORMAT}/{imgfilename} {piwigo_album_dir}') | identifier_body |
full-calendar.js | $(document).ready(function() {
/* initialize the external events
-----------------------------------------------------------------*/
$('#external-events div.external-event').each(function() {
// create an Event Object (http://arshaw.com/fullcalendar/docs/event_data/Event_Object/)
// it doesn'... | title: 'Lunch',
start: new Date(y, m, d, 12, 0),
end: new Date(y, m, d, 14, 0),
allDay: false
},
{
title: 'Birthday Party',
start: new Date(y, m, d+1, 19, 0),
end: new Date(y, m, d+1, ... | title: 'Meeting',
start: new Date(y, m, d, 10, 30),
allDay: false
},
{ | random_line_split |
full-calendar.js | $(document).ready(function() {
/* initialize the external events
-----------------------------------------------------------------*/
$('#external-events div.external-event').each(function() {
// create an Event Object (http://arshaw.com/fullcalendar/docs/event_data/Event_Object/)
// it doesn'... |
},
events: [
{
title: 'All Day Event',
start: new Date(y, m, 1)
},
{
title: 'Long Event',
start: new Date(y, m, d-5),
end: new Date(y, m, d-2)
},
{
... | {
// if so, remove the element from the "Draggable Events" list
$(this).remove();
} | conditional_block |
mod.rs | /// Shareable data structures.
pub mod directory;
pub use self::shared_vec::*;
mod shared_vec;
use libc::{self, c_void, close, ftruncate, mmap, munmap, shm_open, shm_unlink};
use std::ffi::CString;
use std::io::Error;
use std::ptr;
use utils::PAGE_SIZE;
struct SharedMemory<T> {
pub mem: *mut T,
name: CString,
... | let size = self.size;
let _ret = munmap(self.mem as *mut c_void, size); // Unmap pages.
// Record munmap failure.
let shm_ret = shm_unlink(self.name.as_ptr());
assert!(shm_ret == 0, "Could not unlink shared mem... | fn drop(&mut self) {
unsafe { | random_line_split |
mod.rs | /// Shareable data structures.
pub mod directory;
pub use self::shared_vec::*;
mod shared_vec;
use libc::{self, c_void, close, ftruncate, mmap, munmap, shm_open, shm_unlink};
use std::ffi::CString;
use std::io::Error;
use std::ptr;
use utils::PAGE_SIZE;
struct SharedMemory<T> {
pub mem: *mut T,
name: CString,
... |
close(fd);
SharedMemory {
mem: address as *mut T,
name: name,
size: size,
}
}
| {
let err_string = CString::new("mmap failed").unwrap();
libc::perror(err_string.as_ptr());
panic!("Could not mmap shared region");
} | conditional_block |
mod.rs | /// Shareable data structures.
pub mod directory;
pub use self::shared_vec::*;
mod shared_vec;
use libc::{self, c_void, close, ftruncate, mmap, munmap, shm_open, shm_unlink};
use std::ffi::CString;
use std::io::Error;
use std::ptr;
use utils::PAGE_SIZE;
struct | <T> {
pub mem: *mut T,
name: CString,
size: usize,
}
impl<T> Drop for SharedMemory<T> {
fn drop(&mut self) {
unsafe {
let size = self.size;
let _ret = munmap(self.mem as *mut c_void, size); // Unmap pages.
// ... | SharedMemory | identifier_name |
phrase_query.rs | use schema::Term;
use query::Query;
use core::searcher::Searcher;
use super::PhraseWeight;
use std::any::Any;
use query::Weight;
use Result;
/// `PhraseQuery` matches a specific sequence of word.
/// For instance the phrase query for `"part time"` will match
/// the sentence
///
/// **Alan just got a part time job.**... | (phrase_terms: Vec<Term>) -> PhraseQuery {
assert!(phrase_terms.len() > 1);
PhraseQuery { phrase_terms: phrase_terms }
}
}
| from | identifier_name |
phrase_query.rs | use schema::Term;
use query::Query;
use core::searcher::Searcher;
use super::PhraseWeight; | use query::Weight;
use Result;
/// `PhraseQuery` matches a specific sequence of word.
/// For instance the phrase query for `"part time"` will match
/// the sentence
///
/// **Alan just got a part time job.**
///
/// On the other hand it will not match the sentence.
///
/// **This is my favorite part of the job.**
//... | use std::any::Any; | random_line_split |
amp-instagram.js | /**
* Copyright 2015 The AMP HTML Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless require... | () {
const placeholder = this.win.document.createElement('div');
placeholder.setAttribute('placeholder', '');
const image = this.win.document.createElement('amp-img');
image.setAttribute('noprerender', '');
// This will redirect to the image URL. By experimentation this is
// always the same URL... | createPlaceholderCallback | identifier_name |
amp-instagram.js | /**
* Copyright 2015 The AMP HTML Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless require... |
}
/** @override */
unlayoutOnPause() {
return true;
}
/** @override */
unlayoutCallback() {
if (this.iframe_) {
removeElement(this.iframe_);
this.iframe_ = null;
this.iframePromise_ = null;
}
if (this.unlistenMessage_) {
this.unlistenMessage_();
}
return tr... | {
const height = data['details']['height'];
this.getVsync().measure(() => {
if (this.iframe_ && this.iframe_./*OK*/offsetHeight !== height) {
this./*OK*/changeHeight(height);
}
});
} | conditional_block |
amp-instagram.js | /**
* Copyright 2015 The AMP HTML Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless require... | });
}
}
/** @override */
unlayoutOnPause() {
return true;
}
/** @override */
unlayoutCallback() {
if (this.iframe_) {
removeElement(this.iframe_);
this.iframe_ = null;
this.iframePromise_ = null;
}
if (this.unlistenMessage_) {
this.unlistenMessage_();
... | {
if (event.origin != 'https://www.instagram.com' ||
event.source != this.iframe_.contentWindow) {
return;
}
const eventData = getData(event);
if (!eventData || !(isObject(eventData)
|| startsWith(/** @type {string} */ (eventData), '{'))) {
return; // Doesn't look like JSON.
... | identifier_body |
amp-instagram.js | /**
* Copyright 2015 The AMP HTML Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless require... | * @override
*/
preconnectCallback(opt_onLayout) {
// See
// https://instagram.com/developer/embedding/?hl=en
this.preconnect.url('https://www.instagram.com', opt_onLayout);
// Host instagram used for image serving. While the host name is
// funky this appears to be stable in the post-domain sh... | }
/**
* @param {boolean=} opt_onLayout | random_line_split |
consts.rs | ]
static_assert_size!(Const<'_>, 48);
impl<'tcx> Const<'tcx> {
/// Literals and const generic parameters are eagerly converted to a constant, everything else
/// becomes `Unevaluated`.
pub fn from_anon_const(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> &'tcx Self {
Self::from_opt_const_arg_anon_const(... | let typeck_root_def_id = tcx.typeck_root_def_id(def_id.to_def_id());
let parent_substs =
tcx.erase_regions(InternalSubsts::identity_for_item(tcx, typeck_root_def_id));
let substs =
InlineConstSubsts::new(tcx, InlineConstSubstsParts ... | {
debug!("Const::from_inline_const(def_id={:?})", def_id);
let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
let body_id = match tcx.hir().get(hir_id) {
hir::Node::AnonConst(ac) => ac.body,
_ => span_bug!(
tcx.def_span(def_id.to_def_id()),
... | identifier_body |
consts.rs | ::from_anon_const(def={:?})", def);
let hir_id = tcx.hir().local_def_id_to_hir_id(def.did);
let body_id = match tcx.hir().get(hir_id) {
hir::Node::AnonConst(ac) => ac.body,
_ => span_bug!(
tcx.def_span(def.did.to_def_id()),
"from_anon_const can o... | random_line_split | ||
consts.rs | ]
static_assert_size!(Const<'_>, 48);
impl<'tcx> Const<'tcx> {
/// Literals and const generic parameters are eagerly converted to a constant, everything else
/// becomes `Unevaluated`.
pub fn from_anon_const(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> &'tcx Self {
Self::from_opt_const_arg_anon_const(... | (&self, tcx: TyCtxt<'tcx>, param_env: ParamEnv<'tcx>) -> Option<u64> {
self.val | try_eval_usize | identifier_name |
jit.py | '''
Notice:
1. The function for jit should locate in mfs
2. For the usage of jit types and signatures, please refer Numba documentation <http://numba.github.com/numba-doc/0.10/index.html>
'''
from dpark import _ctx as dpark, jit, autojit
import numpy
@jit('f8(f8[:])')
def add1(x):
sum = 0.0
for i ... |
return sum
rdd = dpark.makeRDD(range(0, 10)).map(lambda x: numpy.arange(x*1e7, (x+1)*1e7))
print rdd.map(add1).collect()
print rdd.map(add2).collect()
print rdd.map(add3).collect()
| sum += i*x[i] | conditional_block |
jit.py | '''
Notice:
1. The function for jit should locate in mfs
2. For the usage of jit types and signatures, please refer Numba documentation <http://numba.github.com/numba-doc/0.10/index.html>
'''
from dpark import _ctx as dpark, jit, autojit
import numpy
@jit('f8(f8[:])')
def add1(x):
sum = 0.0
for i ... | (x):
sum = 0.0
for i in xrange(x.shape[0]):
sum += i*x[i]
return sum
rdd = dpark.makeRDD(range(0, 10)).map(lambda x: numpy.arange(x*1e7, (x+1)*1e7))
print rdd.map(add1).collect()
print rdd.map(add2).collect()
print rdd.map(add3).collect()
| add3 | identifier_name |
jit.py | '''
Notice:
1. The function for jit should locate in mfs
2. For the usage of jit types and signatures, please refer Numba documentation <http://numba.github.com/numba-doc/0.10/index.html>
'''
from dpark import _ctx as dpark, jit, autojit
import numpy
@jit('f8(f8[:])')
def add1(x):
sum = 0.0
for i ... | sum += i*x[i]
return sum
rdd = dpark.makeRDD(range(0, 10)).map(lambda x: numpy.arange(x*1e7, (x+1)*1e7))
print rdd.map(add1).collect()
print rdd.map(add2).collect()
print rdd.map(add3).collect() |
def add3(x):
sum = 0.0
for i in xrange(x.shape[0]): | random_line_split |
jit.py | '''
Notice:
1. The function for jit should locate in mfs
2. For the usage of jit types and signatures, please refer Numba documentation <http://numba.github.com/numba-doc/0.10/index.html>
'''
from dpark import _ctx as dpark, jit, autojit
import numpy
@jit('f8(f8[:])')
def add1(x):
|
@autojit
def add2(x):
sum = 0.0
for i in xrange(x.shape[0]):
sum += i*x[i]
return sum
def add3(x):
sum = 0.0
for i in xrange(x.shape[0]):
sum += i*x[i]
return sum
rdd = dpark.makeRDD(range(0, 10)).map(lambda x: numpy.arange(x*1e7, (x+1)*1e7))
print rdd.map(add1).collect()
pr... | sum = 0.0
for i in xrange(x.shape[0]):
sum += i*x[i]
return sum | identifier_body |
speech.py | # Copyright (C) 2011 One Laptop Per Child
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distribu... |
def say_selected_text(self):
clipboard = Gtk.Clipboard.get(Gdk.SELECTION_PRIMARY)
clipboard.request_text(self.__primary_selection_cb, None)
def pause(self):
self._player.pause_sound_device()
def restart(self):
self._player.restart_sound_device()
def stop(self):
... | self._player.speak(self._pitch, self._rate, self._voice_name, text) | conditional_block |
speech.py | # Copyright (C) 2011 One Laptop Per Child
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distribu... | (self):
self._player.pause_sound_device()
def restart(self):
self._player.restart_sound_device()
def stop(self):
self._player.stop_sound_device()
def __primary_selection_cb(self, clipboard, text, user_data):
self.say_text(text)
def save(self):
client = GConf.C... | pause | identifier_name |
speech.py | # Copyright (C) 2011 One Laptop Per Child
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distribu... |
is_paused = GObject.property(type=bool, getter=get_is_paused,
setter=None, default=False)
def get_pitch(self):
return self._pitch
def get_rate(self):
return self._rate
def set_pitch(self, pitch):
self._pitch = pitch
self.save()
def set_rate(self, rat... | return self._is_paused | identifier_body |
speech.py | # Copyright (C) 2011 One Laptop Per Child
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distribu... | language = language_location.split('_')[0]
# if the language is es but not es_es default to es_la (latin voice)
if language == 'es' and language_location != 'es_es':
language_location = 'es_la'
best = voices.get(language_location) or voices.get(language) \
or... |
locale = os.environ.get('LANG', '')
language_location = locale.split('.', 1)[0].lower() | random_line_split |
readable.js | /*
* Copyright (c) 2015 by Greg Reimer <gregreimer@gmail.com>
* MIT License. See license.txt for more info.
*/
var stream = require('stream')
, util = require('util')
, co = require('co')
, unresolved = require('./unresolved')
// -----------------------------------------------------
function Readable(opts, ... |
});
}
co(sender.bind(this, output))
.then(function() { self.push(null); })
.catch(function(err) { self.emit('error', err); });
}
util.inherits(Readable, stream.Readable);
Readable.prototype._read = function() {
this._ponySending.resolve();
};
// -----------------------------------------------------
m... | {
self._ponySending = unresolved();
} | conditional_block |
readable.js | /*
* Copyright (c) 2015 by Greg Reimer <gregreimer@gmail.com>
* MIT License. See license.txt for more info.
*/
var stream = require('stream')
, util = require('util')
, co = require('co')
, unresolved = require('./unresolved')
// -----------------------------------------------------
function | (opts, sender) {
stream.Readable.call(this, opts);
this._ponySending = unresolved();
var self = this;
function output(data, enc) {
return self._ponySending.then(function() {
if (!self.push(data, enc)) {
self._ponySending = unresolved();
}
});
}
co(sender.bind(this, output))
.th... | Readable | identifier_name |
readable.js | var stream = require('stream')
, util = require('util')
, co = require('co')
, unresolved = require('./unresolved')
// -----------------------------------------------------
function Readable(opts, sender) {
stream.Readable.call(this, opts);
this._ponySending = unresolved();
var self = this;
function out... | /*
* Copyright (c) 2015 by Greg Reimer <gregreimer@gmail.com>
* MIT License. See license.txt for more info.
*/
| random_line_split | |
readable.js | /*
* Copyright (c) 2015 by Greg Reimer <gregreimer@gmail.com>
* MIT License. See license.txt for more info.
*/
var stream = require('stream')
, util = require('util')
, co = require('co')
, unresolved = require('./unresolved')
// -----------------------------------------------------
function Readable(opts, ... |
util.inherits(Readable, stream.Readable);
Readable.prototype._read = function() {
this._ponySending.resolve();
};
// -----------------------------------------------------
module.exports = Readable;
| {
stream.Readable.call(this, opts);
this._ponySending = unresolved();
var self = this;
function output(data, enc) {
return self._ponySending.then(function() {
if (!self.push(data, enc)) {
self._ponySending = unresolved();
}
});
}
co(sender.bind(this, output))
.then(function() {... | identifier_body |
state.js | /*
* SonarQube
* Copyright (C) 2009-2016 SonarSource SA
* mailto:contact AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License... |
export default Backbone.Model.extend({
defaults: function () {
return {
page: 1,
maxResultsReached: false,
query: {},
facets: []
};
},
nextPage: function () {
var page = this.get('page');
this.set({ page: page + 1 });
},
clearQuery: function (query) {
var q = {};... | * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
import _ from 'underscore';
import Backbone from 'backbone'; | random_line_split |
state.js | /*
* SonarQube
* Copyright (C) 2009-2016 SonarSource SA
* mailto:contact AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License... |
});
return q;
},
_areQueriesEqual: function (a, b) {
var equal = Object.keys(a).length === Object.keys(b).length;
Object.keys(a).forEach(function (key) {
equal = equal && a[key] === b[key];
});
return equal;
},
updateFilter: function (obj, options) {
var oldQuery = this.get(... | {
q[key] = query[key];
} | conditional_block |
cogroup.rs | for each key.
//!
//! ```ignore
//! stream.group(|key, vals, output| {
//! let (mut max_val, mut max_wgt) = vals.peek().unwrap();
//! for (val, wgt) in vals {
//! if wgt > max_wgt {
//! max_wgt = wgt;
//! max_val = val;
//! }
//! }
//! output.push((max_val.clone(... | // create an exchange channel based on the supplied Fn(&D1)->u64.
let exch1 = Exchange::new(move |&((ref k, _),_)| key_1(k).as_u64());
let exch2 = Exchange::new(move |&((ref k, _),_)| key_2(k).as_u64());
let mut sorter1 = LSBRadixSorter::new();
let mut sorter2 = LSBRadixSorter::... | {
let mut source1 = Trace::new(look(0));
let mut source2 = Trace::new(look(0));
let mut result = Trace::new(look(0));
// A map from times to received (key, val, wgt) triples.
let mut inputs1 = Vec::new();
let mut inputs2 = Vec::new();
// A map from times to a l... | identifier_body |
cogroup.rs | LookG: Fn(u64)->Look,
Logic: Fn(&K, &mut CollectionIterator<DifferenceIterator<V1>>, &mut CollectionIterator<DifferenceIterator<V2>>, &mut Vec<(V3, i32)>)+'static,
Reduc: Fn(&K, &V3)->D+'static,
>
(&self, other: &Collection<G, (K, V2)>, key_h: KH, reduc: Reduc, look: LookG, logic: Logic)... | {
// println!("group2");
result.set_difference(index.time(), accumulation);
} | conditional_block | |
cogroup.rs | for each key.
//!
//! ```ignore
//! stream.group(|key, vals, output| {
//! let (mut max_val, mut max_wgt) = vals.peek().unwrap();
//! for (val, wgt) in vals {
//! if wgt > max_wgt {
//! max_wgt = wgt;
//! max_val = val;
//! }
//! }
//! output.push((max_val.clone(... | let mut sorted = sorter2.finish(&|x| key_h(&(x.0).0));
let result = Compact::from_radix(&mut sorted, &|k| key_h(k));
sorted.truncate(256);
sorter2.recycle(sorted);
result
}
... | } | random_line_split |
cogroup.rs | for each key.
//!
//! ```ignore
//! stream.group(|key, vals, output| {
//! let (mut max_val, mut max_wgt) = vals.peek().unwrap();
//! for (val, wgt) in vals {
//! if wgt > max_wgt {
//! max_wgt = wgt;
//! max_val = val;
//! }
//! }
//! output.push((max_val.clone(... | <
D: Data,
V2: Data+Default,
V3: Data+Default,
U: Unsigned+Default,
KH: Fn(&K)->U+'static,
Look: Lookup<K, Offset>+'static,
LookG: Fn(u64)->Look,
Logic: Fn(&K, &mut CollectionIterator<V1>, &mut CollectionIterator<V2>, &mut Vec<(V3, i32)>)... | cogroup_by_inner | identifier_name |
functions.ts | import { chunk, flatten, initial, startCase, uniqBy } from 'lodash';
import { ALIGNMENTS, AGGREGATIONS, SYSTEM_LABELS } from './constants';
import CloudMonitoringDatasource from './datasource';
import { TemplateSrv, getTemplateSrv } from '@grafana/runtime';
import { MetricDescriptor, ValueTypes, MetricKind, AlignmentTy... | return message;
}; | } catch (err) {
error.error = err;
}
} | random_line_split |
functions.ts | import { chunk, flatten, initial, startCase, uniqBy } from 'lodash';
import { ALIGNMENTS, AGGREGATIONS, SYSTEM_LABELS } from './constants';
import CloudMonitoringDatasource from './datasource';
import { TemplateSrv, getTemplateSrv } from '@grafana/runtime';
import { MetricDescriptor, ValueTypes, MetricKind, AlignmentTy... |
return message;
};
| {
try {
message = JSON.parse(error.data.message).error.message;
} catch (err) {
error.error = err;
}
} | conditional_block |
mergeAccounts.ts | import Users from '../../lib/collections/users/collection';
import { Vulcan, editMutation, getCollection, Utils } from '../vulcan-lib';
import { Revisions } from '../../lib/index';
import { editableCollectionsFields } from '../../lib/editor/make_editable'
import ReadStatuses from '../../lib/collections/readStatus/colle... | (userId: string) {
const user = await Users.findOne({_id: userId})
if (!user) throw Error("Can't find user")
const allTargetVotes = await Votes.find({
authorId: user._id,
userId: {$ne: user._id},
legacy: {$ne: true},
cancelled: false
}).fetch()
const totalNonLegacyKarma = sumBy(allTargetVotes,... | recomputeKarma | identifier_name |
mergeAccounts.ts | import Users from '../../lib/collections/users/collection';
import { Vulcan, editMutation, getCollection, Utils } from '../vulcan-lib';
import { Revisions } from '../../lib/index';
import { editableCollectionsFields } from '../../lib/editor/make_editable'
import ReadStatuses from '../../lib/collections/readStatus/colle... |
Vulcan.getTotalKarmaForUser = recomputeKarma
| {
const user = await Users.findOne({_id: userId})
if (!user) throw Error("Can't find user")
const allTargetVotes = await Votes.find({
authorId: user._id,
userId: {$ne: user._id},
legacy: {$ne: true},
cancelled: false
}).fetch()
const totalNonLegacyKarma = sumBy(allTargetVotes, vote => {
re... | identifier_body |
mergeAccounts.ts | import Users from '../../lib/collections/users/collection';
import { Vulcan, editMutation, getCollection, Utils } from '../vulcan-lib';
import { Revisions } from '../../lib/index';
import { editableCollectionsFields } from '../../lib/editor/make_editable'
import ReadStatuses from '../../lib/collections/readStatus/colle... | await editMutation({
collection,
documentId,
set: {[fieldName]: targetUserId},
unset: {},
validate: false,
})
}
const transferCollection = async ({sourceUserId, targetUserId, collectionName, fieldName = "userId"}: {
sourceUserId: string,
targetUserId: string,
collectionName: CollectionNam... |
const transferOwnership = async ({documentId, targetUserId, collection, fieldName = "userId"}) => { | random_line_split |
bind-by-move-no-guards.rs | // Copyright 2012 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 ... | Some(z) => { assert!(!z.recv().unwrap()); },
None => panic!()
}
} | random_line_split | |
bind-by-move-no-guards.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {
let (tx, rx) = channel();
let x = Some(rx);
tx.send(false);
match x {
Some(z) if z.recv().unwrap() => { panic!() },
//~^ ERROR cannot bind by-move into a pattern guard
Some(z) => { assert!(!z.recv().unwrap()); },
None => panic!()
}
}
| main | identifier_name |
bind-by-move-no-guards.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | {
let (tx, rx) = channel();
let x = Some(rx);
tx.send(false);
match x {
Some(z) if z.recv().unwrap() => { panic!() },
//~^ ERROR cannot bind by-move into a pattern guard
Some(z) => { assert!(!z.recv().unwrap()); },
None => panic!()
}
} | identifier_body | |
bind-by-move-no-guards.rs | // Copyright 2012 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 ... | ,
//~^ ERROR cannot bind by-move into a pattern guard
Some(z) => { assert!(!z.recv().unwrap()); },
None => panic!()
}
}
| { panic!() } | conditional_block |
cardfight.py | #!/usr/bin/python3
import random
import copy
import enum
import jsonpickle
import pickle
import argparse
from sharedlib import Attr, Card, Config
import json
class Die:
def __init__(self, attack, defense, magic, mundane, numSides=12):
self.attack = attack
self.defense = defense
self.magic = magic
self.mundane... | diceType = diceTypes[key]
for _ in range(0,dice[key]):
if random.randint(1,diceType.numSides) <= getattr(diceType,successSide):
total += 1
return total
def attack(attacker, defender):
damage = None
if Attr.theroll in defender.attrs:
damage = 1
else:
damage = calculateDamage(attacker, defender)
if ... |
def roll(dice, successSide):
total = 0
for key in dice: | random_line_split |
cardfight.py | #!/usr/bin/python3
import random
import copy
import enum
import jsonpickle
import pickle
import argparse
from sharedlib import Attr, Card, Config
import json
class Die:
def __init__(self, attack, defense, magic, mundane, numSides=12):
self.attack = attack
self.defense = defense
self.magic = magic
self.mundane... |
if winner == None:
return Winner.draw, i
elif winner.name == initialAttacker.name:
return Winner.attacker, i
else:
return Winner.defender, i
if __name__ == '__main__':
diceTypes = None
with open("dice.json") as f:
diceTypes = jsonpickle.decode(f.read())
parser = argparse.ArgumentParser(description='... | break | conditional_block |
cardfight.py | #!/usr/bin/python3
import random
import copy
import enum
import jsonpickle
import pickle
import argparse
from sharedlib import Attr, Card, Config
import json
class Die:
def __init__(self, attack, defense, magic, mundane, numSides=12):
self.attack = attack
self.defense = defense
self.magic = magic
self.mundane... | winner, distance = takeTurn(attacker, defender, distance)
if winner != None:
break
if winner == None:
return Winner.draw, i
elif winner.name == initialAttacker.name:
return Winner.attacker, i
else:
return Winner.defender, i
if __name__ == '__main__':
diceTypes = None
with open("dice.json") as ... | distance = max(initialAttacker.range, initialDefender.range) + 1
#print("distance:",distance)
winner = None
i = 1
for i in range(1,maxTurns+1):
attacker = None
defender = None
if is_odd(i):
attacker = initialAttacker
defender = initialDefender
else:
attacker = initialDefender
defender = initial... | identifier_body |
cardfight.py | #!/usr/bin/python3
import random
import copy
import enum
import jsonpickle
import pickle
import argparse
from sharedlib import Attr, Card, Config
import json
class Die:
def __init__(self, attack, defense, magic, mundane, numSides=12):
self.attack = attack
self.defense = defense
self.magic = magic
self.mundane... | (dice, successSide):
total = 0
for key in dice:
diceType = diceTypes[key]
for _ in range(0,dice[key]):
if random.randint(1,diceType.numSides) <= getattr(diceType,successSide):
total += 1
return total
def attack(attacker, defender):
damage = None
if Attr.theroll in defender.attrs:
damage = 1
else:
... | roll | identifier_name |
thingspeak_cpu_loop.py | from time import localtime, strftime
# download from http://code.google.com/p/psutil/
import psutil
import time
import thingspeak
channel_id = 0 # PUT CHANNEL ID HERE
write_key = 0 # PUT YOUR WRITE KEY HERE
def doit(channel):
cpu_pc = psutil.cpu_percent()
mem_avail_mb = psutil.virtual_memory().percent
... | channel = thingspeak.Channel(id=channel_id, write_key=write_key)
while True:
doit(channel)
time.sleep(16) | conditional_block | |
thingspeak_cpu_loop.py | from time import localtime, strftime
# download from http://code.google.com/p/psutil/
import psutil
import time
import thingspeak
channel_id = 0 # PUT CHANNEL ID HERE
write_key = 0 # PUT YOUR WRITE KEY HERE
def doit(channel):
|
# sleep for 16 seconds (api limit of 15 secs)
if __name__ == "__main__":
channel = thingspeak.Channel(id=channel_id, write_key=write_key)
while True:
doit(channel)
time.sleep(16)
| cpu_pc = psutil.cpu_percent()
mem_avail_mb = psutil.virtual_memory().percent
try:
response = channel.update({1: cpu_pc, 2: mem_avail})
print(cpu_pc)
print(mem_avail_mb)
print(strftime("%a, %d %b %Y %H:%M:%S", localtime()))
print(response)
except:
print("conne... | identifier_body |
thingspeak_cpu_loop.py | from time import localtime, strftime
# download from http://code.google.com/p/psutil/
import psutil
import time
import thingspeak
channel_id = 0 # PUT CHANNEL ID HERE
write_key = 0 # PUT YOUR WRITE KEY HERE
def | (channel):
cpu_pc = psutil.cpu_percent()
mem_avail_mb = psutil.virtual_memory().percent
try:
response = channel.update({1: cpu_pc, 2: mem_avail})
print(cpu_pc)
print(mem_avail_mb)
print(strftime("%a, %d %b %Y %H:%M:%S", localtime()))
print(response)
except:
... | doit | identifier_name |
thingspeak_cpu_loop.py | from time import localtime, strftime
# download from http://code.google.com/p/psutil/
import psutil
import time
import thingspeak
channel_id = 0 # PUT CHANNEL ID HERE
write_key = 0 # PUT YOUR WRITE KEY HERE
def doit(channel):
cpu_pc = psutil.cpu_percent()
mem_avail_mb = psutil.virtual_memory().percent | print(strftime("%a, %d %b %Y %H:%M:%S", localtime()))
print(response)
except:
print("connection failed")
# sleep for 16 seconds (api limit of 15 secs)
if __name__ == "__main__":
channel = thingspeak.Channel(id=channel_id, write_key=write_key)
while True:
doit(channel)
... |
try:
response = channel.update({1: cpu_pc, 2: mem_avail})
print(cpu_pc)
print(mem_avail_mb) | random_line_split |
settings.py | # Django settings for flexy project.
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email@example.com'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django_mongodb_engine',
'NAME': 'sheesh',
... | TEMPLATE_DIRS = (
os.path.join(BASE_DIR, 'templates')
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
INSTALLED_APPS = (
'django.contrib.auth',
'django... | WSGI_APPLICATION = 'flexy.wsgi.application'
| random_line_split |
tempdir.rs | // Mainly taken from crate `tempdir`
extern crate rand;
use rand::{Rng, thread_rng};
use std::io::Result as IOResult;
use std::io::{Error, ErrorKind};
use std::path::Path;
// How many times should we (re)try finding an unused random name? It should be
// enough that an attacker will run out of luck before we run out... | pub fn new_in<P: AsRef<Path>>(tmpdir: P, prefix: &str, rand: usize, suffix: &str) -> IOResult<String> {
let mut rng = thread_rng();
for _ in 0..NUM_RETRIES {
let rand_chars: String = rng.gen_ascii_chars().take(rand).collect();
let leaf = format!("{}{}{}", prefix, rand_chars, suffix);
le... | }
| random_line_split |
tempdir.rs | // Mainly taken from crate `tempdir`
extern crate rand;
use rand::{Rng, thread_rng};
use std::io::Result as IOResult;
use std::io::{Error, ErrorKind};
use std::path::Path;
// How many times should we (re)try finding an unused random name? It should be
// enough that an attacker will run out of luck before we run out... | <P: AsRef<Path>>(path: P) -> IOResult<()> {
use std::fs::DirBuilder;
use std::os::unix::fs::DirBuilderExt;
DirBuilder::new().mode(0o700).create(path)
}
#[cfg(windows)]
fn create_dir<P: AsRef<Path>>(path: P) -> IOResult<()> {
::std::fs::create_dir(path)
}
pub fn new_in<P: AsRef<Path>>(tmpdir: P, prefi... | create_dir | identifier_name |
tempdir.rs | // Mainly taken from crate `tempdir`
extern crate rand;
use rand::{Rng, thread_rng};
use std::io::Result as IOResult;
use std::io::{Error, ErrorKind};
use std::path::Path;
// How many times should we (re)try finding an unused random name? It should be
// enough that an attacker will run out of luck before we run out... |
pub fn new_in<P: AsRef<Path>>(tmpdir: P, prefix: &str, rand: usize, suffix: &str) -> IOResult<String> {
let mut rng = thread_rng();
for _ in 0..NUM_RETRIES {
let rand_chars: String = rng.gen_ascii_chars().take(rand).collect();
let leaf = format!("{}{}{}", prefix, rand_chars, suffix);
... | {
::std::fs::create_dir(path)
} | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.