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
dialogflow_generated_dialogflow_v2_versions_create_version_async.py
# -*- coding: utf-8 -*- # Copyright 2020 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
dialogflow_generated_dialogflow_v2_versions_create_version_async.py
# -*- coding: utf-8 -*- # Copyright 2020 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 dialogflow_generated_dialogflow_v2_Versions_CreateVersion_async]
client = dialogflow_v2.VersionsAsyncClient() # Initialize request argument(s) request = dialogflow_v2.CreateVersionRequest( parent="parent_value", ) # Make the request response = await client.create_version(request=request) # Handle the response print(response)
identifier_body
dialogflow_generated_dialogflow_v2_versions_create_version_async.py
# -*- coding: utf-8 -*- # Copyright 2020 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 = dialogflow_v2.VersionsAsyncClient() # Initialize request argument(s) request = dialogflow_v2.CreateVersionRequest( parent="parent_value", ) # Make the request response = await client.create_version(request=request) # Handle the response print...
sample_create_version
identifier_name
models.py
from app import db import datetime from geoalchemy2 import Geometry from sqlalchemy.dialects import postgresql from sqlalchemy.dialects.postgresql import UUID from sqlalchemy import Column import sqlalchemy from slugify import slugify from flask.ext.login import UserMixin class User(UserMixin, db.Model):
__tablename__ = "users" id = Column(UUID(as_uuid=True), server_default=sqlalchemy.text("uuid_generate_v4()"), primary_key=True) session_token = Column(UUID(as_uuid=True), server_default=sqlalchemy.text("uuid_generate_v4()"), unique=True) permissions_group = db.Column(db.String, default='use...
identifier_body
models.py
from app import db import datetime from geoalchemy2 import Geometry from sqlalchemy.dialects import postgresql from sqlalchemy.dialects.postgresql import UUID from sqlalchemy import Column import sqlalchemy from slugify import slugify from flask.ext.login import UserMixin class User(UserMixin, db.Model): __tablen...
(self): return unicode(self.session_token)
get_id
identifier_name
models.py
from app import db import datetime from geoalchemy2 import Geometry from sqlalchemy.dialects import postgresql
from sqlalchemy import Column import sqlalchemy from slugify import slugify from flask.ext.login import UserMixin class User(UserMixin, db.Model): __tablename__ = "users" id = Column(UUID(as_uuid=True), server_default=sqlalchemy.text("uuid_generate_v4()"), primary_key=True) session_token = Column...
from sqlalchemy.dialects.postgresql import UUID
random_line_split
appliance.ts
export interface Image { compression?: string; direct_download_url?: string; download_url: string; filename: string; filesize: any; md5sum: string; version: string; } export interface Qemu { adapter_type: string; adapters: number; arch: string; boot_priority: string; console_type: string; hda...
ram: number; } export interface Docker { adapters: number; console_type: string; image: string; } export interface Dynamips { chassis: string; nvram: number; platform: string; ram: number; slot0: string; slot1: string; slot2: string; slot3: string; slot4: string; slot5: string; slot6: st...
kvm: string;
random_line_split
errors.rs
//! Error types. //! //! Some events are handled are errors so that they propagate upwards naturally, although //! technically they're not really errors: //! //! - [`ErrorKind::Unsat`] //! - [`ErrorKind::Timeout`] //! - [`ErrorKind::Unknown`] (when hoice gave up on solving the clauses) //! //! As such, one should **not...
} false } /// True if the kind of the error is [`ErrorKind::Unknown`][unknown]. /// /// [unknown]: enum.ErrorKind.html#variant.Unknown /// (ErrorKind's Unknown variant) pub fn is_unknown(&self) -> bool { for err in self.iter() { if err.to_string() == consts:...
{ return true; }
conditional_block
errors.rs
//! Error types. //! //! Some events are handled are errors so that they propagate upwards naturally, although //! technically they're not really errors: //! //! - [`ErrorKind::Unsat`] //! - [`ErrorKind::Timeout`] //! - [`ErrorKind::Unknown`] (when hoice gave up on solving the clauses) //! //! As such, one should **not...
(&self) -> Option<ClsIdx> { match self.kind() { ErrorKind::UnsatFrom(clause) => Some(*clause), _ => None, } } /// True if the kind of the error is a timeout. /// /// [timeout]: enum.ErrorKind.html#variant.Timeout /// (ErrorKind's Timeout variant) pub fn i...
unsat_cause
identifier_name
errors.rs
//! Error types. //! //! Some events are handled are errors so that they propagate upwards naturally, although //! technically they're not really errors: //! //! - [`ErrorKind::Unsat`] //! - [`ErrorKind::Timeout`] //! - [`ErrorKind::Unknown`] (when hoice gave up on solving the clauses) //! //! As such, one should **not...
#[doc = "Not really an error, unsat early return."] Unsat { description(consts::err::unsat_desc) display("unsat") } #[doc = "Not really an error, unsat early return because of some clause."] UnsatFrom(clause: ClsIdx) { description(consts::err::...
random_line_split
statix.js
/* jshint node: true */ (function () { "use strict"; var APP; var utils = require("./utils"); var fs = require("fs"); var path = require("path"); var wrench = require("wrench"); var colors = require("colors");
utils.loadSettings(settingsFile, function (settings) { var i; dir = dir || path.join(path.dirname(settings.file), settings.source_dir); dir = dir.split(","); port = port || 8000; var reload = function (e, f) { restartServer(settings, port); }; for (i = 0; i < dir.length; i++) { fs.wat...
var supervisor = require("supervisor"); function server(settingsFile, dir, port, interval) {
random_line_split
statix.js
/* jshint node: true */ (function () { "use strict"; var APP; var utils = require("./utils"); var fs = require("fs"); var path = require("path"); var wrench = require("wrench"); var colors = require("colors"); var supervisor = require("supervisor"); function server(settingsFile, dir, port, interval) { u...
}); } function callback() { settings.postBuild = settings.postBuild || function (cb) { return cb(); }; settings.postBuild(function () { console.log("Statix build complete!".green); console.log(""); process.exit(); }); } for (var i = 0; i < settings.pa...
{ cb(); }
conditional_block
statix.js
/* jshint node: true */ (function () { "use strict"; var APP; var utils = require("./utils"); var fs = require("fs"); var path = require("path"); var wrench = require("wrench"); var colors = require("colors"); var supervisor = require("supervisor"); function server(settingsFile, dir, port, interval) { u...
if (settings.expressConfig) { app.configure(settings.expressConfig(express, app)); } app.use(express.errorHandler({dumpExceptions: true, showStack: true})); function renderTemplate(page) { return function (req, res, next) { var prop, data = {layout : false}; for (prop in settings.global_d...
{ var rootDir = path.join(settings.source_dir), indexFound = false, express = require("express"), consolidate = require("consolidate"), app = express.createServer(); if (APP) { APP.close(); APP = null; } app.configure(function () { app.disable("view cache"); app.use(express.bodyParser...
identifier_body
statix.js
/* jshint node: true */ (function () { "use strict"; var APP; var utils = require("./utils"); var fs = require("fs"); var path = require("path"); var wrench = require("wrench"); var colors = require("colors"); var supervisor = require("supervisor"); function server(settingsFile, dir, port, interval) { u...
(settingsFile) { utils.loadSettings(settingsFile, function (settings) { var consolidate = require("consolidate"), sourceDir = path.join(settings.source_dir), outputDir = path.join(settings.output_dir); console.log(""); settings.preBuild = settings.preBuild || function (cb) { return cb(); };...
build
identifier_name
main.rs
extern crate clap; extern crate env_logger; extern crate habitat_common as common; extern crate habitat_core as hcore; extern crate habitat_pkg_export_tar as export_tar; #[macro_use] extern crate log; use clap::App; use common::ui::{UIWriter, UI}; use hcore::PROGRAM_NAME; use export_tar::{Cli, Result}; fn main() { ...
export_tar::export_for_cli_matches(ui, &m) } fn cli<'a, 'b>() -> App<'a, 'b> { let name: &str = &*PROGRAM_NAME; let about = "Creates a tar package from a Habitat package"; Cli::new(name, about) .add_base_packages_args() .add_builder_args() .add_pkg_ident_arg() .app }
let cli = cli(); let m = cli.get_matches(); debug!("clap cli args: {:?}", m);
random_line_split
main.rs
extern crate clap; extern crate env_logger; extern crate habitat_common as common; extern crate habitat_core as hcore; extern crate habitat_pkg_export_tar as export_tar; #[macro_use] extern crate log; use clap::App; use common::ui::{UIWriter, UI}; use hcore::PROGRAM_NAME; use export_tar::{Cli, Result}; fn main() { ...
} fn start(ui: &mut UI) -> Result<()> { env_logger::init(); let cli = cli(); let m = cli.get_matches(); debug!("clap cli args: {:?}", m); export_tar::export_for_cli_matches(ui, &m) } fn cli<'a, 'b>() -> App<'a, 'b> { let name: &str = &*PROGRAM_NAME; let about = "Creates a tar package fro...
{ ui.fatal(e).unwrap(); std::process::exit(1) }
conditional_block
main.rs
extern crate clap; extern crate env_logger; extern crate habitat_common as common; extern crate habitat_core as hcore; extern crate habitat_pkg_export_tar as export_tar; #[macro_use] extern crate log; use clap::App; use common::ui::{UIWriter, UI}; use hcore::PROGRAM_NAME; use export_tar::{Cli, Result}; fn main() { ...
fn cli<'a, 'b>() -> App<'a, 'b> { let name: &str = &*PROGRAM_NAME; let about = "Creates a tar package from a Habitat package"; Cli::new(name, about) .add_base_packages_args() .add_builder_args() .add_pkg_ident_arg() .app }
{ env_logger::init(); let cli = cli(); let m = cli.get_matches(); debug!("clap cli args: {:?}", m); export_tar::export_for_cli_matches(ui, &m) }
identifier_body
main.rs
extern crate clap; extern crate env_logger; extern crate habitat_common as common; extern crate habitat_core as hcore; extern crate habitat_pkg_export_tar as export_tar; #[macro_use] extern crate log; use clap::App; use common::ui::{UIWriter, UI}; use hcore::PROGRAM_NAME; use export_tar::{Cli, Result}; fn main() { ...
<'a, 'b>() -> App<'a, 'b> { let name: &str = &*PROGRAM_NAME; let about = "Creates a tar package from a Habitat package"; Cli::new(name, about) .add_base_packages_args() .add_builder_args() .add_pkg_ident_arg() .app }
cli
identifier_name
15.4.4.16-7-c-i-14.js
/// Copyright (c) 2012 Ecma International. All rights reserved. /** * @path ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-7-c-i-14.js * @description Array.prototype.every - element to be retrieved is own accessor property that overrides an inherited accessor property on an Array */ function testcase() { functio...
var arr = []; try { Object.defineProperty(Array.prototype, "0", { get: function () { return 5; }, configurable: true }); Object.defineProperty(arr, "0", { get: function () { ...
{ if (idx === 0) { return val === 5; } else { return true; } }
identifier_body
15.4.4.16-7-c-i-14.js
/// Copyright (c) 2012 Ecma International. All rights reserved. /** * @path ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-7-c-i-14.js * @description Array.prototype.every - element to be retrieved is own accessor property that overrides an inherited accessor property on an Array */ function testcase() { functio...
}); Object.defineProperty(arr, "0", { get: function () { return 11; }, configurable: true }); return !arr.every(callbackfn); } finally { delete Array.prototype[0]; } } ru...
}, configurable: true
random_line_split
15.4.4.16-7-c-i-14.js
/// Copyright (c) 2012 Ecma International. All rights reserved. /** * @path ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-7-c-i-14.js * @description Array.prototype.every - element to be retrieved is own accessor property that overrides an inherited accessor property on an Array */ function testcase() { functio...
(val, idx, obj) { if (idx === 0) { return val === 5; } else { return true; } } var arr = []; try { Object.defineProperty(Array.prototype, "0", { get: function () { return 5; ...
callbackfn
identifier_name
15.4.4.16-7-c-i-14.js
/// Copyright (c) 2012 Ecma International. All rights reserved. /** * @path ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-7-c-i-14.js * @description Array.prototype.every - element to be retrieved is own accessor property that overrides an inherited accessor property on an Array */ function testcase() { functio...
} var arr = []; try { Object.defineProperty(Array.prototype, "0", { get: function () { return 5; }, configurable: true }); Object.defineProperty(arr, "0", { get: function ()...
{ return true; }
conditional_block
message_based_server.py
############################################################################### # # The MIT License (MIT) # # Copyright (c) Tavendo GmbH # # 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 Softw...
factory = WebSocketServerFactory(u"ws://127.0.0.1:9000") factory.protocol = MessageBasedHashServerProtocol listenWS(factory) reactor.run()
conditional_block
message_based_server.py
############################################################################### # # The MIT License (MIT) # # Copyright (c) Tavendo GmbH # # 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 Softw...
if __name__ == '__main__': factory = WebSocketServerFactory(u"ws://127.0.0.1:9000") factory.protocol = MessageBasedHashServerProtocol listenWS(factory) reactor.run()
sha256 = hashlib.sha256() sha256.update(payload) digest = sha256.hexdigest() self.sendMessage(digest.encode('utf8')) print("Sent digest for message: {}".format(digest))
identifier_body
message_based_server.py
############################################################################### # # The MIT License (MIT) # # Copyright (c) Tavendo GmbH # # 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 Softw...
from autobahn.twisted.websocket import WebSocketServerFactory, \ WebSocketServerProtocol, \ listenWS class MessageBasedHashServerProtocol(WebSocketServerProtocol): """ Message-based WebSockets server that computes a SHA-256 for every message it receives and sends back the computed digest...
import hashlib from twisted.internet import reactor
random_line_split
message_based_server.py
############################################################################### # # The MIT License (MIT) # # Copyright (c) Tavendo GmbH # # 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 Softw...
(WebSocketServerProtocol): """ Message-based WebSockets server that computes a SHA-256 for every message it receives and sends back the computed digest. """ def onMessage(self, payload, isBinary): sha256 = hashlib.sha256() sha256.update(payload) digest = sha256.he...
MessageBasedHashServerProtocol
identifier_name
transform_assignable_fragment_spreads_in_updatable_queries.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use common::{NamedItem, WithLocation}; use graphql_ir::{ associated_data_impl, Directive, FragmentDefinition, FragmentSpread,...
( &mut self, operation: &FragmentDefinition, ) -> Transformed<FragmentDefinition> { if operation.directives.named(*UPDATABLE_DIRECTIVE).is_some() { self.default_transform_fragment(operation) } else { Transformed::Keep } } fn transform_fragment...
transform_fragment
identifier_name
transform_assignable_fragment_spreads_in_updatable_queries.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use common::{NamedItem, WithLocation}; use graphql_ir::{ associated_data_impl, Directive, FragmentDefinition, FragmentSpread,...
Concrete { concrete_type: StringKey }, } associated_data_impl!(TypeConditionInfo); /// Transform all of the updatable queries and fragments in a program by adding /// an internal-only directive on every fragment spread containing /// TypeConditionInfo in the associated data. /// /// This directive is then consume...
Abstract,
random_line_split
transform_assignable_fragment_spreads_in_updatable_queries.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use common::{NamedItem, WithLocation}; use graphql_ir::{ associated_data_impl, Directive, FragmentDefinition, FragmentSpread,...
}
{ TypeConditionInfo::Concrete { concrete_type: schema.get_type_name(type_condition), } }
conditional_block
transform_assignable_fragment_spreads_in_updatable_queries.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use common::{NamedItem, WithLocation}; use graphql_ir::{ associated_data_impl, Directive, FragmentDefinition, FragmentSpread,...
} fn get_directive(type_condition: Type, schema: &SDLSchema) -> Directive { Directive { name: WithLocation::generated(*ASSIGNABLE_DIRECTIVE_FOR_TYPEGEN), arguments: vec![], data: Some(Box::new(get_associated_data(type_condition, schema))), } } fn get_associated_data(type_condition: Ty...
{ let fragment_definition = self .program .fragment(fragment_spread.fragment.item) .expect("Expected fragment to exist."); let spread = fragment_spread.clone(); Transformed::Replace(Selection::FragmentSpread(Arc::new(FragmentSpread { directives: v...
identifier_body
param_dict.py
#!/user/bin/env python """ @package mi.dataset.param_dict @file mi/dataset/param_dict.py @author Emily Hahn @brief Extend the protocol param dict to handle dataset encoding exceptions """ import re from mi.core.instrument.protocol_param_dict import ProtocolParameterDict, ParameterDescription from mi.core.instrument.p...
""" params = self._param_dict.keys() for name in params: log.trace("update param dict name: %s", name) try: val = self._param_dict[name] val.update(in_data) except Exception as e: # set the value to None if we f...
random_line_split
param_dict.py
#!/user/bin/env python """ @package mi.dataset.param_dict @file mi/dataset/param_dict.py @author Emily Hahn @brief Extend the protocol param dict to handle dataset encoding exceptions """ import re from mi.core.instrument.protocol_param_dict import ProtocolParameterDict, ParameterDescription from mi.core.instrument.p...
description=None, type=None, units=None, value_description=None) self.value = DatasetParameterValue(name, f_for...
""" Parameter value constructor. @param name The parameter name. @param f_format The function that formats the parameter value for a set command. @param value The parameter value (initializes to None). """ self.description = ParameterDescription(name, ...
identifier_body
param_dict.py
#!/user/bin/env python """ @package mi.dataset.param_dict @file mi/dataset/param_dict.py @author Emily Hahn @brief Extend the protocol param dict to handle dataset encoding exceptions """ import re from mi.core.instrument.protocol_param_dict import ProtocolParameterDict, ParameterDescription from mi.core.instrument.p...
if match: self.value.set_value(self.f_getval(match)) return True else: return False class DatasetParameterDict(ProtocolParameterDict): """ Dataset parameter dictionary. Manages, matches and formats parameters. """ def __init__(self): """ ...
match = self.regex.search(input)
conditional_block
param_dict.py
#!/user/bin/env python """ @package mi.dataset.param_dict @file mi/dataset/param_dict.py @author Emily Hahn @brief Extend the protocol param dict to handle dataset encoding exceptions """ import re from mi.core.instrument.protocol_param_dict import ProtocolParameterDict, ParameterDescription from mi.core.instrument.p...
(self, in_data): """ Update the dictionaray with a line input. Iterate through all objects and attempt to match and update a parameter. Only updates the first match encountered. If we pass in a target params list then will will only iterate through those allowing us to limit upst...
update
identifier_name
card.py
class Card: """ Static class that handles cards. We represent cards as 32-bit integers, so there is no object instantiation - they are just ints. Most of the bits are used, and have a specific meaning. See below: Card: bitrank suit rank...
(card_int): rank_int = Card.get_rank_int(card_int) suit_int = Card.get_suit_int(card_int) return Card.STR_RANKS[rank_int] + Card.INT_SUIT_TO_CHAR_SUIT[suit_int] @staticmethod def get_rank_int(card_int): return (card_int >> 8) & 0xF @staticmethod def get_suit_int(card_in...
int_to_str
identifier_name
card.py
class Card: """ Static class that handles cards. We represent cards as 32-bit integers, so there is no object instantiation - they are just ints. Most of the bits are used, and have a specific meaning. See below: Card: bitrank suit rank...
# output the string to console output.reverse() return "".join(output) @staticmethod def int_to_pretty_str(card_int): """ Returns a single card string """ # suit and rank suit_int = Card.get_suit_int(card_int) rank_int = Card.get_rank_i...
output[i + int(i//4)] = bstr[i]
conditional_block
card.py
class Card: """ Static class that handles cards. We represent cards as 32-bit integers, so there is no object instantiation - they are just ints. Most of the bits are used, and have a specific meaning. See below: Card: bitrank suit rank...
@staticmethod def get_suit_int(card_int): return (card_int >> 12) & 0xF @staticmethod def get_bitrank_int(card_int): return (card_int >> 16) & 0x1FFF @staticmethod def get_prime(card_int): return card_int & 0x3F @staticmethod def hand_to_binary(card_strs): ...
return (card_int >> 8) & 0xF
identifier_body
card.py
class Card: """ Static class that handles cards. We represent cards as 32-bit integers, so there is no object instantiation - they are just ints. Most of the bits are used, and have a specific meaning. See below: Card: bitrank suit rank...
""" bstr = bin(card_int)[2:][::-1] # chop off the 0b and THEN reverse string output = list("".join(["0000" + "\t"] * 7) + "0000") for i in range(len(bstr)): output[i + int(i//4)] = bstr[i] # output the string to console output.reverse() return "".jo...
For debugging purposes. Displays the binary number as a human readable string in groups of four digits.
random_line_split
SyntheticWheelEvent.js
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import SyntheticMouseEvent from './SyntheticMouseEvent'; /** * @interface WheelEvent * @see http://www.w3.org/TR/DOM-Level-3-Ev...
(event) { return 'deltaX' in event ? event.deltaX : // Fallback to `wheelDeltaX` for Webkit and normalize (right is positive). 'wheelDeltaX' in event ? -event.wheelDeltaX : 0; }, deltaY(event) { return 'deltaY' in event ? event.deltaY : // Fallback to `wheelDe...
deltaX
identifier_name
SyntheticWheelEvent.js
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import SyntheticMouseEvent from './SyntheticMouseEvent'; /** * @interface WheelEvent * @see http://www.w3.org/TR/DOM-Level-3-Ev...
, deltaZ: null, // Browsers without "deltaMode" is reporting in raw wheel delta where one // notch on the scroll is always +/- 120, roughly equivalent to pixels. // A good approximation of DOM_DELTA_LINE (1) is 5% of viewport size or // ~40 pixels, for DOM_DELTA_SCREEN (2) it is 87.5% of viewport size. del...
{ return 'deltaY' in event ? event.deltaY : // Fallback to `wheelDeltaY` for Webkit and normalize (down is positive). 'wheelDeltaY' in event ? -event.wheelDeltaY : // Fallback to `wheelDelta` for IE<9 and normalize (down is positive). 'wheelDelta' in event ? -...
identifier_body
SyntheticWheelEvent.js
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import SyntheticMouseEvent from './SyntheticMouseEvent'; /** * @interface WheelEvent * @see http://www.w3.org/TR/DOM-Level-3-Ev...
: 0; }, deltaZ: null, // Browsers without "deltaMode" is reporting in raw wheel delta where one // notch on the scroll is always +/- 120, roughly equivalent to pixels. // A good approximation of DOM_DELTA_LINE (1) is 5% of viewport size or // ~40 pixels, for DOM_DELTA_SCREEN (2) it is 87.5% of vi...
'wheelDelta' in event ? -event.wheelDelta
random_line_split
generator2.py
#!/usr/bin/env python # Module: generator2.py # Purpose: sample generator classes #2 # Date: N/A # Notes: # 1) Test python code # 2) Ref: https://docs.python.org/2/reference/expressions.html import numpy as np print "generator2.py: python generator test code #2" # echo from the generator examples # - ...
except Exception, e: yield e finally: print "g1() done, call close()" print "Creating g1(10) generator and testing" g=g1(10) for x in g: print "x=", x g.close() print "Creating g1(7) and using next() and send()" g=g1(7) x=g.next() print "g.next()= ", x print "g.next()= ", ...
print "g1() setting to ", xv iiv=xv
conditional_block
generator2.py
#!/usr/bin/env python # Module: generator2.py # Purpose: sample generator classes #2 # Date: N/A # Notes: # 1) Test python code # 2) Ref: https://docs.python.org/2/reference/expressions.html import numpy as np print "generator2.py: python generator test code #2" # echo from the generator examples # - ...
(value=None): print "Execution starts when 'next()' is called for the first time." try: while True: try: value = (yield value) except Exception, e: value = e finally: print "Don't forget to clean up when 'close()' is called." print "te...
echo
identifier_name
generator2.py
#!/usr/bin/env python # Module: generator2.py # Purpose: sample generator classes #2 # Date: N/A # Notes: # 1) Test python code # 2) Ref: https://docs.python.org/2/reference/expressions.html import numpy as np print "generator2.py: python generator test code #2" # echo from the generator examples # - ...
print "testing the echo generator from examples" g=echo(1) v=g.next() print "g.next()=", v v=g.next() print "g.next()=", v g.throw(TypeError, "test") print "Sending 2: ", g.send(2) print "g.next()=", g.next() print "Closing g" g.close() # test generator, return n*gv (typ def g1(iv=1, gv=0.9): iiv=iv print ...
print "Execution starts when 'next()' is called for the first time." try: while True: try: value = (yield value) except Exception, e: value = e finally: print "Don't forget to clean up when 'close()' is called."
identifier_body
generator2.py
#!/usr/bin/env python # Module: generator2.py # Purpose: sample generator classes #2 # Date: N/A # Notes: # 1) Test python code # 2) Ref: https://docs.python.org/2/reference/expressions.html import numpy as np print "generator2.py: python generator test code #2" # echo from the generator examples # - ...
# test generator, return n*gv (typ def g1(iv=1, gv=0.9): iiv=iv print "g1() created, iv=%f, gv=%f" % (iv, gv) try: while True: try: # compute next value for the loop iiv=iiv*gv # print "iiv=", iiv if (iiv < 1): ...
g.close()
random_line_split
response.py
"""Responses.""" from io import StringIO from csv import DictWriter from flask import Response, jsonify, make_response from .__version__ import __version__ class ApiResult: """A representation of a generic JSON API result.""" def __init__(self, data, metadata=None, **kwargs): """Store input argumen...
# Default is JSON return self.json_response(self.record_list, self.extra_metadata, **self.kwargs) @staticmethod def csv_response(record_list): """CSV Response.""" string_io = StringIO() header = record_list[0].keys() writer = Di...
return make_response('', 204)
conditional_block
response.py
"""Responses.""" from io import StringIO from csv import DictWriter from flask import Response, jsonify, make_response from .__version__ import __version__ class ApiResult: """A representation of a generic JSON API result.""" def __init__(self, data, metadata=None, **kwargs): """Store input argumen...
(self): """Convert the list of records into a response.""" if self.return_format == 'csv' and self.record_list: return self.csv_response(self.record_list) elif self.return_format == 'csv': # and not self.record_list return make_response('', 204) # Default is JSON...
to_response
identifier_name
response.py
"""Responses.""" from io import StringIO from csv import DictWriter from flask import Response, jsonify, make_response from .__version__ import __version__ class ApiResult: """A representation of a generic JSON API result.""" def __init__(self, data, metadata=None, **kwargs): """Store input argumen...
} if extra_metadata: obj.update(extra_metadata) return obj class QuerySetApiResult(ApiResult): """A representation of a list of records (Python dictionaries).""" def __init__(self, record_list, return_format, metadata=None, **kwargs): """Store the list of records a...
from .models import SourceData obj = { 'version': __version__, 'datasetMetadata': [item.to_json() for item in SourceData.query.all()]
random_line_split
response.py
"""Responses.""" from io import StringIO from csv import DictWriter from flask import Response, jsonify, make_response from .__version__ import __version__ class ApiResult: """A representation of a generic JSON API result.""" def __init__(self, data, metadata=None, **kwargs): """Store input argumen...
class QuerySetApiResult(ApiResult): """A representation of a list of records (Python dictionaries).""" def __init__(self, record_list, return_format, metadata=None, **kwargs): """Store the list of records and the format.""" super().__init__(record_list, metadata, **kwargs) self.recor...
"""Return metadata.""" from .models import SourceData obj = { 'version': __version__, 'datasetMetadata': [item.to_json() for item in SourceData.query.all()] } if extra_metadata: obj.update(extra_metadata) return ...
identifier_body
warequest.py
, 119, 77, 34, 251, 111, 18, 37, 18, 48, 45 ]) ) def __init__(self, config_or_profile): """ :type method: str :param config_or_profile: :type config: yowsup.config.v1.config.Config | YowProfile """ self.pvars = [] self.port = 443 ...
logger.debug("Opening connection to %s" % host) conn = httplib.HTTPSConnection(host, port) if port == 443 else httplib.HTTPConnection(host, port)
conditional_block
warequest.py
if sys.version_info >= (2, 7, 9): # see https://github.com/tgalal/yowsup/issues/677 import ssl ssl._create_default_https_context = ssl._create_unverified_context else: from http import client as httplib from urllib.parse import quote as urllib_quote logger = logging.getLogger(__name_...
(object): OK = 200 ENC_PUBKEY = Curve.decodePoint( bytearray([ 5, 142, 140, 15, 116, 195, 235, 197, 215, 166, 134, 92, 108, 60, 132, 56, 86, 176, 97, 33, 204, 232, 234, 119, 77, 34, 251, 111, 18, 37, 18, 48, 45 ]) ) def __init__(self, config_or_profil...
WARequest
identifier_name
warequest.py
from http import client as httplib from urllib.parse import quote as urllib_quote logger = logging.getLogger(__name__) class WARequest(object): OK = 200 ENC_PUBKEY = Curve.decodePoint( bytearray([ 5, 142, 140, 15, 116, 195, 235, 197, 215, 166, 134, 92, 108, 60, 132, 56, 8...
merged = [] for k, v in params: merged.append( "%s=%s" % (k, cls.urlencode(v)) ) return "&".join(merged)
identifier_body
warequest.py
ssl._create_unverified_context else: from http import client as httplib from urllib.parse import quote as urllib_quote logger = logging.getLogger(__name__) class WARequest(object): OK = 200 ENC_PUBKEY = Curve.decodePoint( bytearray([ 5, 142, 140, 15, 116, 195, 235, 197, 215, 166...
"%s=%s" % (k, cls.urlencode(v))
random_line_split
exhaustMap.ts
/** @prettier */ import { Observable } from '../Observable'; import { Subscriber } from '../Subscriber'; import { ObservableInput, OperatorFunction, ObservedValueOf } from '../types'; import { map } from './map'; import { from } from '../observable/from'; import { operate } from '../util/lift'; import { OperatorSubscri...
<T, R, O extends ObservableInput<any>>( project: (value: T, index: number) => O, resultSelector?: (outerValue: T, innerValue: ObservedValueOf<O>, outerIndex: number, innerIndex: number) => R ): OperatorFunction<T, ObservedValueOf<O> | R> { if (resultSelector) { // DEPRECATED PATH return (source: Observabl...
exhaustMap
identifier_name
exhaustMap.ts
/** @prettier */ import { Observable } from '../Observable'; import { Subscriber } from '../Subscriber'; import { ObservableInput, OperatorFunction, ObservedValueOf } from '../types'; import { map } from './map'; import { from } from '../observable/from'; import { operate } from '../util/lift'; import { OperatorSubscri...
} }, undefined, () => { isComplete = true; !innerSub && subscriber.complete(); } ) ); }); }
innerSub = new OperatorSubscriber(subscriber, undefined, undefined, () => { innerSub = null; isComplete && subscriber.complete(); }); from(project(outerValue, index++)).subscribe(innerSub);
random_line_split
exhaustMap.ts
/** @prettier */ import { Observable } from '../Observable'; import { Subscriber } from '../Subscriber'; import { ObservableInput, OperatorFunction, ObservedValueOf } from '../types'; import { map } from './map'; import { from } from '../observable/from'; import { operate } from '../util/lift'; import { OperatorSubscri...
} }, undefined, () => { isComplete = true; !innerSub && subscriber.complete(); } ) ); }); }
{ if (resultSelector) { // DEPRECATED PATH return (source: Observable<T>) => source.pipe(exhaustMap((a, i) => from(project(a, i)).pipe(map((b: any, ii: any) => resultSelector(a, b, i, ii))))); } return operate((source, subscriber) => { let index = 0; let innerSub: Subscriber<T> | null = null...
identifier_body
exhaustMap.ts
/** @prettier */ import { Observable } from '../Observable'; import { Subscriber } from '../Subscriber'; import { ObservableInput, OperatorFunction, ObservedValueOf } from '../types'; import { map } from './map'; import { from } from '../observable/from'; import { operate } from '../util/lift'; import { OperatorSubscri...
}, undefined, () => { isComplete = true; !innerSub && subscriber.complete(); } ) ); }); }
{ innerSub = new OperatorSubscriber(subscriber, undefined, undefined, () => { innerSub = null; isComplete && subscriber.complete(); }); from(project(outerValue, index++)).subscribe(innerSub); }
conditional_block
ResourceEditor.controller.ts
/// <reference path="../main/Resource.ts" /> /// <reference path="../../../typings/index.d.ts" /> module ArmViz { export class ResourceEditorController { private $modalInstance: any; private arm: ArmTemplate; private resource: Resource; resourceJson: string; validationResult: string; /** @...
let resource = this.resource; (<any>resource).deleteFlag = true; this.$modalInstance.close(resource); Telemetry.sendEvent('ResourceEditor', 'Delete', this.resource.type); } save() { var newResource: Resource; try { newResource = JSON.parse(this.resourceJson); ...
}
random_line_split
ResourceEditor.controller.ts
/// <reference path="../main/Resource.ts" /> /// <reference path="../../../typings/index.d.ts" /> module ArmViz { export class ResourceEditorController { private $modalInstance: any; private arm: ArmTemplate; private resource: Resource; resourceJson: string; validationResult: string; /** @...
} $.extend(this.resource, newResource); this.$modalInstance.close(this.resource); Telemetry.sendEvent('ResourceEditor', 'Save', this.resource.type); }; cancel() { this.$modalInstance.dismiss('cancel'); }; } }
{ delete this.resource[key]; }
conditional_block
ResourceEditor.controller.ts
/// <reference path="../main/Resource.ts" /> /// <reference path="../../../typings/index.d.ts" /> module ArmViz { export class ResourceEditorController { private $modalInstance: any; private arm: ArmTemplate; private resource: Resource; resourceJson: string; validationResult: string; /** @...
($modalInstance: any, arm: ArmTemplate, resource: Resource) { this.$modalInstance = $modalInstance; this.arm = arm; this.resource = resource; this.resourceJson = JSON.stringify(this.resource, null, 2); Telemetry.sendEvent('ResourceEditor', 'Open', this.resource.type); } validate...
constructor
identifier_name
man_pages.rs
use crate::types; /// Print the given help if the -h or --help argument are found pub fn check_help(args: &[types::Str], man_page: &'static str) -> bool
// pub const MAN_FN: &str = r#"NAME // fn - print a list of all functions or create a function // // SYNOPSIS // fn // // fn example arg:int // echo $arg // end // // DESCRIPTION // fn prints a list of all functions that exist in the shell or creates a // function when combined with the 'end' keyword. Functions can h...
{ for arg in args { if arg == "-h" || arg == "--help" { println!("{}", man_page); return true; } } false }
identifier_body
man_pages.rs
use crate::types; /// Print the given help if the -h or --help argument are found pub fn check_help(args: &[types::Str], man_page: &'static str) -> bool { for arg in args { if arg == "-h" || arg == "--help" { println!("{}", man_page); return true; } } false
// // SYNOPSIS // fn // // fn example arg:int // echo $arg // end // // DESCRIPTION // fn prints a list of all functions that exist in the shell or creates a // function when combined with the 'end' keyword. Functions can have type // hints, to tell ion to check the type of a functions arguments. An error will // occur...
} // pub const MAN_FN: &str = r#"NAME // fn - print a list of all functions or create a function
random_line_split
man_pages.rs
use crate::types; /// Print the given help if the -h or --help argument are found pub fn check_help(args: &[types::Str], man_page: &'static str) -> bool { for arg in args { if arg == "-h" || arg == "--help"
} false } // pub const MAN_FN: &str = r#"NAME // fn - print a list of all functions or create a function // // SYNOPSIS // fn // // fn example arg:int // echo $arg // end // // DESCRIPTION // fn prints a list of all functions that exist in the shell or creates a // function when combined with the 'end' keywor...
{ println!("{}", man_page); return true; }
conditional_block
man_pages.rs
use crate::types; /// Print the given help if the -h or --help argument are found pub fn
(args: &[types::Str], man_page: &'static str) -> bool { for arg in args { if arg == "-h" || arg == "--help" { println!("{}", man_page); return true; } } false } // pub const MAN_FN: &str = r#"NAME // fn - print a list of all functions or create a function // // SYNOP...
check_help
identifier_name
main.js
let fs = require("fs"), path = require("path"), debug = require("debug"), debugBuild = debug("graffito-build"), debugData = debug("graffito-data"), site = require("./plugins/site"), conrefifier = require("./plugins/conrefifier"), datafiles = require("./plugins/datafiles"), renderer = re...
} } catch(e) { /* file doesn't exist */ } // Next, iterate on the data folder, picking up YML files if (process.env.SKIP_DATA != "true") { const DATA_PATH = path.join(options.base, "data"); debugData("Start data"); try { if (fs.lstatSync(DATA_PATH)) { let dataFiles = await walk(DATA...
random_line_split
main.js
let fs = require("fs"), path = require("path"), debug = require("debug"), debugBuild = debug("graffito-build"), debugData = debug("graffito-data"), site = require("./plugins/site"), conrefifier = require("./plugins/conrefifier"), datafiles = require("./plugins/datafiles"), renderer = re...
if (process.env.JASMINE_TEST != "true") { smith = smith.use( watch({ paths: { "${source}/**/*": true }, livereload: false }) ); } ...
{ return new Promise(function (resolve) { // someone is being a jerk if (!_.isObject(build) || _.isEmpty(build)) { return resolve(); } let smith = Metalsmith(__dirname) .source(path.join(options.base, build.source)) .destination(path.join(options.destination, build.d...
identifier_body
main.js
let fs = require("fs"), path = require("path"), debug = require("debug"), debugBuild = debug("graffito-build"), debugData = debug("graffito-data"), site = require("./plugins/site"), conrefifier = require("./plugins/conrefifier"), datafiles = require("./plugins/datafiles"), renderer = re...
if (build.plugins) { for (let plugin of build.plugins) { smith = smith.use(plugin()); } } smith.build(function (err) { if (err) { console.error(`Error processing build: ${err}`); throw err; } return resolve(); }...
{ smith = smith.use( watch({ paths: { "${source}/**/*": true }, livereload: false }) ); }
conditional_block
main.js
let fs = require("fs"), path = require("path"), debug = require("debug"), debugBuild = debug("graffito-build"), debugData = debug("graffito-data"), site = require("./plugins/site"), conrefifier = require("./plugins/conrefifier"), datafiles = require("./plugins/datafiles"), renderer = re...
(build) { return new Promise(function (resolve) { // someone is being a jerk if (!_.isObject(build) || _.isEmpty(build)) { return resolve(); } let smith = Metalsmith(__dirname) .source(path.join(options.base, build.source)) .destination(path.join(options.destination,...
processBuild
identifier_name
utils.ts
export function wrapCallbackAsPromise(func: (...args: any[]) => any, ...args: any[]): Promise<any> { return new Promise<any>((resolve, reject) => { args.push((err, ...returnArgs: any[]) => { if(err) { reject(err); } else if(returnArgs.length === 0) { ...
else { return '.'; } } export function join(...paths: string[]): string { if(paths[0].endsWith('/')) { paths[0] = paths[0].slice(0, paths[0].length - 1); } for(let i = 1; i < paths.length; i++) { if(paths[i].startsWith('/')) { paths[i] = paths[i].slice(1, paths[i]...
{ splitPath.pop(); return splitPath.join('/'); }
conditional_block
utils.ts
export function wrapCallbackAsPromise(func: (...args: any[]) => any, ...args: any[]): Promise<any> { return new Promise<any>((resolve, reject) => { args.push((err, ...returnArgs: any[]) => { if(err) { reject(err); } else if(returnArgs.length === 0) { r...
for(let i = 1; i < paths.length; i++) { if(paths[i].startsWith('/')) { paths[i] = paths[i].slice(1, paths[i].length); } if(paths[i].endsWith('/')) { paths[i] = paths[i].slice(0, paths[i].length - 1); } } return paths.join('/'); } // from: https://w...
export function join(...paths: string[]): string { if(paths[0].endsWith('/')) { paths[0] = paths[0].slice(0, paths[0].length - 1); }
random_line_split
utils.ts
export function wrapCallbackAsPromise(func: (...args: any[]) => any, ...args: any[]): Promise<any> { return new Promise<any>((resolve, reject) => { args.push((err, ...returnArgs: any[]) => { if(err) { reject(err); } else if(returnArgs.length === 0) { ...
(encoded: string) { return genericFromBase64(encoded.split('-').join('+').split('_').join('=').split('.').join('/')); }
genericFromBase64IdSafe
identifier_name
utils.ts
export function wrapCallbackAsPromise(func: (...args: any[]) => any, ...args: any[]): Promise<any> { return new Promise<any>((resolve, reject) => { args.push((err, ...returnArgs: any[]) => { if(err) { reject(err); } else if(returnArgs.length === 0) { ...
{ return genericFromBase64(encoded.split('-').join('+').split('_').join('=').split('.').join('/')); }
identifier_body
baseController.js
define([ "jquery", "utils", "lib/pusher.min"], function($, utils) { BaseController = function(){ control = this; this.fieldsToLoad = []; this.permissions = []; }; function BaseController_genericOnLoad(debug){ this.loadData(debug); } function BaseController_loadData(debug){ var copy = this; var notificatio...
dataBlock.remove(); //no longer needed, so we remove it from the DOM } function BaseController_setGenericHandlers(parent) { var copy = this; if (arguments.length === 0) parent = $("html"); this.setMenuHandler(); this.setReferenceHandler(); //button text shouldn't be selectable //$(".button").disableSelecti...
} copy[field] = data; } });
random_line_split
baseController.js
define([ "jquery", "utils", "lib/pusher.min"], function($, utils) { BaseController = function(){ control = this; this.fieldsToLoad = []; this.permissions = []; }; function BaseController_genericOnLoad(debug){ this.loadData(debug); } function BaseController_loadData(debug){ var copy = this; var notificatio...
() { //Open the menu // Change to classes $(".menu").click(function() { $('#mainArea').css('min-height', $(window).height()); $('nav').css('opacity', 1); $('nav').css('z-index', 1); //set the width of primary content container -> content should not scale while animating var contentWidth = $('#mainArea')...
BaseController_setMenuHandler
identifier_name
baseController.js
define([ "jquery", "utils", "lib/pusher.min"], function($, utils) { BaseController = function(){ control = this; this.fieldsToLoad = []; this.permissions = []; }; function BaseController_genericOnLoad(debug){ this.loadData(debug); } function BaseController_loadData(debug){ var copy = this; var notificatio...
$('#page').bind('touchmove', function (e) { e.preventDefault() }); //set margin for the whole page with a $ UI animation $("#page").animate({"marginRight": "30%"}, { duration: 200 }); }); //close the menu $("#mainOverlay").click(function() { //enable all scrolling on mobile devices when menu is ...
{ //Open the menu // Change to classes $(".menu").click(function() { $('#mainArea').css('min-height', $(window).height()); $('nav').css('opacity', 1); $('nav').css('z-index', 1); //set the width of primary content container -> content should not scale while animating var contentWidth = $('#mainArea').wi...
identifier_body
baseController.js
define([ "jquery", "utils", "lib/pusher.min"], function($, utils) { BaseController = function(){ control = this; this.fieldsToLoad = []; this.permissions = []; }; function BaseController_genericOnLoad(debug){ this.loadData(debug); } function BaseController_loadData(debug){ var copy = this; var notificatio...
copy[Class.prototype.getPluralName().decapitalize()] = (new Class()).fromDjangoJSONObjectAll(data); } else { var field = elInfo.field; if (!field) { console.warn("Missing field on element", this); return; //continue to next } copy[field] = data; } }); dataBlock.remove(); //no longer neede...
{ console.warn("Warning: Class " + elInfo.model + " not found. Probably not loaded."); return; //continue to next }
conditional_block
test_satellitesync.py
# -*- encoding: utf-8 -*- """Test class for InterSatellite Sync feature :Requirement: Satellitesync :CaseAutomation: Automated :CaseLevel: Acceptance :CaseComponent: UI :TestType: Functional :CaseImportance: High :Upstream: No """ from robottelo.decorators import ( run_only_on, stubbed, tier1, t...
""" @run_only_on('sat') @stubbed() @tier1 def test_negative_update_cdn_url(self): """Update non existing CDN URL to import from upstream. :id: 4bf74712-dac8-447b-9c9f-227a41cdec4d :steps: 1. In downstream, Update CDN URL with some non existing url. ...
"""Update CDN URL to import from upstream. :id: 5ff30764-a1b1-48df-a6a1-0f1d23f883b9 :steps: 1. In upstream, Export Redhat repo/CV to a directory. 2. Copy exported contents to /var/www/html. 3. In downstream, Update CDN URL with step 2 location to import the ...
identifier_body
test_satellitesync.py
# -*- encoding: utf-8 -*- """Test class for InterSatellite Sync feature :Requirement: Satellitesync :CaseAutomation: Automated :CaseLevel: Acceptance :CaseComponent: UI :TestType: Functional :CaseImportance: High :Upstream: No """ from robottelo.decorators import ( run_only_on, stubbed, tier1, t...
:steps: Export a CV to a specified location in settings. :expectedresults: CV history should reflect the export history with user, version, action and time. :caseautomation: notautomated :CaseLevel: System """ @run_only_on('sat') @stubbed() @tier1 ...
def test_positive_show_cv_export_history(self): """CV history shows CV version export history on export. :id: 06e26cca-e262-4eff-b8d7-fbca504a8acb
random_line_split
test_satellitesync.py
# -*- encoding: utf-8 -*- """Test class for InterSatellite Sync feature :Requirement: Satellitesync :CaseAutomation: Automated :CaseLevel: Acceptance :CaseComponent: UI :TestType: Functional :CaseImportance: High :Upstream: No """ from robottelo.decorators import ( run_only_on, stubbed, tier1, t...
(self): """Restrict the import/sync of non exported repos. :id: 7091ca13-7f58-4733-87d5-1fa3670bfcee :steps: 1. Export Red Hat YUM repo to path which will be accessible over HTTP. 2. Define the CDN URL the same as the exported HTTP URL. 3. A...
test_positive_restrict_other_redhat_repo_import
identifier_name
lib.rs
//! Implementation of build script for all Qt crates //! //! See [README](https://github.com/rust-qt/ritual) of the repository root for more information. //! //! The build script uses `qmake` available in `PATH` to determine paths to the Qt installation and passes them to //! `ritual_build`. #![forbid(unsafe_code)] #!...
}) .collect::<String>(); let project_name = format!("ritual_qt_resources_{}", escaped_base_name); let out_dir = PathBuf::from(env::var("OUT_DIR").with_context(|_| "OUT_DIR env var is missing")?); let dir = out_dir.join(&project_name); create_dir_all(&dir)?; let pro_file_pat...
{ let path = path.as_ref(); if !path.exists() { bail!("no such file: {:?}", path); } if !path.is_file() { bail!("not a file: {:?}", path); } let base_name = os_str_to_str( path.file_stem() .ok_or_else(|| format_err!("can't extract base name from path: {:?}", p...
identifier_body
lib.rs
//! Implementation of build script for all Qt crates //! //! See [README](https://github.com/rust-qt/ritual) of the repository root for more information. //! //! The build script uses `qmake` available in `PATH` to determine paths to the Qt installation and passes them to //! `ritual_build`. #![forbid(unsafe_code)] #!...
else { dir }; println!("cargo:rustc-link-search={}", path_to_str(&lib_dir)?); println!("cargo:rerun-if-changed={}", path_to_str(&path)?); Ok(()) } /// Calls `try_add_resources` and panic on an error. pub fn add_resources(path: impl AsRef<Path>) { try_add_resources(path).fancy_unwrap(); } ...
{ dir.join("release") }
conditional_block
lib.rs
//! Implementation of build script for all Qt crates //! //! See [README](https://github.com/rust-qt/ritual) of the repository root for more information. //! //! The build script uses `qmake` available in `PATH` to determine paths to the Qt installation and passes them to //! `ritual_build`. #![forbid(unsafe_code)] #!...
(crate_name: &str) -> ! { try_run(crate_name).fancy_unwrap(); std::process::exit(0); } /// Builds and links a [Qt resource file](https://doc.qt.io/qt-5/resources.html). /// /// The resource file must also be registered using the `qt_core::q_init_resource` macro. /// /// Note that the resource file may not be r...
run
identifier_name
lib.rs
//! Implementation of build script for all Qt crates //! //! See [README](https://github.com/rust-qt/ritual) of the repository root for more information. //! //! The build script uses `qmake` available in `PATH` to determine paths to the Qt installation and passes them to //! `ritual_build`. #![forbid(unsafe_code)] #!...
writeln!(pro_file, "CONFIG += staticlib")?; writeln!(pro_file, "SOURCES += 1.cpp")?; writeln!(pro_file, "RESOURCES += {}", path_to_str(&path)?)?; drop(pro_file); let mut cpp_file = create_file(dir.join("1.cpp"))?; writeln!(cpp_file, "#include <QDir>")?; // `Q_INIT_RESOURCE` doesn't work ins...
let pro_file_path = dir.join(format!("{}.pro", project_name)); let mut pro_file = create_file(&pro_file_path)?; writeln!(pro_file, "TEMPLATE = lib")?;
random_line_split
conf.py
This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys import os # To get scipy t...
# If true, the current module name will be prepended to all description # unit titles (such as .. function::). # add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. # show_authors = False # The name of the Pygments (syntax highlight...
# add_function_parentheses = True
random_line_split
conf.py
This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys import os # To get scipy t...
# If extensions (or modules to document with autodoc) are in another # directory, add these directories to sys.path here. If the directory is # relative to the documentation root, use os.path.abspath to make it # absolute, like shown here. # sys.path.insert(0, os.path.abspath('.')) # Get the project root dir, which ...
sys.modules[mod_name] = Mock()
conditional_block
conf.py
This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys import os # To get scipy t...
(object): def __init__(self, *args, **kwargs): pass def __call__(self, *args, **kwargs): return Mock() @classmethod def __getattr__(cls, name): if name in ('__file__', '__path__'): return '/dev/null' elif name[0] == name[0].upper(): return type(n...
Mock
identifier_name
conf.py
This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys import os # To get scipy t...
MOCK_MODULES = [ 'scipy', 'sklearn', 'sklearn.naive_bayes', 'sklearn.feature_extraction', ] for mod_name in MOCK_MODULES: sys.modules[mod_name] = Mock() # If extensions (or modules to document with autodoc) are in another # directory, add these directories to sys.path here. If the directory i...
if name in ('__file__', '__path__'): return '/dev/null' elif name[0] == name[0].upper(): return type(name, (), {}) else: return Mock()
identifier_body
build.js
/** * Module dependencies. */ var fs = require('fs') , package = JSON.parse(fs.readFileSync(__dirname+ '/../package.json')) , uglify = require('uglify-js'); /** * License headers. * * @api private */ var template = '/*! sink.%ext% build:' + package.version + ', %type%. Copyright(c) 2013 Eric Zhang, Michell...
settings[option] = options[option]; } // Start creating a dependencies chain with all the required files for the // custom sinkJS client bundle. var files = []; base.forEach(function (file) { files.push(__dirname + '/../lib/' + file); }); var results = {}; files.forEach(function (file) { f...
// Merge the data for(var option in options) {
random_line_split
models.py
from __future__ import unicode_literals from blanc_basic_assets.fields import AssetForeignKey from django.core.exceptions import ValidationError from django.core.urlresolvers import get_script_prefix from django.core.validators import RegexValidator from django.db import models from django.utils.encoding import iri_to...
@python_2_unicode_compatible class Page(MPTTModel): url = models.CharField( 'URL', max_length=100, unique=True, help_text="Example: '/about/contact/'. Make sure to have leading and trailing slashes.", validators=[url_validator, slash_validator]) title = models.CharField(max_length=200...
raise ValidationError("This value must end with a trailing slash.")
conditional_block
models.py
from __future__ import unicode_literals from blanc_basic_assets.fields import AssetForeignKey from django.core.exceptions import ValidationError from django.core.urlresolvers import get_script_prefix from django.core.validators import RegexValidator from django.db import models from django.utils.encoding import iri_to...
@python_2_unicode_compatible class Page(MPTTModel): url = models.CharField( 'URL', max_length=100, unique=True, help_text="Example: '/about/contact/'. Make sure to have leading and trailing slashes.", validators=[url_validator, slash_validator]) title = models.CharField(max_length=200...
if not url.startswith('/'): raise ValidationError("This value must start with a leading slash.") elif not url.endswith('/'): raise ValidationError("This value must end with a trailing slash.")
identifier_body
models.py
from __future__ import unicode_literals from blanc_basic_assets.fields import AssetForeignKey from django.core.exceptions import ValidationError from django.core.urlresolvers import get_script_prefix from django.core.validators import RegexValidator from django.db import models from django.utils.encoding import iri_to...
# Handle script prefix manually because we bypass reverse() return iri_to_uri(get_script_prefix().rstrip('/') + self.url)
def __str__(self): return '%s -- %s' % (self.url, self.title) def get_absolute_url(self):
random_line_split
models.py
from __future__ import unicode_literals from blanc_basic_assets.fields import AssetForeignKey from django.core.exceptions import ValidationError from django.core.urlresolvers import get_script_prefix from django.core.validators import RegexValidator from django.db import models from django.utils.encoding import iri_to...
(self): # Handle script prefix manually because we bypass reverse() return iri_to_uri(get_script_prefix().rstrip('/') + self.url)
get_absolute_url
identifier_name
task.js
var mongoose = require('mongoose'), Schema = mongoose.Schema; /** * Task Schema * @type {Object} */ var TaskSchema = new Schema({ title: { type: String, default: '', trim: true }, project: { type: String, default: '', trim: true }, date: { ...
* Validations */ TaskSchema.path('title').validate(function(title) { "use strict"; return title.length; }, 'Titulo em branco'); TaskSchema.path('project').validate(function(project) { "use strict"; return project.length; }, 'Projeto em branco'); /** * Statics */ TaskSchema.statics = { load: fu...
} }); /**
random_line_split
stream_color.js
import $ from "jquery"; import * as color_class from "./color_class"; import {$t} from "./i18n"; import * as message_view_header from "./message_view_header"; import * as stream_settings_ui from "./stream_settings_ui"; function update_table_stream_color(table, stream_name, color) { // This is ugly, but temporary,...
function update_historical_message_color(stream_name, color) { update_table_stream_color($(".focused_table"), stream_name, color); if ($(".focused_table").attr("id") !== "#zhome") { update_table_stream_color($("#zhome"), stream_name, color); } } const stream_color_palette = [ ["a47462", "c272...
{ $(`#stream_sidebar_swatch_${CSS.escape(id)}`).css("background-color", color); $(`#stream_sidebar_privacy_swatch_${CSS.escape(id)}`).css("color", color); }
identifier_body
stream_color.js
import $ from "jquery"; import * as color_class from "./color_class"; import {$t} from "./i18n"; import * as message_view_header from "./message_view_header"; import * as stream_settings_ui from "./stream_settings_ui"; function update_table_stream_color(table, stream_name, color) { // This is ugly, but temporary,...
update_table_stream_color($(".focused_table"), stream_name, color); if ($(".focused_table").attr("id") !== "#zhome") { update_table_stream_color($("#zhome"), stream_name, color); } } const stream_color_palette = [ ["a47462", "c2726a", "e4523d", "e7664d", "ee7e4a", "f4ae55"], ["76ce90", "53a...
function update_historical_message_color(stream_name, color) {
random_line_split
stream_color.js
import $ from "jquery"; import * as color_class from "./color_class"; import {$t} from "./i18n"; import * as message_view_header from "./message_view_header"; import * as stream_settings_ui from "./stream_settings_ui"; function update_table_stream_color(table, stream_name, color) { // This is ugly, but temporary,...
(id, color) { $(`#stream_sidebar_swatch_${CSS.escape(id)}`).css("background-color", color); $(`#stream_sidebar_privacy_swatch_${CSS.escape(id)}`).css("color", color); } function update_historical_message_color(stream_name, color) { update_table_stream_color($(".focused_table"), stream_name, color); if ...
update_stream_sidebar_swatch_color
identifier_name
stream_color.js
import $ from "jquery"; import * as color_class from "./color_class"; import {$t} from "./i18n"; import * as message_view_header from "./message_view_header"; import * as stream_settings_ui from "./stream_settings_ui"; function update_table_stream_color(table, stream_name, color) { // This is ugly, but temporary,...
} } function update_stream_sidebar_swatch_color(id, color) { $(`#stream_sidebar_swatch_${CSS.escape(id)}`).css("background-color", color); $(`#stream_sidebar_privacy_swatch_${CSS.escape(id)}`).css("color", color); } function update_historical_message_color(stream_name, color) { update_table_stream_co...
{ const messages = $label.closest(".recipient_row").children(".message_row"); messages .children(".messagebox") .css( "box-shadow", "inset 2px 0px 0px 0px " + style + ", -1px 0px 0px 0px " + style, ); ...
conditional_block
multi_err.rs
use std::ffi::CStr; use std::error; use std::fmt; use std::str; use curl_ffi as ffi; /* please call curl_multi_perform() or curl_multi_socket*() soon */ pub use curl_ffi::CURLMcode::CURLM_CALL_MULTI_PERFORM as OK; /* the passed-in handle is not a valid CURLM handle */ pub use curl_ffi::CURLMcode::CURLM_BAD_HANDLE as...
(pub ffi::CURLMcode); impl ErrCodeM { pub fn is_success(self) -> bool { self.code() as i32 == OK as i32 } pub fn code(self) -> ffi::CURLMcode { let ErrCodeM(c) = self; c } } impl fmt::Debug for ErrCodeM { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(self, f)...
ErrCodeM
identifier_name
multi_err.rs
use std::ffi::CStr; use std::error; use std::fmt; use std::str; use curl_ffi as ffi; /* please call curl_multi_perform() or curl_multi_socket*() soon */ pub use curl_ffi::CURLMcode::CURLM_CALL_MULTI_PERFORM as OK; /* the passed-in handle is not a valid CURLM handle */ pub use curl_ffi::CURLMcode::CURLM_BAD_HANDLE as...
}
{ let code = self.code(); let s = unsafe { CStr::from_ptr(ffi::curl_multi_strerror(code) as *const _).to_bytes() }; str::from_utf8(s).unwrap() }
identifier_body
multi_err.rs
use std::ffi::CStr; use std::error; use std::fmt; use std::str; use curl_ffi as ffi; /* please call curl_multi_perform() or curl_multi_socket*() soon */ pub use curl_ffi::CURLMcode::CURLM_CALL_MULTI_PERFORM as OK; /* the passed-in handle is not a valid CURLM handle */ pub use curl_ffi::CURLMcode::CURLM_BAD_HANDLE as...
str::from_utf8(s).unwrap() } }
};
random_line_split