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
slope_histogram_cumulative_graph.py
#!/usr/bin/env python #/****************************************************************************** # * $Id$ # * # * Project: GDAL Make Histogram and Cumulative graph from Tab delimited tab as # generated by gdal_hist.py # * Purpose: Take a gdal_hist.py output and create a histogram plot using matp...
else: Usage() i = i + 1 if infile is None: usage() if not(os.path.isfile(infile)): input = sys.argv[1] print "filename %s does not exist." % (infile) sys.exit(1) #load table df = pd.DataFrame.from_csv(infile, sep='\t', header=1) #initialize figure fig, ax1 = plt.subplots() #calcula...
outfile = arg
conditional_block
slope_histogram_cumulative_graph.py
#!/usr/bin/env python #/****************************************************************************** # * $Id$ # * # * Project: GDAL Make Histogram and Cumulative graph from Tab delimited tab as # generated by gdal_hist.py # * Purpose: Take a gdal_hist.py output and create a histogram plot using matp...
ax1.ticklabel_format(style='sci', axis='y', scilimits=(0,0)) ax1.get_yaxis().set_tick_params(direction='out') #get min and max as found by pandas for plotting 'arrow' at X=15 #minY = round(df['count'].min(),0) #maxY = round(df['count'].max(),0) #grab existing ax1 axes #ax = plt.axes() #ax.arrow(15, minY, 0, maxY, hea...
#Plot frequency histogram from input table ax1.fill(df.value,df['count'],'gray') #df.plot(ax1=ax1, kind='area', color='gray', legend=True)
random_line_split
custom.js
00); }); jQuery("#toTop").addClass("hidett"); jQuery(window).scroll(function () { if (jQuery(this).scrollTop() < 400) { jQuery("#toTop").addClass("hidett").removeClass("showtt"); } else { jQuery("#toTop").removeClass("hidett").addClass("showtt"); } }); // Slideshows if ($("#Flexslidert")[0]) { $('#...
{ try { // just in case. maybe prettyphoto isnt loaded on this site jQuery('a.prettyphoto, .gallery-icon a[href*=".jpg"]').prettyPhoto({ animationSpeed:'normal', /* fast/slow/normal */ padding:15, /* padding for each side of the picture */ opacity:0.7, /* Value betwee 0 and 1 */ ...
identifier_body
custom.js
wo"><i class="fa fa-bars"></i></a>'); jQuery("#mymenutwo").mmenu({ dragOpen: true, position: "left", zposition: "next" }, { clone : true }); } jQuery('.mm-menu .mm-list').removeClass('sf-menu res_mode sf-js-enabled sf-shadow'); } // Superfish if ($(".sf-menu")[0]) { $('.sf-menu').supe...
jQuery("#toTop").addClass("hidett").removeClass("showtt"); } else { jQuery("#toTop").removeClass("hidett").addClass("showtt"); } }); // Slideshows if ($("#Flexslidert")[0]) { $('#Flexslidert').flexslider({ animation: "slide", manualControls: "#slider_nav li" }); } if ($("[class^='gallery_']")[...
}, 1000); }); jQuery("#toTop").addClass("hidett"); jQuery(window).scroll(function () { if (jQuery(this).scrollTop() < 400) {
random_line_split
custom.js
(); }); $tabsNavLis.on('click', function(e) { var $this = $(this); $this.siblings().removeClass('active').end() .addClass('active'); $this.parent().next().children('.T20-tab').stop(true,true).hide() .siblings( $this.find('a').attr('href') ).fadeIn(); e.preventDefault(); }).children( window...
vc_prettyPhoto
identifier_name
custom.js
$this.children('li').first().addClass('active').stop(true,true).show(); }); $tabsNavLis.on('click', function(e) { var $this = $(this); $this.siblings().removeClass('active').end() .addClass('active'); $this.parent().next().children('.T20-tab').stop(true,true).hide() .siblings( $this.find('a').a...
{ if($('.my_sticky').hasClass('ssticky')){ $('.my_sticky').removeClass('ssticky'); $('.my_sticky').stop(true).animate({opacity : 0}, 300, function(){ $('.my_sticky').removeClass('ssticky'); $('.my_sticky').stop(true).animate({opacity : 1}, 300); $('.Corpse_Sticky').css('padding-top', '')...
conditional_block
HttpTypes.ts
import { FutureResult } from '@ephox/katamari'; import { ResponseBodyDataTypes, RequestBody, ResponseBody } from './HttpData'; import { HttpError } from './HttpError'; export const enum HttpMethod { Get = 'get', Post = 'post', Delete = 'delete', Patch = 'patch', Put = 'put' }
responseType: T; body: RequestBody; url: string; method: HttpMethod; query?: Record<string, string>; progress?: ProgressFunction; headers?: Record<string, string>; credentials?: boolean; } export interface HttpResponse<T extends ResponseBody> { headers: Record<string, string>; statusCode: number; ...
export type ProgressFunction = (loaded: number, total: number) => void; export type LoadedProgressFunction = (loaded: number) => void; export interface HttpRequest<T extends ResponseBodyDataTypes> {
random_line_split
Analyser.spec.ts
/// <reference path="../ref.d.ts" /> import jasmine_tss = require('../../jasmine_tss'); var setSpy = jasmine_tss.setSpy, spyOf = jasmine_tss.spyOf; import IResultImage = require('../../../src/common/Result/IResultImage'); import ActionType = require('../../../src/common/Test/ActionType'); import ISegment = require('.....
_cropper = jasmine.createSpyObj<Cropper>('Cropper', ['crop']); analyser = new Analyser(_cropper, _comparer); }); it('delegates to Cropper to create a cropped images', () => { var segments: ISegment[] = [ { topLeft: { x: 2, y: 2 }, bottomRight: { x: 3, y: 3} } ]; analyser.process('testNa...
random_line_split
stacks-utils.ts
import { WebAppStack } from '../models/stacks/web-app-stacks'; import { IDropdownOption } from 'office-ui-fabric-react'; import { AppStackOs } from '../models/stacks/app-stacks'; import { FunctionAppStack } from '../models/stacks/function-app-stacks'; export const getStacksSummaryForDropdown = (stack: WebAppStack | Fu...
}); }); return options; }; export class JavaVersions { public static WindowsVersion8 = '1.8'; public static WindowsVersion11 = '11'; public static LinuxVersion8 = 'java8'; public static LinuxVersion11 = 'java11'; } export class JavaContainers { public static JavaSE = 'java'; public static Tomcat ...
{ options.push({ key: settings.runtimeVersion, text: stackMinorVersion.displayText, data: stackMinorVersion, }); }
conditional_block
stacks-utils.ts
import { WebAppStack } from '../models/stacks/web-app-stacks'; import { IDropdownOption } from 'office-ui-fabric-react'; import { AppStackOs } from '../models/stacks/app-stacks'; import { FunctionAppStack } from '../models/stacks/function-app-stacks'; export const getStacksSummaryForDropdown = (stack: WebAppStack | Fu...
{ public static JavaSE = 'java'; public static Tomcat = 'tomcat'; } export class RuntimeStacks { public static aspnet = 'asp.net'; public static node = 'node'; public static python = 'python'; public static dotnetcore = 'dotnetcore'; public static java8 = 'java-8'; public static java11 = 'java-11'; }
JavaContainers
identifier_name
stacks-utils.ts
import { WebAppStack } from '../models/stacks/web-app-stacks'; import { IDropdownOption } from 'office-ui-fabric-react'; import { AppStackOs } from '../models/stacks/app-stacks'; import { FunctionAppStack } from '../models/stacks/function-app-stacks'; export const getStacksSummaryForDropdown = (stack: WebAppStack | Fu...
}
random_line_split
task-perf-alloc-unwind.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 ...
res: r(box List::Cons((), st.res._l.clone())), } } }; recurse_or_panic(depth, Some(st)); } }
{ if depth == 0 { panic!(); } else { let depth = depth - 1; let st = match st { None => { State { unique: box List::Nil, vec: vec!(box List::Nil), res: r(box List::Nil) } ...
identifier_body
task-perf-alloc-unwind.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 ...
{ unique: Box<nillist>, vec: Vec<Box<nillist>>, res: r } struct r { _l: Box<nillist>, } #[unsafe_destructor] impl Drop for r { fn drop(&mut self) {} } fn r(l: Box<nillist>) -> r { r { _l: l } } fn recurse_or_panic(depth: int, st: Option<State>) { if depth == 0 { panic!...
State
identifier_name
task-perf-alloc-unwind.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 ...
}); println!("iter: {}", dur); } } type nillist = List<()>; // Filled with things that have to be unwound struct State { unique: Box<nillist>, vec: Vec<Box<nillist>>, res: r } struct r { _l: Box<nillist>, } #[unsafe_destructor] impl Drop for r { fn drop(&mut self) {} } fn r(l...
for _ in 0..repeat { let dur = Duration::span(|| { let _ = Thread::scoped(move|| { recurse_or_panic(depth, None) }).join();
random_line_split
task-perf-alloc-unwind.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 ...
else { let depth = depth - 1; let st = match st { None => { State { unique: box List::Nil, vec: vec!(box List::Nil), res: r(box List::Nil) } } Some(st) => { l...
{ panic!(); }
conditional_block
evaluate-template-input.component.ts
import {ChangeDetectionStrategy, Component, forwardRef} from '@angular/core'; import {ControlValueAccessor, NG_VALUE_ACCESSOR} from '@angular/forms'; import {MatDialog} from '@angular/material'; import {BehaviorSubject} from 'rxjs/BehaviorSubject'; import {UtilService} from '../../../core/services/util.service'; import...
pick() { this.dialog.open(EvaluateTemplatePickDialogComponent, { disableClose: true, panelClass: 'my-dialog' }).afterClosed() .filter(it => it) .subscribe(it => this.handleChange(it)); } update() { this.dialog.open(EvaluateTemplateUpdateDialogComponent, { disableClose: t...
}
random_line_split
evaluate-template-input.component.ts
import {ChangeDetectionStrategy, Component, forwardRef} from '@angular/core'; import {ControlValueAccessor, NG_VALUE_ACCESSOR} from '@angular/forms'; import {MatDialog} from '@angular/material'; import {BehaviorSubject} from 'rxjs/BehaviorSubject'; import {UtilService} from '../../../core/services/util.service'; import...
implements ControlValueAccessor { evaluateTemplate$ = new BehaviorSubject<EvaluateTemplate>(null); onModelChange: Function = () => { } onModelTouched: Function = () => { } constructor(private dialog: MatDialog, private utilService: UtilService) { } pick() { this.dialog.open(Evaluate...
EvaluateTemplateInputComponent
identifier_name
evaluate-template-input.component.ts
import {ChangeDetectionStrategy, Component, forwardRef} from '@angular/core'; import {ControlValueAccessor, NG_VALUE_ACCESSOR} from '@angular/forms'; import {MatDialog} from '@angular/material'; import {BehaviorSubject} from 'rxjs/BehaviorSubject'; import {UtilService} from '../../../core/services/util.service'; import...
}
{ this.evaluateTemplate$.next(feedbackTemplate); this.onModelChange(feedbackTemplate); }
identifier_body
GetPoints.js
/** * @author Richard Davey <rich@photonstorm.com> * @copyright 2019 Photon Storm Ltd. * @license {@link https://opensource.org/licenses/MIT|MIT License} */ var Length = require('./Length'); var Point = require('../point/Point'); /** * Get a number of points along a line's length. * * Provide a `...
module.exports = GetPoints;
random_line_split
GetPoints.js
/** * @author Richard Davey <rich@photonstorm.com> * @copyright 2019 Photon Storm Ltd. * @license {@link https://opensource.org/licenses/MIT|MIT License} */ var Length = require('./Length'); var Point = require('../point/Point'); /** * Get a number of points along a line's length. * * Provide a `...
var x1 = line.x1; var y1 = line.y1; var x2 = line.x2; var y2 = line.y2; for (var i = 0; i < quantity; i++) { var position = i / quantity; var x = x1 + (x2 - x1) * position; var y = y1 + (y2 - y1) * position; out.push(new Point(x, y)); } return out; ...
{ quantity = Length(line) / stepRate; }
conditional_block
defaults.rs
// Copyright 2013 The GLFW-RS Developers. For a full listing of the authors, // refer to the AUTHORS file at the top-level directory of this distribution. // // 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...
extern "C" { fn glGetIntegerv(pname: GLenum, params: *const GLint); } }
{ glGetIntegerv(pname, params) }
identifier_body
defaults.rs
// Copyright 2013 The GLFW-RS Developers. For a full listing of the authors, // refer to the AUTHORS file at the top-level directory of this distribution. // // 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...
let (mut window, _) = glfw.create_window(640, 480, "Defaults", glfw::WindowMode::Windowed) .expect("Failed to create GLFW window."); window.make_current(); let (width, height) = window.get_size(); println!("window size: ({:?}, {:?})", width, height); println!("Context version: {:?}", ...
random_line_split
defaults.rs
// Copyright 2013 The GLFW-RS Developers. For a full listing of the authors, // refer to the AUTHORS file at the top-level directory of this distribution. // // 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...
; } } mod gl { extern crate libc; #[cfg(target_os = "macos")] #[link(name="OpenGL", kind="framework")] extern { } #[cfg(target_os = "linux")] #[link(name="GL")] extern { } pub type GLenum = libc::c_uint; pub type GLint = libc::c_int; pub static RED_BITS : G...
{ let value = 0; unsafe { gl::GetIntegerv(param, &value) }; println!("OpenGL {:?}: {:?}", name, value); }
conditional_block
defaults.rs
// Copyright 2013 The GLFW-RS Developers. For a full listing of the authors, // refer to the AUTHORS file at the top-level directory of this distribution. // // 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...
(pname: GLenum, params: *const GLint) { glGetIntegerv(pname, params) } extern "C" { fn glGetIntegerv(pname: GLenum, params: *const GLint); } }
GetIntegerv
identifier_name
index.js
import Color from "./../../webgl/Color"; export default { prepareVector : prepareVector, initColorArray : initColorArray, scalePaletteColorValues: scalePaletteColorValues }; export function prepareVector(mesh, min, max, colorArray) { const colors = []; for (let i = 0; i < mesh.vectorData.le...
(alpha, min, max, array) { if (alpha <= min || min === max) { alpha = min; } else if (alpha >= max) { alpha = max; } else { alpha = (alpha - min) / (max - min); } let colorPosition = Math.round(alpha * array.length); if (colorPosition === array.length) { colorPosition -= 1; } return arra...
getColorFromArray
identifier_name
index.js
import Color from "./../../webgl/Color"; export default { prepareVector : prepareVector, initColorArray : initColorArray, scalePaletteColorValues: scalePaletteColorValues }; export function prepareVector(mesh, min, max, colorArray) { const colors = []; for (let i = 0; i < mesh.vectorData.le...
let colorPosition = Math.round(alpha * array.length); if (colorPosition === array.length) { colorPosition -= 1; } return array[colorPosition]; } export function scalePaletteColorValues(min, max, steps) { const newSteps = []; for (let i = 0; i < steps.length; i++) { newSteps.push({...steps[i], scal...
{ alpha = (alpha - min) / (max - min); }
conditional_block
index.js
import Color from "./../../webgl/Color"; export default { prepareVector : prepareVector, initColorArray : initColorArray, scalePaletteColorValues: scalePaletteColorValues }; export function prepareVector(mesh, min, max, colorArray) { const colors = []; for (let i = 0; i < mesh.vectorData.le...
export function scalePaletteColorValues(min, max, steps) { const newSteps = []; for (let i = 0; i < steps.length; i++) { newSteps.push({...steps[i], scaledVal: min + i * (max - min) / (steps.length - 1)}); } return newSteps; }
{ if (alpha <= min || min === max) { alpha = min; } else if (alpha >= max) { alpha = max; } else { alpha = (alpha - min) / (max - min); } let colorPosition = Math.round(alpha * array.length); if (colorPosition === array.length) { colorPosition -= 1; } return array[colorPosition]; }
identifier_body
index.js
import Color from "./../../webgl/Color"; export default { prepareVector : prepareVector, initColorArray : initColorArray, scalePaletteColorValues: scalePaletteColorValues }; export function prepareVector(mesh, min, max, colorArray) { const colors = []; for (let i = 0; i < mesh.vectorData.le...
colorArray.unshift(color); } else { colorArray.push(color); } } } } return colorArray; } export function getColorFromArray(alpha, min, max, array) { if (alpha <= min || min === max) { alpha = min; } else if (alpha >= max) { alpha = max; } else { ...
random_line_split
status-completed.js
sap.ui.define(['sap/ui/webc/common/thirdparty/base/asset-registries/Icons'], function (Icons) { 'use strict'; const name = "status-completed"; const pathData = "M256 0q53 0 99.5 20T437 75t55 81.5 20 99.5-20 99.5-55 81.5-81.5 55-99.5 20-99.5-20T75 437t-55-81.5T0 256t20-99.5T75 75t81.5-55T256 0zM128 256q-14 0-23 9t-9 ...
return pathDataV4; });
const collection = "SAP-icons-v5"; const packageName = "@ui5/webcomponents-icons"; Icons.registerIcon(name, { pathData, ltr, collection, packageName }); var pathDataV4 = { pathData };
random_line_split
comments.ts
import Ember from 'ember'; import { IDatasetComment, IDatasetCommentsGetResponse } from 'wherehows-web/typings/api/datasets/comments'; import { datasetUrlById } from 'wherehows-web/utils/api/datasets/shared'; import { ApiStatus } from 'wherehows-web/utils/api/shared'; const { $: { getJSON, post, ajax } } = Ember; /** ...
}; export { datasetCommentsFor, addDatasetCommentFor, deleteDatasetComment, modifyDatasetComment };
{ throw new Error(datasetCommentsApiException); }
conditional_block
comments.ts
import Ember from 'ember'; import { IDatasetComment, IDatasetCommentsGetResponse } from 'wherehows-web/typings/api/datasets/comments'; import { datasetUrlById } from 'wherehows-web/utils/api/datasets/shared'; import { ApiStatus } from 'wherehows-web/utils/api/shared'; const { $: { getJSON, post, ajax } } = Ember; /** ...
/** * Gets a specific comment on a dataset * @param {number} datasetId the id of the dataset * @param {number} commentId the id of the comment * @return {string} */ const datasetCommentUrlById = (datasetId: number, commentId: number): string => `${datasetCommentsUrlById(datasetId)}/${commentId}`; /** * For a ...
const datasetCommentsUrlById = (id: number): string => `${datasetUrlById(id)}/comments`;
random_line_split
__init__.py
# -*- coding: utf-8 -*-
# under the terms of the GNU General Public License as published by the Free # Software Foundation, either version 3 of the License, or (at your option) # any later version. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILI...
# # This file is part of bd808's stashbot application # Copyright (C) 2015 Bryan Davis and contributors # # This program is free software: you can redistribute it and/or modify it
random_line_split
tiledebugsource.js
goog.provide('ol.source.TileDebug'); goog.require('ol.Tile'); goog.require('ol.TileState'); goog.require('ol.dom'); goog.require('ol.size'); goog.require('ol.source.Tile'); /** * @constructor * @extends {ol.Tile} * @param {ol.TileCoord} tileCoord Tile coordinate. * @param {ol.Size} tileSize Tile size. * @param ...
else { var tileSize = this.tileSize_; var context = ol.dom.createCanvasContext2D(tileSize[0], tileSize[1]); context.strokeStyle = 'black'; context.strokeRect(0.5, 0.5, tileSize[0] + 0.5, tileSize[1] + 0.5); context.fillStyle = 'black'; context.textAlign = 'center'; context.textBaseline =...
{ return this.canvasByContext_[key]; }
conditional_block
tiledebugsource.js
goog.provide('ol.source.TileDebug'); goog.require('ol.Tile'); goog.require('ol.TileState'); goog.require('ol.dom'); goog.require('ol.size'); goog.require('ol.source.Tile'); /** * @constructor * @extends {ol.Tile} * @param {ol.TileCoord} tileCoord Tile coordinate. * @param {ol.Size} tileSize Tile size. * @param ...
* @api */ ol.source.TileDebug = function(options) { ol.source.Tile.call(this, { opaque: false, projection: options.projection, tileGrid: options.tileGrid, wrapX: options.wrapX !== undefined ? options.wrapX : true }); }; ol.inherits(ol.source.TileDebug, ol.source.Tile); /** * @inheritDoc */ o...
* @param {olx.source.TileDebugOptions} options Debug tile options.
random_line_split
export_5x_dashboards.py
from elasticsearch import Elasticsearch import argparse import os import json import re def ExportDashboards(es, regex, kibana_index, output_directory): res = es.search( index=kibana_index, doc_type="dashboard", size=1000) try: reg_exp = re.compile(regex, re.IGNORECASE) ex...
es, search, kibana_index, output_directory) def ExportSearch(es, search, kibana_index, output_directory): doc = es.get( index=kibana_index, doc_type="search", id=search) # save search SaveJson("search", doc, output_directory) def S...
if "savedSearchId" in doc["_source"]: search = doc["_source"]['savedSearchId'] ExportSearch(
random_line_split
export_5x_dashboards.py
from elasticsearch import Elasticsearch import argparse import os import json import re def ExportDashboards(es, regex, kibana_index, output_directory): res = es.search( index=kibana_index, doc_type="dashboard", size=1000) try: reg_exp = re.compile(regex, re.IGNORECASE) ex...
def main(): parser = argparse.ArgumentParser( description="Export the Kibana dashboards together with" " all used visualizations, searches and index pattern") parser.add_argument("--url", help="Elasticsearch URL. By default: http://localhost:9200", ...
dir = os.path.join(output_directory, doc_type) if not os.path.exists(dir): os.makedirs(dir) # replace unsupported characters filepath = os.path.join(dir, re.sub(r'[\>\<:"/\\\|\?\*]', '', doc['_id']) + '.json') with open(filepath, 'w') as f: json.dump(doc['_source'], f, indent=2) ...
identifier_body
export_5x_dashboards.py
from elasticsearch import Elasticsearch import argparse import os import json import re def ExportDashboards(es, regex, kibana_index, output_directory): res = es.search( index=kibana_index, doc_type="dashboard", size=1000) try: reg_exp = re.compile(regex, re.IGNORECASE) ex...
def ExportSearch(es, search, kibana_index, output_directory): doc = es.get( index=kibana_index, doc_type="search", id=search) # save search SaveJson("search", doc, output_directory) def SaveJson(doc_type, doc, output_directory): dir = os.path.join(output_directory, doc_typ...
search = doc["_source"]['savedSearchId'] ExportSearch( es, search, kibana_index, output_directory)
conditional_block
export_5x_dashboards.py
from elasticsearch import Elasticsearch import argparse import os import json import re def
(es, regex, kibana_index, output_directory): res = es.search( index=kibana_index, doc_type="dashboard", size=1000) try: reg_exp = re.compile(regex, re.IGNORECASE) except: print("Wrong regex {}".format(regex)) return for doc in res['hits']['hits']: ...
ExportDashboards
identifier_name
reload.ts
import { UntitledClient, BaseCommand, BaseCommandGroup, BaseCommandDecorators, BaseMessage, disambiguation } from '../../../'; import { oneLine, stripIndents } from 'common-tags'; import { Collection, Message } from 'discord.js'; const { name, aliases, group, memberName, description, details, examples, guarded, args }...
extends BaseCommand { public hasPermission(msg: BaseMessage): boolean { return this.client.isOwner(msg.author); } @args({ key: 'cmdOrGrp', label: 'command/group', prompt: 'which command or group would you like to reload?\n', validate: (val: string) => { if (!val) return false; const groups: BaseCom...
ReloadCommandCommand
identifier_name
reload.ts
import { UntitledClient, BaseCommand, BaseCommandGroup, BaseCommandDecorators, BaseMessage, disambiguation } from '../../../'; import { oneLine, stripIndents } from 'common-tags'; import { Collection, Message } from 'discord.js'; const { name, aliases, group, memberName, description, details, examples, guarded, args }...
Only the bot owner(s) may use this command. `) @examples('reload some-command') @guarded export class ReloadCommandCommand extends BaseCommand { public hasPermission(msg: BaseMessage): boolean { return this.client.isOwner(msg.author); } @args({ key: 'cmdOrGrp', label: 'command/group', prompt: 'which comman...
The argument must be the name/ID (partial or whole) of a command or command group. Providing a command group will reload all of the commands in that group.
random_line_split
reload.ts
import { UntitledClient, BaseCommand, BaseCommandGroup, BaseCommandDecorators, BaseMessage, disambiguation } from '../../../'; import { oneLine, stripIndents } from 'common-tags'; import { Collection, Message } from 'discord.js'; const { name, aliases, group, memberName, description, details, examples, guarded, args }...
return null; } }
{ await msg.reply(`Reloaded all of the commands in the \`${cmdOrGrp.name}\` group.`); }
conditional_block
task.rs
(proc(TaskResult):Send), /// A channel to send the result of the task on when the task exits SendMessage(Sender<TaskResult>), } /// Per-task state related to task death, killing, failure, etc. pub struct Death { pub on_exit: Option<DeathAction>, } pub struct BlockedTasks { inner: UnsafeArc<AtomicUint>...
// TLS, or possibly some destructors for those objects being // annihilated invoke TLS. Sadly these two operations seemed to // be intertwined, and miraculously work for now... let mut task = Local::borrow(None::<Task>); let storage_map = {...
// that the destructors for the objects in TLS themselves invoke
random_line_split
task.rs
imp: None, } } /// Executes the given closure as if it's running inside this task. The task /// is consumed upon entry, and the destroyed task is returned from this /// function in order for the caller to free. This function is guaranteed to /// not unwind because the closure specified is ...
{ Some(Shared(self.inner.clone())) }
identifier_body
task.rs
(TaskResult):Send), /// A channel to send the result of the task on when the task exits SendMessage(Sender<TaskResult>), } /// Per-task state related to task death, killing, failure, etc. pub struct Death { pub on_exit: Option<DeathAction>, } pub struct BlockedTasks { inner: UnsafeArc<AtomicUint>, } ...
(mut ~self) { let ops = self.imp.take_unwrap(); ops.reawaken(self); } /// Yields control of this task to another task. This function will /// eventually return, but possibly not immediately. This is used as an /// opportunity to allow other tasks a chance to run. pub fn yield_now(mu...
reawaken
identifier_name
test.py
# coding=utf-8 import sys sys.path.append("bindings/python/") from unittestpy import TeamcityTestRunner from elliptics_proxy import * import unittest r = remote('localhost', 1025) c = config() c.groups.append(1) c.groups.append(2) c.log_path = 'log' c.remotes.append(r) proxy = elliptics_proxy_t(c) class TestTeamcit...
(self): data = 'test data of test_sync' key = 'test_sync_key' lr = proxy.write(key, data) assert len(lr) == 2 dc2 = proxy.read(key) assert dc2.data == data proxy.remove(key) def test_async(self): data = 'test data for test_async' key = 'test_async_key' dc = data_container_t(data) dc.timestamp = ...
test_sync
identifier_name
test.py
# coding=utf-8 import sys sys.path.append("bindings/python/") from unittestpy import TeamcityTestRunner from elliptics_proxy import * import unittest r = remote('localhost', 1025) c = config() c.groups.append(1) c.groups.append(2) c.log_path = 'log' c.remotes.append(r) proxy = elliptics_proxy_t(c) class TestTeamcit...
runner = TeamcityTestRunner() unittest.main(testRunner=runner)
conditional_block
test.py
# coding=utf-8 import sys sys.path.append("bindings/python/") from unittestpy import TeamcityTestRunner from elliptics_proxy import * import unittest r = remote('localhost', 1025) c = config() c.groups.append(1) c.groups.append(2) c.log_path = 'log' c.remotes.append(r) proxy = elliptics_proxy_t(c) class TestTeamcit...
def test_async(self): data = 'test data for test_async' key = 'test_async_key' dc = data_container_t(data) dc.timestamp = timespec(123, 456789) awr = proxy.write_async(key, dc) lr = awr.get() assert len(lr) == 2 arr = proxy.read_async(key, embeded = True, groups = [1]); ldc = arr.get() dc = ...
data = 'test data of test_sync' key = 'test_sync_key' lr = proxy.write(key, data) assert len(lr) == 2 dc2 = proxy.read(key) assert dc2.data == data proxy.remove(key)
identifier_body
test.py
# coding=utf-8 import sys sys.path.append("bindings/python/") from unittestpy import TeamcityTestRunner from elliptics_proxy import * import unittest r = remote('localhost', 1025) c = config() c.groups.append(1) c.groups.append(2) c.log_path = 'log' c.remotes.append(r) proxy = elliptics_proxy_t(c) class TestTeamcit...
dc = data_container_t(data) dc.timestamp = timespec(123, 456789) awr = proxy.write_async(key, dc) lr = awr.get() assert len(lr) == 2 arr = proxy.read_async(key, embeded = True, groups = [1]); ldc = arr.get() dc = ldc[0] assert dc.data == data ts2 = dc.timestamp assert ts2.tv_sec == 123 asse...
def test_async(self): data = 'test data for test_async' key = 'test_async_key'
random_line_split
eventshandler.py
# ============================================================================= # periscope-ps (unis) # # Copyright (c) 2012-2016, Trustees of Indiana University, # All rights reserved. # # This software may be modified and distributed under the terms of the BSD # license. See the COPYING file for details. # # T...
generic.pop("numExtents",None) generic.pop("nindexes",None) generic.pop("lastExtentSize",None) generic.pop("paddingFactor",None) generic.pop("flags",None) generic.pop("totalIndexSize",None) generic.pop("indexSizes",None) generic.pop("max",None) gen...
def del_stat_fields(self,generic): generic.pop("ns",None)
random_line_split
eventshandler.py
# ============================================================================= # periscope-ps (unis) # # Copyright (c) 2012-2016, Trustees of Indiana University, # All rights reserved. # # This software may be modified and distributed under the terms of the BSD # license. See the COPYING file for details. # # T...
(self, cursor, is_list = False, inline=False, unique=False, count=0): response = [] if cursor: async for resource in cursor: try: mid = resource["metadata_URL"].split('/')[-1] response.insert(0, await self.generate_response(mid)) ...
_write_get
identifier_name
eventshandler.py
# ============================================================================= # periscope-ps (unis) # # Copyright (c) 2012-2016, Trustees of Indiana University, # All rights reserved. # # This software may be modified and distributed under the terms of the BSD # license. See the COPYING file for details. # # T...
db_query = {"ts": { "$gt": 0 } } if startTime in specific: db_query["ts"]["$gte"] = specific["startTime"] if endTime in specific: db_query["ts"]["$lte"] = specific["endTime"] specific["numRecords"] = await self.application.db...
specific["endTime"] = int(criteria[1])
conditional_block
eventshandler.py
# ============================================================================= # periscope-ps (unis) # # Copyright (c) 2012-2016, Trustees of Indiana University, # All rights reserved. # # This software may be modified and distributed under the terms of the BSD # license. See the COPYING file for details. # # T...
async def _find(self, **options): options["query"].pop("\\$status", None) if not options["query"]: return await self.dblayer.count(**options), self.dblayer.find() elif self.Id in options["query"] or "$or" in options["query"]: return await self.dblayer.co...
resource = resources[0] http_client = AsyncHTTPClient() response = await http_client.fetch(resource["metadata_URL"], validate_cert=False, client_cert=settings.MS_CLIENT_CERT, ...
identifier_body
markdown.config.js
'use strict'; /* eslint-disable no-restricted-syntax */ const { rules } = require('./index'); const ruleTableRows = Object.keys(rules) .sort() .map((id) => { const { meta } = rules[id]; const { fixable, docs } = meta; return [ docs.recommended ? '✔' : '', fixable ? '🔧' : '', `[reac...
.join('\n'); }; const BASIC_RULES = () => buildRulesTable(ruleTableRows.filter((rule) => !rule.includes('react/jsx-'))); const JSX_RULES = () => buildRulesTable(ruleTableRows.filter((rule) => rule.includes('react/jsx-'))); module.exports = { transforms: { BASIC_RULES, JSX_RULES, }, callback: () => {...
const separator = ':---: | :---: | :--- | :---'; return [header, separator, ...rows] .map((row) => `| ${row} |`)
random_line_split
taikoa.py
import re import time from flask import Flask, render_template, request, flash, redirect from flaskext.babel import Babel from flask.ext.mail import Mail, Message from flask.ext.cache import Cache from flask.ext.assets import Environment from raven.contrib.flask import Sentry import feedparser app = Flask(__name__) ...
return render_template('lab.html', active='lab', items=items) @app.route("/contact_form", methods=['POST']) def contact_form(): email_re = re.compile( r"(^[-!#$%&'*+/=?^_`{}|~0-9A-Z]+(\.[-!#$%&'*+/=?^_`{}|~0-9A-Z]+)*" # dot-atom r'|^"([\001-\010\013\014\016-\037!#-\[\]-\177]|\\[\001-011\013\014\016...
item['published_parsed'] = time.strftime("%d %B %Y", item['published_parsed'])
conditional_block
taikoa.py
import re import time from flask import Flask, render_template, request, flash, redirect from flaskext.babel import Babel from flask.ext.mail import Mail, Message from flask.ext.cache import Cache from flask.ext.assets import Environment from raven.contrib.flask import Sentry import feedparser app = Flask(__name__) ...
babel = Babel(app) cache = Cache(app) mail = Mail(app) assets = Environment(app) sentry = Sentry(app) @babel.localeselector def get_locale(): return request.accept_languages.best_match(['es', 'fr', 'en']) @cache.cached(timeout=50) @app.route("/") def index(): return render_template('index.html', active='hom...
random_line_split
taikoa.py
import re import time from flask import Flask, render_template, request, flash, redirect from flaskext.babel import Babel from flask.ext.mail import Mail, Message from flask.ext.cache import Cache from flask.ext.assets import Environment from raven.contrib.flask import Sentry import feedparser app = Flask(__name__) ...
(): feed = feedparser.parse('http://javaguirre.net/rss/') items = feed['items'] for item in items: item['published_parsed'] = time.strftime("%d %B %Y", item['published_parsed']) return render_template('lab.html', active='lab', items=items) @ap...
lab
identifier_name
taikoa.py
import re import time from flask import Flask, render_template, request, flash, redirect from flaskext.babel import Babel from flask.ext.mail import Mail, Message from flask.ext.cache import Cache from flask.ext.assets import Environment from raven.contrib.flask import Sentry import feedparser app = Flask(__name__) ...
@cache.cached(timeout=50) @app.route("/projects") def projects(): return render_template('projects.html', active='project') @cache.cached(timeout=50) @app.route("/about/me") def about_me(): return render_template('about-me.html', active='about') @cache.cached(timeout=50) @app.route("/contact") def contac...
return render_template('index.html', active='home')
identifier_body
character.rs
//! Operations on characters. use remacs_macros::lisp_fn; use remacs_sys::EmacsInt; use lisp::LispObject; use lisp::defsubr; use multibyte::{make_char_multibyte, raw_byte_from_codepoint_safe}; use multibyte::MAX_CHAR; /// Return the character of the maximum code. #[lisp_fn] pub fn max_char() -> LispObject { Lisp...
include!(concat!(env!("OUT_DIR"), "/character_exports.rs"));
{ let c = ch.as_character_or_error(); if c < 256 { // Can't distinguish a byte read from a unibyte buffer from // a latin1 char, so let's let it slide. ch } else { LispObject::from_fixnum(raw_byte_from_codepoint_safe(c)) } }
identifier_body
character.rs
//! Operations on characters. use remacs_macros::lisp_fn; use remacs_sys::EmacsInt; use lisp::LispObject; use lisp::defsubr; use multibyte::{make_char_multibyte, raw_byte_from_codepoint_safe}; use multibyte::MAX_CHAR; /// Return the character of the maximum code. #[lisp_fn] pub fn max_char() -> LispObject { Lisp...
(ch: LispObject) -> LispObject { let c = ch.as_character_or_error(); if c >= 0x100 { error!("Not a unibyte character: {}", c); } LispObject::from_fixnum(make_char_multibyte(c) as EmacsInt) } /// Convert the multibyte character CH to a byte. /// If the multibyte character does not represent a by...
unibyte_char_to_multibyte
identifier_name
character.rs
//! Operations on characters. use remacs_macros::lisp_fn; use remacs_sys::EmacsInt; use lisp::LispObject; use lisp::defsubr; use multibyte::{make_char_multibyte, raw_byte_from_codepoint_safe}; use multibyte::MAX_CHAR; /// Return the character of the maximum code. #[lisp_fn] pub fn max_char() -> LispObject { Lisp...
} include!(concat!(env!("OUT_DIR"), "/character_exports.rs"));
{ LispObject::from_fixnum(raw_byte_from_codepoint_safe(c)) }
conditional_block
character.rs
//! Operations on characters. use remacs_macros::lisp_fn; use remacs_sys::EmacsInt; use lisp::LispObject; use lisp::defsubr; use multibyte::{make_char_multibyte, raw_byte_from_codepoint_safe}; use multibyte::MAX_CHAR;
} /// Return non-nil if OBJECT is a character. /// In Emacs Lisp, characters are represented by character codes, which /// are non-negative integers. The function `max-char' returns the /// maximum character code. /// usage: (fn OBJECT) #[lisp_fn(min = "1")] pub fn characterp(object: LispObject, _ignore: LispObject) ...
/// Return the character of the maximum code. #[lisp_fn] pub fn max_char() -> LispObject { LispObject::from_fixnum(MAX_CHAR as EmacsInt)
random_line_split
models.py
import keyedcache import logging log = logging.getLogger(__name__) class CachedObjectMixin(object): """Provides basic object keyedcache for any objects using this as a mixin. The class name of the object should be unambiguous. """ def cache_delete(self, *args, **kwargs): key = self.cache_key...
return ob def find_by_slug(cls, groupkey, slug, raises=False): """A helper function to look up an object by slug""" ob = None try: ob = keyedcache.cache_get(groupkey, slug) except keyedcache.NotCachedError as e: try: ob = cls.objects.get(slug__exact=slug) ...
raise
conditional_block
models.py
import keyedcache import logging log = logging.getLogger(__name__) class CachedObjectMixin(object): """Provides basic object keyedcache for any objects using this as a mixin. The class name of the object should be unambiguous. """ def cache_delete(self, *args, **kwargs): key = self.cache_key...
def cache_reset(self): self.cache_delete() self.cache_set() def cache_set(self, *args, **kwargs): val = kwargs.pop('value', self) key = self.cache_key(*args, **kwargs) keyedcache.cache_set(key, value=val) def is_cached(self, *args, **kwargs): retur...
keys = [self.__class__.__name__, self] keys.extend(args) return keyedcache.cache_key(keys, **kwargs)
identifier_body
models.py
import keyedcache
log = logging.getLogger(__name__) class CachedObjectMixin(object): """Provides basic object keyedcache for any objects using this as a mixin. The class name of the object should be unambiguous. """ def cache_delete(self, *args, **kwargs): key = self.cache_key(*args, **kwargs) log.deb...
import logging
random_line_split
models.py
import keyedcache import logging log = logging.getLogger(__name__) class CachedObjectMixin(object): """Provides basic object keyedcache for any objects using this as a mixin. The class name of the object should be unambiguous. """ def cache_delete(self, *args, **kwargs): key = self.cache_key...
(cls, groupkey, key, raises=False): """A helper function to look up an object by key""" ob = None try: ob = keyedcache.cache_get(groupkey, key) except keyedcache.NotCachedError as e: try: ob = cls.objects.get(key__exact=key) keyedcache.cache_set(e.key, value=ob) ...
find_by_key
identifier_name
models.py
# -------------------------------- Database models---------------------------------------------------------------------- import sys, os import sqlalchemy from sqlalchemy import create_engine sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))) import secrets import settings MY...
# The consumed_timestamp should ideally have a null value for default but that is not feasible here so # for checking we will first check whether the is_fetched value is true, if so we consider the consumed_timestamp # as the date and time when the message was dequeued. def __repr__(self): """...
random_line_split
models.py
# -------------------------------- Database models---------------------------------------------------------------------- import sys, os import sqlalchemy from sqlalchemy import create_engine sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))) import secrets import settings MY...
(self): """ representation of the Message class :return: """ return "<Message (queue_id: {}, is_fetched: {}, content: {}...{}, publish_timestamp: {}, " \ "consumed_timestamp: {})>".format(self.queue_id, self.is_fetched, self.content[:10],self.content[10:], ...
__repr__
identifier_name
models.py
# -------------------------------- Database models---------------------------------------------------------------------- import sys, os import sqlalchemy from sqlalchemy import create_engine sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))) import secrets import settings MY...
class Message(Base): """ Message model class """ __tablename__ = "Message" id = Column(Integer, primary_key=True) queue_id = Column(Integer, ForeignKey('Queue.id')) is_fetched = Column(Boolean, default=False) content = Column(Text) publish_timestamp = Column(DateTime) consume...
""" representation of the Queue class :return: """ return "<Queue (name: {}, created_timestamp: {})>".format(self.name, self.created_timestamp)
identifier_body
useVisibleStatus.ts
import { useState, useEffect, useRef } from 'react'; import raf from 'rc-util/lib/raf'; /** * Popup should follow the steps for each component work correctly: * measure - check for the current stretch size * align - let component align the position * aligned - re-align again in case additional className changed th...
( nextStatus: PopupStatus | ((prevStatus: PopupStatus) => PopupStatus), ) { if (!destroyRef.current) { setInternalStatus(nextStatus); } } function cancelRaf() { raf.cancel(rafRef.current); } function goNextStatus(callback?: () => void) { cancelRaf(); rafRef.current = raf(() => ...
setStatus
identifier_name
useVisibleStatus.ts
import { useState, useEffect, useRef } from 'react'; import raf from 'rc-util/lib/raf'; /** * Popup should follow the steps for each component work correctly: * measure - check for the current stretch size * align - let component align the position * aligned - re-align again in case additional className changed th...
function goNextStatus(callback?: () => void) { cancelRaf(); rafRef.current = raf(() => { // Only align should be manually trigger setStatus((prev) => { switch (status) { case 'align': return 'motion'; case 'motion': return 'stable'; d...
{ raf.cancel(rafRef.current); }
identifier_body
useVisibleStatus.ts
import { useState, useEffect, useRef } from 'react'; import raf from 'rc-util/lib/raf'; /** * Popup should follow the steps for each component work correctly: * measure - check for the current stretch size * align - let component align the position * aligned - re-align again in case additional className changed th...
}, [status]); useEffect( () => () => { destroyRef.current = true; cancelRaf(); }, [], ); return [status, goNextStatus]; };
{ rafRef.current = raf(async () => { const index = StatusQueue.indexOf(status); const nextStatus = StatusQueue[index + 1]; if (nextStatus && index !== -1) { setStatus(nextStatus); } }); }
conditional_block
useVisibleStatus.ts
import { useState, useEffect, useRef } from 'react'; import raf from 'rc-util/lib/raf'; /** * Popup should follow the steps for each component work correctly: * measure - check for the current stretch size * align - let component align the position * aligned - re-align again in case additional className changed th...
useEffect( () => () => { destroyRef.current = true; cancelRaf(); }, [], ); return [status, goNextStatus]; };
}); } }, [status]);
random_line_split
parse_datetime.py
""" Simple robust time and date parsing. Note: Follows the Australian standard, dd/mm/yyyy. Americans should replace '%d %m %Y' with '%m %d %Y' and '%d %m %y' with '%m %d %y' below. Routines will either - return a date or time - return None if the string is empty - throw ...
(string): string = string.strip() if not string: return None string = string.replace('/',' ').replace('-',' ').replace(',',' ') for format in date_formats_with_year: try: result = time.strptime(string, format) return datetime.date(result.tm_year, result.tm_mon, ...
parse_date
identifier_name
parse_datetime.py
""" Simple robust time and date parsing. Note: Follows the Australian standard, dd/mm/yyyy. Americans should replace '%d %m %Y' with '%m %d %Y' and '%d %m %y' with '%m %d %y' below. Routines will either - return a date or time - return None if the string is empty - throw ...
raise ValueError() if __name__ == '__main__': # Run some simple tests for test in ['1pm', '13:30', '5:05pm']: print parse_time(test), test for test in ['2/6/1977', '02/06/77', '1977-06-02', '2 June, 1977', 'Jun 2, 1977', '2 June', 'Jun 2']: print parse_date(test), test
string = string.strip() if not string: return None string = string.replace('/',' ').replace('-',' ').replace(',',' ') for format in date_formats_with_year: try: result = time.strptime(string, format) return datetime.date(result.tm_year, result.tm_mon, result.tm_mday...
identifier_body
parse_datetime.py
""" Simple robust time and date parsing. Note: Follows the Australian standard, dd/mm/yyyy. Americans should replace '%d %m %Y' with '%m %d %Y' and '%d %m %y' with '%m %d %y' below. Routines will either - return a date or time - return None if the string is empty - throw a...
for test in ['2/6/1977', '02/06/77', '1977-06-02', '2 June, 1977', 'Jun 2, 1977', '2 June', 'Jun 2']: print parse_date(test), test
random_line_split
parse_datetime.py
""" Simple robust time and date parsing. Note: Follows the Australian standard, dd/mm/yyyy. Americans should replace '%d %m %Y' with '%m %d %Y' and '%d %m %y' with '%m %d %y' below. Routines will either - return a date or time - return None if the string is empty - throw ...
raise ValueError() if __name__ == '__main__': # Run some simple tests for test in ['1pm', '13:30', '5:05pm']: print parse_time(test), test for test in ['2/6/1977', '02/06/77', '1977-06-02', '2 June, 1977', 'Jun 2, 1977', '2 June', 'Jun 2']: print parse_date(test), test ...
try: result = time.strptime(string, format) year = datetime.date.today().year return datetime.date(year, result.tm_mon, result.tm_mday) except ValueError: pass
conditional_block
parsers.py
# -*- coding: utf-8 -*- # Copyright 2015 Spanish National Research Council # # 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 requ...
def parse(self): raise NotImplemented class TextParser(BaseParser): def parse_categories(self, headers): kind = action = None mixins = collections.Counter() schemes = collections.defaultdict(list) try: categories = headers["Category"] except KeyErro...
self.body = body
random_line_split
parsers.py
# -*- coding: utf-8 -*- # Copyright 2015 Spanish National Research Council # # 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 requ...
(self): raise NotImplemented class TextParser(BaseParser): def parse_categories(self, headers): kind = action = None mixins = collections.Counter() schemes = collections.defaultdict(list) try: categories = headers["Category"] except KeyError: ...
parse
identifier_name
parsers.py
# -*- coding: utf-8 -*- # Copyright 2015 Spanish National Research Council # # 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 requ...
def parse(self): return self._parse(self._convert_to_headers()) class HeaderParser(TextParser): def parse(self): return self._parse(self.headers) _PARSERS_MAP = { "text": TextParser, "header": HeaderParser, } def get_media_map(): return _MEDIA_TYPE_MAP def get_default_parse...
obj = self.parse_categories(headers) obj['attributes'] = self.parse_attributes(headers) obj['links'] = self.parse_links(headers) return obj
identifier_body
parsers.py
# -*- coding: utf-8 -*- # Copyright 2015 Spanish National Research Council # # 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 requ...
action = ctg_type elif ctg_class == "mixin": mixins[ctg_type] += 1 schemes[d["scheme"]].append(d["term"]) if action and kind: raise exception.OCCIInvalidSchema("Action and kind together?") return { "category": kind or actio...
raise exception.OCCIInvalidSchema("Duplicated action")
conditional_block
__init__.py
from collections import deque from functools import partial import voluptuous as vol from camacq.exceptions import TemplateError from camacq.helper import BASE_ACTION_SCHEMA, get_module, has_at_least_one_key from camacq.helper.template import make_template, render_template from camacq.const import CAMACQ_STOP_EVENT, ...
(self, seconds, variables, waiting): """Delay action sequence. Parameters ---------- seconds : float A time interval to delay the pending action sequence. variables : dict A dict of template variables. """ sequence = ActionSequence(self._c...
delay
identifier_name
__init__.py
from collections import deque from functools import partial import voluptuous as vol from camacq.exceptions import TemplateError from camacq.helper import BASE_ACTION_SCHEMA, get_module, has_at_least_one_key from camacq.helper.template import make_template, render_template from camacq.const import CAMACQ_STOP_EVENT, ...
return False return check_condition def template_check(value): """Check if a rendered template string equals true. If value is not a string, return value as is. """ if isinstance(value, str): return value.lower() == "true" return value def _process_trigger(center, config_b...
return any(template_check(check(variables)) for check in checks)
conditional_block
__init__.py
from collections import deque from functools import partial import voluptuous as vol from camacq.exceptions import TemplateError from camacq.helper import BASE_ACTION_SCHEMA, get_module, has_at_least_one_key from camacq.helper.template import make_template, render_template from camacq.const import CAMACQ_STOP_EVENT, ...
def _process_condition(center, config_block): """Return a function that parses the condition.""" if CONF_TYPE in config_block: checks = [] condition_type = config_block[CONF_TYPE] conditions = config_block[CONF_CONDITIONS] for cond in conditions: check = _process_con...
actions = (TemplateAction(center, action_conf) for action_conf in config_block) return ActionSequence(center, actions)
random_line_split
__init__.py
from collections import deque from functools import partial import voluptuous as vol from camacq.exceptions import TemplateError from camacq.helper import BASE_ACTION_SCHEMA, get_module, has_at_least_one_key from camacq.helper.template import make_template, render_template from camacq.const import CAMACQ_STOP_EVENT, ...
async def __call__(self, variables=None): """Execute action with optional template variables."""
"""Set up instance.""" self._center = center self.action_id = action_conf[CONF_ID] self.action_type = action_conf[CONF_TYPE] action_data = action_conf[CONF_DATA] self.template = make_template(center, action_data)
identifier_body
age.js
/** * Copyright (C) 2017 3D Repo Ltd *
* it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warr...
* This program is free software: you can redistribute it and/or modify
random_line_split
ILoadBalancer.ts
import { IMoniker } from 'core/naming'; import { IInstance } from './IInstance'; import { IInstanceCounts } from './IInstanceCounts'; import { IManagedResource } from './IManagedEntity'; import { IServerGroup } from './IServerGroup'; import { ITaggedEntity } from './ITaggedEntity'; export interface ILoadBalancerSourc...
moniker?: IMoniker; name?: string; provider?: string; region?: string; searchField?: string; securityGroups?: string[]; serverGroups?: IServerGroup[]; stack?: string; type?: string; vpcId?: string; vpcName?: string; } export interface ILoadBalancerGroup extends IManagedResource { heading: strin...
healthState?: string; instanceCounts?: IInstanceCounts; instances?: IInstance[]; listenerDescriptions?: any[]; loadBalancerType?: string;
random_line_split
SentenceSimilarityEvaluation.py
# @see http://www.idayer.com/sentences-similarity.html # kindled by https://github.com/ineo6/chinese-segmentation import sys import math from pinyin.pinyin import Pinyin import biligrab.Functions from importlib import reload reload(sys) class Evaluator: d = {} @staticmethod def log(x): if not x:...
s1 = list(Evaluator.__solve(sentence1)) s2 = list(Evaluator.__solve(sentence2)) key = list(set(s1 + s2)) keylenth = len(key) keyvalue = 0 sk1 = [keyvalue] * keylenth sk2 = [keyvalue] * keylenth for index, keyElement in enumerate(key): if k...
Evaluator.init() Evaluator.first_run = False
conditional_block
SentenceSimilarityEvaluation.py
# @see http://www.idayer.com/sentences-similarity.html # kindled by https://github.com/ineo6/chinese-segmentation import sys import math from pinyin.pinyin import Pinyin import biligrab.Functions from importlib import reload reload(sys) class Evaluator: d = {} @staticmethod def log(x): if not x:...
if Evaluator.first_run: Evaluator.init() Evaluator.first_run = False s1 = list(Evaluator.__solve(sentence1)) s2 = list(Evaluator.__solve(sentence2)) key = list(set(s1 + s2)) keylenth = len(key) keyvalue = 0 sk1 = [keyvalue] * keylenth sk...
identifier_body
SentenceSimilarityEvaluation.py
# @see http://www.idayer.com/sentences-similarity.html # kindled by https://github.com/ineo6/chinese-segmentation import sys import math from pinyin.pinyin import Pinyin import biligrab.Functions from importlib import reload reload(sys) class Evaluator: d = {} @staticmethod def log(x): if not x:...
with open(filename, 'r', encoding="utf-8") as handle: for line in handle: word, freq = line.split('\t')[0:2] Evaluator.d['_t_'] += int(freq) + 1 try: Evaluator.d[word.decode('utf-8')] = int(freq) + 1 except: ...
Evaluator.d['_t_'] = 0.0
random_line_split
SentenceSimilarityEvaluation.py
# @see http://www.idayer.com/sentences-similarity.html # kindled by https://github.com/ineo6/chinese-segmentation import sys import math from pinyin.pinyin import Pinyin import biligrab.Functions from importlib import reload reload(sys) class
: d = {} @staticmethod def log(x): if not x: return float('-inf') else: return math.log(x) @staticmethod def prob(x): if x in Evaluator.d: return Evaluator.d[x] elif len(x) > 1: return 0 else: retur...
Evaluator
identifier_name
fullstream.py
# -*- coding: utf-8 -*- """ Exodus Add-on 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 3 of the License, or (at your option) any later version. This progra...
(self): self.priority = 1 self.language = ['fr'] self.domains = ['full-stream.nu'] self.base_link = 'http://full-stream.nu' self.search_link = 'index.php' def movie(self, imdb, title, localtitle, aliases, year): try: url = self.__search([localtitle] + sou...
__init__
identifier_name
fullstream.py
# -*- coding: utf-8 -*- """ Exodus Add-on 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 3 of the License, or (at your option) any later version. This progra...
if url: return urllib.urlencode({'url': source_utils.strip_domain(url), 'episode': episode}) except: return def sources(self, url, hostDict, hostprDict): sources = [] try: if not url: return sources data = urlparse.parse_qs...
url = self.__search([tvshowtitle] + source_utils.aliases_to_array(aliases), year, season)
conditional_block
fullstream.py
# -*- coding: utf-8 -*- """ Exodus Add-on 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 3 of the License, or (at your option) any later version. This progra...
return
try: query = urlparse.urljoin(self.base_link, self.search_link) t = [cleantitle.get(i) for i in set(titles) if i] y = ['%s' % str(year), '%s' % str(int(year) + 1), '%s' % str(int(year) - 1), '0'] r = client.request(query, post={'do': 'search', 'subaction': 'search', 'se...
identifier_body
fullstream.py
# -*- coding: utf-8 -*- """ Exodus Add-on 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 3 of the License, or (at your option) any later version. This progra...
data = urlparse.parse_qs(url) data = dict([(i, data[i][0]) if data[i] else (i, '') for i in data]) url = data['url'] episode = data.get('episode') r = client.request(urlparse.urljoin(self.base_link, url)) if episode: rel = dom_pa...
random_line_split
domexception.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::codegen::Bindings::DOMExceptionBinding; use crate::dom::bindings::codegen::Bindings::DO...
(global: &GlobalScope, code: DOMErrorName) -> DomRoot<DOMException> { reflect_dom_object( Box::new(DOMException::new_inherited(code)), global, DOMExceptionBinding::Wrap, ) } } impl DOMExceptionMethods for DOMException { // https://heycam.github.io/webidl/#dfn...
new
identifier_name
domexception.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::codegen::Bindings::DOMExceptionBinding; use crate::dom::bindings::codegen::Bindings::DO...
DOMErrorName::NamespaceError => "The operation is not allowed by Namespaces in XML.", DOMErrorName::InvalidAccessError => { "The object does not support the operation or argument." }, DOMErrorName::SecurityError => "The operation is insecure.", ...
DOMErrorName::SyntaxError => "The string did not match the expected pattern.", DOMErrorName::InvalidModificationError => "The object can not be modified in this way.",
random_line_split
GraphQLErrorPage.tsx
import React from "react" import ServerError from "./ServerError" import NotFoundError from "./NotFoundError" import OtherError from "./OtherError" import { ApolloError } from "@apollo/client" type Props = { /** GraphQL error object */ error: ApolloError } /** * Displays any errors found when issuing a GraphQL q...
let errorCode, errorMsg if (error.graphQLErrors && error.graphQLErrors[0].extensions) { errorCode = error.graphQLErrors[0].extensions.code errorMsg = error.graphQLErrors[0].message } if (errorCode === "Unavailable") { return <ServerError /> } if (errorCode === "NotFound" && errorMsg) { ...
{ console.error(error.networkError) return <ServerError /> }
conditional_block
GraphQLErrorPage.tsx
import React from "react" import ServerError from "./ServerError" import NotFoundError from "./NotFoundError" import OtherError from "./OtherError" import { ApolloError } from "@apollo/client" type Props = { /** GraphQL error object */ error: ApolloError } /** * Displays any errors found when issuing a GraphQL q...
errorCode = error.graphQLErrors[0].extensions.code errorMsg = error.graphQLErrors[0].message } if (errorCode === "Unavailable") { return <ServerError /> } if (errorCode === "NotFound" && errorMsg) { return ( <NotFoundError error={errorMsg.charAt(0).toUpperCase() + errorMsg.slice(...
let errorCode, errorMsg if (error.graphQLErrors && error.graphQLErrors[0].extensions) {
random_line_split
modelsHelper.py
# -*- coding: utf-8 -*- from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from sqlalchemy.ext.declarative import as_declarative import settings def db_connect(): """ Performs database connection using database settings from settings.py. :return: sqlalchemy engine instance ...
self.session.close() self.conn.close() engine.dispose()
identifier_body
modelsHelper.py
# -*- coding: utf-8 -*- from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from sqlalchemy.ext.declarative import as_declarative import settings def db_connect(): """ Performs database connection using database settings from settings.py. :return: sqlalchemy engine instance ...
(self): self.conn = engine.connect() self.session = session_maker(bind=self.conn) def close(self): self.session.close() self.conn.close() engine.dispose()
open
identifier_name