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 |
|---|---|---|---|---|
in_queue.test.ts | /*
* Copyright (c) 2022 Snowplow Analytics Ltd, 2010 Anthon Pang
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice... |
return false;
});
const asyncQueueOps = [
['newTracker', 'firstTracker', 'firstEndpoint'],
['enableActivityTracking', { n: 5 }],
['trackPageView'],
];
const asyncQueue = InQueueManager('snowplow', asyncQueueOps);
it('Make a proxy, Function originally stored in asyncQueue is executed when as... | {
return true;
} | conditional_block |
ios-simulator-discovery.ts | import { DeviceDiscovery } from "./device-discovery";
import { IOSSimulator } from "./../ios/simulator/ios-simulator-device";
import { EmulatorDiscoveryNames } from "../../constants";
import { IDictionary, IHostInfo } from "../../declarations";
import { IInjector } from "../../definitions/yok";
import { injector } from... | }
private raiseOnEmulatorImagesLost(simulators: Mobile.IDeviceInfo[]) {
_.forEach(simulators, (simulator) => {
delete this.availableSimulators[simulator.imageIdentifier];
this.emit(EmulatorDiscoveryNames.EMULATOR_IMAGE_LOST, simulator);
});
}
}
injector.register("iOSSimulatorDiscovery", IOSSimulatorDisco... | this.emit(EmulatorDiscoveryNames.EMULATOR_IMAGE_FOUND, simulator);
}); | random_line_split |
ios-simulator-discovery.ts | import { DeviceDiscovery } from "./device-discovery";
import { IOSSimulator } from "./../ios/simulator/ios-simulator-device";
import { EmulatorDiscoveryNames } from "../../constants";
import { IDictionary, IHostInfo } from "../../declarations";
import { IInjector } from "../../definitions/yok";
import { injector } from... | _.some(
this.cachedSimulators,
(simulator) =>
simulator &&
s &&
simulator.id === s.id &&
simulator.state === s.state
)
)
.each((s) => this.createAndAddDevice(s));
}
}
public async checkForAvailableSimulators(): Promise<Mobile.IDeviceInfo[]> {
if (!this.$... | {
const currentSimulators: Mobile.IiSimDevice[] = await this.$iOSSimResolver.iOSSim.getRunningSimulators();
// Remove old simulators
_(this.cachedSimulators)
.reject((s) =>
_.some(
currentSimulators,
(simulator) =>
simulator &&
s &&
simulator.id === s.id &&
sim... | conditional_block |
ios-simulator-discovery.ts | import { DeviceDiscovery } from "./device-discovery";
import { IOSSimulator } from "./../ios/simulator/ios-simulator-device";
import { EmulatorDiscoveryNames } from "../../constants";
import { IDictionary, IHostInfo } from "../../declarations";
import { IInjector } from "../../definitions/yok";
import { injector } from... | (
private $injector: IInjector,
private $iOSSimResolver: Mobile.IiOSSimResolver,
private $mobileHelper: Mobile.IMobileHelper,
private $hostInfo: IHostInfo,
private $iOSEmulatorServices: Mobile.IiOSSimulatorService
) {
super();
}
public async startLookingForDevices(
options?: Mobile.IDeviceLookingOptio... | constructor | identifier_name |
ios-simulator-discovery.ts | import { DeviceDiscovery } from "./device-discovery";
import { IOSSimulator } from "./../ios/simulator/ios-simulator-device";
import { EmulatorDiscoveryNames } from "../../constants";
import { IDictionary, IHostInfo } from "../../declarations";
import { IInjector } from "../../definitions/yok";
import { injector } from... |
private raiseOnEmulatorImagesLost(simulators: Mobile.IDeviceInfo[]) {
_.forEach(simulators, (simulator) => {
delete this.availableSimulators[simulator.imageIdentifier];
this.emit(EmulatorDiscoveryNames.EMULATOR_IMAGE_LOST, simulator);
});
}
}
injector.register("iOSSimulatorDiscovery", IOSSimulatorDiscove... | {
_.forEach(simulators, (simulator) => {
this.availableSimulators[simulator.imageIdentifier] = simulator;
this.emit(EmulatorDiscoveryNames.EMULATOR_IMAGE_FOUND, simulator);
});
} | identifier_body |
workqueue.rs | WorkData,
}
/// Messages from the supervisor to the worker.
enum WorkerMsg<QueueData: 'static, WorkData: 'static> {
/// Tells the worker to start work.
Start(Worker<WorkUnit<QueueData, WorkData>>, *mut AtomicUsize, *const QueueData),
/// Tells the worker to stop. It can be restarted again with a `WorkerMs... |
}
}
// At this point, we have some work. Perform it.
let mut proxy = WorkerProxy {
worker: &mut deque,
ref_count: ref_count,
queue_data: queue_data,
worker_index: self.in... | {
break
} | conditional_block |
workqueue.rs | : WorkData,
}
/// Messages from the supervisor to the worker.
enum WorkerMsg<QueueData: 'static, WorkData: 'static> {
/// Tells the worker to start work.
Start(Worker<WorkUnit<QueueData, WorkData>>, *mut AtomicUsize, *const QueueData),
/// Tells the worker to stop. It can be restarted again with a `WorkerM... | _ => {}
}
}
unsafe {
usleep(back_off_sleep as u32);
}
back_off_sleep += BACKOFF... | break
}
Ok(WorkerMsg::Exit) => return,
Ok(_) => panic!("unexpected message"), | random_line_split |
workqueue.rs | WorkData,
}
/// Messages from the supervisor to the worker.
enum WorkerMsg<QueueData: 'static, WorkData: 'static> {
/// Tells the worker to start work.
Start(Worker<WorkUnit<QueueData, WorkData>>, *mut AtomicUsize, *const QueueData),
/// Tells the worker to stop. It can be restarted again with a `WorkerMs... | (&self) -> u8 {
self.worker_index
}
}
/// A work queue on which units of work can be submitted.
pub struct WorkQueue<QueueData: 'static, WorkData: 'static> {
/// Information about each of the workers.
workers: Vec<WorkerInfo<QueueData, WorkData>>,
/// A port on which deques can be received from... | worker_index | identifier_name |
angular-loader.js | error is useful.
* @returns {function(code:string, template:string, ...templateArgs): Error} minErr instance
*/
function minErr(module, ErrorConstructor) {
ErrorConstructor = ErrorConstructor || Error;
return function() {
var SKIP_INDEXES = 2;
var templateArgs = arguments,
code = templateArgs[0],... | // We need to expose `angular.$$minErr` to modules such as `ngResource` that reference it during bootstrap
angular.$$minErr = angular.$$minErr || minErr;
return ensure(angular, 'module', function() {
/** @type {Object.<string, angular.Module>} */
var modules = {};
/**
* @ngdoc function
* @... | }
var angular = ensure(window, 'angular', Object);
| random_line_split |
angular-loader.js | error is useful.
* @returns {function(code:string, template:string, ...templateArgs): Error} minErr instance
*/
function | (module, ErrorConstructor) {
ErrorConstructor = ErrorConstructor || Error;
return function() {
var SKIP_INDEXES = 2;
var templateArgs = arguments,
code = templateArgs[0],
message = '[' + (module ? module + ':' : '') + code + '] ',
template = templateArgs[1],
paramPrefix, i;
mes... | minErr | identifier_name |
angular-loader.js | . If registering a module ensure that you ' +
'specify the dependencies as the second argument.', name);
}
/** @type {!Array.<Array.<*>>} */
var invokeQueue = [];
/** @type {!Array.<Function>} */
var configBlocks = [];
/** @type {!Array.<Function>} */
... | {
if (!queue) queue = invokeQueue;
return function(recipeName, factoryFunction) {
if (factoryFunction && isFunction(factoryFunction)) factoryFunction.$$moduleName = name;
queue.push([provider, method, arguments]);
return moduleInstance;
};
} | identifier_body | |
visualizations.py | import logging
import pandas as pd
import matplotlib.pyplot as plt
def running_total_comparison(df1, window=15):
fig_size = [12,12]
xlim = [0,365]
ylim = [0,max(df1.Pages)]
years = df1.Year.unique()[-window:].tolist()
y = years.pop(0)
_df = df1.loc[df1.Year == y]
ax = _df.plot("Day", "Page... | now = df.loc[df.Year == current_year]
fig_size = [12, 6]
ax = df.hist("Pages Read", bins=14, color="darkblue", figsize=fig_size)
plt.axvline(x=int(now["Pages Read"]), color="red")
plt.show()
df.plot.bar(x="Rank", y="Pages Read", width=.95, color="darkblue", figsize=fig_size)
plt.axvline(x=int(no... | identifier_body | |
visualizations.py | import logging
import pandas as pd
import matplotlib.pyplot as plt
def running_total_comparison(df1, window=15):
fig_size = [12,12]
xlim = [0,365]
ylim = [0,max(df1.Pages)]
years = df1.Year.unique()[-window:].tolist()
y = years.pop(0)
_df = df1.loc[df1.Year == y]
ax = _df.plot("Day", "Page... | (df, current_year=2020):
now = df.loc[df.Year == current_year]
fig_size = [12, 6]
ax = df.hist("Pages Read", bins=14, color="darkblue", figsize=fig_size)
plt.axvline(x=int(now["Pages Read"]), color="red")
plt.show()
df.plot.bar(x="Rank", y="Pages Read", width=.95, color="darkblue", figsize=fig_s... | yearly_comparisons | identifier_name |
visualizations.py | import logging
import pandas as pd
import matplotlib.pyplot as plt
def running_total_comparison(df1, window=15):
fig_size = [12,12]
xlim = [0,365]
ylim = [0,max(df1.Pages)]
years = df1.Year.unique()[-window:].tolist()
y = years.pop(0)
_df = df1.loc[df1.Year == y]
ax = _df.plot("Day", "Page... | fig_size = [12, 6]
ax = df.hist("Pages Read", bins=14, color="darkblue", figsize=fig_size)
plt.axvline(x=int(now["Pages Read"]), color="red")
plt.show()
df.plot.bar(x="Rank", y="Pages Read", width=.95, color="darkblue", figsize=fig_size)
plt.axvline(x=int(now["Rank"]) - 1, color="red")
plt.s... |
def yearly_comparisons(df, current_year=2020):
now = df.loc[df.Year == current_year] | random_line_split |
visualizations.py | import logging
import pandas as pd
import matplotlib.pyplot as plt
def running_total_comparison(df1, window=15):
fig_size = [12,12]
xlim = [0,365]
ylim = [0,max(df1.Pages)]
years = df1.Year.unique()[-window:].tolist()
y = years.pop(0)
_df = df1.loc[df1.Year == y]
ax = _df.plot("Day", "Page... |
def yearly_comparisons(df, current_year=2020):
now = df.loc[df.Year == current_year]
fig_size = [12, 6]
ax = df.hist("Pages Read", bins=14, color="darkblue", figsize=fig_size)
plt.axvline(x=int(now["Pages Read"]), color="red")
plt.show()
df.plot.bar(x="Rank", y="Pages Read", width=.95, color=... | _df = df1.loc[df1.Year == y]
ax = _df.plot("Day", "Pages", figsize=fig_size, xlim=xlim, ylim=ylim, ax=ax, label=y) | conditional_block |
typedarray-prototype.js | // Any copyright is dedicated to the Public Domain.
// http://creativecommons.org/licenses/publicdomain/
//-----------------------------------------------------------------------------
var BUGNUMBER = 565604;
var summary =
"Typed-array properties don't work when accessed from an object whose " +
"prototype (or fur... |
reportCompare(true, true); | random_line_split | |
compare-generic-enums.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 ... | (x: Option<an_int>, y: Option<isize>) -> bool {
x == y
}
pub fn main() {
assert!(!cmp(Some(3), None));
assert!(!cmp(Some(3), Some(4)));
assert!(cmp(Some(3), Some(3)));
assert!(cmp(None, None));
}
| cmp | identifier_name |
compare-generic-enums.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 ... | // run-pass
#![allow(non_camel_case_types)]
type an_int = isize;
fn cmp(x: Option<an_int>, y: Option<isize>) -> bool {
x == y
}
pub fn main() {
assert!(!cmp(Some(3), None));
assert!(!cmp(Some(3), Some(4)));
assert!(cmp(Some(3), Some(3)));
assert!(cmp(None, None));
} | random_line_split | |
compare-generic-enums.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 ... | {
assert!(!cmp(Some(3), None));
assert!(!cmp(Some(3), Some(4)));
assert!(cmp(Some(3), Some(3)));
assert!(cmp(None, None));
} | identifier_body | |
message.py | # -*- coding:utf-8 -*-
"""
用户消息相关的视图
"""
from rest_framework import generics
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework.filters import SearchFilter
from account.serializers.message... | user = self.request.user
instance = self.get_object()
# 2. 如果是自己的消息或者是超级管理员,那么就可以删除本条消息
if instance.is_deleted:
response = Response(status=204)
else:
if instance.user == user or user.is_superuser:
instance.is_deleted = True
inst... | ):
# 1. 获取到对象
instance = self.get_object()
# 2. 修改unread
if instance.unread:
instance.unread = False
instance.save(update_fields=('unread',))
return super().retrieve(request, *args, **kwargs)
def delete(self, request, *args, **kwargs):
# 1. 获... | identifier_body |
message.py | # -*- coding:utf-8 -*-
"""
用户消息相关的视图
"""
from rest_framework import generics
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework.filters import SearchFilter
from account.serializers.message... | # 搜索和过滤
filter_backends = (DjangoFilterBackend, SearchFilter)
filter_fields = ('category', 'unread')
search_fields = ('title', 'content')
ordering_fields = ('id', 'time_added')
ordering = ('-time_added',)
def get_queryset(self):
# 第1步:获取到请求的用户
# 用户只可以看到自己的消息列表
user =... | random_line_split | |
message.py | # -*- coding:utf-8 -*-
"""
用户消息相关的视图
"""
from rest_framework import generics
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework.filters import SearchFilter
from account.serializers.message... | response = Response(status=204)
else:
response = Response("没权限删除", status=403)
# 3. 返回响应
return response
| ()
| identifier_name |
message.py | # -*- coding:utf-8 -*-
"""
用户消息相关的视图
"""
from rest_framework import generics
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework.filters import SearchFilter
from account.serializers.message... | conditional_block | ||
baseFilter.d.ts | // Type definitions for ag-grid-community v20.2.0
// Project: http://www.ag-grid.com/
// Definitions by: Niall Crosby <https://github.com/ag-grid/>
import { Component } from "../widgets/component";
import { IFilterOptionDef, IDoesFilterPassParams, IFilterComp, IFilterParams } from "../interfaces/iFilter";
import { Grid... | greaterThan?: boolean;
}
export interface IComparableFilterParams extends IFilterParams {
suppressAndOrCondition: boolean;
}
export interface IScalarFilterParams extends IComparableFilterParams {
inRangeInclusive?: boolean;
nullComparator?: NullComparator;
}
/**
* Comparable filter with scalar underlyi... | export interface NullComparator {
equals?: boolean;
lessThan?: boolean; | random_line_split |
bolter-memory.js | 'use strict';
var Q = require('q')
, _ = require('underscore');
exports.defaults = function () { return { storage: {} }; };
exports.mixin = {
/**
* Converts `arguments` to a key to be stored.
*/
toKey: function () {
return _.toArray(arguments);
},
contains: function () {
return this.contain... |
set: function (key, val) {
this.storage[key] = val;
return Q.when(true);
},
get: function (key) {
return Q.when(this.storage[key]);
}
}; | }, | random_line_split |
entry.py | # -*- coding: utf-8 -*-
# entry.py, part for evparse : EisF Video Parse, evdh Video Parse.
# entry: evparse/lib/hunantv
# version 0.1.0.0 test201505151816
# author sceext <sceext@foxmail.com> 2009EisF2015, 2015.05.
# copyright 2015 sceext
#
# This is FREE SOFTWARE, released under GNU GPLv3+
# please see README.md an... | (config):
# just copy it
etc['flag_debug'] = config['flag_debug']
etc['hd_min'] = config['hd_min']
etc['hd_max'] = config['hd_max']
# get vid
def get_vid(url_to):
vid_info = {}
vid_info['url'] = url_to
# get vid
vids = re.findall(RE_VID, url_to)
vid_info['vid'] = vids[0]
# done
... | set_config | identifier_name |
entry.py | # -*- coding: utf-8 -*-
# entry.py, part for evparse : EisF Video Parse, evdh Video Parse.
# entry: evparse/lib/hunantv
# version 0.1.0.0 test201505151816
# author sceext <sceext@foxmail.com> 2009EisF2015, 2015.05.
# copyright 2015 sceext
#
# This is FREE SOFTWARE, released under GNU GPLv3+
# please see README.md an... | # end entry.py | random_line_split | |
entry.py | # -*- coding: utf-8 -*-
# entry.py, part for evparse : EisF Video Parse, evdh Video Parse.
# entry: evparse/lib/hunantv
# version 0.1.0.0 test201505151816
# author sceext <sceext@foxmail.com> 2009EisF2015, 2015.05.
# copyright 2015 sceext
#
# This is FREE SOFTWARE, released under GNU GPLv3+
# please see README.md an... |
# get vid
def get_vid(url_to):
vid_info = {}
vid_info['url'] = url_to
# get vid
vids = re.findall(RE_VID, url_to)
vid_info['vid'] = vids[0]
# done
return vid_info
def parse(url_to): # this site entry main entry function
# frist re-check url, if supported by this
if not re.match(RE... | etc['flag_debug'] = config['flag_debug']
etc['hd_min'] = config['hd_min']
etc['hd_max'] = config['hd_max'] | identifier_body |
entry.py | # -*- coding: utf-8 -*-
# entry.py, part for evparse : EisF Video Parse, evdh Video Parse.
# entry: evparse/lib/hunantv
# version 0.1.0.0 test201505151816
# author sceext <sceext@foxmail.com> 2009EisF2015, 2015.05.
# copyright 2015 sceext
#
# This is FREE SOFTWARE, released under GNU GPLv3+
# please see README.md an... |
# get base, more info
info, more = get_base_info.get_info(vid_info, flag_debug=etc['flag_debug'])
# add more info
evinfo['info']['title'] = more['title']
evinfo['info']['title_sub'] = more['sub_title']
evinfo['info']['title_short'] = more['short_title']
evinfo['info']['title_no'] = mor... | print('lib.hunantv: DEBUG: got vid \"' + vid_info['vid'] + '\" ') | conditional_block |
GameState.js | var EvolutionGame = EvolutionGame || {};
EvolutionGame.GameState = {
create: function() {
this.background = this.game.add.sprite(0, 0, 'space'); //fundo
this.background.inputEnabled = true;
this.game.physics.startSystem(Phaser.Physics.ARCADE);
this.playerManager = new EvolutionGame.PlayerManager(this... |
if (this.playerManager.players.length < this.MAX_PLAYER_COUNT) {
var minX = 30,
maxX = this.game.width-30,
minY = 370,
maxY = this.game.height-60;
dropX = Utils.getRandomInt(minX, maxX);
dropY = Utils.getRandomInt(minY, maxY);
this.playerManager.createPlayer(dropX, dropY, 1, false);
}
... |
createPlayer: function() {
// console.log(this.playerManager.players.length); | random_line_split |
GameState.js |
var EvolutionGame = EvolutionGame || {};
EvolutionGame.GameState = {
create: function() {
this.background = this.game.add.sprite(0, 0, 'space'); //fundo
this.background.inputEnabled = true;
this.game.physics.startSystem(Phaser.Physics.ARCADE);
this.playerManager = new EvolutionGame.PlayerManager(thi... |
}
}; | {
var minX = 30,
maxX = this.game.width-30,
minY = 370,
maxY = this.game.height-60;
dropX = Utils.getRandomInt(minX, maxX);
dropY = Utils.getRandomInt(minY, maxY);
this.playerManager.createPlayer(dropX, dropY, 1, false);
} | conditional_block |
reduceVCF.py | # -*- coding: utf-8 -*-
"""
Created on Sun Mar 10 10:43:53 2019
@author: Heathro
Description: Reduces a vcf file to meta section and
one line for each chromosome number for testing and
debugging purposes.
"""
# Open files to read from and write to
vcfpath = open("D:/MG_GAP/Ali_w_767.vcf", "rU")
testvcf = open("REDU... | elif current_chrom != temp_chrom:
counter = 0
temp_chrom = current_chrom
testvcf.write(line)
# Include the meta lines and header line
else:
testvcf.write(line)
testvcf.close()
vcfpath.close() | # If a new chromosome, write a line, start counter at 0 | random_line_split |
reduceVCF.py | # -*- coding: utf-8 -*-
"""
Created on Sun Mar 10 10:43:53 2019
@author: Heathro
Description: Reduces a vcf file to meta section and
one line for each chromosome number for testing and
debugging purposes.
"""
# Open files to read from and write to
vcfpath = open("D:/MG_GAP/Ali_w_767.vcf", "rU")
testvcf = open("REDU... |
# If a new chromosome, write a line, start counter at 0
elif current_chrom != temp_chrom:
counter = 0
temp_chrom = current_chrom
testvcf.write(line)
# Include the meta lines and header line
else:
testvcf.write(line)
... | counter = counter + 1
if counter < 1000:
testvcf.write(line) | conditional_block |
control.py | # Copyright (C) 2016 East Asian Observatory
# All Rights Reserved.
#
# 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.
#
#... | ans = ExampleRequestCollection()
with self._transaction() as conn:
for iter_stmt in self._iter_stmt(
stmt, iter_field, iter_list):
for row in conn.execute(
iter_stmt.order_by(
example_request.c.id.asc())... | """
Retrieve observing requests
for the given proposal or proposals.
"""
stmt = example_request.select()
iter_field = None
iter_list = None
if proposal_id is not None:
if is_list_like(proposal_id):
assert iter_field is None
... | identifier_body |
control.py | # Copyright (C) 2016 East Asian Observatory
# All Rights Reserved.
#
# 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.
#
#... |
return ans
def sync_example_proposal_request(
self, proposal_id, records):
"""
Update the observing requests
for the given proposal.
"""
with self._transaction() as conn:
return self._sync_records(
conn,
examp... | for row in conn.execute(
iter_stmt.order_by(
example_request.c.id.asc())):
ans[row['id']] = ExampleRequest(**row) | random_line_split |
control.py | # Copyright (C) 2016 East Asian Observatory
# All Rights Reserved.
#
# 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.
#
#... | (self, proposal_id):
"""
Retrieve observing requests
for the given proposal or proposals.
"""
stmt = example_request.select()
iter_field = None
iter_list = None
if proposal_id is not None:
if is_list_like(proposal_id):
assert... | search_example_request | identifier_name |
control.py | # Copyright (C) 2016 East Asian Observatory
# All Rights Reserved.
#
# 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.
#
#... |
ans = ExampleRequestCollection()
with self._transaction() as conn:
for iter_stmt in self._iter_stmt(
stmt, iter_field, iter_list):
for row in conn.execute(
iter_stmt.order_by(
example_request.c.id.asc(... | if is_list_like(proposal_id):
assert iter_field is None
iter_field = example_request.c.proposal_id
iter_list = proposal_id
else:
stmt = stmt.where(
example_request.c.proposal_id
== proposal_id) | conditional_block |
Storage.ts | // Copyright 2020-2021 Signal Messenger, LLC
// SPDX-License-Identifier: AGPL-3.0-only
/* eslint-disable @typescript-eslint/no-explicit-any */
import utils from './Helpers';
// Default implementation working with localStorage
const localStorageImpl: StorageInterface = {
put(key: string, value: any) {
if (value ... | (key: string) {
localStorage.removeItem(`${key}`);
},
};
export type StorageInterface = {
put(key: string, value: any): void | Promise<void>;
get(key: string, defaultValue: any): any;
remove(key: string): void | Promise<void>;
};
const Storage = {
impl: localStorageImpl,
put(key: string, value: unkno... | remove | identifier_name |
Storage.ts | // Copyright 2020-2021 Signal Messenger, LLC
// SPDX-License-Identifier: AGPL-3.0-only
/* eslint-disable @typescript-eslint/no-explicit-any */
import utils from './Helpers';
// Default implementation working with localStorage
const localStorageImpl: StorageInterface = {
put(key: string, value: any) {
if (value ... | return JSON.parse(value);
},
remove(key: string) {
localStorage.removeItem(`${key}`);
},
};
export type StorageInterface = {
put(key: string, value: any): void | Promise<void>;
get(key: string, defaultValue: any): any;
remove(key: string): void | Promise<void>;
};
const Storage = {
impl: localS... | get(key: string, defaultValue: any) {
const value = localStorage.getItem(`${key}`);
if (value === null) {
return defaultValue;
} | random_line_split |
Storage.ts | // Copyright 2020-2021 Signal Messenger, LLC
// SPDX-License-Identifier: AGPL-3.0-only
/* eslint-disable @typescript-eslint/no-explicit-any */
import utils from './Helpers';
// Default implementation working with localStorage
const localStorageImpl: StorageInterface = {
put(key: string, value: any) {
if (value ... |
localStorage.setItem(`${key}`, utils.jsonThing(value));
},
get(key: string, defaultValue: any) {
const value = localStorage.getItem(`${key}`);
if (value === null) {
return defaultValue;
}
return JSON.parse(value);
},
remove(key: string) {
localStorage.removeItem(`${key}`);
},
... | {
throw new Error('Tried to store undefined');
} | conditional_block |
Storage.ts | // Copyright 2020-2021 Signal Messenger, LLC
// SPDX-License-Identifier: AGPL-3.0-only
/* eslint-disable @typescript-eslint/no-explicit-any */
import utils from './Helpers';
// Default implementation working with localStorage
const localStorageImpl: StorageInterface = {
put(key: string, value: any) | ,
get(key: string, defaultValue: any) {
const value = localStorage.getItem(`${key}`);
if (value === null) {
return defaultValue;
}
return JSON.parse(value);
},
remove(key: string) {
localStorage.removeItem(`${key}`);
},
};
export type StorageInterface = {
put(key: string, value: a... | {
if (value === undefined) {
throw new Error('Tried to store undefined');
}
localStorage.setItem(`${key}`, utils.jsonThing(value));
} | identifier_body |
app.js | /**
* Coder for Raspberry Pi
* A simple platform for experimenting with web stuff. | * 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 writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARR... | * http://goo.gl/coder
*
* Copyright 2013 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); | random_line_split |
users-routes.Spec.js | "use strict";
var chai = require('chai');
var chaiHttp = require('chai-http');
var expect = require('chai').expect;
var app = require('../app');
var port = 3001;
var user1 = {
username: 'Laura',
password: 'tiger',
address: {
street: '123 Main St',
city: 'Beaverton',
state: 'OR',
zip: 97007,
},... | () {
return chai.request(`localhost:${port}`);
}
describe('Single Resource REST API', function() {
before(function(done) {
app.listen(port, done);
});
it('POST /users request should add a user to DB', function(done) {
chaiRequest()
.post('/users')
.send(user1)
.end(function(err, res) {
... | chaiRequest | identifier_name |
users-routes.Spec.js | "use strict";
var chai = require('chai');
var chaiHttp = require('chai-http');
var expect = require('chai').expect;
var app = require('../app');
var port = 3001;
var user1 = {
username: 'Laura',
password: 'tiger',
address: {
street: '123 Main St',
city: 'Beaverton',
state: 'OR',
zip: 97007,
},... |
it('GET /users/:id request for INVALID ID should return empty object', function(done) {
chaiRequest()
.get('/users/999999')
.end(function(err, res) {
expect(res.body).to.be.empty;
done();
});
});
// it('PUT /users/:id request for user1 ID should update user1 password in DB', functi... | done();
});
}); | random_line_split |
users-routes.Spec.js | "use strict";
var chai = require('chai');
var chaiHttp = require('chai-http');
var expect = require('chai').expect;
var app = require('../app');
var port = 3001;
var user1 = {
username: 'Laura',
password: 'tiger',
address: {
street: '123 Main St',
city: 'Beaverton',
state: 'OR',
zip: 97007,
},... |
describe('Single Resource REST API', function() {
before(function(done) {
app.listen(port, done);
});
it('POST /users request should add a user to DB', function(done) {
chaiRequest()
.post('/users')
.send(user1)
.end(function(err, res) {
expect(res).to.have.status(200);
//e... | {
return chai.request(`localhost:${port}`);
} | identifier_body |
05-flickr.py | import os, sys; sys.path.insert(0, os.path.join("..", ".."))
from pattern.web import Flickr, extension
from pattern.web import RELEVANCY, LATEST, INTERESTING # Image sort order. | # - the second query is executed behind the scenes in the FlickResult.url property,
# - the third query downloads the actual image data using this URL.
# It is a good idea to cache results from Flickr locally,
# which is what the cached=True parameter does.
# You should obtain your own license key at:
# http://www.fli... | from pattern.web import SMALL, MEDIUM, LARGE # Image size.
# This example downloads an image from Flickr (http://flickr.com).
# Acquiring the image data takes three Flickr queries:
# - the first query with Flickr.search() retrieves a list of results, | random_line_split |
05-flickr.py | import os, sys; sys.path.insert(0, os.path.join("..", ".."))
from pattern.web import Flickr, extension
from pattern.web import RELEVANCY, LATEST, INTERESTING # Image sort order.
from pattern.web import SMALL, MEDIUM, LARGE # Image size.
# This example downloads an image from Flickr (http://flickr.com).
# Ac... |
# Download and save the image:
img = results[0]
data = img.download()
path = q.replace(" ","_") + extension(img.url)
f = open(path, "wb")
f.write(data)
f.close()
print "Download:", img.url
print "Saved as:", path | print img.description
print img.author
print | conditional_block |
rgb_led.py | #! /usr/bin/env python
"""
This is an example that demonstrates how to use an
RGB led with BreakfastSerial. It assumes you have an
RGB led wired up with red on pin 10, green on pin 9,
and blue on pin 8.
"""
from BreakfastSerial import RGBLed, Arduino
from time import sleep
board = Arduino()
led = RGBLed(board, { "red... | code.InteractiveConsole(locals=globals()).interact() | random_line_split | |
mixup.py | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | (models.MultiModel):
def augment(self, x, l, beta, **kwargs):
del kwargs
mix = tf.distributions.Beta(beta, beta).sample([tf.shape(x)[0], 1, 1, 1])
mix = tf.maximum(mix, 1 - mix)
xmix = x * mix + x[::-1] * (1 - mix)
lmix = l * mix[:, :, 0, 0] + l[::-1] * (1 - mix[:, :, 0, 0])... | Mixup | identifier_name |
mixup.py | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | utils.setup_tf()
flags.DEFINE_float('wd', 0.02, 'Weight decay.')
flags.DEFINE_float('ema', 0.999, 'Exponential moving average of params.')
flags.DEFINE_float('beta', 0.5, 'Mixup beta distribution.')
flags.DEFINE_integer('scales', 0, 'Number of 2x2 downscalings in the classifier.')
flags.DEFINE_integ... | conditional_block | |
mixup.py | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0 | # limitations under the License.
"""mixup: Beyond Empirical Risk Minimization.
Adaption to SSL of MixUp: https://arxiv.org/abs/1710.09412
"""
import functools
import os
import tensorflow as tf
from absl import app
from absl import flags
from libml import data, utils, models
from libml.utils import EasyDict
FLAGS = ... | #
# 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 | random_line_split |
mixup.py | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | loss_xe = tf.reduce_mean(loss_xe)
loss_xeu = tf.nn.softmax_cross_entropy_with_logits_v2(labels=labels_y, logits=logits_y)
loss_xeu = tf.reduce_mean(loss_xeu)
tf.summary.scalar('losses/xe', loss_xe)
tf.summary.scalar('losses/xeu', loss_xeu)
ema = tf.train.ExponentialMovin... | hwc = [self.dataset.height, self.dataset.width, self.dataset.colors]
xt_in = tf.placeholder(tf.float32, [batch] + hwc, 'xt') # For training
x_in = tf.placeholder(tf.float32, [None] + hwc, 'x')
y_in = tf.placeholder(tf.float32, [batch] + hwc, 'y')
l_in = tf.placeholder(tf.int32, [batch],... | identifier_body |
kinds.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 ... | #[lang="owned"]
pub trait Send {
// empty.
}
#[cfg(not(stage0))]
#[lang="send"]
pub trait Send {
// empty.
}
#[cfg(stage0)]
#[lang="const"]
pub trait Freeze {
// empty.
}
#[cfg(not(stage0))]
#[lang="freeze"]
pub trait Freeze {
// empty.
}
#[lang="sized"]
pub trait Sized {
// Empty.
} | // Empty.
}
#[cfg(stage0)] | random_line_split |
search.js | numResults = populateResults(userString, dataLength, data);
// If "results" is empty, activate the "add new client" button.
if (numResults > 0) {
// We've found some results, but we may still have to add a
// new client (maybe a person with the same name as an
// exi... | var matchLength = 0;
var hit = null;
// Turn the user's input into a list of regexes that will try to match against our matching terms.
var userRegexes = $.map(userSubstrings, function(userSubstring) { return new RegExp("^" + userSubstring, "i"); });
// This is the list of "matc... | {
// First Trim any non-alphanumerics from the ends of the user's input.
userString = userString.replace(/^[^\w]+/i, "").replace(/[^\w]+$/i, "");
// Then split the user's string on non-alphanumeric sequences. This
// eliminates a dot after a middle initial, a comma if name is
//... | identifier_body |
search.js | numResults = populateResults(userString, dataLength, data);
// If "results" is empty, activate the "add new client" button.
if (numResults > 0) {
// We've found some results, but we may still have to add a
// new client (maybe a person with the same name as an
// exi... | if (result !== null) {
// We found a match. Figure out how long it is.
matchLength = result[0].length;
// If the match is perfect OR if there are no more
// user-entered search terms after this one, we ma... | } | random_line_split |
search.js | numResults = populateResults(userString, dataLength, data);
// If "results" is empty, activate the "add new client" button.
if (numResults > 0) {
// We've found some results, but we may still have to add a
// new client (maybe a person with the same name as an
// exi... | (hit) {
var summaryDiv = $("<div class='hit'></div>");
if (hit.picture){
var picture = $("<div class='picture'><img src=\"img/" + hit.picture + "\"></div>");
}
| getSummaryDiv | identifier_name |
eapearson_TestRichReports_server_test.py | # -*- coding: utf-8 -*-
import unittest
import os # noqa: F401
import json # noqa: F401
import time
import requests
from os import environ
try:
from ConfigParser import ConfigParser # py2
except:
from configparser import ConfigParser # py3
from pprint import pprint # noqa: F401
from biokbase.workspace.c... | return self.__class__.ctx
# NOTE: According to Python unittest naming rules test method names should start from 'test'. # noqa
def test_filter_contigs_ok(self):
obj_name = "contigset.1"
contig1 = {'id': '1', 'length': 10, 'md5': 'md5', 'sequence': 'agcttttcat'}
contig2 = {'id': ... | return self.__class__.serviceImpl
def getContext(self): | random_line_split |
eapearson_TestRichReports_server_test.py | # -*- coding: utf-8 -*-
import unittest
import os # noqa: F401
import json # noqa: F401
import time
import requests
from os import environ
try:
from ConfigParser import ConfigParser # py2
except:
from configparser import ConfigParser # py3
from pprint import pprint # noqa: F401
from biokbase.workspace.c... | (self):
return self.__class__.wsClient
def getWsName(self):
if hasattr(self.__class__, 'wsName'):
return self.__class__.wsName
suffix = int(time.time() * 1000)
wsName = "test_eapearson_TestRichReports_" + str(suffix)
ret = self.getWsClient().create_workspace({'wo... | getWsClient | identifier_name |
eapearson_TestRichReports_server_test.py | # -*- coding: utf-8 -*-
import unittest
import os # noqa: F401
import json # noqa: F401
import time
import requests
from os import environ
try:
from ConfigParser import ConfigParser # py2
except:
from configparser import ConfigParser # py3
from pprint import pprint # noqa: F401
from biokbase.workspace.c... |
def test_filter_contigs_err1(self):
with self.assertRaises(ValueError) as context:
self.getImpl().filter_contigs(self.getContext(), {'workspace': self.getWsName(),
'contigset_id': 'fake', 'min_length': 10})
self.assertTrue('Error loading original ContigSet object' in st... | obj_name = "contigset.1"
contig1 = {'id': '1', 'length': 10, 'md5': 'md5', 'sequence': 'agcttttcat'}
contig2 = {'id': '2', 'length': 5, 'md5': 'md5', 'sequence': 'agctt'}
contig3 = {'id': '3', 'length': 12, 'md5': 'md5', 'sequence': 'agcttttcatgg'}
obj1 = {'contigs': [contig1, contig2, c... | identifier_body |
eapearson_TestRichReports_server_test.py | # -*- coding: utf-8 -*-
import unittest
import os # noqa: F401
import json # noqa: F401
import time
import requests
from os import environ
try:
from ConfigParser import ConfigParser # py2
except:
from configparser import ConfigParser # py3
from pprint import pprint # noqa: F401
from biokbase.workspace.c... |
suffix = int(time.time() * 1000)
wsName = "test_eapearson_TestRichReports_" + str(suffix)
ret = self.getWsClient().create_workspace({'workspace': wsName}) # noqa
self.__class__.wsName = wsName
return wsName
def getImpl(self):
return self.__class__.serviceImpl
... | return self.__class__.wsName | conditional_block |
gulpfile.js | const fs = require('fs-extra')
const gulp = require('gulp')
const handlebars = require('handlebars')
const autoprefixer = require('gulp-autoprefixer')
const clean = require('gulp-clean-css')
const connect = require('gulp-connect')
const sass = require('gulp-sass')
gulp.task('connect', () =>
connect.server({
liv... | gulp.watch('./public/**/*', ['livereload'])
})
gulp.task('dev', ['connect', 'watch', 'default'])
gulp.task('stylesheets', () =>
gulp
.src('./src/stylesheets/*.scss')
.pipe(sass().on('error', sass.logError))
.pipe(autoprefixer())
.pipe(clean())
.pipe(gulp.dest('./public/assets/css/'))
.pipe... | gulp.task('watch', () => {
gulp.watch('./src/stylesheets/*.scss', ['stylesheets'])
gulp.watch('./src/data.json', ['templates'])
gulp.watch('./src/templates/*.hbs', ['templates']) | random_line_split |
qingjia_calendar.py | #!usr/bin/python
# -*- coding:utf-8 -*-
from osv import osv,fields
import time
from datetime import datetime
from dateutil import rrule
class qingjia_calendar(osv.osv):
_name='qingjia.calendar'
_columns={
'start_date':fields.datetime('start_date'),
'end_date':fields.datetime('end... |
qingjia_calendar_line()
| if res:
print res,'res'
return {'value':{'name':res}} | identifier_body |
qingjia_calendar.py | #!usr/bin/python
# -*- coding:utf-8 -*-
from osv import osv,fields
import time
from datetime import datetime
from dateutil import rrule
class qingjia_calendar(osv.osv):
_name='qingjia.calendar'
_columns={
'start_date':fields.datetime('start_date'),
'end_date':fields.datetime('end... |
qingjia_calendar()
class qingjia_calendar_line(osv.osv):
_name='qingjia.calendar.line'
_columns={
'qingjia_calendar_id':fields.many2one('qingjia.calendar','qingjia_calendar_id'),
'name':fields.char('type',size=64),
'date':fields.datetime('date'),
'type':fiel... | datas.append((0,0,{'date':day,'type':'holiday','state':'arrange','name':'holiday'}))
self.write(cr,uid,ids,{'calendar_line_ids':datas})
return True | random_line_split |
qingjia_calendar.py | #!usr/bin/python
# -*- coding:utf-8 -*-
from osv import osv,fields
import time
from datetime import datetime
from dateutil import rrule
class qingjia_calendar(osv.osv):
_name='qingjia.calendar'
_columns={
'start_date':fields.datetime('start_date'),
'end_date':fields.datetime('end... |
for day in holidays:
line_search=line_obj.search(cr,uid,[('date','=',day),('type','=','holiday'),('state','=','arrange')])
if line_search:
datas.append((4,line_search[0]))
else:
datas.append((0,0,{'date':day,'type':'holiday','state':'arra... | date_info=ge.next()
date_list=map(str,(date_info.year,date_info.month,date_info.day))
date='-'.join(date_list)
holidays.append(date) | conditional_block |
qingjia_calendar.py | #!usr/bin/python
# -*- coding:utf-8 -*-
from osv import osv,fields
import time
from datetime import datetime
from dateutil import rrule
class qingjia_calendar(osv.osv):
_name='qingjia.calendar'
_columns={
'start_date':fields.datetime('start_date'),
'end_date':fields.datetime('end... | (osv.osv):
_name='qingjia.calendar.line'
_columns={
'qingjia_calendar_id':fields.many2one('qingjia.calendar','qingjia_calendar_id'),
'name':fields.char('type',size=64),
'date':fields.datetime('date'),
'type':fields.selection([('work','Work'),('holiday','Holiday')]... | qingjia_calendar_line | identifier_name |
wave-loading.d.ts | import { Options as WaveOptions } from './wave'
export interface Options extends WaveOptions {
// [font style][font weight][font size][font family]
// 文本样式,同css一样,必须包含 [font size] 和 [font family]
font: string
// 文本颜色
textColor: string
// 进度文本模板,`%d` 将被替换成取整的进度值
textFormatter: string
// 画布外边框圆角
bor... | export type InputOptions = Omit<Options, 'offsetTop' | 'color'>
export interface IElement {
// x 坐标
x: number
// y 坐标
y: number
} | // 目前支持匀速(linear),先加速再减速(swing),两种
easing: 'linear' | 'swing' | 'easeInOutQuad'
}
| random_line_split |
applicationsettings.rs | //! Stores all settings related to the application from a user perspective
use app_dirs::*;
use clap::ArgMatches;
use crate::io::constants::{APP_INFO, SCALE}; | use log4rs::config::{Appender, Config, Root};
use log4rs::encode::pattern::PatternEncoder;
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct ApplicationSettings {
pub rom_file_name: String,
pub debug_mode: bool,
pub trace_mode: bool,
pub memvis_mode: bool,
pub debugger_on: bool,
pub vu... | use std::path::PathBuf;
use log::LevelFilter;
use log4rs;
use log4rs::append::console::ConsoleAppender; | random_line_split |
applicationsettings.rs | //! Stores all settings related to the application from a user perspective
use app_dirs::*;
use clap::ArgMatches;
use crate::io::constants::{APP_INFO, SCALE};
use std::path::PathBuf;
use log::LevelFilter;
use log4rs;
use log4rs::append::console::ConsoleAppender;
use log4rs::config::{Appender, Config, Root};
use log4r... | (arguments: &ArgMatches) -> Result<ApplicationSettings, String> {
// Attempt to read ROM first
let rom_file_name = arguments
.value_of("game")
.expect("Could not open specified rom")
.to_string();
let debug_mode = arguments.is_present("debug");
let tra... | new | identifier_name |
DragItemConfig.ts | import ReactDom from 'react-dom'
export default {
dragSourceConfig: {
beginDrag(props) {
return { | item: props.item,
index: props.index,
targetIndex: undefined
}
},
endDrag(props, monitor, component) {
if (!monitor.didDrop()) {
return
}
const item = monitor.getItem()
const dragIndex = item.index
const targetIndex = item.targetIndex
... | id: props.id, | random_line_split |
DragItemConfig.ts | import ReactDom from 'react-dom'
export default {
dragSourceConfig: {
beginDrag(props) {
return {
id: props.id,
item: props.item,
index: props.index,
targetIndex: undefined
}
},
endDrag(props, monitor, component) {
if (!monitor.didDrop()) {
return... | (props, monitor, component) {
// update style of targer?
const dragIndex = monitor.getItem().index
const targetIndex = props.index
monitor.getItem().targetIndex = targetIndex
// Determine rectangle on screen
/* eslint-disable react/no-find-dom-node */
const hoverBoundingRect =... | hover | identifier_name |
DragItemConfig.ts | import ReactDom from 'react-dom'
export default {
dragSourceConfig: {
beginDrag(props) {
return {
id: props.id,
item: props.item,
index: props.index,
targetIndex: undefined
}
},
endDrag(props, monitor, component) | monitor.getItem().index = targetIndex
}
},
/**
* Specifies the props to inject into your component.
*/
collect(connect, monitor) {
return {
connectDragSource: connect.dragSource(),
isDragging: monitor.isDragging()
}
},
connect(connect) {
return {
connectDropTar... | {
if (!monitor.didDrop()) {
return
}
const item = monitor.getItem()
const dragIndex = item.index
const targetIndex = item.targetIndex
// Don't replace items with themselves
if (targetIndex === undefined || dragIndex === targetIndex) {
return
}
// ... | identifier_body |
DragItemConfig.ts | import ReactDom from 'react-dom'
export default {
dragSourceConfig: {
beginDrag(props) {
return {
id: props.id,
item: props.item,
index: props.index,
targetIndex: undefined
}
},
endDrag(props, monitor, component) {
if (!monitor.didDrop()) {
return... |
// Time to actually perform the action
props.moveItem(dragIndex, targetIndex)
// Note: we're mutating the monitor item here!
// Generally it's better to avoid mutations,
// but it's good here for the sake of performance
// to avoid expensive index searches.
monitor.getItem().... | {
return
} | conditional_block |
rb_menu.js | /*
* simple sliding menu using jQuery and Interface - http://www.getintothis.com
*
* note: this library depends on jquery (http://www.jquery.com) and
* interface (http://interface.eyecon.ro)
*
* Copyright (c) 2006 Ramin Bozorgzadeh
* Dual licensed under the MIT (MIT-LICENSE.txt)
* and GPL (GPL-LECENSE.txt) lin... | return this.each(function() {
var menu = jQuery(this).find('.rb_menu');
var toggle = jQuery(this).find('.rb_toggle span');
// add 'hover' class to trigger for css styling
toggle.hover( function() {
jQuery(this).addClass('hover');
}, function() {
jQuery(this).rem... | jQuery.extend(self.options, options);
}
| random_line_split |
rb_menu.js | /*
* simple sliding menu using jQuery and Interface - http://www.getintothis.com
*
* note: this library depends on jquery (http://www.jquery.com) and
* interface (http://interface.eyecon.ro)
*
* Copyright (c) 2006 Ramin Bozorgzadeh
* Dual licensed under the MIT (MIT-LICENSE.txt)
* and GPL (GPL-LECENSE.txt) lin... |
});
menu.hideMenu = function() {
if(this.css('display') == 'block' && !self.closed) {
this.SlideOutLeft(
self.options.effectDuration,
function() {
self.closed = true;
self.unbind();
... | {
menu.showMenu();
} | conditional_block |
ffi.rs | use std::io::Write;
use std::net::{SocketAddr, SocketAddrV4 as V4, Ipv4Addr};
use std::sync::mpsc::channel;
use std::slice::from_raw_parts;
use rotor_redis::conversion::ToRedisCommand;
use rotor_stream::Buf;
use inner::{MANAGER, Command, SockId, Socket};
#[repr(C)]
pub struct Arg {
data: *const u8,
len: usiz... |
impl ToRedisCommand for ArgSet {
fn write_into(self, buf: &mut Buf) {
unsafe {
let items = from_raw_parts(self.items, self.num);
let n = items.len();
write!(buf, "*{}\r\n", n).expect("buffer write");
for item in items {
let slc = from_raw_par... | {
MANAGER.with_socket(sock as SockId, |s| {
match s {
&mut Socket::Redis(ref red) => {
let mut lock = red.0.lock().expect("lock redis connection");
ArgSet { items: args, num: num }.write_into(
lock.transport().expect("valid redis transport").ou... | identifier_body |
ffi.rs | use std::io::Write;
use std::net::{SocketAddr, SocketAddrV4 as V4, Ipv4Addr};
use std::sync::mpsc::channel;
use std::slice::from_raw_parts;
use rotor_redis::conversion::ToRedisCommand;
use rotor_stream::Buf;
use inner::{MANAGER, Command, SockId, Socket};
#[repr(C)]
pub struct Arg {
data: *const u8,
len: usiz... | {
items: *const Arg,
num: usize,
}
#[no_mangle]
pub extern fn stator_redis_connect_ipv4(ip: u32, port: u16, db: u32) -> u64 {
let (tx, rx) = channel();
MANAGER.post_message(
Command::NewRedis((
SocketAddr::V4(V4::new(Ipv4Addr::from(ip), port)),
db,
tx,
... | ArgSet | identifier_name |
ffi.rs | use std::io::Write;
use std::net::{SocketAddr, SocketAddrV4 as V4, Ipv4Addr};
use std::sync::mpsc::channel; | use rotor_stream::Buf;
use inner::{MANAGER, Command, SockId, Socket};
#[repr(C)]
pub struct Arg {
data: *const u8,
len: usize,
}
pub struct ArgSet {
items: *const Arg,
num: usize,
}
#[no_mangle]
pub extern fn stator_redis_connect_ipv4(ip: u32, port: u16, db: u32) -> u64 {
let (tx, rx) = channel(... | use std::slice::from_raw_parts;
use rotor_redis::conversion::ToRedisCommand; | random_line_split |
ffi.rs | use std::io::Write;
use std::net::{SocketAddr, SocketAddrV4 as V4, Ipv4Addr};
use std::sync::mpsc::channel;
use std::slice::from_raw_parts;
use rotor_redis::conversion::ToRedisCommand;
use rotor_stream::Buf;
use inner::{MANAGER, Command, SockId, Socket};
#[repr(C)]
pub struct Arg {
data: *const u8,
len: usiz... |
_ => {
error!("Socket {} is a redis", sock);
return 0;
}
}
}).unwrap_or(0) as u64
}
impl ToRedisCommand for ArgSet {
fn write_into(self, buf: &mut Buf) {
unsafe {
let items = from_raw_parts(self.items, self.num);
l... | {
let mut lock = red.0.lock().expect("lock redis connection");
ArgSet { items: args, num: num }.write_into(
lock.transport().expect("valid redis transport").output());
let id = lock.protocol().expect("valid redis proto")
.receiver.n... | conditional_block |
DU_ABPTableSkewed_txtBIOStmb_sepSIO_line.py | # -*- coding: utf-8 -*-
"""
***
Labelling is B I O St Sm Sb
Singletons are split into:
- St : a singleton on "top" of its cell, vertically
- Sm : a singleton in "middle" of its cell, vertically
- Sb : a singleton in "bottom" of its cell, vertically
Copyright Naver Labs Eu... |
# ROW
ntR = NodeType_BIESO_to_SIOStSmSb_Shape("row"
, lLabels_SIOStSmSb_row
, None
, False
, None
)
ntR.setLabelAttribute("DU_row")
... | """
In this class method, we must return a configured graph class
"""
# Textline labels
# Begin Inside End Single Other
lLabels_SIOStSmSb_row = ['B', 'I', 'O', 'St', 'Sm', 'Sb']
# Cut lines:
# Border Ignore Separator Outside
lLabels_SIO_Cut ... | identifier_body |
DU_ABPTableSkewed_txtBIOStmb_sepSIO_line.py | # -*- coding: utf-8 -*-
"""
***
Labelling is B I O St Sm Sb
Singletons are split into:
- St : a singleton on "top" of its cell, vertically
- Sm : a singleton in "middle" of its cell, vertically
- Sb : a singleton in "bottom" of its cell, vertically
Copyright Naver Labs Eu... |
DU_GRAPH.iBlockVisibility = cls.iBlockVisibility
DU_GRAPH.iLineVisibility = cls.iLineVisibility
DU_GRAPH.fCutHeight = cls.fCutHeight
DU_GRAPH.bCutAbove = cls.bCutAbove
DU_GRAPH.lRadAngle = cls.lRadAngle
# ROW
ntR = ... | DU_GRAPH = GraphSkewedCut_H_lines | random_line_split |
DU_ABPTableSkewed_txtBIOStmb_sepSIO_line.py | # -*- coding: utf-8 -*-
"""
***
Labelling is B I O St Sm Sb
Singletons are split into:
- St : a singleton on "top" of its cell, vertically
- Sm : a singleton in "middle" of its cell, vertically
- Sb : a singleton in "bottom" of its cell, vertically
Copyright Naver Labs Eu... | (NodeType_BIESO_to_BIO_Shape):
"""
Convert BIESO labeling to SIOStSmSb
"""
bColumnHeader = False # ignore headers for now
dConverter = { 'B':'B',
'I':'I',
'E':'I',
'S':None, # St Sm Sb => specific processing to get it
... | NodeType_BIESO_to_SIOStSmSb_Shape | identifier_name |
DU_ABPTableSkewed_txtBIOStmb_sepSIO_line.py | # -*- coding: utf-8 -*-
"""
***
Labelling is B I O St Sm Sb
Singletons are split into:
- St : a singleton on "top" of its cell, vertically
- Sm : a singleton in "middle" of its cell, vertically
- Sb : a singleton in "bottom" of its cell, vertically
Copyright Naver Labs Eu... |
else:
if ptTxt.y < plgCell.centroid.y:
sXmlLabel = "St"
else:
sXmlLabel = "Sb"
try:
sLabel = self.dXmlLabel2Label[sXmlLabel]
except KeyError:
# #not a label of interest, can we ignore it?
# ... | sXmlLabel = "Sm" | conditional_block |
parameterDeclarationStructurePrinterTests.ts | import { expect } from "chai";
import { ParameterDeclarationStructurePrinter } from "../../../structurePrinters";
import { OptionalKind, ParameterDeclarationStructure } from "../../../structures";
import { getStructureFactoryAndWriter } from "../../testHelpers";
describe(nameof(ParameterDeclarationStructurePrinter), (... | (structures: OptionalKind<ParameterDeclarationStructure>[], expectedOutput: string) {
const { writer, factory } = getStructureFactoryAndWriter();
factory.forParameterDeclaration().printTextsWithParenthesis(writer, structures);
expect(writer.toString()).to.equal(expectedOutput);
... | doTest | identifier_name |
parameterDeclarationStructurePrinterTests.ts | import { expect } from "chai";
import { ParameterDeclarationStructurePrinter } from "../../../structurePrinters";
import { OptionalKind, ParameterDeclarationStructure } from "../../../structures";
import { getStructureFactoryAndWriter } from "../../testHelpers";
describe(nameof(ParameterDeclarationStructurePrinter), (... |
it("should print multiple on a single line", () => {
doTest([{ name: "p" }, { name: "p1" }], "(p, p1)");
});
it("should handle when there are newlines in the type", () => {
doTest(
[{ name: "p", type: writer => writer.write("string").newLine().write("| ... | {
const { writer, factory } = getStructureFactoryAndWriter();
factory.forParameterDeclaration().printTextsWithParenthesis(writer, structures);
expect(writer.toString()).to.equal(expectedOutput);
} | identifier_body |
parameterDeclarationStructurePrinterTests.ts | import { expect } from "chai";
import { ParameterDeclarationStructurePrinter } from "../../../structurePrinters";
import { OptionalKind, ParameterDeclarationStructure } from "../../../structures";
import { getStructureFactoryAndWriter } from "../../testHelpers";
describe(nameof(ParameterDeclarationStructurePrinter), (... | });
});
}); | random_line_split | |
command_handlers.py | #!/usr/bin/env python3
#
# Copyright (c) 2020, The OpenThread Authors.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source code must retain the above copyright
# ... |
if not OtCliCommandRunner.__PATTERN_LOG_LINE.match(line):
self.__pending_lines.put(line)
class OtbrSshCommandRunner(OTCommandHandler):
def __init__(self, host, port, username, password, sudo):
import paramiko
self.__host = host
self.__port = port
sel... | try:
line = self.__otcli.readline()
except Exception:
if self.__should_close.is_set():
break
else:
raise
logging.debug('%s: %r', self.__otcli, line)
if line is None:
break
... | conditional_block |
command_handlers.py | #!/usr/bin/env python3
#
# Copyright (c) 2020, The OpenThread Authors.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source code must retain the above copyright
# ... |
def shell(self, cmd: str, timeout: float) -> List[str]:
raise NotImplementedError("shell command is not supported on %s" % self.__class__.__name__)
class OtCliCommandRunner(OTCommandHandler):
__PATTERN_COMMAND_DONE_OR_ERROR = re.compile(
r'(Done|Error|Error \d+:.*|.*: command not found)$') ... | """Method set_line_read_callback should register a callback that will be called for every line
output by the OT CLI.
This is useful for handling asynchronous command output while still being able to execute
other commands.
"""
pass | identifier_body |
command_handlers.py | #!/usr/bin/env python3
#
# Copyright (c) 2020, The OpenThread Authors.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source code must retain the above copyright
# ... | (self, callback: Optional[Callable[[str], Any]]):
self.__line_read_callback = callback
| set_line_read_callback | identifier_name |
command_handlers.py | #!/usr/bin/env python3
#
# Copyright (c) 2020, The OpenThread Authors.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source code must retain the above copyright
# ... | return output
def shell(self, cmd: str, timeout: float) -> List[str]:
cmd_in, cmd_out, cmd_err = self.__ssh.exec_command(cmd, timeout=int(timeout), bufsize=1024)
errput = [l.rstrip('\r\n') for l in cmd_err.readlines()]
output = [l.rstrip('\r\n') for l in cmd_out.readlines()]
... | random_line_split | |
datagram.rs | use super::{socket_addr, SocketAddr};
use crate::sys::unix::net::new_socket;
use std::io;
use std::os::unix::io::{AsRawFd, FromRawFd};
use std::os::unix::net;
use std::path::Path;
pub(crate) fn bind(path: &Path) -> io::Result<net::UnixDatagram> {
let fd = new_socket(libc::AF_UNIX, libc::SOCK_DGRAM)?;
// Ensur... | pub(crate) fn local_addr(socket: &net::UnixDatagram) -> io::Result<SocketAddr> {
super::local_addr(socket.as_raw_fd())
}
pub(crate) fn peer_addr(socket: &net::UnixDatagram) -> io::Result<SocketAddr> {
super::peer_addr(socket.as_raw_fd())
}
pub(crate) fn recv_from(
socket: &net::UnixDatagram,
dst: &mut... | pub(crate) fn pair() -> io::Result<(net::UnixDatagram, net::UnixDatagram)> {
super::pair(libc::SOCK_DGRAM)
}
| random_line_split |
datagram.rs | use super::{socket_addr, SocketAddr};
use crate::sys::unix::net::new_socket;
use std::io;
use std::os::unix::io::{AsRawFd, FromRawFd};
use std::os::unix::net;
use std::path::Path;
pub(crate) fn bind(path: &Path) -> io::Result<net::UnixDatagram> {
let fd = new_socket(libc::AF_UNIX, libc::SOCK_DGRAM)?;
// Ensur... |
pub(crate) fn peer_addr(socket: &net::UnixDatagram) -> io::Result<SocketAddr> {
super::peer_addr(socket.as_raw_fd())
}
pub(crate) fn recv_from(
socket: &net::UnixDatagram,
dst: &mut [u8],
) -> io::Result<(usize, SocketAddr)> {
let mut count = 0;
let socketaddr = SocketAddr::new(|sockaddr, socklen... | {
super::local_addr(socket.as_raw_fd())
} | identifier_body |
datagram.rs | use super::{socket_addr, SocketAddr};
use crate::sys::unix::net::new_socket;
use std::io;
use std::os::unix::io::{AsRawFd, FromRawFd};
use std::os::unix::net;
use std::path::Path;
pub(crate) fn | (path: &Path) -> io::Result<net::UnixDatagram> {
let fd = new_socket(libc::AF_UNIX, libc::SOCK_DGRAM)?;
// Ensure the fd is closed.
let socket = unsafe { net::UnixDatagram::from_raw_fd(fd) };
let (sockaddr, socklen) = socket_addr(path)?;
let sockaddr = &sockaddr as *const libc::sockaddr_un as *const... | bind | identifier_name |
web_platform_test_server.py | forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
# ... | if (not self._filesystem.compare(wpt_testharnessjs_file, layout_tests_testharnessjs_file)):
_log.warning("\n//////////\nWPT tests are not using the same testharness.js file as other WebKit Layout tests.\nWebKit testharness.js might need to be updated according WPT testharness.js.\n//////////\n")
... | # FIXME: Next line to be removed once all bots have wpt_testharnessjs_file updated correctly. See https://bugs.webkit.org/show_bug.cgi?id=152257.
self._filesystem.copyfile(layout_tests_testharnessjs_file, wpt_testharnessjs_file) | random_line_split |
web_platform_test_server.py | forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
# ... | (self):
_log.debug('Cleaning WPT resources files')
for f in self._resources_files_to_copy:
wpt_filename = self._filesystem.join(self._doc_root, "resources", f)
if self._filesystem.isfile(wpt_filename):
self._filesystem.remove(wpt_filename)
_log.debug('Clea... | _clean_webkit_test_files | identifier_name |
web_platform_test_server.py | , with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
# n... |
finally:
self._filesystem.remove(self._servers_file)
def stop(self):
super(WebPlatformTestServer, self).stop()
# In case of orphaned pid, kill the running subservers if any still alive.
self._stop_running_subservers()
def _stop_running_server(self):
... | if self._executive.check_running_pid(server['pid']):
_log.warning('Killing server process (protocol: %s , port: %d, pid: %d).' % (server['protocol'], server['port'], server['pid']))
self._executive.kill_process(server['pid']) | conditional_block |
web_platform_test_server.py | , with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
# n... |
def _stop_running_server(self):
_log.debug('Stopping %s server' % (self._name))
self._clean_webkit_test_files()
if self._process:
(self._stdout_data, self._stderr_data) = self._process.communicate(input='\n')
if self._wsout:
self._wsout.close()
... | super(WebPlatformTestServer, self).stop()
# In case of orphaned pid, kill the running subservers if any still alive.
self._stop_running_subservers() | identifier_body |
data.js | var DATA = {"a" : "b", "c" : "d"};
|
var REQUEST = {
"name":"alex",
"vendor":"OpenPolicy",
"version":"0.1",
"preferences":["germany"],
"attributes":[
{
"#http://www.q-team.org/Ontology#Einwilligung_Zur_Datensammlung":true
},
{
"#http://www.q-team.org/Ontology#minAge":12
},
{
"#http://www.q-team.org/Ontology#Recht_auf_Vergessen":false
},... | var RESPONSE = {"vendor":"OpenPolicy","name":"alex","locations":[{"continent":"Europe","country":"Germany","price":5,"latitude":"48.105964","name":"Slot_ger_4","longitude":"11.612549"},{"continent":"Europe","country":"Germany","price":6,"latitude":"52.473412","name":"Slot_ger_1","longitude":"13.390961"},{"continent":"E... | random_line_split |
interfaces.d.ts | /// <reference types="node" />
/** @ignore */
export declare const ITERATOR_DONE: any;
/** @ignore */
export declare type FileHandle = import('fs').promises.FileHandle;
/** @ignore */
export declare type ArrowJSONLike = {
schema: any;
batches?: any[]; | type: 'bytes' | undefined;
autoAllocateChunkSize?: number;
highWaterMark?: number;
};
/** @ignore */
export declare class ArrowJSON {
private _json;
constructor(_json: ArrowJSONLike);
readonly schema: any;
readonly batches: any[];
readonly dictionaries: any[];
}
/** @ignore */
export int... | dictionaries?: any[];
};
/** @ignore */
export declare type ReadableDOMStreamOptions = { | random_line_split |
interfaces.d.ts | /// <reference types="node" />
/** @ignore */
export declare const ITERATOR_DONE: any;
/** @ignore */
export declare type FileHandle = import('fs').promises.FileHandle;
/** @ignore */
export declare type ArrowJSONLike = {
schema: any;
batches?: any[];
dictionaries?: any[];
};
/** @ignore */
export declare t... | <TReadable = Uint8Array, TWritable = TReadable> extends ReadableInterop<TReadable> implements AsyncIterableIterator<TReadable>, ReadableWritable<TReadable, TWritable> {
protected _values: TWritable[];
protected _error?: {
error: any;
};
protected _closedPromise: Promise<void>;
protected _clo... | AsyncQueue | identifier_name |
buffered_stream.rs | #![cfg(feature = "std")]
extern crate combine;
use combine::parser::char::{char, digit, spaces, string};
use combine::stream::buffered::BufferedStream;
use combine::stream::easy::{self, Error};
use combine::stream::state::State;
use combine::stream::IteratorStream;
use combine::{choice, many, many1, sep_by, try, Parser... | () {
let text = "apple,apple,ananas,orangeblah";
let mut iter = text.chars();
// Iterator that can't be cloned
let stream = BufferedStream::new(easy::Stream(State::new(IteratorStream::new(&mut iter))), 1);
let value: &mut Parser<Input = _, Output = _, PartialState = _> = &mut choice([
try(s... | shared_stream_insufficent_backtrack | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.