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
lib.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ #![deny(warnings)] /// We have a few jobs that maintain some counters for each Mononoke repository. For example, /// the latest blobimport...
}) } }
{ ctx.perf_counters() .increment_counter(PerfCounterType::SqlWrites); let (txn, result) = if let Some(prev_value) = prev_value { SetCounterConditionally::query_with_transaction( txn, &repoid, &name, &value, ...
identifier_body
lib.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ #![deny(warnings)] /// We have a few jobs that maintain some counters for each Mononoke repository. For example, /// the latest blobimport...
{ write_connection: Connection, read_connection: Connection, read_master_connection: Connection, } impl SqlConstruct for SqlMutableCounters { const LABEL: &'static str = "mutable_counters"; const CREATION_QUERY: &'static str = include_str!("../schemas/sqlite-mutable-counters.sql"); fn from_s...
SqlMutableCounters
identifier_name
layercollection.test.js
/* * μlogger * * Copyright(C) 2020 Bartek Fabiszewski (www.fabiszewski.net) * * This 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 ver...
import uLayer from '../src/layer.js'; import uLayerCollection from '../src/layercollection.js'; describe('LayerCollection tests', () => { let layers; const testId = 5; const testName = 'test name'; const testUrl = 'https://layer.url'; const testPriority = 0; beforeEach(() => { layers = new uLayerColl...
random_line_split
Endorsements.js
import React from 'react' import PropTypes from 'prop-types' import { connect } from 'react-redux' import { Collapse } from 'antd' const Panel = Collapse.Panel import { makeManifestByID } from '../../../../../selectors' import { Loading } from '../../../../../components' /* ENDORSEMENTS PANEL: Renders a ...
) } } export default Endorsements
</div> </Loading> </section>
random_line_split
Endorsements.js
import React from 'react' import PropTypes from 'prop-types' import { connect } from 'react-redux' import { Collapse } from 'antd' const Panel = Collapse.Panel import { makeManifestByID } from '../../../../../selectors' import { Loading } from '../../../../../components' /* ENDORSEMENTS PANEL: Renders a ...
extends React.Component { static propTypes = { id: PropTypes.string.isRequired, manifest: PropTypes.object, comments: PropTypes.array, user: PropTypes.object } render ( { screen, manifest, comments } = this.props ) { return ( <section> <Loading render={manifest...
Endorsements
identifier_name
Wall.js
function Wall(layer, id) { powerupjs.GameObject.call(this, layer, id); // Some physical properties of the wall this.strokeColor = 'none'; this.fillColor = 'none'; this.scoreFrontColor = "#FFC800"; this.scoreSideColor = "#B28C00"; this.defaultFrontColor = '#0018FF'; this.defaultSideColor = '#0010B2'; this.fr...
"use strict";
random_line_split
Wall.js
this.smartWallRate = 2; this.initX = powerupjs.Game.size.x + 100; this.position = this.randomHolePosition(); this.velocity = new powerupjs.Vector2(this._minVelocity, 0); } Wall.prototype = Object.create(powerupjs.GameObject.prototype); Object.defineProperty(Wall.prototype, "minDiameterY", { get: function () {...
{ powerupjs.GameObject.call(this, layer, id); // Some physical properties of the wall this.strokeColor = 'none'; this.fillColor = 'none'; this.scoreFrontColor = "#FFC800"; this.scoreSideColor = "#B28C00"; this.defaultFrontColor = '#0018FF'; this.defaultSideColor = '#0010B2'; this.frontColor = this.defaultFro...
identifier_body
Wall.js
none'; this.scoreFrontColor = "#FFC800"; this.scoreSideColor = "#B28C00"; this.defaultFrontColor = '#0018FF'; this.defaultSideColor = '#0010B2'; this.frontColor = this.defaultFrontColor; this.sideColor = this.defaultSideColor; this._minVelocity = -250; this._minDiameterY = 200; this._maxDiameterY = 300; this....
// Move the hole if (this.smartWall) this.moveHole(delta); // Determine if user collides with wall. if (this.position.x <= playingState.user.boundingBox.right && this.position.x > playingState.user.boundingBox.center.x) { if (this.isColliding(playingState.user)) { playingState.lives -= 1; playingStat...
{ this.reset(); //this.velocity = new Vector2(this._minVelocity - (20 * score.score), 0); }
conditional_block
Wall.js
(layer, id) { powerupjs.GameObject.call(this, layer, id); // Some physical properties of the wall this.strokeColor = 'none'; this.fillColor = 'none'; this.scoreFrontColor = "#FFC800"; this.scoreSideColor = "#B28C00"; this.defaultFrontColor = '#0018FF'; this.defaultSideColor = '#0010B2'; this.frontColor = thi...
Wall
identifier_name
client.py
# -*- coding: utf-8 -*- __docformat__="restructuredtext" from rest import RestClient, Result, ResponseFormats
class NeocortexRestClient(object): BASE_URL = "http://api.meaningtool.com/0.2/neocortex" __builder__ = None class Builder(RestClient): _functions = {} _params = {} _input = None _format = None _tree_key = None def format(self, value): ...
from datetime import datetime
random_line_split
client.py
# -*- coding: utf-8 -*- __docformat__="restructuredtext" from rest import RestClient, Result, ResponseFormats from datetime import datetime class NeocortexRestClient(object): BASE_URL = "http://api.meaningtool.com/0.2/neocortex" __builder__ = None class Builder(RestClient): _functions = {...
(self, api_key, base_url=None): self.api_key = api_key self.BASE_URL = base_url or self.BASE_URL def get_builder(self): if self.__builder__ is None: self.__builder__ = NeocortexRestClient.Builder(self.BASE_URL, self.api_key).format(ResponseFormats.JSON) self...
__init__
identifier_name
client.py
# -*- coding: utf-8 -*- __docformat__="restructuredtext" from rest import RestClient, Result, ResponseFormats from datetime import datetime class NeocortexRestClient(object): BASE_URL = "http://api.meaningtool.com/0.2/neocortex" __builder__ = None class Builder(RestClient): _functions = {...
def get_builder(self): if self.__builder__ is None: self.__builder__ = NeocortexRestClient.Builder(self.BASE_URL, self.api_key).format(ResponseFormats.JSON) self.__builder__._reset() return self.__builder__ def categories(self, input, tree_key=None, a...
self.api_key = api_key self.BASE_URL = base_url or self.BASE_URL
identifier_body
client.py
# -*- coding: utf-8 -*- __docformat__="restructuredtext" from rest import RestClient, Result, ResponseFormats from datetime import datetime class NeocortexRestClient(object): BASE_URL = "http://api.meaningtool.com/0.2/neocortex" __builder__ = None class Builder(RestClient): _functions = {...
fs = ";".join(fs) url = "%s.%s" % (fs, self._format) try: res = self.post(url, self._params, response_format=self._format) except Exception, e: raise e finally: self._reset() ...
kk = k if isinstance(v, dict): if v.has_key("additionals"): for a in v["additionals"]: kk = "%s+%s" % (kk, a) if v.has_key("tree_key") and v["tree_key"] is not None and kk == 'categories': ...
conditional_block
pulsarspout.py
#!/usr/bin/env python # -*- encoding: utf-8 -*- # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache...
return flHandler.name class PulsarSpout(Spout, StreamletBoltBase): """PulsarSpout: reads from a pulsar topic""" # pylint: disable=too-many-instance-attributes # pylint: disable=no-self-use def default_deserializer(self, msg): return [str(msg)] # TopologyBuilder uses these constants to set # cluste...
flHandler = tempfile.NamedTemporaryFile(prefix=namePrefix, suffix='.conf', dir=os.getcwd(), delete=False) flHandler.write(GenerateLogConfContents(logFileName)) flHandler.flush() flHandler.close()
random_line_split
pulsarspout.py
#!/usr/bin/env python # -*- encoding: utf-8 -*- # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache...
else: self.deserializer = self.default_deserializer # First generate the config self.logConfFileName = GenerateLogConfig(context) self.logger.info("Generated LogConf at %s" % self.logConfFileName) # We currently use the high level consumer API # For supporting effectively once, we will ...
self.deserializer = config[PulsarSpout.deserializer] if not callable(self.deserializer): self.logger.fatal("Pulsar Message Deserializer needs to be callable")
conditional_block
pulsarspout.py
#!/usr/bin/env python # -*- encoding: utf-8 -*- # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache...
else: self.receive_timeout_ms = 10 if PulsarSpout.deserializer in config: self.deserializer = config[PulsarSpout.deserializer] if not callable(self.deserializer): self.logger.fatal("Pulsar Message Deserializer needs to be callable") else: self.deserializer = self.default_dese...
"""Implements Pulsar Spout's initialize method""" self.logger.info("Initializing PulsarSpout with the following") self.logger.info("Component-specific config: \n%s" % str(config)) self.logger.info("Context: \n%s" % str(context)) self.emit_count = 0 self.ack_count = 0 self.fail_count = 0 if...
identifier_body
pulsarspout.py
#!/usr/bin/env python # -*- encoding: utf-8 -*- # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache...
(self, tup_id): self.fail_count += 1 self.logger.debug("Failed tuple %s" % str(tup_id))
fail
identifier_name
debug-spec.js
'use strict' /* global * describe, it, beforeEach, afterEach, expect, spyOn, * loadFixtures, Waypoint */ describe('Waypoints debug script', function() { var waypoint, element beforeEach(function() { loadFixtures('standard.html') }) afterEach(function() { waypoint.destroy() }) describe('displ...
describe('fixed position detection', function() { }) describe('respect waypoint disabling', function() { beforeEach(function() { element = document.getElementById('same1') waypoint = new Waypoint({ element: element, handler: function() {} }) element.style.display = '...
waypoint.context.refresh() expect(console.error).toHaveBeenCalled() }) })
random_line_split
SeoProductsForCollections.tsx
import { SeoProductsForCollections_ascending_artworks } from "v2/__generated__/SeoProductsForCollections_ascending_artworks.graphql" import { SeoProductsForCollections_descending_artworks } from "v2/__generated__/SeoProductsForCollections_descending_artworks.graphql" import { Product } from "v2/Components/Seo/Product" ...
ascending_artworks: SeoProductsForCollections_ascending_artworks collectionDescription: string collectionURL: string collectionName: string } export const getMaxMinPrice = ( descending_artworks: SeoProductsForCollections_descending_artworks, ascending_artworks: SeoProductsForCollections_ascending_artworks ...
import { get } from "v2/Utils/get" export interface SeoProductsProps { descending_artworks: SeoProductsForCollections_descending_artworks
random_line_split
useUser.ts
/* * Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to i...
export function useUser(): UseQueryResult<User> { return useAuthUser('user', auth); }
random_line_split
useUser.ts
/* * Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to i...
{ return useAuthUser('user', auth); }
identifier_body
useUser.ts
/* * Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to i...
(): UseQueryResult<User> { return useAuthUser('user', auth); }
useUser
identifier_name
_chipmunk_ffi.py
""" Contains low level wrapper around the chipmunk_ffi methods exported by chipmunk_ffi.h as those methods are not automatically generated by the wrapper generator. You usually dont need to use this module directly, instead use the high level binding in pymunk """ from ctypes import *
from ._chipmunk import cpBool, cpFloat from ._chipmunk import cpBB, cpBody, cpVect, cpArbiter, cpShape, cpConstraint, cpGrooveJoint from ._chipmunk import chipmunk_lib from ._chipmunk import function_pointer cpBodyIsSleeping = (function_pointer(cpBool, POINTER(cpBody))).in_dll(chipmunk_lib, '_cpBodyIsSleeping') ...
from .vec2d import Vec2d
random_line_split
replication-couchdb.ts
{ isInstanceOf as isInstanceOfPouchDB, addPouchPlugin } from '../plugins/pouchdb'; import { isRxCollection } from '../rx-collection'; import type { RxCollection, PouchSyncHandler, PouchReplicationOptions, RxPlugin, SyncOptions, PouchDBInstance } from '../types'; import { runPluginH...
function getIsAlive(emitter: any): Promise<boolean> { // "state" will live in emitter.state if single direction replication // or in emitter.push.state & emitter.pull.state when syncing for both let state = emitter.state; if (!state) { state = [emitter.pull.state, emitte...
random_line_split
replication-couchdb.ts
{ isInstanceOf as isInstanceOfPouchDB, addPouchPlugin } from '../plugins/pouchdb'; import { isRxCollection } from '../rx-collection'; import type { RxCollection, PouchSyncHandler, PouchReplicationOptions, RxPlugin, SyncOptions, PouchDBInstance } from '../types'; import { runPluginH...
// if remote is RxCollection, get internal pouchdb if (isRxCollection(remote)) { remote = (remote as RxCollection).storageInstance.internals.pouch; } if (query && this !== query.collection) { throw newRxError('RC2', { query }); } const syncFun = pouchRepli...
{ throw newRxError('RC3', { database: this.database.name, collection: this.name }); }
conditional_block
replication-couchdb.ts
{ isInstanceOf as isInstanceOfPouchDB, addPouchPlugin } from '../plugins/pouchdb'; import { isRxCollection } from '../rx-collection'; import type { RxCollection, PouchSyncHandler, PouchReplicationOptions, RxPlugin, SyncOptions, PouchDBInstance } from '../types'; import { runPluginH...
} rxRepState._subs.push( fromEvent(evEmitter as any, 'paused') .pipe( skipUntil(fromEvent(evEmitter as any, 'active')) ).subscribe(() => { getIsAlive(rxRepState._pouchEventEmitterObject) .then(isAlive => rxRepState._subjects.a...
{ // "state" will live in emitter.state if single direction replication // or in emitter.push.state & emitter.pull.state when syncing for both let state = emitter.state; if (!state) { state = [emitter.pull.state, emitter.push.state] .reduce((acc, val) => { ...
identifier_body
replication-couchdb.ts
{ isInstanceOf as isInstanceOfPouchDB, addPouchPlugin } from '../plugins/pouchdb'; import { isRxCollection } from '../rx-collection'; import type { RxCollection, PouchSyncHandler, PouchReplicationOptions, RxPlugin, SyncOptions, PouchDBInstance } from '../types'; import { runPluginH...
(): Promise<void> { if (this.syncOptions.options && this.syncOptions.options.live) { throw newRxError('RC4', { database: this.collection.database.name, collection: this.collection.name }); } if (this.collection.database.multiInstance && thi...
awaitInitialReplication
identifier_name
submission_page.py
self.content = SubmissionContent.from_url( reddit, url, term.loader, max_comment_cols=config['max_comment_cols']) else: self.content = SubmissionContent( submission, term.loader, max_comment_cols=config['max_comment_cols']) ...
if url:
random_line_split
submission_page.py
= SubmissionContent.from_url( reddit, url, term.loader, max_comment_cols=config['max_comment_cols']) else: self.content = SubmissionContent( submission, term.loader, max_comment_cols=config['max_comment_cols']) # Start at the s...
(self): "Toggle the selected comment tree between visible and hidden" current_index = self.nav.absolute_index self.content.toggle(current_index) # This logic handles a display edge case after a comment toggle. We # want to make sure that when we re-draw the page, the cursor sta...
toggle_comment
identifier_name
submission_page.py
= SubmissionContent.from_url( reddit, url, term.loader, max_comment_cols=config['max_comment_cols']) else: self.content = SubmissionContent( submission, term.loader, max_comment_cols=config['max_comment_cols']) # Start at the s...
@SubmissionController.register(Command('SUBMISSION_OPEN_IN_URLVIEWER')) def comment_urlview(self): data = self.get_selected_item() comment = data.get('body') or data.get('text') or data.get('url_full') if comment: self.term.open_urlview(comment) else: se...
"Delete the selected comment" if self.get_selected_item()['type'] == 'Comment': self.delete_item() else: self.term.flash()
identifier_body
submission_page.py
@SubmissionController.register(Command('REFRESH')) def refresh_content(self, order=None, name=None): "Re-download comments and reset the page index" order = order or self.content.order url = name or self.content.name with self.term.loader('Refreshing page'): self.conte...
text, attr = 'NSFW', (curses.A_BOLD | Color.RED) self.term.add_line(win, text, attr=attr)
conditional_block
wasm_testsuite.rs
use cranelift_codegen::isa; use cranelift_codegen::print_errors::pretty_verifier_error; use cranelift_codegen::settings::{self, Flags}; use cranelift_codegen::verifier; use cranelift_wasm::{translate_module, DummyEnvironment, ReturnMode}; use std::fs; use std::fs::File; use std::io; use std::io::prelude::*; use std::pa...
(path: &Path) -> io::Result<Vec<u8>> { let mut buf: Vec<u8> = Vec::new(); let mut file = File::open(path)?; file.read_to_end(&mut buf)?; Ok(buf) } fn handle_module(path: &Path, flags: &Flags, return_mode: ReturnMode) { let data = match path.extension() { None => { panic!("the fi...
read_file
identifier_name
wasm_testsuite.rs
use cranelift_codegen::isa; use cranelift_codegen::print_errors::pretty_verifier_error; use cranelift_codegen::settings::{self, Flags}; use cranelift_codegen::verifier; use cranelift_wasm::{translate_module, DummyEnvironment, ReturnMode}; use std::fs; use std::fs::File; use std::io; use std::io::prelude::*; use std::pa...
fn read_file(path: &Path) -> io::Result<Vec<u8>> { let mut buf: Vec<u8> = Vec::new(); let mut file = File::open(path)?; file.read_to_end(&mut buf)?; Ok(buf) } fn handle_module(path: &Path, flags: &Flags, return_mode: ReturnMode) { let data = match path.extension() { None => { ...
{ let flags = Flags::new(settings::builder()); handle_module( Path::new("../wasmtests/use_fallthrough_return.wat"), &flags, ReturnMode::FallthroughReturn, ); }
identifier_body
wasm_testsuite.rs
use cranelift_codegen::isa; use cranelift_codegen::print_errors::pretty_verifier_error; use cranelift_codegen::settings::{self, Flags}; use cranelift_codegen::verifier; use cranelift_wasm::{translate_module, DummyEnvironment, ReturnMode}; use std::fs; use std::fs::File; use std::io; use std::io::prelude::*; use std::pa...
#[test] fn use_fallthrough_return() { let flags = Flags::new(settings::builder()); handle_module( Path::new("../wasmtests/use_fallthrough_return.wat"), &flags, ReturnMode::FallthroughReturn, ); } fn read_file(path: &Path) -> io::Result<Vec<u8>> { let mut buf: Vec<u8> = Vec::new(...
random_line_split
AmbientLightBridge.ts
/** --| ADAPTIVE RUNTIME PLATFORM |---------------------------------------------------------------------------------------- (C) Copyright 2013-2015 Carlos Lozano Diez t/a Adaptive.me <http://adaptive.me>. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance wi...
* See source code files for contributors. Release: * @version v2.2.15 -------------------------------------------| aut inveniam viam aut faciam |-------------------------------------------- */ ///<reference path="APIRequest.ts"/> ///<reference path="APIResponse.ts"/> ///<reference path="BaseSensorBridge.ts...
* Ferran Vila Conesa <http://github.com/fnva> <http://twitter.com/ferran_vila> <mailto:ferran.vila.conesa@gmail.com>
random_line_split
AmbientLightBridge.ts
/** --| ADAPTIVE RUNTIME PLATFORM |---------------------------------------------------------------------------------------- (C) Copyright 2013-2015 Carlos Lozano Diez t/a Adaptive.me <http://adaptive.me>. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance wi...
} } /** ------------------------------------| Engineered with ♥ in Barcelona, Catalonia |-------------------------------------- */
{ super(); }
identifier_body
AmbientLightBridge.ts
/** --| ADAPTIVE RUNTIME PLATFORM |---------------------------------------------------------------------------------------- (C) Copyright 2013-2015 Carlos Lozano Diez t/a Adaptive.me <http://adaptive.me>. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance wi...
() { super(); } } } /** ------------------------------------| Engineered with ♥ in Barcelona, Catalonia |-------------------------------------- */
constructor
identifier_name
threatfox.py
# -*- coding: utf-8 -*- import requests import json misperrors = {'error': 'Error'} mispattributes = {'input': ['md5', 'sha1', 'sha256', 'domain', 'url', 'email-src', 'ip-dst|port', 'ip-src|port'], 'output': ['text']} moduleinfo = {'version': '0.1', 'author': 'Corsin Camichel', 'description': 'Module to search for an ...
63: 'misp:confidence-level="usually-confident"', 90: 'misp:confidence-level="completely-confident"', } confidence_tag = "" for tag_minvalue, tag in confidence_tagging.items(): if level >= tag_minvalue: confidence_tag = tag return confidence_tag def handler(q=False)...
10: 'misp:confidence-level="rarely-confident"', 37: 'misp:confidence-level="fairly-confident"',
random_line_split
threatfox.py
# -*- coding: utf-8 -*- import requests import json misperrors = {'error': 'Error'} mispattributes = {'input': ['md5', 'sha1', 'sha256', 'domain', 'url', 'email-src', 'ip-dst|port', 'ip-src|port'], 'output': ['text']} moduleinfo = {'version': '0.1', 'author': 'Corsin Camichel', 'description': 'Module to search for an ...
def handler(q=False): if q is False: return False request = json.loads(q) ret_val = "" for input_type in mispattributes['input']: if input_type in request: to_query = request[input_type] break else: misperrors['error'] = "Unsupported attributes ty...
confidence_tagging = { 0: 'misp:confidence-level="unconfident"', 10: 'misp:confidence-level="rarely-confident"', 37: 'misp:confidence-level="fairly-confident"', 63: 'misp:confidence-level="usually-confident"', 90: 'misp:confidence-level="completely-confident"', } confide...
identifier_body
threatfox.py
# -*- coding: utf-8 -*- import requests import json misperrors = {'error': 'Error'} mispattributes = {'input': ['md5', 'sha1', 'sha256', 'domain', 'url', 'email-src', 'ip-dst|port', 'ip-src|port'], 'output': ['text']} moduleinfo = {'version': '0.1', 'author': 'Corsin Camichel', 'description': 'Module to search for an ...
(q=False): if q is False: return False request = json.loads(q) ret_val = "" for input_type in mispattributes['input']: if input_type in request: to_query = request[input_type] break else: misperrors['error'] = "Unsupported attributes type:" r...
handler
identifier_name
threatfox.py
# -*- coding: utf-8 -*- import requests import json misperrors = {'error': 'Error'} mispattributes = {'input': ['md5', 'sha1', 'sha256', 'domain', 'url', 'email-src', 'ip-dst|port', 'ip-src|port'], 'output': ['text']} moduleinfo = {'version': '0.1', 'author': 'Corsin Camichel', 'description': 'Module to search for an ...
return confidence_tag def handler(q=False): if q is False: return False request = json.loads(q) ret_val = "" for input_type in mispattributes['input']: if input_type in request: to_query = request[input_type] break else: misperrors['error'] = ...
if level >= tag_minvalue: confidence_tag = tag
conditional_block
unsubscribe-on-destroy.func.ts
import { Subscription } from 'rxjs/Subscription'; import * as _ from 'lodash-es'; import { ObservablesInterface } from './ngx-reactive-decorator.interface'; export const unsubscribeOnDestroy = function (target: any, observables?: ObservablesInterface): void { // Original ngOnDestroy const ngOnDestroy = target.pro...
}); }); } if (ngOnDestroy !== undefined) { ngOnDestroy.apply(this, arguments); } }; }
{ if (subscription instanceof Subscription && subscription.closed === false) { subscription.unsubscribe(); } }
conditional_block
unsubscribe-on-destroy.func.ts
import { Subscription } from 'rxjs/Subscription'; import * as _ from 'lodash-es'; import { ObservablesInterface } from './ngx-reactive-decorator.interface'; export const unsubscribeOnDestroy = function (target: any, observables?: ObservablesInterface): void { // Original ngOnDestroy const ngOnDestroy = target.pro...
}); } if (ngOnDestroy !== undefined) { ngOnDestroy.apply(this, arguments); } }; }
if (subscription instanceof Subscription && subscription.closed === false) { subscription.unsubscribe(); } } });
random_line_split
markdownRenderCodeStyle.ts
// List of available code styles. enum MdrCodeStyle { agate = 'agate', androidstudio = 'androidstudio', arduinoLight = 'arduino-light', arta = 'arta', ascetic = 'ascetic', atelierCaveDark = 'atelier-cave-dark', atelierCaveLight = 'atelier-cave-light', atelierDuneDark = 'atelier-dune-dark', atelierDune...
vs2015 = 'vs2015', xcode = 'xcode', xt256 = 'xt256', zenburn = 'zenburn', } // Change here code style by default. const defaultCodeStyle = MdrCodeStyle.atomOneLight; // Code style dynamic loader. const loadCodeStyle = (style: MdrCodeStyle) => { return require(`highlight.js/styles/${style}.css`); }; export ...
tomorrow = 'tomorrow', vs = 'vs',
random_line_split
__init__.py
# coding=utf-8 from __future__ import unicode_literals from .. import Provider as BaseProvider # Ukrainian job names taken from # https://uk.wikipedia.org/wiki/%D0%A1%D0%BF%D0%B8%D1%81%D0%BE%D0%BA_%D0%BF%D1%80%D0%BE%D1%84%D0%B5%D1%81%D1%96%D0%B9 # on 22th September 2014 class Provider(BaseProvider): jobs = [ ...
]
random_line_split
__init__.py
# coding=utf-8 from __future__ import unicode_literals from .. import Provider as BaseProvider # Ukrainian job names taken from # https://uk.wikipedia.org/wiki/%D0%A1%D0%BF%D0%B8%D1%81%D0%BE%D0%BA_%D0%BF%D1%80%D0%BE%D1%84%D0%B5%D1%81%D1%96%D0%B9 # on 22th September 2014 class
(BaseProvider): jobs = [ # А 'Агроном', 'Адвокат', 'Актор', 'Акушер', 'Антрополог', 'Архітектор', 'Археолог', 'Астронавт', 'Астроном', 'Астрофізик', # Б 'Бібліограф', 'Біолог', 'Бізнесмен', 'Ботанік', 'Будник', 'Бухгалтер', 'Бібліотекар', # В 'Ветеринар', 'Вип...
Provider
identifier_name
__init__.py
# coding=utf-8 from __future__ import unicode_literals from .. import Provider as BaseProvider # Ukrainian job names taken from # https://uk.wikipedia.org/wiki/%D0%A1%D0%BF%D0%B8%D1%81%D0%BE%D0%BA_%D0%BF%D1%80%D0%BE%D1%84%D0%B5%D1%81%D1%96%D0%B9 # on 22th September 2014 class Provider(BaseProvider):
'Євнух', 'Єгер', # Ж 'Журналіст', 'Живописець', # З 'Золотар', 'Зоолог', # І 'Інженер', 'Історик', # К 'Каскадер', 'Кінорежисер', 'Клавішник', 'Клоун', 'Композитор', 'Конструктор', 'Краєзнавець', 'Кушнір', 'Кіноактор', 'Кінокритик', 'Кіноре...
jobs = [ # А 'Агроном', 'Адвокат', 'Актор', 'Акушер', 'Антрополог', 'Архітектор', 'Археолог', 'Астронавт', 'Астроном', 'Астрофізик', # Б 'Бібліограф', 'Біолог', 'Бізнесмен', 'Ботанік', 'Будник', 'Бухгалтер', 'Бібліотекар', # В 'Ветеринар', 'Випробувач', 'Водій', '...
identifier_body
animation_example_spec.ts
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {$, browser, by, element, ExpectedConditions} from 'protractor'; import {verifyNoBrowserErrors} from '../../....
describe('animation example', () => { afterEach(verifyNoBrowserErrors); describe('index view', () => { const URL = '/animation/dsl/'; it('should list out the current collection of items', () => { browser.get(URL); waitForElement('.toggle-container'); expect(element.all(by.css('.toggle-...
{ const EC = ExpectedConditions; // Waits for the element with id 'abc' to be present on the dom. browser.wait(EC.presenceOf($(selector)), 20000); }
identifier_body
animation_example_spec.ts
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {$, browser, by, element, ExpectedConditions} from 'protractor'; import {verifyNoBrowserErrors} from '../../....
(selector: string) { const EC = ExpectedConditions; // Waits for the element with id 'abc' to be present on the dom. browser.wait(EC.presenceOf($(selector)), 20000); } describe('animation example', () => { afterEach(verifyNoBrowserErrors); describe('index view', () => { const URL = '/animation/dsl/'; ...
waitForElement
identifier_name
animation_example_spec.ts
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {$, browser, by, element, ExpectedConditions} from 'protractor'; import {verifyNoBrowserErrors} from '../../....
});
random_line_split
build.rs
extern crate symbiosis; use std::path::Path; use std::fs::{File, create_dir_all}; use std::io::Read; use std::default::Default; use symbiosis::TemplateGroup; use symbiosis::rust::{self, Rust}; use symbiosis::javascript::{self, JavaScript}; fn
() { let out_dir = std::env::var("OUT_DIR").unwrap(); let rust_dest = Path::new(&out_dir).join("symbiosis/"); if let Err(e) = create_dir_all(&rust_dest) { panic!("failed to create Symbiosis output directory: {}", e); } let js_dest = Path::new("res"); let mut templates = TemplateGroup::n...
main
identifier_name
build.rs
extern crate symbiosis; use std::path::Path; use std::fs::{File, create_dir_all}; use std::io::Read; use std::default::Default; use symbiosis::TemplateGroup; use symbiosis::rust::{self, Rust}; use symbiosis::javascript::{self, JavaScript}; fn main() { let out_dir = std::env::var("OUT_DIR").unwrap(); let rust...
let js = JavaScript { namespace: Some("templates"), ..Default::default() }; let rust = Rust { ..Default::default() }; if let Err(e) = File::create(js_dest.join("templates.js")).map_err(|e| javascript::Error::Io(e)).and_then(|mut file| templates.emit_code(&mut file, &js)) { pa...
{ panic!("failed to precompile templates/shared: {}", e); }
conditional_block
build.rs
extern crate symbiosis; use std::path::Path; use std::fs::{File, create_dir_all}; use std::io::Read; use std::default::Default; use symbiosis::TemplateGroup; use symbiosis::rust::{self, Rust}; use symbiosis::javascript::{self, JavaScript}; fn main() {
let rust_dest = Path::new(&out_dir).join("symbiosis/"); if let Err(e) = create_dir_all(&rust_dest) { panic!("failed to create Symbiosis output directory: {}", e); } let js_dest = Path::new("res"); let mut templates = TemplateGroup::new(); if let Err(e) = templates.parse_directory("temp...
let out_dir = std::env::var("OUT_DIR").unwrap();
random_line_split
build.rs
extern crate symbiosis; use std::path::Path; use std::fs::{File, create_dir_all}; use std::io::Read; use std::default::Default; use symbiosis::TemplateGroup; use symbiosis::rust::{self, Rust}; use symbiosis::javascript::{self, JavaScript}; fn main()
if let Err(e) = File::create(js_dest.join("templates.js")).map_err(|e| javascript::Error::Io(e)).and_then(|mut file| templates.emit_code(&mut file, &js)) { panic!("failed to create res/templates.js: {}", e); } let mut source = String::new(); if let Err(e) = File::open("templates/Document.html"...
{ let out_dir = std::env::var("OUT_DIR").unwrap(); let rust_dest = Path::new(&out_dir).join("symbiosis/"); if let Err(e) = create_dir_all(&rust_dest) { panic!("failed to create Symbiosis output directory: {}", e); } let js_dest = Path::new("res"); let mut templates = TemplateGroup::new(...
identifier_body
diagnostic.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
(di: DiagnosticInfoRef) -> Diagnostic { let kind = super::LLVMGetDiagInfoKind(di); match kind { super::DK_InlineAsm => InlineAsm(InlineAsmDiagnostic::unpack(di)), super::DK_OptimizationRemark => Optimization(OptimizationDiagnostic::unpack(Optimiz...
unpack
identifier_name
diagnostic.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
message: ptr::null_mut(), }; super::LLVMUnpackOptimizationDiagnostic(di, &mut opt.pass_name, &mut opt.function, &mut opt.debug_loc, &mut opt.message); opt } } pub struct InlineAsmDiagnostic { pub cookie: c_uint, pub messa...
kind: kind, pass_name: ptr::null(), function: ptr::null_mut(), debug_loc: ptr::null_mut(),
random_line_split
IPssimisticalConfig.ts
export interface IPssimisticalConfig { inputs: IPssimisticalInput[], tables: IPssimisticalTable[], query: IPssimisticalQuery, readers: TypedMap<IPssimisticalReader> } export interface TypedMap<T> {
export interface IPssimisticalTable { columns: IPssimisticalColumn[], name: string } export interface IPssimisticalInput { path: string, table: string, reader: string } export interface IPssimisticalColumn { name: string, type: string, index: boolean } export interface IPssimistical...
[name: string]: T; }
random_line_split
setup.py
# -*- coding: utf-8 -*- from distutils.core import setup import os.path classifiers = [ "Programming Language :: Python", "Programming Language :: Python :: 3", "Development Status :: 4 - Beta", "Intended Audience :: Developers", "License :: OSI Approved :: GNU Library or Lesser General Public Lice...
] def read(fname): fname = os.path.join(os.path.dirname(__file__), fname) return open(fname).read().strip() def read_files(*fnames): return '\r\n\r\n\r\n'.join(map(read, fnames)) setup( name = 'icall', version = '0.3.4', py_modules = ['icall'], description = 'Parameters call function,...
"Topic :: Software Development :: Libraries :: Python Modules",
random_line_split
setup.py
# -*- coding: utf-8 -*- from distutils.core import setup import os.path classifiers = [ "Programming Language :: Python", "Programming Language :: Python :: 3", "Development Status :: 4 - Beta", "Intended Audience :: Developers", "License :: OSI Approved :: GNU Library or Lesser General Public Lice...
setup( name = 'icall', version = '0.3.4', py_modules = ['icall'], description = 'Parameters call function, :-)', long_description = read_files('README.rst', 'CHANGES.rst'), author = 'huyx', author_email = 'ycyuxin@gmail.com', url = 'https://github.com/huyx/icall', keywords = ['func...
return '\r\n\r\n\r\n'.join(map(read, fnames))
identifier_body
setup.py
# -*- coding: utf-8 -*- from distutils.core import setup import os.path classifiers = [ "Programming Language :: Python", "Programming Language :: Python :: 3", "Development Status :: 4 - Beta", "Intended Audience :: Developers", "License :: OSI Approved :: GNU Library or Lesser General Public Lice...
(*fnames): return '\r\n\r\n\r\n'.join(map(read, fnames)) setup( name = 'icall', version = '0.3.4', py_modules = ['icall'], description = 'Parameters call function, :-)', long_description = read_files('README.rst', 'CHANGES.rst'), author = 'huyx', author_email = 'ycyuxin@gmail.com', ...
read_files
identifier_name
GenericConsole.js
this.historyButton = null; this.stateButton = null; this.clearOutButton = null; this.clearInButton = null; this.loadButton = null; this.defaultMessage = null; this.label1 = null; this.nTab = 0; this.incompleteCmd = null; Clazz.instantialize (this, arguments); }, J.console, "GenericConsole", null, [J.api.JmolAppConsoleI...
this.runButton = null;
random_line_split
base.py
# Copyright (C) 2016 Google Inc. # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> """Base objects for csv file converters.""" from collections import defaultdict from ggrc import settings from ggrc.utils import structures from ggrc.cache.memcache import MemCache from ggrc.converters imp...
def import_secondary_objects(self): for converter in self.block_converters: converter.import_secondary_objects(self.new_objects) def get_info(self): for converter in self.block_converters: self.response_data.append(converter.get_info()) return self.response_data def get_object_names(se...
converter.handle_row_data() converter.import_objects()
conditional_block
base.py
# Copyright (C) 2016 Google Inc. # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> """Base objects for csv file converters.""" from collections import defaultdict from ggrc import settings from ggrc.utils import structures from ggrc.cache.memcache import MemCache from ggrc.converters imp...
"Custom Attribute Definition", "Assessment", "Workflow", "Task Group", "Task Group Task", ] priority_columns = [ "email", "slug", "delete", "task_type", ] def __init__(self, **kwargs): self.dry_run = kwargs.get("dry_run", True) self.csv_data = kwar...
"Regulation", "Standard", "Section", "Control", "Assessment Template",
random_line_split
base.py
# Copyright (C) 2016 Google Inc. # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> """Base objects for csv file converters.""" from collections import defaultdict from ggrc import settings from ggrc.utils import structures from ggrc.cache.memcache import MemCache from ggrc.converters imp...
(self): self.block_converters_from_csv() self.row_converters_from_csv() self.handle_priority_columns() self.import_objects() self.import_secondary_objects() self.drop_cache() def handle_priority_columns(self): for attr_name in self.priority_columns: for block_converter in self.block...
import_csv
identifier_name
base.py
# Copyright (C) 2016 Google Inc. # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> """Base objects for csv file converters.""" from collections import defaultdict from ggrc import settings from ggrc.utils import structures from ggrc.cache.memcache import MemCache from ggrc.converters imp...
def block_converters_from_csv(self): """Prepare BlockConverters and order them like specified in self.CLASS_ORDER. """ offsets, data_blocks = split_array(self.csv_data) for offset, data in zip(offsets, data_blocks): if len(data) < 2: continue # empty block class_name = data[...
""" fill the block_converters class variable Generate block converters from a list of tuples with an object name and ids """ object_map = {o.__name__: o for o in self.exportable.values()} for object_data in self.ids_by_type: class_name = object_data["object_name"] object_class = object_map[...
identifier_body
htmlvideoelement.rs
; use html5ever::{LocalName, Prefix}; use ipc_channel::ipc; use ipc_channel::router::ROUTER; use net_traits::image_cache::{ ImageCache, ImageCacheResult, ImageOrMetadataAvailable, ImageResponse, PendingImageId, UsePlaceholder, }; use net_traits::request::{CredentialsMode, Destination, RequestBuilder}; use net_t...
pub fn set_video_width(&self, width: u32) { self.video_width.set(width); } pub fn get_video_height(&self) -> u32 { self.video_height.get() } pub fn set_video_height(&self, height: u32) { self.video_height.set(height); } pub fn allow_load_event(&self) { Lo...
{ self.video_width.get() }
identifier_body
htmlvideoelement.rs
Cell<Option<VideoFrame>>, } impl HTMLVideoElement { fn new_inherited( local_name: LocalName, prefix: Option<Prefix>, document: &Document, ) -> HTMLVideoElement { HTMLVideoElement { htmlmediaelement: HTMLMediaElement::new_inherited(local_name, prefix, document), ...
process_response_chunk
identifier_name
htmlvideoelement.rs
D; use html5ever::{LocalName, Prefix}; use ipc_channel::ipc; use ipc_channel::router::ROUTER; use net_traits::image_cache::{ ImageCache, ImageCacheResult, ImageOrMetadataAvailable, ImageResponse, PendingImageId, UsePlaceholder, }; use net_traits::request::{CredentialsMode, Destination, RequestBuilder}; use net_...
if self.htmlmediaelement.get_ready_state() == ReadyState::HaveNothing { return 0; } self.video_width.get() } // https://html.spec.whatwg.org/multipage/#dom-video-videoheight fn VideoHeight(&self) -> u32 { if self.htmlmediaelement.get_ready_state() == ReadyState::...
random_line_split
__init__.py
# -*- coding: utf-8 -*- """The application's model objects""" from zope.sqlalchemy import ZopeTransactionExtension from sqlalchemy.orm import scoped_session, sessionmaker # from sqlalchemy import MetaData from sqlalchemy.ext.declarative import declarative_base # Global session manager: DBSession() returns the Thread-l...
_old, _new = self._2string(obj_col, attr_old_value, attr_new_value) log.append((obj_col.info.get("field_name", prop.key), _old, _new)) if log : print log def _isUpdateReally(self, col, old_value, new_value): if not old_value and not new_value :...
continue
conditional_block
__init__.py
# -*- coding: utf-8 -*- """The application's model objects""" from zope.sqlalchemy import ZopeTransactionExtension from sqlalchemy.orm import scoped_session, sessionmaker # from sqlalchemy import MetaData from sqlalchemy.ext.declarative import declarative_base # Global session manager: DBSession() returns the Thread-l...
(self, col, old_value, new_value): if not old_value and not new_value : return False if not (old_value and new_value) : return True if isinstance(col.type, sqlalchemy.types.Integer): return old_value == int(new_value) if isinstance(col.type, sqlalchemy.types.Float): return old_value =...
_isUpdateReally
identifier_name
__init__.py
# -*- coding: utf-8 -*- """The application's model objects""" from zope.sqlalchemy import ZopeTransactionExtension from sqlalchemy.orm import scoped_session, sessionmaker # from sqlalchemy import MetaData from sqlalchemy.ext.declarative import declarative_base # Global session manager: DBSession() returns the Thread-l...
# maker = sessionmaker(autoflush = True, autocommit = False, # extension = [ LogSessionExtension(), ZopeTransactionExtension(), ]) maker = sessionmaker(autoflush = True, autocommit = False, extension = ZopeTransactionExtension()) DBSession = scoped_session(maker) # Base class f...
random_line_split
__init__.py
# -*- coding: utf-8 -*- """The application's model objects""" from zope.sqlalchemy import ZopeTransactionExtension from sqlalchemy.orm import scoped_session, sessionmaker # from sqlalchemy import MetaData from sqlalchemy.ext.declarative import declarative_base # Global session manager: DBSession() returns the Thread-l...
if not need2log : continue if prop.key not in obj_state.dict: getattr(obj, prop.key) history = attributes.get_history(obj, prop.key) if not history.has_changes():continue a, u, d = history ...
def before_flush(self, session, flush_context, instances): print "_^" * 30 print "Come into my log session extension" print "_*" * 30 log = [] for obj in session.dirty: obj_mapper = object_mapper(obj) obj_state = attributes.instance_state(obj) ...
identifier_body
default.js
module.exports = { "Redis":{ "redisip":"104.131.105.222", "redisport":6379, "redisdb":6 }, "Services" : { "routingServiceHost": "localhost", "routingServicePort": "2223", "routingServiceVersion": "1.0.0.0" }, "Host": { "LBIP":"127.0.0.1", "LBPort":"2225", "Ip": "127.0.0.1", "Port": "2225", "...
};
random_line_split
servicemanagement_v1_generated_service_manager_create_service_sync.py
# -*- coding: utf-8 -*- # Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
(): # Create a client client = servicemanagement_v1.ServiceManagerClient() # Initialize request argument(s) request = servicemanagement_v1.CreateServiceRequest( ) # Make the request operation = client.create_service(request=request) print("Waiting for operation to complete...") r...
sample_create_service
identifier_name
servicemanagement_v1_generated_service_manager_create_service_sync.py
# -*- coding: utf-8 -*- # Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at #
# Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # ...
# http://www.apache.org/licenses/LICENSE-2.0 #
random_line_split
servicemanagement_v1_generated_service_manager_create_service_sync.py
# -*- coding: utf-8 -*- # Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
# [END servicemanagement_v1_generated_ServiceManager_CreateService_sync]
client = servicemanagement_v1.ServiceManagerClient() # Initialize request argument(s) request = servicemanagement_v1.CreateServiceRequest( ) # Make the request operation = client.create_service(request=request) print("Waiting for operation to complete...") response = operation.result() ...
identifier_body
__init__.py
# -*- coding: utf-8 -*- # MIT license # # Copyright (C) 2018 by XESS Corporation / Hildo Guillardi Júnior # # 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 with...
return distributor_class.get_distributor_info(name) def get_dist_name_from_label(label): ''' Returns the internal distributor name for a provided label. ''' return distributor_class.label2name.get(label.lower()) def set_distributors_logger(logger): ''' Sets the logger used by the class ''' distr...
''' Gets all the information about a supported distributor. This information comes from the list collected from the APIs, not from the fixed template. '''
random_line_split
__init__.py
# -*- coding: utf-8 -*- # MIT license # # Copyright (C) 2018 by XESS Corporation / Hildo Guillardi Júnior # # 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 with...
api, enabled): ''' Enable/Disable a particular API ''' distributor_class.set_api_status(api, enabled) def get_api_status(api): ''' Find if an API is enabled ''' return distributor_class.get_api_status(api) # Init distributor dict during import. init_distributor_dict()
et_api_status(
identifier_name
__init__.py
# -*- coding: utf-8 -*- # MIT license # # Copyright (C) 2018 by XESS Corporation / Hildo Guillardi Júnior # # 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 with...
def get_api_status(api): ''' Find if an API is enabled ''' return distributor_class.get_api_status(api) # Init distributor dict during import. init_distributor_dict()
'' Enable/Disable a particular API ''' distributor_class.set_api_status(api, enabled)
identifier_body
intuition.js
= function(depth) { var _super = {}; // if the depth is a number greater than zero, then a _super class exists if(depth && depth > 0) { // the parent is like a linked list. When we finally reach the parent with depth, 1 less than the context depth // we know we have found the correct parent var paren...
})(Class) return Class; }; /** * copyStaticMethods copies the static methods of one level of inheritance into the inheriting class * @param {Intuition<Class>} _class */ Intuition.copyStaticMethods = function(_class) { for(var prop in _class) { if(!this[prop]) this[prop] = _class[prop]; } if(_clas...
return promiseConstructor; }
random_line_split
intuition.js
= function(depth) { var _super = {}; // if the depth is a number greater than zero, then a _super class exists if(depth && depth > 0) { // the parent is like a linked list. When we finally reach the parent with depth, 1 less than the context depth // we know we have found the correct parent var paren...
} } return _super; }; /** * extend enables classical inheritance in javascript, anything that extends an Intuition Class can be Extended * @param {Function} constructor - is a function that retuns an object literal of inheritable methods * @returns {Intuition<Class>} Class - is a set of methods belonging to...
{ _super[method] = parent[method].bind(this); }
conditional_block
iterateArcMapDocsByFolder.py
# Copyright 2012 majgis Contributors # # Individuals comprising majgis Contributors are identified in # the NOTICE file found in the root directory of this project. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # Y...
lyrs = mapping.ListLayers(mxd) mxde = MxdExtras(mxdPath) msdPath = mxdPath.replace(mxdSuffix, msdSuffix) for lyr in lyrs: lyre = mxde[lyr.name] joinTable = lyre.joinedTableName joinField = lyre.symbologyShort...
random_line_split
iterateArcMapDocsByFolder.py
# Copyright 2012 majgis Contributors # # Individuals comprising majgis Contributors are identified in # the NOTICE file found in the root directory of this project. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # Y...
#export msd mapping.ConvertToMSD(mxd,msdPath) print msdPath
os.remove(msdPath)
conditional_block
cargo_output_metadata.rs
use crate::core::compiler::{CompileKind, CompileTarget, RustcTargetData}; use crate::core::dependency::DepKind; use crate::core::resolver::{HasDevUnits, Resolve, ResolveOpts}; use crate::core::{Dependency, InternedString, Package, PackageId, Workspace}; use crate::ops::{self, Packages}; use crate::util::CargoResult; us...
requested_kind, ); } }
package_map, target_data,
random_line_split
cargo_output_metadata.rs
use crate::core::compiler::{CompileKind, CompileTarget, RustcTargetData}; use crate::core::dependency::DepKind; use crate::core::resolver::{HasDevUnits, Resolve, ResolveOpts}; use crate::core::{Dependency, InternedString, Package, PackageId, Workspace}; use crate::ops::{self, Packages}; use crate::util::CargoResult; us...
{ nodes: Vec<MetadataResolveNode>, root: Option<PackageId>, } #[derive(Serialize)] struct MetadataResolveNode { id: PackageId, dependencies: Vec<PackageId>, deps: Vec<Dep>, features: Vec<InternedString>, } #[derive(Serialize)] struct Dep { name: String, pkg: PackageId, dep_kinds: ...
MetadataResolve
identifier_name
validators.py
import stdnum import re from datetime import datetime, date from django.utils import timezone from django.core.exceptions import ValidationError from django.utils.deconstruct import deconstructible from stdnum.it import codicefiscale def _valida_codice_fiscale(codice_fiscale): """ Validatore esteso che ver...
): anni = 14 al_giorno = timezone.now().date() if (al_giorno.year - data.year - ((al_giorno.month, al_giorno.day) < (data.month, data.day))) < anni: raise ValidationError("Sono necessari almeno %d anni di età" % (anni,)) def valida_email_personale(email): coppie = ( ('cl.', '@cri.it')...
a_almeno_14_anni(data
identifier_name
validators.py
import stdnum import re from datetime import datetime, date from django.utils import timezone from django.core.exceptions import ValidationError from django.utils.deconstruct import deconstructible from stdnum.it import codicefiscale def _valida_codice_fiscale(codice_fiscale): """ Validatore esteso che ver...
if isinstance(data, date): if data > date.today(): raise ValidationError("La data non può essere nel futuro.") else: raise TypeError("Fornito tipo di data non valido.") @deconstructible class ValidateFileSize(object): def __init__(self, filesize=2): self.filesize = filesize...
alidationError("Data ed ora non possono essere nel futuro.") el
conditional_block
validators.py
import stdnum import re from datetime import datetime, date from django.utils import timezone from django.core.exceptions import ValidationError from django.utils.deconstruct import deconstructible from stdnum.it import codicefiscale def _valida_codice_fiscale(codice_fiscale):
def valida_codice_fiscale(codice_fiscale): try: _valida_codice_fiscale(codice_fiscale) except: raise ValidationError("Il codice fiscale non è valido.") def ottieni_genere_da_codice_fiscale(codice_fiscale, default=None): try: return codicefiscale.get_gender(codice_fiscale) ex...
""" Validatore esteso che verifica che il codice fiscale sia valido. Se il codice fiscale e' temporaneo (11 cifre numeriche), e' considerato valido. :param codice_fiscale: Il codice fiscale. :return: None. Exception in caso di validazione. """ try: codicefiscale.validate(codice_fiscale) ...
identifier_body
validators.py
import stdnum import re from datetime import datetime, date from django.utils import timezone from django.core.exceptions import ValidationError from django.utils.deconstruct import deconstructible from stdnum.it import codicefiscale def _valida_codice_fiscale(codice_fiscale): """ Validatore esteso che ver...
return codicefiscale.get_gender(codice_fiscale) except: return default def crea_validatore_dimensione_file(mb=10): def _validatore(fieldfile_obj): filesize = fieldfile_obj.file.size megabyte_limit = mb if filesize > megabyte_limit*1024*1024: raise Validatio...
random_line_split
eecli.py
#!/usr/bin/env python """Executable for the Earth Engine command line interface. This executable starts a Python Cmd instance to receive and process command line input entered by the user. If the executable is invoked with some command line arguments, the Cmd is launched in the one-off mode, where the provided argumen...
(): # Set the program name to 'earthengine' for proper help text display. parser = argparse.ArgumentParser( prog='earthengine', description='Earth Engine Command Line Interface.') parser.add_argument( '--ee_config', help='Path to the earthengine configuration file. ' 'Defaults to "~/%s".' % util...
main
identifier_name
eecli.py
#!/usr/bin/env python """Executable for the Earth Engine command line interface. This executable starts a Python Cmd instance to receive and process command line input entered by the user. If the executable is invoked with some command line arguments, the Cmd is launched in the one-off mode, where the provided argumen...
# errors, and print the error message without the irrelevant local # stack trace. (Individual commands may also catch EEException if # they want to be able to continue despite errors.) try: dispatcher.run(args, config) except ee.EEException as e: print(e) sys.exit(1) if __name__ == '__main__': ...
parser = argparse.ArgumentParser( prog='earthengine', description='Earth Engine Command Line Interface.') parser.add_argument( '--ee_config', help='Path to the earthengine configuration file. ' 'Defaults to "~/%s".' % utils.DEFAULT_EE_CONFIG_FILE_RELATIVE) parser.add_argument( '--service_acc...
identifier_body
eecli.py
#!/usr/bin/env python """Executable for the Earth Engine command line interface. This executable starts a Python Cmd instance to receive and process command line input entered by the user. If the executable is invoked with some command line arguments, the Cmd is launched in the one-off mode, where the provided argumen...
main()
conditional_block
index.js
function __processArg(obj, key) { var arg = null; if (obj)
return arg; } function Controller() { require("alloy/controllers/BaseController").apply(this, Array.prototype.slice.call(arguments)); this.__controllerPath = "index"; this.args = arguments[0] || {}; if (arguments[0]) { { __processArg(arguments[0], "__parentSymbol"); } ...
{ arg = obj[key] || null; delete obj[key]; }
conditional_block
index.js
function
(obj, key) { var arg = null; if (obj) { arg = obj[key] || null; delete obj[key]; } return arg; } function Controller() { require("alloy/controllers/BaseController").apply(this, Array.prototype.slice.call(arguments)); this.__controllerPath = "index"; this.args = arguments[0] ...
__processArg
identifier_name
index.js
function __processArg(obj, key) { var arg = null;
} return arg; } function Controller() { require("alloy/controllers/BaseController").apply(this, Array.prototype.slice.call(arguments)); this.__controllerPath = "index"; this.args = arguments[0] || {}; if (arguments[0]) { { __processArg(arguments[0], "__parentSymbol"); ...
if (obj) { arg = obj[key] || null; delete obj[key];
random_line_split
index.js
function __processArg(obj, key) { var arg = null; if (obj) { arg = obj[key] || null; delete obj[key]; } return arg; } function Controller()
exitOnClose: true, id: "index" }); $.__views.index && $.addTopLevelView($.__views.index); $.__views.__alloyId0 = Ti.UI.createLabel({ text: "This app is supported only on iOS", id: "__alloyId0" }); $.__views.index.add($.__views.__alloyId0); exports.destroy = functi...
{ require("alloy/controllers/BaseController").apply(this, Array.prototype.slice.call(arguments)); this.__controllerPath = "index"; this.args = arguments[0] || {}; if (arguments[0]) { { __processArg(arguments[0], "__parentSymbol"); } { __processArg(argument...
identifier_body
htmlcanvaselement.rs
enum CanvasContext { Context2d(JS<CanvasRenderingContext2D>), WebGL(JS<WebGLRenderingContext>), } impl HeapGCValue for CanvasContext {} #[dom_struct] pub struct HTMLCanvasElement { htmlelement: HTMLElement, context: DOMRefCell<Option<CanvasContext>>, } impl PartialEq for HTMLCanvasElement { fn e...
{ Some(self.upcast::<HTMLElement>() as &VirtualMethods) }
identifier_body
htmlcanvaselement.rs
use dom::canvasrenderingcontext2d::{CanvasRenderingContext2D, LayoutCanvasRenderingContext2DHelpers}; use dom::document::Document; use dom::element::{AttributeMutation, Element, RawLayoutElementHelpers}; use dom::htmlelement::HTMLElement; use dom::node::{Node, window_from_node}; use dom::virtualmethods::VirtualMethods;...
{ pub renderer_id: Option<usize>, pub ipc_renderer: Option<IpcSender<CanvasMsg>>, pub width: u32, pub height: u32, } pub trait LayoutHTMLCanvasElementHelpers { fn data(&self) -> HTMLCanvasData; } impl LayoutHTMLCanvasElementHelpers for LayoutJS<HTMLCanvasElement> { #[allow(unsafe_code)] f...
HTMLCanvasData
identifier_name
htmlcanvaselement.rs
use dom::canvasrenderingcontext2d::{CanvasRenderingContext2D, LayoutCanvasRenderingContext2DHelpers}; use dom::document::Document; use dom::element::{AttributeMutation, Element, RawLayoutElementHelpers}; use dom::htmlelement::HTMLElement; use dom::node::{Node, window_from_node}; use dom::virtualmethods::VirtualMethods;...
use ipc_channel::ipc::{self, IpcSender}; use js::jsapi::{HandleValue, JSContext}; use offscreen_gl_context::GLContextAttributes; use rustc_serialize::base64::{STANDARD, ToBase64}; use std::iter::repeat; use string_cache::Atom; use util::str::DOMString; const DEFAULT_WIDTH: u32 = 300; const DEFAULT_HEIGHT: u32 = 150; ...
use image::png::PNGEncoder;
random_line_split
CollapsibleSection.js
/** * Copyright (C) 2005-2016 Alfresco Software Limited. * * This file is part of Alfresco * * Alfresco is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at ...
/** * This extends the [Twister]{@link module:alfresco/layout/Twister} and mixes in * the [LayoutMixin]{@link module:alfresco/forms/LayoutMixin} to provide a collapsible section * into which form controls can be placed. * * @example <caption>Example form with a CollapsibleSection</caption> * { * name: "alfre...
*/
random_line_split