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
CreateHeightMap.ts
import { Laya } from "Laya"; import { Camera } from "laya/d3/core/Camera"; import { HeightMap } from "laya/d3/core/HeightMap"; import { MeshSprite3D } from "laya/d3/core/MeshSprite3D"; import { Scene } from "laya/d3/core/scene/Scene"; import { Sprite3D } from "laya/d3/core/Sprite3D"; import { Vector2 } from "laya/d3/ma...
var compressionRatio: number = (maxHeight - minHeight) / 254; //把高度数据画到canvas画布上,并保存为png图片 this.pringScreen(this.width, this.height, compressionRatio, minHeight, heightMap); }); } private pringScreen(tWidth: number, tHeight: number, cr: number, min: number, th: HeightMap): void { var pixel: any = Laya.s...
age.scaleMode = Stage.SCALE_FULL; Laya.stage.screenMode = Stage.SCREEN_HORIZONTAL; var scene: Scene = (<Scene>Laya.stage.addChild(new Scene())); scene.currentCamera = (<Camera>(scene.addChild(new Camera(0, 0.1, 2000)))); //3d场景 var sceneSprite3d: Sprite3D = (<Sprite3D>scene.addChild(Sprite3D.load("maze/maze...
identifier_body
CreateHeightMap.ts
import { Laya } from "Laya"; import { Camera } from "laya/d3/core/Camera"; import { HeightMap } from "laya/d3/core/HeightMap"; import { MeshSprite3D } from "laya/d3/core/MeshSprite3D"; import { Scene } from "laya/d3/core/scene/Scene"; import { Sprite3D } from "laya/d3/core/Sprite3D"; import { Vector2 } from "laya/d3/ma...
{ //生成高度图的宽度 width: number = 64; //生成高度图的高度 height: number = 64; constructor() { Laya3D.init(0, 0); Laya.stage.scaleMode = Stage.SCALE_FULL; Laya.stage.screenMode = Stage.SCREEN_HORIZONTAL; var scene: Scene = (<Scene>Laya.stage.addChild(new Scene())); scene.currentCamera = (<Camera>(scene.addChild(new...
CreateHeightMap
identifier_name
CreateHeightMap.ts
import { Laya } from "Laya"; import { Camera } from "laya/d3/core/Camera"; import { HeightMap } from "laya/d3/core/HeightMap"; import { MeshSprite3D } from "laya/d3/core/MeshSprite3D"; import { Scene } from "laya/d3/core/scene/Scene"; import { Sprite3D } from "laya/d3/core/Sprite3D"; import { Vector2 } from "laya/d3/ma...
constructor() { Laya3D.init(0, 0); Laya.stage.scaleMode = Stage.SCALE_FULL; Laya.stage.screenMode = Stage.SCREEN_HORIZONTAL; var scene: Scene = (<Scene>Laya.stage.addChild(new Scene())); scene.currentCamera = (<Camera>(scene.addChild(new Camera(0, 0.1, 2000)))); //3d场景 var sceneSprite3d: Sprite3D = (<S...
width: number = 64; //生成高度图的高度 height: number = 64;
random_line_split
CreateHeightMap.ts
import { Laya } from "Laya"; import { Camera } from "laya/d3/core/Camera"; import { HeightMap } from "laya/d3/core/HeightMap"; import { MeshSprite3D } from "laya/d3/core/MeshSprite3D"; import { Scene } from "laya/d3/core/scene/Scene"; import { Sprite3D } from "laya/d3/core/Sprite3D"; import { Vector2 } from "laya/d3/ma...
(oriHeight - min) / cr); tRed = height; tGreed = height; tBlue = height; } tAlpha = 1; tStr = "rgba(" + tRed.toString() + "," + tGreed.toString() + "," + tBlue.toString() + "," + tAlpha.toString() + ")"; ctx.fillStyle = tStr; ctx.fillRect(j, i, 1, 1); } } var image = ncanvas....
conditional_block
robotics.py
""" Classes for using robotic or other hardware using Topographica. This module contains several classes for constructing robotics interfaces to Topographica simulations. It includes modules that read input from or send output to robot devices, and a (quasi) real-time simulation object that attempts to maintain a cor...
self.debug("Executing shift, amplitude=%.2f, direction=%.2f"%(amplitude,direction)) if self.invert_amplitude: amplitude *= -1 # if the amplitude is negative, invert the direction, so up is still up. if amplitude < 0: direction *= -1 angle = direction * pi/180 ...
identifier_body
robotics.py
""" Classes for using robotic or other hardware using Topographica. This module contains several classes for constructing robotics interfaces to Topographica simulations. It includes modules that read input from or send output to robot devices, and a (quasi) real-time simulation object that attempts to maintain a cor...
def shift(self,amplitude,direction): self.debug("Executing shift, amplitude=%.2f, direction=%.2f"%(amplitude,direction)) if self.invert_amplitude: amplitude *= -1 # if the amplitude is negative, invert the direction, so up is still up. if amplitude < 0: di...
amplitude,direction = data self.shift(amplitude,direction)
conditional_block
robotics.py
""" Classes for using robotic or other hardware using Topographica. This module contains several classes for constructing robotics interfaces to Topographica simulations. It includes modules that read input from or send output to robot devices, and a (quasi) real-time simulation object that attempts to maintain a cor...
pan,tilt,zoom = self.ptz.state_deg pan += amplitude * cos(angle) tilt += amplitude * sin(angle) self.ptz.set_ws_deg(pan,tilt,self.zoom,self.speed,self.speed) ## self.ptz.cmd_queue.put_nowait(('set_ws_deg', ## (pan,tilt,self.zoom,self.speed,...
# if the amplitude is negative, invert the direction, so up is still up. if amplitude < 0: direction *= -1 angle = direction * pi/180
random_line_split
robotics.py
""" Classes for using robotic or other hardware using Topographica. This module contains several classes for constructing robotics interfaces to Topographica simulations. It includes modules that read input from or send output to robot devices, and a (quasi) real-time simulation object that attempts to maintain a cor...
(CameraImage): """ A version of CameraImage that gets the image from the camera's image queue, rather than directly from the camera object. Using queues is necessary when running the playerrobot in a separate process without shared memory. When getting an image, this pattern generator will fet...
CameraImageQueued
identifier_name
gash.rs
// // gash.rs // // Reference solution for PS2 // Running on Rust 0.8 // // Special thanks to Kiet Tran for porting code from Rust 0.7 to Rust 0.8. // // University of Virginia - cs4414 Fall 2013 // Weilin Xu, Purnam Jantrania, David Evans // Version 0.2 // // Modified use std::{run, os, libc}; use std::task; fn get...
}
{ let mut output_opt = None; for i in range(0, progs.len()) { let prog = progs[i].to_owned(); if i == 0 { let pipe_i = pipes[i]; task::spawn_sched(task::SingleThreaded, ||{handle_cmd(prog, 0, pipe_i.out, 2)}); } else if i =...
conditional_block
gash.rs
// // gash.rs // // Reference solution for PS2 // Running on Rust 0.8 // // Special thanks to Kiet Tran for porting code from Rust 0.7 to Rust 0.8. // // University of Virginia - cs4414 Fall 2013 // Weilin Xu, Purnam Jantrania, David Evans // Version 0.2 // // Modified use std::{run, os, libc}; use std::task; fn get...
fn _handle_cmd(cmd_line: &str, pipe_in: libc::c_int, pipe_out: libc::c_int, pipe_err: libc::c_int, output: bool) -> Option<run::ProcessOutput> { let out_fd = pipe_out; let in_fd = pipe_in; let err_fd = pipe_err; let mut argv: ~[~str] = cmd_line.split_iter(' ').filter_map(|x...
{ #[fixed_stack_segment]; #[inline(never)]; unsafe { libc::exit(status); } }
identifier_body
gash.rs
// // gash.rs // // Reference solution for PS2 // Running on Rust 0.8 // // Special thanks to Kiet Tran for porting code from Rust 0.7 to Rust 0.8. // // University of Virginia - cs4414 Fall 2013 // Weilin Xu, Purnam Jantrania, David Evans // Version 0.2 // // Modified use std::{run, os, libc}; use std::task; fn get...
(cmd_line: &str) -> Option<run::ProcessOutput> { // handle pipes let progs: ~[~str] = cmd_line.split_iter('|').map(|x| x.trim().to_owned()).collect(); let mut pipes = ~[]; for _ in range(0, progs.len()-1) { pipes.push(os::pipe()); } if progs.len() == 1 { return hand...
handle_cmdline
identifier_name
gash.rs
// // gash.rs // // Reference solution for PS2 // Running on Rust 0.8 // // Special thanks to Kiet Tran for porting code from Rust 0.7 to Rust 0.8. // // University of Virginia - cs4414 Fall 2013 // Weilin Xu, Purnam Jantrania, David Evans // Version 0.2 // // Modified use std::{run, os, libc}; use std::task; fn get...
} fn exit(status: libc::c_int) { #[fixed_stack_segment]; #[inline(never)]; unsafe { libc::exit(status); } } fn _handle_cmd(cmd_line: &str, pipe_in: libc::c_int, pipe_out: libc::c_int, pipe_err: libc::c_int, output: bool) -> Option<run::ProcessOutput> { let out_fd = pipe_out; let in_fd =...
let modebuf = mode.to_c_str().unwrap(); return libc::fileno(libc::fopen(fpathbuf, modebuf)); }
random_line_split
test_dominating_set.py
#!/usr/bin/env python from nose.tools import ok_ from nose.tools import eq_ import networkx as nx from networkx.algorithms.approximation import min_weighted_dominating_set from networkx.algorithms.approximation import min_edge_dominating_set class TestMinWeightDominatingSet: def test_min_weighted_dominating_set(...
(self): """Tests that an approximate dominating set for the star graph, even when the center node does not have the smallest integer label, gives just the center node. For more information, see #1527. """ # Create a star graph in which the center node has the highest ...
test_star_graph
identifier_name
test_dominating_set.py
#!/usr/bin/env python from nose.tools import ok_ from nose.tools import eq_ import networkx as nx from networkx.algorithms.approximation import min_weighted_dominating_set from networkx.algorithms.approximation import min_edge_dominating_set class TestMinWeightDominatingSet: def test_min_weighted_dominating_set(...
graph = nx.complete_graph(10) dom_set = min_edge_dominating_set(graph) # this is a crappy way to test, but good enough for now. for edge in graph.edges_iter(): if edge in dom_set: continue else: u, v = edge found ...
if edge in dom_set: continue else: u, v = edge found = False for dom_edge in dom_set: found |= u == dom_edge[0] or u == dom_edge[1] ok_(found, "Non adjacent edge found!")
conditional_block
test_dominating_set.py
#!/usr/bin/env python from nose.tools import ok_ from nose.tools import eq_ import networkx as nx from networkx.algorithms.approximation import min_weighted_dominating_set from networkx.algorithms.approximation import min_edge_dominating_set class TestMinWeightDominatingSet: def test_min_weighted_dominating_set(...
G = nx.star_graph(10) G = nx.relabel_nodes(G, {0: 9, 9: 0}) eq_(min_weighted_dominating_set(G), {9}) def test_min_edge_dominating_set(self): graph = nx.path_graph(5) dom_set = min_edge_dominating_set(graph) # this is a crappy way to test, but good enough for now. ...
# Create a star graph in which the center node has the highest # label instead of the lowest.
random_line_split
test_dominating_set.py
#!/usr/bin/env python from nose.tools import ok_ from nose.tools import eq_ import networkx as nx from networkx.algorithms.approximation import min_weighted_dominating_set from networkx.algorithms.approximation import min_edge_dominating_set class TestMinWeightDominatingSet: def test_min_weighted_dominating_set(...
def test_star_graph(self): """Tests that an approximate dominating set for the star graph, even when the center node does not have the smallest integer label, gives just the center node. For more information, see #1527. """ # Create a star graph in which the cente...
graph = nx.Graph() graph.add_edge(1, 2) graph.add_edge(1, 5) graph.add_edge(2, 3) graph.add_edge(2, 5) graph.add_edge(3, 4) graph.add_edge(3, 6) graph.add_edge(5, 6) vertices = set([1, 2, 3, 4, 5, 6]) # due to ties, this might be hard to test tigh...
identifier_body
debug.py
# Based on Rapptz's RoboDanny's repl cog import contextlib import inspect import logging import re import sys import textwrap import traceback from io import StringIO from typing import * from typing import Pattern import discord from discord.ext import commands # i took this from somewhere and i cant remember where ...
except (SystemExit, KeyboardInterrupt): raise except Exception: await self.on_error(ctx) else: await ctx.message.add_reaction('✅') return result, stdout.getvalue(), stderr.getvalue() async def on_error(self, ctx: commands....
result = eval(code, scope) # eval doesn't allow `await` if inspect.isawaitable(result): result = await result
conditional_block
debug.py
# Based on Rapptz's RoboDanny's repl cog import contextlib import inspect import logging import re import sys import textwrap import traceback from io import StringIO from typing import * from typing import Pattern import discord from discord.ext import commands # i took this from somewhere and i cant remember where ...
t.add_cog(BotDebug(bot))
identifier_body
debug.py
# Based on Rapptz's RoboDanny's repl cog import contextlib import inspect import logging import re import sys import textwrap import traceback from io import StringIO from typing import * from typing import Pattern import discord from discord.ext import commands # i took this from somewhere and i cant remember where ...
ot: commands.Bot, cfg: dict): bot.add_cog(BotDebug(bot))
it(b
identifier_name
debug.py
# Based on Rapptz's RoboDanny's repl cog import contextlib import inspect import logging import re import sys import textwrap import traceback from io import StringIO
from discord.ext import commands # i took this from somewhere and i cant remember where md: Pattern = re.compile(r"^(([ \t]*`{3,4})([^\n]*)(?P<code>[\s\S]+?)(^[ \t]*\2))", re.MULTILINE) logger = logging.getLogger(__name__) class BotDebug(object): def __init__(self, client: commands.Bot): self.client = cl...
from typing import * from typing import Pattern import discord
random_line_split
bypass-security.component.ts
// #docplaster
import { Component } from '@angular/core'; import { DomSanitizer, SafeResourceUrl, SafeUrl } from '@angular/platform-browser'; @Component({ selector: 'app-bypass-security', templateUrl: './bypass-security.component.html', }) export class BypassSecurityComponent { dangerousUrl: string; trustedUrl: SafeUrl; da...
// #docregion
random_line_split
bypass-security.component.ts
// #docplaster // #docregion import { Component } from '@angular/core'; import { DomSanitizer, SafeResourceUrl, SafeUrl } from '@angular/platform-browser'; @Component({ selector: 'app-bypass-security', templateUrl: './bypass-security.component.html', }) export class BypassSecurityComponent { dangerousUrl: string...
(private sanitizer: DomSanitizer) { // javascript: URLs are dangerous if attacker controlled. // Angular sanitizes them in data binding, but you can // explicitly tell Angular to trust this value: this.dangerousUrl = 'javascript:alert("Hi there")'; this.trustedUrl = sanitizer.bypassSecurityTrustUrl(...
constructor
identifier_name
mpd_mediaplayer_it.ts
<?xml version="1.0" ?><!DOCTYPE TS><TS language="it" version="2.1"> <context> <name>@default</name> <message> <source>MediaPlayer</source> <translation>MediaPlayer</translation> </message>
<source>General</source> <translation>Generale</translation> </message> <message> <source>Media Player Daemon Settings</source> <translation>Impostazioni Demone Media Player</translation> </message> <message> <source>Host</source> <translation>Host</transl...
<message>
random_line_split
move-nodetest.js
'use strict'; var expect = require('chai').expect; var ember = require('ember-cli/tests/helpers/ember'); var MockUI = require('ember-cli/tests/helpers/mock-ui'); var MockAnalytics = require('ember-cli/tests/helpers/mock-analytics'); var Command = require('ember-cli/lib/models/command'); var...
function generateFile(path) { return ensureFile(path); } function addFileToGit(path) { return ensureFile(path) .then(function() { return exec('git add .'); }); } function addFilesToGit(files) { var filesToAdd = files.map(addFileToGit); return RSVP.all(filesToAdd);...
{ return exec('git --version') .then(function(){ return exec('git rev-parse --is-inside-work-tree', { encoding: 'utf8' }) .then(function(result) { console.log('result',result) return; // return exec('git init'); }) .catch(function(e){ ...
identifier_body
move-nodetest.js
'use strict'; var expect = require('chai').expect; var ember = require('ember-cli/tests/helpers/ember'); var MockUI = require('ember-cli/tests/helpers/mock-ui'); var MockAnalytics = require('ember-cli/tests/helpers/mock-analytics'); var Command = require('ember-cli/lib/models/command'); var...
}); */ /* //TODO: fix so this isn't moving the fixtures it('smoke test', function() { return new CommandUnderTest({ ui: ui, analytics: analytics, project: project, environment: { }, tasks: tasks, settings: {}, runCommand: function(command, args) { expect.d...
random_line_split
move-nodetest.js
'use strict'; var expect = require('chai').expect; var ember = require('ember-cli/tests/helpers/ember'); var MockUI = require('ember-cli/tests/helpers/mock-ui'); var MockAnalytics = require('ember-cli/tests/helpers/mock-analytics'); var Command = require('ember-cli/lib/models/command'); var...
(path) { return ensureFile(path) .then(function() { return exec('git add .'); }); } function addFilesToGit(files) { var filesToAdd = files.map(addFileToGit); return RSVP.all(filesToAdd); } function setupForMove() { return setupTmpDir() // .then(setupGit) .th...
addFileToGit
identifier_name
dependency_loader.ts
import {ScriptReceivers, ScriptReceiverFactory} from './script_receiver_factory';
import ScriptRequest from './script_request'; /** Handles loading dependency files. * * Dependency loaders don't remember whether a resource has been loaded or * not. It is caller's responsibility to make sure the resource is not loaded * twice. This is because it's impossible to detect resource loading status * ...
import Runtime from 'runtime';
random_line_split
dependency_loader.ts
import {ScriptReceivers, ScriptReceiverFactory} from './script_receiver_factory'; import Runtime from 'runtime'; import ScriptRequest from './script_request'; /** Handles loading dependency files. * * Dependency loaders don't remember whether a resource has been loaded or * not. It is caller's responsibility to mak...
}); request.send(receiver); } } /** Returns a root URL for pusher-js CDN. * * @returns {String} */ getRoot(options : any) : string { var cdn; var protocol = Runtime.getDocument().location.protocol; if ((options && options.encrypted) || protocol === "https:") { ...
{ self.loading[name] = [callback]; var request = Runtime.createScriptRequest(self.getPath(name, options)); var receiver = self.receivers.create(function(error) { self.receivers.remove(receiver); if (self.loading[name]) { var callbacks = self.loading[name]; ...
conditional_block
dependency_loader.ts
import {ScriptReceivers, ScriptReceiverFactory} from './script_receiver_factory'; import Runtime from 'runtime'; import ScriptRequest from './script_request'; /** Handles loading dependency files. * * Dependency loaders don't remember whether a resource has been loaded or * not. It is caller's responsibility to mak...
{ options: any; receivers: ScriptReceiverFactory; loading: any; constructor(options : any) { this.options = options; this.receivers = options.receivers || ScriptReceivers; this.loading = {}; } /** Loads the dependency from CDN. * * @param {String} name * @param {Function} ...
DependencyLoader
identifier_name
tkinter_gui.py
from Tkinter import * root = Tk() root.title('first test window') #root.geometry('300x200') frm = Frame(root) frm_l = Frame(frm) Label(frm_l, text='left_top').pack(side=TOP) Label(frm_l, text='left_bottom').pack(side=BOTTOM) frm_l.pack(side=LEFT) frm_r = Frame(frm) Label(frm_r, text='right_top').pack(side=TOP) Label...
(): t.insert(END, var.get()) Button(frm1, text='copy', command=print_entry).pack(side=TOP) frm1.pack(side=TOP) ########################################################## frm2 = Frame(root) redbutton = Button(frm2, text="Red", fg="red") redbutton.pack( side = LEFT) greenbutton = Button(frm2, text="Brown", fg="br...
print_entry
identifier_name
tkinter_gui.py
from Tkinter import * root = Tk() root.title('first test window') #root.geometry('300x200') frm = Frame(root) frm_l = Frame(frm) Label(frm_l, text='left_top').pack(side=TOP) Label(frm_l, text='left_bottom').pack(side=BOTTOM) frm_l.pack(side=LEFT) frm_r = Frame(frm) Label(frm_r, text='right_top').pack(side=TOP) Label...
t.insert(END, var.get()) Button(frm1, text='copy', command=print_entry).pack(side=TOP) frm1.pack(side=TOP) ########################################################## frm2 = Frame(root) redbutton = Button(frm2, text="Red", fg="red") redbutton.pack( side = LEFT) greenbutton = Button(frm2, text="Brown", fg="brown"...
t = Text(frm1) t.pack(side=TOP) def print_entry():
random_line_split
tkinter_gui.py
from Tkinter import * root = Tk() root.title('first test window') #root.geometry('300x200') frm = Frame(root) frm_l = Frame(frm) Label(frm_l, text='left_top').pack(side=TOP) Label(frm_l, text='left_bottom').pack(side=BOTTOM) frm_l.pack(side=LEFT) frm_r = Frame(frm) Label(frm_r, text='right_top').pack(side=TOP) Label...
Button(frm1, text='copy', command=print_entry).pack(side=TOP) frm1.pack(side=TOP) ########################################################## frm2 = Frame(root) redbutton = Button(frm2, text="Red", fg="red") redbutton.pack( side = LEFT) greenbutton = Button(frm2, text="Brown", fg="brown") greenbutton.pack( side = L...
t.insert(END, var.get())
identifier_body
squeeze-more.js
define(function(require, exports, module) { var jsp = require("./parse-js"), pro = require("./process"), slice = jsp.slice, member = jsp.member, curry = jsp.curry, MAP = pro.MAP, PRECEDENCE = jsp.PRECEDENCE, OPERATORS = jsp.OPERATORS; function ast_squeeze_more(ast) { var w = pro.as...
; function _lambda(name, args, body) { return [ this[0], name, args, with_scope(body.scope, curry(MAP, body, walk)) ]; }; return w.with_walkers({ "toplevel": function(body) { return [ this[0], with_scope(this.scope, curry(MAP, body, walk)) ...
{ var save = scope, ret; scope = s; ret = cont(); scope = save; return ret; }
identifier_body
squeeze-more.js
define(function(require, exports, module) { var jsp = require("./parse-js"), pro = require("./process"), slice = jsp.slice, member = jsp.member, curry = jsp.curry, MAP = pro.MAP, PRECEDENCE = jsp.PRECEDENCE, OPERATORS = jsp.OPERATORS; function ast_squeeze_more(ast) { var w = pro.as...
(s, cont) { var save = scope, ret; scope = s; ret = cont(); scope = save; return ret; }; function _lambda(name, args, body) { return [ this[0], name, args, with_scope(body.scope, curry(MAP, body, walk)) ]; ...
with_scope
identifier_name
squeeze-more.js
define(function(require, exports, module) { var jsp = require("./parse-js"), pro = require("./process"), slice = jsp.slice, member = jsp.member, curry = jsp.curry, MAP = pro.MAP, PRECEDENCE = jsp.PRECEDENCE, OPERATORS = jsp.OPERATORS; function ast_squeeze_more(ast) { var w = pro.as...
if (expr[0] == "name" && expr[1] == "Array" && args.length != 1 && !scope.has("Array")) { return [ "array", args ]; } } }, function() { return walk(pro.ast_add_scope(ast)); }); }; exports.ast...
"call": function(expr, args) { if (expr[0] == "dot" && expr[2] == "toString" && args.length == 0) { // foo.toString() ==> foo+"" return [ "binary", "+", expr[1], [ "string", "" ]]; }
random_line_split
squeeze-more.js
define(function(require, exports, module) { var jsp = require("./parse-js"), pro = require("./process"), slice = jsp.slice, member = jsp.member, curry = jsp.curry, MAP = pro.MAP, PRECEDENCE = jsp.PRECEDENCE, OPERATORS = jsp.OPERATORS; function ast_squeeze_more(ast) { var w = pro.as...
if (expr[0] == "name" && expr[1] == "Array" && args.length != 1 && !scope.has("Array")) { return [ "array", args ]; } } }, function() { return walk(pro.ast_add_scope(ast)); }); }; exports.as...
{ // foo.toString() ==> foo+"" return [ "binary", "+", expr[1], [ "string", "" ]]; }
conditional_block
lib.rs
`phase` feature and import //! the `regex_macros` crate as a syntax extension: //! //! ```rust //! #![feature(phase)] //! #[phase(plugin)] //! extern crate regex_macros; //! extern crate regex; //! //! fn main() { //! let re = regex!(r"^\d{4}-\d{2}-\d{2}$"); //! assert_eq!(re.is_match("2014-01-01"), true); //!...
//! This implementation executes regular expressions **only** on sequences of //! Unicode code points while exposing match locations as byte indices into the //! search string. //! //! Currently, only naive case folding is supported. Namely, when matching //! case insensitively, the characters are first converted to th...
//!
random_line_split
package.py
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class BashCompletion(AutotoolsPackage): """Programmable completion functions for bash.""" h...
def create_install_directory(self): mkdirp(join_path(self.prefix.share, 'bash-completion', 'completions')) @run_after('install') def show_message_to_user(self): prefix = self.prefix # Guidelines for individual user as provided by the author at # https://github.com/scop/bash-...
# Other dependencies depends_on('bash@4.1:', type='run') @run_before('install')
random_line_split
package.py
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class BashCompletion(AutotoolsPackage):
mkdirp(join_path(self.prefix.share, 'bash-completion', 'completions')) @run_after('install') def show_message_to_user(self): prefix = self.prefix # Guidelines for individual user as provided by the author at # https://github.com/scop/bash-completion print('==============...
"""Programmable completion functions for bash.""" homepage = "https://github.com/scop/bash-completion" url = "https://github.com/scop/bash-completion/archive/2.3.tar.gz" git = "https://github.com/scop/bash-completion.git" version('develop', branch='master') version('2.7', sha256='dba2b88...
identifier_body
package.py
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class BashCompletion(AutotoolsPackage): """Programmable completion functions for bash.""" h...
(self): prefix = self.prefix # Guidelines for individual user as provided by the author at # https://github.com/scop/bash-completion print('=====================================================') print('Bash completion has been installed. To use it, please') print('includ...
show_message_to_user
identifier_name
runner.py
# docker-pipeline # # The MIT License (MIT) # # Copyright (c) 2015 Dan Leehr # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # t...
self.result = None @classmethod def get_client(cls): # Using boot2docker instructions for now # http://docker-py.readthedocs.org/en/latest/boot2docker/ # Workaround for requests.exceptions.SSLError: hostname '192.168.59.103' doesn't match 'boot2docker' client = Client(ve...
self.pipeline = pipeline self.client = Runner.get_client() self.remove_containers = False
random_line_split
runner.py
# docker-pipeline # # The MIT License (MIT) # # Copyright (c) 2015 Dan Leehr # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # t...
def finish_container(self, container, step): if self.pipeline.debug: print 'Cleaning up container for step {}'.format(step) if self.remove_containers: self.client.remove_container(container)
logs = self.client.attach(container, stream=True, logs=True) result = {'image': step.image} print 'step: {}\nimage: {}\n==============='.format(step.name, step.image) all_logs = str() for log in logs: all_logs = all_logs + log print log, # Store the return...
identifier_body
runner.py
# docker-pipeline # # The MIT License (MIT) # # Copyright (c) 2015 Dan Leehr # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # t...
self.client.remove_container(container)
conditional_block
runner.py
# docker-pipeline # # The MIT License (MIT) # # Copyright (c) 2015 Dan Leehr # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # t...
(self, container, step): if self.pipeline.debug: print 'Cleaning up container for step {}'.format(step) if self.remove_containers: self.client.remove_container(container)
finish_container
identifier_name
sort-table.js
'use strict'; import React from 'react'; import {BootstrapTable, TableHeaderColumn} from 'react-bootstrap-table'; var products = []; function addProducts(quantity) { var startId = products.length; for (var i = 0; i < quantity; i++) { var id = startId + i; products.push({ id: id, name: "Item n...
};
{ return ( <div> <p style={{color:'red'}}>You cam click header to sort or click following button to perform a sorting by expose API</p> <button onClick={this.handleBtnClick}>Sort Product Name</button> <BootstrapTable ref="table" data={products}> <TableHeaderColumn dataField...
identifier_body
sort-table.js
'use strict'; import React from 'react'; import {BootstrapTable, TableHeaderColumn} from 'react-bootstrap-table'; var products = []; function addProducts(quantity) { var startId = products.length; for (var i = 0; i < quantity; i++) { var id = startId + i; products.push({ id: id, name: "Item n...
export default class SortTable extends React.Component{ handleBtnClick = e => { if(order === 'desc'){ this.refs.table.handleSort('asc', 'name'); order = 'asc'; } else { this.refs.table.handleSort('desc', 'name'); order = 'desc'; } } render(){ return ( <div> ...
addProducts(5); var order = 'desc';
random_line_split
sort-table.js
'use strict'; import React from 'react'; import {BootstrapTable, TableHeaderColumn} from 'react-bootstrap-table'; var products = []; function addProducts(quantity) { var startId = products.length; for (var i = 0; i < quantity; i++) { var id = startId + i; products.push({ id: id, name: "Item n...
} render(){ return ( <div> <p style={{color:'red'}}>You cam click header to sort or click following button to perform a sorting by expose API</p> <button onClick={this.handleBtnClick}>Sort Product Name</button> <BootstrapTable ref="table" data={products}> <TableHeader...
{ this.refs.table.handleSort('desc', 'name'); order = 'desc'; }
conditional_block
sort-table.js
'use strict'; import React from 'react'; import {BootstrapTable, TableHeaderColumn} from 'react-bootstrap-table'; var products = []; function
(quantity) { var startId = products.length; for (var i = 0; i < quantity; i++) { var id = startId + i; products.push({ id: id, name: "Item name " + id, price: 100 + i }); } } addProducts(5); var order = 'desc'; export default class SortTable extends React.Component{ handleBtnClic...
addProducts
identifier_name
Range.ts
import Compiler from '../Compiler'; import Frame from '../Frame'; import { Token } from '../Lexer'; import Node from '../Node'; import Parser from '../Parser'; export default class RangeNode extends Node { public static parse(parser: Parser, next: () => Node) { let node = next(); if (parser.skipValue(Token.O...
else if (parser.skipValue(Token.OPERATOR, '..')) { node = new RangeNode(node.line, node.col, { left: node, right: next(), exclusive: false }); } return node; } public exclusive: boolean; public left: any; public right: any; public compile(compiler: Compiler, frame: Frame) { const exclusive...
{ node = new RangeNode(node.line, node.col, { left: node, right: next(), exclusive: true }); }
conditional_block
Range.ts
import Compiler from '../Compiler'; import Frame from '../Frame'; import { Token } from '../Lexer'; import Node from '../Node'; import Parser from '../Parser'; export default class RangeNode extends Node { public static parse(parser: Parser, next: () => Node) { let node = next(); if (parser.skipValue(Token.O...
public exclusive: boolean; public left: any; public right: any; public compile(compiler: Compiler, frame: Frame) { const exclusive = this.exclusive ? 'true' : 'false'; compiler.emit(`lib.range(${ this.left.value }, ${ this.right.value }, 1, ${ exclusive })`, false); } }
} return node; }
random_line_split
Range.ts
import Compiler from '../Compiler'; import Frame from '../Frame'; import { Token } from '../Lexer'; import Node from '../Node'; import Parser from '../Parser'; export default class RangeNode extends Node { public static parse(parser: Parser, next: () => Node)
public exclusive: boolean; public left: any; public right: any; public compile(compiler: Compiler, frame: Frame) { const exclusive = this.exclusive ? 'true' : 'false'; compiler.emit(`lib.range(${ this.left.value }, ${ this.right.value }, 1, ${ exclusive })`, false); } }
{ let node = next(); if (parser.skipValue(Token.OPERATOR, '...')) { node = new RangeNode(node.line, node.col, { left: node, right: next(), exclusive: true }); } else if (parser.skipValue(Token.OPERATOR, '..')) { node = new RangeNode(node.line, node.col, { left: node, right: next(), exclusive: fa...
identifier_body
Range.ts
import Compiler from '../Compiler'; import Frame from '../Frame'; import { Token } from '../Lexer'; import Node from '../Node'; import Parser from '../Parser'; export default class RangeNode extends Node { public static parse(parser: Parser, next: () => Node) { let node = next(); if (parser.skipValue(Token.O...
(compiler: Compiler, frame: Frame) { const exclusive = this.exclusive ? 'true' : 'false'; compiler.emit(`lib.range(${ this.left.value }, ${ this.right.value }, 1, ${ exclusive })`, false); } }
compile
identifier_name
gamepad.rs
//! Gamepad utility functions. //! //! This is going to be a bit of a work-in-progress as gamepad input //! gets fleshed out. The `gilrs` crate needs help to add better //! cross-platform support. Why not give it a hand? use gilrs::ConnectedGamepadsIterator; use std::fmt; pub use gilrs::{self, Event, Gamepad, Gilrs}...
} } impl<'a> Iterator for GamepadsIterator<'a> { type Item = (GamepadId, Gamepad<'a>); fn next(&mut self) -> Option<(GamepadId, Gamepad<'a>)> { self.wrapped.next().map(|(id, gp)| (GamepadId(id), gp)) } } /// A structure that implements [`GamepadContext`](trait.GamepadContext.html) /// but doe...
random_line_split
gamepad.rs
//! Gamepad utility functions. //! //! This is going to be a bit of a work-in-progress as gamepad input //! gets fleshed out. The `gilrs` crate needs help to add better //! cross-platform support. Why not give it a hand? use gilrs::ConnectedGamepadsIterator; use std::fmt; pub use gilrs::{self, Event, Gamepad, Gilrs}...
(&mut self) -> Option<(GamepadId, Gamepad<'a>)> { self.wrapped.next().map(|(id, gp)| (GamepadId(id), gp)) } } /// A structure that implements [`GamepadContext`](trait.GamepadContext.html) /// but does nothing; a stub for when you don't need it or are /// on a platform that `gilrs` doesn't support. #[derive...
next
identifier_name
gamepad.rs
//! Gamepad utility functions. //! //! This is going to be a bit of a work-in-progress as gamepad input //! gets fleshed out. The `gilrs` crate needs help to add better //! cross-platform support. Why not give it a hand? use gilrs::ConnectedGamepadsIterator; use std::fmt; pub use gilrs::{self, Event, Gamepad, Gilrs}...
fn gamepad(&self, _id: GamepadId) -> Gamepad { panic!("Gamepad module disabled") } fn gamepads(&self) -> GamepadsIterator { panic!("Gamepad module disabled") } } /// Returns the `Gamepad` associated with an `id`. pub fn gamepad(ctx: &Context, id: GamepadId) -> Gamepad { ctx.gamep...
{ panic!("Gamepad module disabled") }
identifier_body
uniform-color-sk.ts
/** * @module modules/uniform-color-sk * @description <h2><code>uniform-color-sk</code></h2> * * A control for editing a float3 uniform which should be represented as a * color. * * The color uniform values are floats in [0, 1] and are in RGB order. */ import { $$ } from 'common-sk/modules/dom'; import { define...
const hex = this.colorInput!.value; hexToSlot(hex.slice(1, 3), uniforms, this.uniform.slot); hexToSlot(hex.slice(3, 5), uniforms, this.uniform.slot + 1); hexToSlot(hex.slice(5, 7), uniforms, this.uniform.slot + 2); // Set the alpha channel if present. if (this.hasAlphaChannel()) { uniform...
} /** Copies the values of the control into the uniforms array. */ applyUniformValues(uniforms: number[]): void { // Set all three floats from the color.
random_line_split
uniform-color-sk.ts
/** * @module modules/uniform-color-sk * @description <h2><code>uniform-color-sk</code></h2> * * A control for editing a float3 uniform which should be represented as a * color. * * The color uniform values are floats in [0, 1] and are in RGB order. */ import { $$ } from 'common-sk/modules/dom'; import { define...
(): Uniform { return this._uniform!; } set uniform(val: Uniform) { if ((val.columns !== 3 && val.columns !== 4) || val.rows !== 1) { throw new Error('uniform-color-sk can only work on a uniform of float3 or float4.'); } this._uniform = val; this._render(); } /** Copies the values of ...
uniform
identifier_name
uniform-color-sk.ts
/** * @module modules/uniform-color-sk * @description <h2><code>uniform-color-sk</code></h2> * * A control for editing a float3 uniform which should be represented as a * color. * * The color uniform values are floats in [0, 1] and are in RGB order. */ import { $$ } from 'common-sk/modules/dom'; import { define...
} onRAF(): void { // noop. } needsRAF(): boolean { return false; } private hasAlphaChannel(): boolean { return this._uniform.columns === 4; } } define('uniform-color-sk', UniformColorSk);
{ this.alphaInput!.valueAsNumber = uniforms[this.uniform.slot + 3]; }
conditional_block
uniform-color-sk.ts
/** * @module modules/uniform-color-sk * @description <h2><code>uniform-color-sk</code></h2> * * A control for editing a float3 uniform which should be represented as a * color. * * The color uniform values are floats in [0, 1] and are in RGB order. */ import { $$ } from 'common-sk/modules/dom'; import { define...
set uniform(val: Uniform) { if ((val.columns !== 3 && val.columns !== 4) || val.rows !== 1) { throw new Error('uniform-color-sk can only work on a uniform of float3 or float4.'); } this._uniform = val; this._render(); } /** Copies the values of the control into the uniforms array. */ ap...
{ return this._uniform!; }
identifier_body
SrvShowHandsDataSerializer.ts
import { ArrayBufferBuilder } from "../../../../utils/ArrayBufferBuilder"; import { BitsReader } from "../../../../utils/BitsReader"; import { SerializerUtils } from "../../../../utils/SerializerUtils"; import { SrvShowHandsData } from "../data/SrvShowHandsData"; import { HandInfoData } from "../data/HandInfoData"; i...
public static deserialize(buffer: ArrayBufferBuilder, data: SrvShowHandsData): void { data.showHandListEvalLowHand = []; for (let i = 0, l = buffer.getUint8(); i < l; i++){ let temp = new HandInfoData(data); HandInfoDataSerializer.deserialize(buffer, temp);...
{ for (let i = 0, l = data.showHandListEvalLowHand.length , t = buffer.setUint8( l ); i < l; i++){ let temp = data.showHandListEvalLowHand[i]; HandInfoDataSerializer.serialize(buffer, temp); } }
identifier_body
SrvShowHandsDataSerializer.ts
import { ArrayBufferBuilder } from "../../../../utils/ArrayBufferBuilder"; import { BitsReader } from "../../../../utils/BitsReader"; import { SerializerUtils } from "../../../../utils/SerializerUtils"; import { SrvShowHandsData } from "../data/SrvShowHandsData"; import { HandInfoData } from "../data/HandInfoData"; i...
} public static deserialize(buffer: ArrayBufferBuilder, data: SrvShowHandsData): void { data.showHandListEvalLowHand = []; for (let i = 0, l = buffer.getUint8(); i < l; i++){ let temp = new HandInfoData(data); HandInfoDataSerializer.deserialize(buffer,...
{ let temp = data.showHandListEvalLowHand[i]; HandInfoDataSerializer.serialize(buffer, temp); }
conditional_block
SrvShowHandsDataSerializer.ts
import { ArrayBufferBuilder } from "../../../../utils/ArrayBufferBuilder"; import { BitsReader } from "../../../../utils/BitsReader"; import { SerializerUtils } from "../../../../utils/SerializerUtils"; import { SrvShowHandsData } from "../data/SrvShowHandsData"; import { HandInfoData } from "../data/HandInfoData"; i...
(buffer: ArrayBufferBuilder, data: SrvShowHandsData): void { data.showHandListEvalLowHand = []; for (let i = 0, l = buffer.getUint8(); i < l; i++){ let temp = new HandInfoData(data); HandInfoDataSerializer.deserialize(buffer, temp); data.showHa...
deserialize
identifier_name
SrvShowHandsDataSerializer.ts
import { ArrayBufferBuilder } from "../../../../utils/ArrayBufferBuilder"; import { BitsReader } from "../../../../utils/BitsReader"; import { SerializerUtils } from "../../../../utils/SerializerUtils";
import { HandInfoDataSerializer } from "../serializers/HandInfoDataSerializer"; export class SrvShowHandsDataSerializer { public static serialize(buffer: ArrayBufferBuilder, data: SrvShowHandsData): void { for (let i = 0, l = data.showHandListEvalLowHand.length , t = buffer.setUint8( l ); i < l; i++)...
import { SrvShowHandsData } from "../data/SrvShowHandsData"; import { HandInfoData } from "../data/HandInfoData";
random_line_split
StopScreenShareSVGIcon.tsx
// This is a generated file from running the "createIcons" script. This file should not be updated manually. import { forwardRef } from "react"; import { SVGIcon, SVGIconProps } from "@react-md/icon";
<path d="M21.22 18.02l2 2H24v-2h-2.78zm.77-2l.01-10c0-1.11-.9-2-2-2H7.22l5.23 5.23c.18-.04.36-.07.55-.1V7.02l4 3.73-1.58 1.47 5.54 5.54c.61-.33 1.03-.99 1.03-1.74zM2.39 1.73L1.11 3l1.54 1.54c-.4.36-.65.89-.65 1.48v10c0 1.1.89 2 2 2H0v2h18.13l2.71 2.71 1.27-1.27L2.39 1.73zM7 15.02c.31-1.48.92-2.95 2.07-4.06l1.59...
export const StopScreenShareSVGIcon = forwardRef<SVGSVGElement, SVGIconProps>( function StopScreenShareSVGIcon(props, ref) { return ( <SVGIcon {...props} ref={ref}>
random_line_split
dir_mod.py
#! /usr/bin/env python import os import time import traceback import re import locale import subprocess import zlib import zipfile import private.metadata as metadata import private.messages as messages from glob import glob from private.exceptionclasses import CustomError, CritError, SyntaxError, Logic...
if ext == '': filepath = filepath + '.dta' file_list.append( filepath ) except Exception as errmsg: print errmsg raise SyntaxError(messages.syn_error_manifest % manifestlog) if not os.path.isdir(output_dir): ...
for i in range(len(manifest_lines)): if manifest_lines[i].startswith('File: '): filepath = os.path.abspath(manifest_lines[i][6:].rstrip()) ext = os.path.splitext(filepath)[1]
random_line_split
dir_mod.py
#! /usr/bin/env python import os import time import traceback import re import locale import subprocess import zlib import zipfile import private.metadata as metadata import private.messages as messages from glob import glob from private.exceptionclasses import CustomError, CritError, SyntaxError, Logic...
(manifestlog = '@DEFAULTVALUE@', output_dir = '@DEFAULTVALUE@', makelog = '@DEFAULTVALUE@'): """ Produce an error if there are any .dta files in "output_dir" and all non-hidden sub-directories that are not in the manifest file "manifestlog", and produce...
check_manifest
identifier_name
dir_mod.py
#! /usr/bin/env python import os import time import traceback import re import locale import subprocess import zlib import zipfile import private.metadata as metadata import private.messages as messages from glob import glob from private.exceptionclasses import CustomError, CritError, SyntaxError, Logic...
def unzip_externals(external_dir='@DEFAULTVALUE@'): if external_dir == '@DEFAULTVALUE@': external_dir = metadata.settings['external_dir'] for dirname, subdirs, files in os.walk(external_dir): for filename in files: absname = os.path.abspath(os.path.join(dirname, ...
zip = zipfile.ZipFile(file_name, allowZip64=True) zip.extractall(output_dir) zip.close()
identifier_body
dir_mod.py
#! /usr/bin/env python import os import time import traceback import re import locale import subprocess import zlib import zipfile import private.metadata as metadata import private.messages as messages from glob import glob from private.exceptionclasses import CustomError, CritError, SyntaxError, Logic...
dirs[:] = dirs_to_keep # Print out the sub-directory and its time stamp created = os.stat(root).st_mtime asciiTime = time.asctime(time.localtime(created)) print >> LOGFILE, root print >> LOGFILE, 'created/modified',...
if not dirname.startswith('.'): dirs_to_keep.append(dirname)
conditional_block
multiclass_classification.py
import os import numpy as np from sklearn.datasets import load_iris from sklearn.ensemble import RandomForestClassifier import shap import mlflow # prepare training data X, y = load_iris(return_X_y=True, as_frame=True) # train a model model = RandomForestClassifier() model.fit(X, y) # log an explanation with mlf...
# show a force plot shap.force_plot(base_values[0], shap_values[0, 0, :], X.iloc[0, :], matplotlib=True)
random_line_split
alpr.py
cv2.cv.CreateImage(license_plate_size, cv2.cv.IPL_DEPTH_8U, 3) cv2.cv.SetData( license_plate_ipl, license_plate.tostring(), license_plate.dtype.itemsize * 3 * license_plate.shape[1]) license_plate_white_ipl = cv2.cv.CreateImage(license_plate_size, cv2.cv.IPL_DEPTH_8U, 1) ...
cv2.imwrite("%s_contours_colored.png" % fname_prefix, license_plate)
random_line_split
alpr.py
) # Segment segmented, labels, regions = pms.segment(license_plate, 3, 3, 50) print "Segmentation results" print "%s: %s" % ("labels", labels) print "%s: %s" % ("regions", regions) cv2.imwrite('%s_segmented.png' % fname_prefix, segmented) license_plate = cv2.imread('%s_segmented.png' % fn...
elif float(contour_area / image_area) > max_plate_to_image_ratio: print "Contour %d over threshold. Countour Area: %f" % (idx, contour_area) continue approx = cv2.approxPolyDP( contour, 0.02 * cv2.arcLength(contour, True), True) ...
print "Contour %d under threshold. Countour Area: %f" % (idx, contour_area) continue
conditional_block
hash.js
/** * Module dependencies. */ var utils = require('../utils/utils'); /** * HLEN <key> */ exports.hlen = function(key){ var obj = this.lookup(key); if (!!obj && 'hash' == obj.type) { return Object.keys(obj.val).length; } else { return -1; } }; /** * HVALS <key> */ exports.hvals = function(key){ ...
return true; }).mutates = true; /** * HMSET <key> (<field> <val>)+ */ (exports.hmset = function(data){ var len = data.length , key = data[0] , obj = this.lookup(key) , field , val; if (obj && 'hash' != obj.type) { return false;} obj = obj || (this.db.data[key] = { type: 'hash', val: {} }); var...
random_line_split
hash.js
/** * Module dependencies. */ var utils = require('../utils/utils'); /** * HLEN <key> */ exports.hlen = function(key){ var obj = this.lookup(key); if (!!obj && 'hash' == obj.type) { return Object.keys(obj.val).length; } else { return -1; } }; /** * HVALS <key> */ exports.hvals = function(key){ ...
else { return null; } }; /** * HGETALL <key> */ exports.hgetall = function(key){ var obj = this.lookup(key); var list = []; var field; if (!!obj && 'hash' == obj.type) { for (field in obj.val) { list.push(field, obj.val[field]); } return list; } else { return null; } }; /**...
{ return obj.val[field] || null; }
conditional_block
main.js
$(document).ready(function() { 'use strict'; if (applicationStatusCode == 1) $('.ui.basic.modal').modal('show'); $('.ui.dropdown').dropdown({ on: 'hover' }); $('.masthead .information').transition('scale in', 1000); var animateIcons = function() { $('.ui.feature .icon .icon').transition({ animation: ...
}
random_line_split
main.js
$(document).ready(function() { 'use strict'; if (applicationStatusCode == 1) $('.ui.basic.modal').modal('show'); $('.ui.dropdown').dropdown({ on: 'hover' }); $('.masthead .information').transition('scale in', 1000); var animateIcons = function() { $('.ui.feature .icon .icon').transition({ animation: ...
identifier_body
main.js
$(document).ready(function() { 'use strict'; if (applicationStatusCode == 1) $('.ui.basic.modal').modal('show'); $('.ui.dropdown').dropdown({ on: 'hover' }); $('.masthead .information').transition('scale in', 1000); var animateIcons = function() { $('.ui.feature .icon .icon').transition({ animation: ...
identifier_name
userpopups.js
Drupal.userpopups = {}; Drupal.behaviors.userpopups = {
jQuery('html').once('popups-initialized').each(function(){ Drupal.userpopups.init(); }); } }; Drupal.userpopups.init = function init(){ var login_box = jQuery('#block-userlogin'); var pass_box = jQuery('.user-pass'); login_box.append('<div class="close">Închide</div>'); pass_box.append('<div c...
attach: function(context, settings) {
random_line_split
exporter.py
# -*- coding: utf-8 -*- # Copyright 2015-2019 grafana-dashboard-builder contributors # # 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 ...
json.dump(dashboard_data, f, sort_keys=True, indent=2, separators=(',', ': '))
def __init__(self, output_folder): super(FileExporter, self).__init__() self._output_folder = output_folder if not os.path.exists(self._output_folder): os.makedirs(self._output_folder) if not os.path.isdir(self._output_folder): raise Exception("'{0}' must be a dir...
identifier_body
exporter.py
# -*- coding: utf-8 -*- # Copyright 2015-2019 grafana-dashboard-builder contributors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License.
# distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import unicode_literals import errno import json import l...
# 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
random_line_split
exporter.py
# -*- coding: utf-8 -*- # Copyright 2015-2019 grafana-dashboard-builder contributors # # 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 ...
class FileExporter(DashboardExporter): def __init__(self, output_folder): super(FileExporter, self).__init__() self._output_folder = output_folder if not os.path.exists(self._output_folder): os.makedirs(self._output_folder) if not os.path.isdir(self._output_folder): ...
logger.info("Processing project '%s'", project.name) for context in project.get_contexts(parent_context): for dashboard in project.get_dashboards(): json_obj = dashboard.gen_json(context) dashboard_name = context.expand_placeholders(dashboard.name) ...
conditional_block
exporter.py
# -*- coding: utf-8 -*- # Copyright 2015-2019 grafana-dashboard-builder contributors # # 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 ...
(object): def __init__(self, dashboard_processors): """ :type dashboard_processors: list[grafana_dashboards.builder.DashboardExporter] """ super(ProjectProcessor, self).__init__() self._dashboard_processors = dashboard_processors def process_projects(self, projects, pa...
ProjectProcessor
identifier_name
store.js
/** * 对Storage的封装 * Author : smohan * Website : https://smohan.net * Date: 2017/10/12 * 参数1:布尔值, true : sessionStorage, 无论get,delete,set都得申明 * 参数1:string key 名 * 参数2:null,用作删除,其他用作设置 * 参数3:string,用于设置键名前缀 * 如果是sessionStorage,即参数1是个布尔值,且为true, * 无论设置/删除/获取都应该指明,而localStorage无需指明 */ const MEMORY_CACHE = Obje...
name, value, prefix let args = arguments if (typeof args[0] === 'boolean') { isSession = args[0] args = [].slice.call(args, 1) } name = args[0] value = args[1] prefix = args[2] === undefined ? '_mo_data_' : args[2] const Storage = isSession ? window.sessionStorage : window.localStorage if (!...
export default function () { let isSession = false,
random_line_split
store.js
/** * 对Storage的封装 * Author : smohan * Website : https://smohan.net * Date: 2017/10/12 * 参数1:布尔值, true : sessionStorage, 无论get,delete,set都得申明 * 参数1:string key 名 * 参数2:null,用作删除,其他用作设置 * 参数3:string,用于设置键名前缀 * 如果是sessionStorage,即参数1是个布尔值,且为true, * 无论设置/删除/获取都应该指明,而localStorage无需指明 */ const MEMORY_CACHE = Obje...
ue = JSON.parse(Storage.getItem(cacheKey)) } catch (e) {} return _value } else { //set MEMORY_CACHE[cacheKey] = value return Storage.setItem(cacheKey, JSON.stringify(value)) } }
return MEMORY_CACHE[cacheKey] } let _value = undefined try { _val
conditional_block
mod.rs
#![cfg(target_os = "android")] use crate::api::egl::{ Context as EglContext, NativeDisplay, SurfaceType as EglSurfaceType, }; use crate::CreationError::{self, OsError}; use crate::{ Api, ContextError, GlAttributes, PixelFormat, PixelFormatRequirements, Rect, }; use crate::platform::android::EventLoopExtAndroi...
#[inline] pub fn get_api(&self) -> Api { self.0.egl_context.get_api() } #[inline] pub fn get_pixel_format(&self) -> PixelFormat { self.0.egl_context.get_pixel_format() } #[inline] pub unsafe fn raw_handle(&self) -> ffi::EGLContext { self.0.egl_context.raw_handl...
self.0.egl_context.swap_buffers_with_damage_supported() }
random_line_split
mod.rs
#![cfg(target_os = "android")] use crate::api::egl::{ Context as EglContext, NativeDisplay, SurfaceType as EglSurfaceType, }; use crate::CreationError::{self, OsError}; use crate::{ Api, ContextError, GlAttributes, PixelFormat, PixelFormatRequirements, Rect, }; use crate::platform::android::EventLoopExtAndroi...
(&self) -> ffi::EGLDisplay { self.0.egl_context.get_egl_display() } }
get_egl_display
identifier_name
mod.rs
#![cfg(target_os = "android")] use crate::api::egl::{ Context as EglContext, NativeDisplay, SurfaceType as EglSurfaceType, }; use crate::CreationError::{self, OsError}; use crate::{ Api, ContextError, GlAttributes, PixelFormat, PixelFormatRequirements, Rect, }; use crate::platform::android::EventLoopExtAndroi...
_ => { return; } }; } } impl Context { #[inline] pub fn new_windowed<T>( wb: WindowBuilder, el: &EventLoopWindowTarget<T>, pf_reqs: &PixelFormatRequirements, gl_attr: &GlAttributes<&Self>, ) -> Result<(winit::window::Windo...
{ let mut stopped = self.0.stopped.as_ref().unwrap().lock(); *stopped = true; }
conditional_block
0014_auto_20180107_1716.py
# -*- coding: utf-8 -*- # Generated by Django 1.11.1 on 2018-01-07 16:16 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class
(migrations.Migration): dependencies = [ ('taborniki', '0013_remove_oseba_rojstvo2'), ] operations = [ migrations.CreateModel( name='Akcija', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ...
Migration
identifier_name
0014_auto_20180107_1716.py
# -*- coding: utf-8 -*- # Generated by Django 1.11.1 on 2018-01-07 16:16 from __future__ import unicode_literals
from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('taborniki', '0013_remove_oseba_rojstvo2'), ] operations = [ migrations.CreateModel( name='Akcija', fields=[ ('id', ...
random_line_split
0014_auto_20180107_1716.py
# -*- coding: utf-8 -*- # Generated by Django 1.11.1 on 2018-01-07 16:16 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration):
model_name='akcije', name='udelezenci', ), migrations.AlterField( model_name='vod', name='rod', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='rodov_vod', to='taborniki.Rod'), ), mi...
dependencies = [ ('taborniki', '0013_remove_oseba_rojstvo2'), ] operations = [ migrations.CreateModel( name='Akcija', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('imeAkcija',...
identifier_body
dashboard.ts
module csComp.Services { export class Widget { public content: Function; constructor() {} } export interface IWidget { directive : string; // name of the directive that should be used as widget data : Object; // json object that can hold parameters for...
(input: Dashboard): Dashboard { var res = <Dashboard>$.extend(new Dashboard(), input); res.widgets = []; if (input.widgets) input.widgets.forEach((w: IWidget) => { this.addNewWidget(w, res); }); if (input.timeline) res.timeline = $.extend(new ...
deserialize
identifier_name
dashboard.ts
module csComp.Services { export class Widget { public content: Function; constructor() {} } export interface IWidget { directive : string; // name of the directive that should be used as widget data : Object; // json object that can hold parameters for...
public hover : boolean; //public static deserialize(input: IWidget): IWidget { // var loader = new InstanceLoader(window); // var w = <IWidget>loader.getInstance(widget.widgetType); // var res = $.extend(new BaseWidget(), input); // return res; //} ...
random_line_split
dashboard.ts
module csComp.Services { export class Widget { public content: Function; constructor()
} export interface IWidget { directive : string; // name of the directive that should be used as widget data : Object; // json object that can hold parameters for the directive url : string; // url of the html page that should be used as widget ...
{}
identifier_body
authorize.js
function showErrorMessage(errorMessage) { $("#authorize-prompt") .addClass("error-prompt") .removeClass("success-prompt") .html(errorMessage); } function showSuccessMessage(message) { $("#authorize-prompt") .removeClass("error-prompt") .addClass("success-prompt") ...
function shake() { var l = 10; var original = -150; for( var i = 0; i < 8; i++ ) { var computed; if (i % 2 > 0.51) { computed = original - l; } else { computed = original + l; } $("#login-box").animate({ "left": computed + "px" ...
}
random_line_split
authorize.js
function showErrorMessage(errorMessage) { $("#authorize-prompt") .addClass("error-prompt") .removeClass("success-prompt") .html(errorMessage); } function showSuccessMessage(message) { $("#authorize-prompt") .removeClass("error-prompt") .addClass("success-prompt") ...
(data) { showErrorMessage(data.responseJSON.message); shake(); } $(function () { $('[data-toggle="tooltip"]').tooltip() }) function handleGrantAuthorization() { var csrf_token = $("#csrf_token").val(); var client_id = $("#client_id").val(); $.ajax("/oauth/authorize", { "method": "POST...
handleAuthFailure
identifier_name
authorize.js
function showErrorMessage(errorMessage) { $("#authorize-prompt") .addClass("error-prompt") .removeClass("success-prompt") .html(errorMessage); } function showSuccessMessage(message) { $("#authorize-prompt") .removeClass("error-prompt") .addClass("success-prompt") ...
else { computed = original + l; } $("#login-box").animate({ "left": computed + "px" }, 100); } $("#login-box").animate({ "left": "-150px" }, 50); } function handleAuthSuccess(data) { showSuccessMessage(data.message); $("#login-button").prop("...
{ computed = original - l; }
conditional_block
authorize.js
function showErrorMessage(errorMessage) { $("#authorize-prompt") .addClass("error-prompt") .removeClass("success-prompt") .html(errorMessage); } function showSuccessMessage(message) { $("#authorize-prompt") .removeClass("error-prompt") .addClass("success-prompt") ...
$(function () { $('[data-toggle="tooltip"]').tooltip() }) function handleGrantAuthorization() { var csrf_token = $("#csrf_token").val(); var client_id = $("#client_id").val(); $.ajax("/oauth/authorize", { "method": "POST", "data": { client_id, csrf_token ...
{ showErrorMessage(data.responseJSON.message); shake(); }
identifier_body
book.rs
use super::Processor; use crate::data::messages::{BookRecord, BookUpdate, RecordUpdate}; use crate::data::trade::TradeBook;
#[derive(Clone)] pub struct Accountant { tb: Arc<Mutex<TradeBook>>, } impl Accountant { pub fn new(tb: Arc<Mutex<TradeBook>>) -> Accountant { Accountant { tb } } } impl Processor for Accountant { fn process_message(&mut self, msg: String) -> Result<(), PoloError> { let err = |title| P...
use crate::error::PoloError; use std::str::FromStr; use std::sync::{Arc, Mutex};
random_line_split
book.rs
use super::Processor; use crate::data::messages::{BookRecord, BookUpdate, RecordUpdate}; use crate::data::trade::TradeBook; use crate::error::PoloError; use std::str::FromStr; use std::sync::{Arc, Mutex}; #[derive(Clone)] pub struct Accountant { tb: Arc<Mutex<TradeBook>>, } impl Accountant { pub fn new(tb: Ar...
() { let tb = Arc::new(Mutex::new(TradeBook::new())); let mut accountant = Accountant::new(tb.clone()); let order = String::from(r#"[189, 5130995, [["i", {"currencyPair": "BTC_BCH", "orderBook": [{"0.13161901": 0.23709568, "0.13164313": "0.17328089"}, {"0.13169621": 0.2331}]}]]]"#); acc...
initial_order
identifier_name
bad_transaction.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::{ account_universe::{AUTransactionGen, AccountUniverse}, common_transactions::{empty_txn, EMPTY_SCRIPT}, gas_costs, }; use diem_crypto::{ ed25519::{self, Ed25519PrivateKey, Ed25519PublicKey}, test_utils::K...
( &self, universe: &mut AccountUniverse, ) -> (SignedTransaction, (TransactionStatus, u64)) { let sender = universe.pick(self.sender).1; let seq = if sender.sequence_number == self.seq { self.seq + 1 } else { self.seq }; let txn = emp...
apply
identifier_name
bad_transaction.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::{ account_universe::{AUTransactionGen, AccountUniverse}, common_transactions::{empty_txn, EMPTY_SCRIPT}, gas_costs, }; use diem_crypto::{ ed25519::{self, Ed25519PrivateKey, Ed25519PublicKey}, test_utils::K...
; let txn = empty_txn( sender.account(), seq, gas_costs::TXN_RESERVED, 0, XUS_NAME.to_string(), ); ( txn, ( if seq >= sender.sequence_number { TransactionStatus::Discard(Stat...
{ self.seq }
conditional_block