file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
39k
suffix
large_stringlengths
0
36.1k
middle
large_stringlengths
0
29.4k
fim_type
large_stringclasses
4 values
advanced_lane_finding-direction_of_the_gradient_exercise.py
import numpy as np import cv2 import matplotlib.pyplot as plt import matplotlib.image as mpimg import pickle # Read in an image image = mpimg.imread('signs_vehicles_xygrad.png') # Define a function that applies Sobel x and y, # then computes the direction of the gradient # and applies a threshold. def
(img, sobel_kernel=3, thresh=(0, np.pi / 2)): # Apply the following steps to img # 1) Convert to grayscale gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY) # 2) Take the gradient in x and y separately sobelx = cv2.Sobel(gray, cv2.CV_64F, 1, 0, ksize=sobel_kernel) sobely = cv2.Sobel(gray, cv2.CV_64...
dir_threshold
identifier_name
advanced_lane_finding-direction_of_the_gradient_exercise.py
import numpy as np import cv2 import matplotlib.pyplot as plt import matplotlib.image as mpimg import pickle # Read in an image image = mpimg.imread('signs_vehicles_xygrad.png') # Define a function that applies Sobel x and y, # then computes the direction of the gradient # and applies a threshold. def dir_threshol...
ax1.set_title('Original Image', fontsize=50) ax2.imshow(dir_binary, cmap='gray') ax2.set_title('Thresholded Grad. Dir.', fontsize=50) plt.subplots_adjust(left=0., right=1, top=0.9, bottom=0.)
dir_binary = dir_threshold(image, sobel_kernel=15, thresh=(0.7, 1.3)) # Plot the result f, (ax1, ax2) = plt.subplots(1, 2, figsize=(24, 9)) f.tight_layout() ax1.imshow(image)
random_line_split
advanced_lane_finding-direction_of_the_gradient_exercise.py
import numpy as np import cv2 import matplotlib.pyplot as plt import matplotlib.image as mpimg import pickle # Read in an image image = mpimg.imread('signs_vehicles_xygrad.png') # Define a function that applies Sobel x and y, # then computes the direction of the gradient # and applies a threshold. def dir_threshol...
# Run the function dir_binary = dir_threshold(image, sobel_kernel=15, thresh=(0.7, 1.3)) # Plot the result f, (ax1, ax2) = plt.subplots(1, 2, figsize=(24, 9)) f.tight_layout() ax1.imshow(image) ax1.set_title('Original Image', fontsize=50) ax2.imshow(dir_binary, cmap='gray') ax2.set_title('Thresholded Grad. Dir.', fon...
gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY) # 2) Take the gradient in x and y separately sobelx = cv2.Sobel(gray, cv2.CV_64F, 1, 0, ksize=sobel_kernel) sobely = cv2.Sobel(gray, cv2.CV_64F, 0, 1, ksize=sobel_kernel) # 3) Take the absolute value of the x and y gradients abs_s_x = np.absolute(sobelx...
identifier_body
if-let.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 ...
if 3i > 4 { panic!("bad math"); } else if let 1 = 2i { panic!("bad pattern match"); } enum Foo { One, Two(uint), Three(String, int) } let foo = Foo::Three("three".to_string(), 42i); if let Foo::One = foo { panic!("bad pattern match"); } ...
} else { clause = 4; } assert_eq!(clause, 4u);
random_line_split
if-let.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 ...
() { let x = Some(3i); if let Some(y) = x { assert_eq!(y, 3i); } else { panic!("if-let panicked"); } let mut worked = false; if let Some(_) = x { worked = true; } assert!(worked); let clause: uint; if let None = Some("test") { clause = 1; } els...
main
identifier_name
KeyboardModifiers.ts
/// <reference path="KeyboardCommand.ts" /> module EndGate.Input.Assets { /** * Defines an object that is used to represent a keyboard modifier state to determine if Ctrl, Alt, or Shift is being pressed. */ export class
{ /** * Gets or sets the Ctrl component. Represents if a Ctrl key is down. */ public Ctrl: boolean; /** * Gets or sets the Alt component. Represents if an Alt key is down. */ public Alt: boolean; /** * Gets or sets the Shift component. ...
KeyboardModifiers
identifier_name
KeyboardModifiers.ts
/// <reference path="KeyboardCommand.ts" /> module EndGate.Input.Assets { /**
/** * Gets or sets the Ctrl component. Represents if a Ctrl key is down. */ public Ctrl: boolean; /** * Gets or sets the Alt component. Represents if an Alt key is down. */ public Alt: boolean; /** * Gets or sets the Shift component. Rep...
* Defines an object that is used to represent a keyboard modifier state to determine if Ctrl, Alt, or Shift is being pressed. */ export class KeyboardModifiers {
random_line_split
piecewise.py
from sympy.core import Basic, S, Function, diff, Tuple, Expr from sympy.core.relational import Equality, Relational from sympy.core.symbol import Dummy from sympy.functions.elementary.miscellaneous import Max, Min from sympy.logic.boolalg import And, Boolean, distribute_and_over_or, Not, Or from sympy.core.compatibilit...
rep = a val = e.subs(sym, mid) - e.subs(sym, a) val += self._eval_interval(sym, mid, b) elif (b > upper) is True: mid = upper rep = a val = e.subs(sym, mid)...
val = e.subs(sym, b) - e.subs(sym, a) elif (b < lower) is True: mid = lower
random_line_split
piecewise.py
from sympy.core import Basic, S, Function, diff, Tuple, Expr from sympy.core.relational import Equality, Relational from sympy.core.symbol import Dummy from sympy.functions.elementary.miscellaneous import Max, Min from sympy.logic.boolalg import And, Boolean, distribute_and_over_or, Not, Or from sympy.core.compatibilit...
elif (curr_low >= b) is not True: holes.append([Min(b, curr_low), b, default]) if holes and default is not None: int_expr.extend(holes) if targetcond is True: return [(h[0], h[1]) for h in holes] elif holes and default is None: ra...
holes.append([Min(b, curr_low), b, default])
conditional_block
piecewise.py
from sympy.core import Basic, S, Function, diff, Tuple, Expr from sympy.core.relational import Equality, Relational from sympy.core.symbol import Dummy from sympy.functions.elementary.miscellaneous import Max, Min from sympy.logic.boolalg import And, Boolean, distribute_and_over_or, Not, Or from sympy.core.compatibilit...
(self, old, new): """ Piecewise conditions may contain bool which are not of Basic type. """ args = list(self.args) for i, (e, c) in enumerate(args): if isinstance(c, bool): pass elif isinstance(c, Basic): c = c._subs(old, n...
_eval_subs
identifier_name
piecewise.py
from sympy.core import Basic, S, Function, diff, Tuple, Expr from sympy.core.relational import Equality, Relational from sympy.core.symbol import Dummy from sympy.functions.elementary.miscellaneous import Max, Min from sympy.logic.boolalg import And, Boolean, distribute_and_over_or, Not, Or from sympy.core.compatibilit...
def _eval_template_is_attr(self, is_attr, when_multiple=None): b = None for expr, _ in self.args: a = getattr(expr, is_attr) if a is None: return None if b is None: b = a elif b is not a: return when_mu...
return Piecewise(*[(e.transpose(), c) for e, c in self.args])
identifier_body
fun_with_regex_done.py
# Regular expressions are a powerful tool for pattern matching when you # know the general format of what you're trying to find but want to keep # it loose in terms of actual content: think finding email addresses or # phone numbers based on what they have in common with each other. Python # has a standard library that...
# If you have multiple character possibilities that act as delimiters for a # string you want to break apart, re.split() can come in handy. my_list = ['OCT-2010', 'NOV/2011', 'FEB 2012', 'MAR/2012'] for item in my_list: print re.split('-|/|\s', item)
print re.sub('\.\w{3}', '.info', record)
conditional_block
fun_with_regex_done.py
# Regular expressions are a powerful tool for pattern matching when you # know the general format of what you're trying to find but want to keep # it loose in terms of actual content: think finding email addresses or # phone numbers based on what they have in common with each other. Python # has a standard library that...
print re.split('-|/|\s', item)
random_line_split
script.ts
class LevelManager { private currentLevel = 0; private levels:string[] = [ //"Scenes/TestPolice", "Scenes/PlayerChoice", "Scenes/SlackName", //"Scenes/TestScene", //"Scenes/Tutorial", //"Scenes/Presentation", //"Scenes/Presentation2", //"Scenes/Formation2", //"Scenes/Experienc...
public getLevel(index:number){ return this.levels[index]; } public start(){ this.loadCurrentScene(); } public next(jumpSize = 1){ this.currentLevel += jumpSize; this.loadCurrentScene(); } public previous(){ this.currentLevel--; this.loadCurrentScene(); } public reload(){ ...
{ return this.levels; }
identifier_body
script.ts
class LevelManager { private currentLevel = 0; private levels:string[] = [ //"Scenes/TestPolice", "Scenes/PlayerChoice", "Scenes/SlackName", //"Scenes/TestScene", //"Scenes/Tutorial", //"Scenes/Presentation", //"Scenes/Presentation2", //"Scenes/Formation2", //"Scenes/Experienc...
(){ var split = this.levels[this.currentLevel].split('/'); return split[split.length]; } public getLevels(){ return this.levels; } public getLevel(index:number){ return this.levels[index]; } public start(){ this.loadCurrentScene(); } public next(jumpSize = 1){ this.currentL...
getCurrentScene
identifier_name
script.ts
class LevelManager { private currentLevel = 0; private levels:string[] = [ //"Scenes/TestPolice", "Scenes/PlayerChoice", "Scenes/SlackName", //"Scenes/TestScene", //"Scenes/Tutorial", //"Scenes/Presentation", //"Scenes/Presentation2", //"Scenes/Formation2", //"Scenes/Experienc...
this.currentLevel += jumpSize; this.loadCurrentScene(); } public previous(){ this.currentLevel--; this.loadCurrentScene(); } public reload(){ this.loadCurrentScene(); } private loadCurrentScene(){ Sup.loadScene(this.getLevel(this.currentLevel)); scoreManager.print(); } }
public next(jumpSize = 1){
random_line_split
ntp.py
"""Parsing and conversion of NTP dates contained in datagrams.""" import datetime import struct import time # 63 zero bits followed by a one in the least signifigant bit is a special # case meaning "immediately." IMMEDIATELY = struct.pack('>q', 1) # From NTP lib. _SYSTEM_EPOCH = datetime.date(*time.gmtime(0)[0:3]) ...
try: ntp = date + _NTP_DELTA except TypeError as ve: raise NtpError('Invalud date: {}'.format(ve)) num_secs, fraction = str(ntp).split('.') return struct.pack('>I', int(num_secs)) + struct.pack('>I', int(fraction))
"""Convert a system time to a NTP time datagram. System time is reprensented by seconds since the epoch in UTC. """
random_line_split
ntp.py
"""Parsing and conversion of NTP dates contained in datagrams.""" import datetime import struct import time # 63 zero bits followed by a one in the least signifigant bit is a special # case meaning "immediately." IMMEDIATELY = struct.pack('>q', 1) # From NTP lib. _SYSTEM_EPOCH = datetime.date(*time.gmtime(0)[0:3]) ...
(Exception): """Base class for ntp module errors.""" def ntp_to_system_time(date): """Convert a NTP time to system time. System time is reprensented by seconds since the epoch in UTC. """ return date - _NTP_DELTA def system_time_to_ntp(date): """Convert a system time to a NTP time datagram. ...
NtpError
identifier_name
ntp.py
"""Parsing and conversion of NTP dates contained in datagrams.""" import datetime import struct import time # 63 zero bits followed by a one in the least signifigant bit is a special # case meaning "immediately." IMMEDIATELY = struct.pack('>q', 1) # From NTP lib. _SYSTEM_EPOCH = datetime.date(*time.gmtime(0)[0:3]) ...
"""Convert a system time to a NTP time datagram. System time is reprensented by seconds since the epoch in UTC. """ try: ntp = date + _NTP_DELTA except TypeError as ve: raise NtpError('Invalud date: {}'.format(ve)) num_secs, fraction = str(ntp).split('.') return struct.pack('>I', in...
identifier_body
label.rs
use sfml::graphics::{RenderTarget, Text, TextStyle, Color}; use sfml::system::vector2::Vector2f; use window::Window; use font::Font; /// A label (text) pub struct Label<'a> { text: Text<'a>, } impl<'a> Label<'a> { /// Create a new label pub fn new(font: &'a Font) -> Self { let mut label = Label {...
} }
/// Draw the label on a window pub fn draw(&mut self, window: &mut Window) { window.to_sfml_window().draw(&mut self.text);
random_line_split
label.rs
use sfml::graphics::{RenderTarget, Text, TextStyle, Color}; use sfml::system::vector2::Vector2f; use window::Window; use font::Font; /// A label (text) pub struct Label<'a> { text: Text<'a>, } impl<'a> Label<'a> { /// Create a new label pub fn new(font: &'a Font) -> Self { let mut label = Label {...
(&self) -> (f32, f32) { let pos = self.text.get_position(); (pos.x, pos.y) } /// Set the position of the label pub fn set(&mut self, (x, y): (f32, f32)) -> &mut Self { self.x(x); self.y(y) } /// Draw the label on a window pub fn draw(&mut self, window: &mut Win...
pos
identifier_name
learning_container_year_types.py
############################################################################## # # OSIS stands for Open Student Information System. It's an application # designed to manage the core business of higher education institutions, # such as universities, faculties, institutes and professional schools. # The core ...
cls) -> tuple: return cls.OTHER_COLLECTIVE.name, cls.OTHER_INDIVIDUAL.name, cls.MASTER_THESIS.name, cls.INTERNSHIP.name LCY_TYPES_WITH_FIXED_ACRONYM = [COURSE, INTERNSHIP, DISSERTATION] LEARNING_CONTAINER_YEAR_TYPES_WITHOUT_EXTERNAL = LearningContainerYearType.choices()[:-1] CONTAINER_TYPE_WITH_DEFAULT_COMP...
or_faculty(
identifier_name
learning_container_year_types.py
############################################################################## # # OSIS stands for Open Student Information System. It's an application # designed to manage the core business of higher education institutions, # such as universities, faculties, institutes and professional schools. # The core ...
class LearningContainerYearType(ChoiceEnum): COURSE = _("Course") INTERNSHIP = _("Internship") DISSERTATION = _("Dissertation") OTHER_COLLECTIVE = _("Other collective") OTHER_INDIVIDUAL = _("Other individual") MASTER_THESIS = _("Thesis") EXTERNAL = _("External") @classmethod def f...
(MASTER_THESIS, _("Thesis")), )
random_line_split
learning_container_year_types.py
############################################################################## # # OSIS stands for Open Student Information System. It's an application # designed to manage the core business of higher education institutions, # such as universities, faculties, institutes and professional schools. # The core ...
LCY_TYPES_WITH_FIXED_ACRONYM = [COURSE, INTERNSHIP, DISSERTATION] LEARNING_CONTAINER_YEAR_TYPES_WITHOUT_EXTERNAL = LearningContainerYearType.choices()[:-1] CONTAINER_TYPE_WITH_DEFAULT_COMPONENT = [COURSE, MASTER_THESIS, OTHER_COLLECTIVE, INTERNSHIP, EXTERNAL] TYPE_ALLOWED_FOR_ATTRIBUTIONS = (OTHER_COLLECTIVE, OTHE...
eturn cls.OTHER_COLLECTIVE.name, cls.OTHER_INDIVIDUAL.name, cls.MASTER_THESIS.name, cls.INTERNSHIP.name
identifier_body
osUtils.ts
// Copied from https://github.com/fwcd/vscode-kotlin-ide and edited. // // Originaly licensed: // // The MIT License (MIT) // // Copyright (c) 2016 George Fraser // Copyright (c) 2018 fwcd // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation...
(binname: string): string { return binname + (process.platform === "win32" ? ".exe" : ""); } export function correctScriptName(binname: string): string { return binname + (process.platform === "win32" ? ".bat" : ""); }
correctBinname
identifier_name
osUtils.ts
// Copied from https://github.com/fwcd/vscode-kotlin-ide and edited. // // Originaly licensed: // // The MIT License (MIT) // // Copyright (c) 2016 George Fraser // Copyright (c) 2018 fwcd // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation...
platform === "linux" || platform === "darwin" || platform === "freebsd" || platform === "openbsd" ); } export function isOSUnix(): boolean { const platform = process.platform; return ( platform === "linux" || platform === "freebsd" || platform === "op...
export function isOSUnixoid(): boolean { const platform = process.platform; return (
random_line_split
osUtils.ts
// Copied from https://github.com/fwcd/vscode-kotlin-ide and edited. // // Originaly licensed: // // The MIT License (MIT) // // Copyright (c) 2016 George Fraser // Copyright (c) 2018 fwcd // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation...
export function correctScriptName(binname: string): string { return binname + (process.platform === "win32" ? ".bat" : ""); }
{ return binname + (process.platform === "win32" ? ".exe" : ""); }
identifier_body
nl.js
CKEDITOR.plugins.setLang('oembed', 'nl', { title : "Integratie van media-inhoud (foto's, video, content)", button : "Media-inhoud van externe websites", pasteUrl : "Geef een URL van een pagina in dat ondersteund wordt (Bijv.: YouTube, Flickr, Qik, Vimeo, Hulu, Viddler, MyOpera, etc.) ...", invalidUrl : "P...
Error: "Media Content could not been retrieved, please try a different URL." });
random_line_split
decode-verify-jwt.py
# Copyright 2017-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file # except in compliance with the License. A copy of the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" file ...
print('Signature successfully verified') # since we passed the verification, we can now safely # use the unverified claims claims = jwt.get_unverified_claims(token) # additionally we can verify the token expiration if time.time() > claims['exp']: print('Token is expired') return...
print('Signature verification failed') return False
conditional_block
decode-verify-jwt.py
# Copyright 2017-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file # except in compliance with the License. A copy of the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" file ...
# the following is useful to make this script executable in both # AWS Lambda and any other local environments if __name__ == '__main__': # for testing locally you can enter the JWT ID Token here event = {'token': ''} lambda_handler(event, None)
token = event['token'] # get the kid from the headers prior to verification headers = jwt.get_unverified_headers(token) kid = headers['kid'] # search for the kid in the downloaded public keys key_index = -1 for i in range(len(keys)): if kid == keys[i]['kid']: key_index = i ...
identifier_body
decode-verify-jwt.py
# Copyright 2017-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file # except in compliance with the License. A copy of the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" file ...
from jose import jwk, jwt from jose.utils import base64url_decode region = 'ap-southeast-2' userpool_id = 'ap-southeast-2_xxxxxxxxx' app_client_id = '<ENTER APP CLIENT ID HERE>' keys_url = 'https://cognito-idp.{}.amazonaws.com/{}/.well-known/jwks.json'.format(region, userpool_id) # instead of re-downloading the public...
import time
random_line_split
decode-verify-jwt.py
# Copyright 2017-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file # except in compliance with the License. A copy of the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" file ...
(event, context): token = event['token'] # get the kid from the headers prior to verification headers = jwt.get_unverified_headers(token) kid = headers['kid'] # search for the kid in the downloaded public keys key_index = -1 for i in range(len(keys)): if kid == keys[i]['kid']: ...
lambda_handler
identifier_name
ControlFlowStorageNode.ts
import { inject, injectable, } from 'inversify'; import { ServiceIdentifiers } from '../../../container/ServiceIdentifiers'; import * as ESTree from 'estree'; import { TIdentifierNamesGeneratorFactory } from '../../../types/container/generators/TIdentifierNamesGeneratorFactory'; import { TStatement } from '../../../t...
( @inject(ServiceIdentifiers.Factory__IIdentifierNamesGenerator) identifierNamesGeneratorFactory: TIdentifierNamesGeneratorFactory, @inject(ServiceIdentifiers.ICustomCodeHelperFormatter) customCodeHelperFormatter: ICustomCodeHelperFormatter, @inject(ServiceIdentifiers.IRandomGenerat...
constructor
identifier_name
ControlFlowStorageNode.ts
import { inject, injectable, } from 'inversify'; import { ServiceIdentifiers } from '../../../container/ServiceIdentifiers'; import * as ESTree from 'estree'; import { TIdentifierNamesGeneratorFactory } from '../../../types/container/generators/TIdentifierNamesGeneratorFactory'; import { TStatement } from '../../../t...
propertyNodes.push( NodeFactory.propertyNode( NodeFactory.identifierNode(key), node.expression ) ); } const structure: ESTree.Node = NodeFactory.variableDeclarationNode( [ NodeF...
{ throw new Error('Function node for control flow storage object should be passed inside the `ExpressionStatement` node!'); }
conditional_block
ControlFlowStorageNode.ts
import { inject, injectable, } from 'inversify'; import { ServiceIdentifiers } from '../../../container/ServiceIdentifiers'; import * as ESTree from 'estree'; import { TIdentifierNamesGeneratorFactory } from '../../../types/container/generators/TIdentifierNamesGeneratorFactory'; import { TStatement } from '../../../t...
/** * @param {IControlFlowStorage} controlFlowStorage */ public initialize (controlFlowStorage: IControlFlowStorage): void { this.controlFlowStorage = controlFlowStorage; } /** * @returns {TStatement[]} */ protected getNodeStructure (): TStatement[] { const pro...
{ super( identifierNamesGeneratorFactory, customCodeHelperFormatter, randomGenerator, options ); }
identifier_body
ControlFlowStorageNode.ts
import { inject, injectable, } from 'inversify'; import { ServiceIdentifiers } from '../../../container/ServiceIdentifiers'; import * as ESTree from 'estree'; import { TIdentifierNamesGeneratorFactory } from '../../../types/container/generators/TIdentifierNamesGeneratorFactory'; import { TStatement } from '../../../t...
@injectable() export class ControlFlowStorageNode extends AbstractCustomNode { /** * @type {IControlFlowStorage} */ @initializable() private controlFlowStorage!: IControlFlowStorage; /** * @param {TIdentifierNamesGeneratorFactory} identifierNamesGeneratorFactory * @param {ICustomCod...
random_line_split
main.rs
use rooster::rclio::RegularInputOutput; use std::env::VarError; use std::path::PathBuf; const ROOSTER_FILE_ENV_VAR: &'static str = "ROOSTER_FILE"; const ROOSTER_FILE_DEFAULT: &'static str = ".passwords.rooster"; fn get_password_file_path() -> Result<PathBuf, i32> { // First, look for the ROOSTER_FILE environment ...
.to_os_string() .into_string() .map_err(|_| 1)?, ); file_default.push(ROOSTER_FILE_DEFAULT); Ok(file_default) } Err(VarError::NotUnicode(_)) => Err(1), } } fn main() { let args = std::env::args().col...
random_line_split
main.rs
use rooster::rclio::RegularInputOutput; use std::env::VarError; use std::path::PathBuf; const ROOSTER_FILE_ENV_VAR: &'static str = "ROOSTER_FILE"; const ROOSTER_FILE_DEFAULT: &'static str = ".passwords.rooster"; fn
() -> Result<PathBuf, i32> { // First, look for the ROOSTER_FILE environment variable. match std::env::var(ROOSTER_FILE_ENV_VAR) { Ok(filename) => Ok(PathBuf::from(filename)), Err(VarError::NotPresent) => { // If the environment variable is not there, we'll look in the default locati...
get_password_file_path
identifier_name
main.rs
use rooster::rclio::RegularInputOutput; use std::env::VarError; use std::path::PathBuf; const ROOSTER_FILE_ENV_VAR: &'static str = "ROOSTER_FILE"; const ROOSTER_FILE_DEFAULT: &'static str = ".passwords.rooster"; fn get_password_file_path() -> Result<PathBuf, i32>
fn main() { let args = std::env::args().collect::<Vec<String>>(); let args_refs = args.iter().map(|s| s.as_str()).collect::<Vec<&str>>(); let rooster_file_path = get_password_file_path().unwrap_or_else(|err| std::process::exit(err)); let stdin = std::io::stdin(); let stdout = std::io::stdout(); ...
{ // First, look for the ROOSTER_FILE environment variable. match std::env::var(ROOSTER_FILE_ENV_VAR) { Ok(filename) => Ok(PathBuf::from(filename)), Err(VarError::NotPresent) => { // If the environment variable is not there, we'll look in the default location: // ~/.passw...
identifier_body
modules_manifest.ts
/** * @license * Copyright Google Inc. 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 */ export interface FileMap<T> { [fileName: string]: T; } /** A class that maintains the module dependency graph of ...
(fileName: string): string[] { return this.referencedModules[fileName]; } }
getReferencedModules
identifier_name
modules_manifest.ts
/** * @license * Copyright Google Inc. 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 */ export interface FileMap<T> { [fileName: string]: T; }
export class ModulesManifest { /** Map of googmodule module name to file name */ private moduleToFileName: FileMap<string> = {}; /** Map of file name to arrays of imported googmodule module names */ private referencedModules: FileMap<string[]> = {}; addManifest(other: ModulesManifest) { Object.assign(thi...
/** A class that maintains the module dependency graph of output JS files. */
random_line_split
l10n_ro_intrastat.py
# © 2008-2020 Dorin Hongu <dhongu(@)gmail(.)com # See README.rst file on addons root folder for license details from odoo import fields, models class IntrastatTransaction(models.Model): _name = "l10n_ro_intrastat.transaction" _description = "Intrastat Transaction" _rec_name = "description" code = f...
("l10n_ro_intrastat_trcodeunique", "UNIQUE (code)", "Code must be unique."), ] class IntrastatTransportMode(models.Model): _name = "l10n_ro_intrastat.transport_mode" _description = "Intrastat Transport Mode" code = fields.Char("Code", required=True, readonly=True) name = fields.Char("Desc...
description = fields.Text("Description", readonly=True) _sql_constraints = [
random_line_split
l10n_ro_intrastat.py
# © 2008-2020 Dorin Hongu <dhongu(@)gmail(.)com # See README.rst file on addons root folder for license details from odoo import fields, models class IntrastatTransaction(models.Model): _name = "l10n_ro_intrastat.transaction" _description = "Intrastat Transaction" _rec_name = "description" code = f...
name = "l10n_ro_intrastat.transport_mode" _description = "Intrastat Transport Mode" code = fields.Char("Code", required=True, readonly=True) name = fields.Char("Description", readonly=True) _sql_constraints = [ ("l10n_ro_intrastat_trmodecodeunique", "UNIQUE (code)", "Code must be unique."), ...
identifier_body
l10n_ro_intrastat.py
# © 2008-2020 Dorin Hongu <dhongu(@)gmail(.)com # See README.rst file on addons root folder for license details from odoo import fields, models class IntrastatTransaction(models.Model): _name = "l10n_ro_intrastat.transaction" _description = "Intrastat Transaction" _rec_name = "description" code = f...
models.Model): _name = "l10n_ro_intrastat.transport_mode" _description = "Intrastat Transport Mode" code = fields.Char("Code", required=True, readonly=True) name = fields.Char("Description", readonly=True) _sql_constraints = [ ("l10n_ro_intrastat_trmodecodeunique", "UNIQUE (code)", "Code m...
ntrastatTransportMode(
identifier_name
badgesService.js
(function() { 'use strict'; /** * @ngdoc function * @name app.service:badgesService * @description * # badgesService * Service of the app */ angular .module('badges') .factory('BadgesService', Badges); // Inject your dependencies as .$inject = ['$http', 'someSevide']; // function Name ($http,...
(vm) { var badges = []; var url = "https://raw.githubusercontent.com/ltouroumov/amt-g4mify/master/client/app/assets/images/"; var req = { method: 'GET', url: 'http://localhost:8080/api/users/' + $rootScope.username +'/badges', headers: { 'Content-Type': 'application/json', 'Iden...
getBadges
identifier_name
badgesService.js
(function() { 'use strict'; /** * @ngdoc function * @name app.service:badgesService * @description * # badgesService * Service of the app */ angular .module('badges') .factory('BadgesService', Badges); // Inject your dependencies as .$inject = ['$http', 'someSevide']; // function Name ($http,...
for(var i = 0; i < res.data.length; i++){ var badge = { level: res.data[i].level, name: res.data[i].type.name, image: url + res.data[i].type.image }; console.log(badges); badges.push(badge); } vm.badges = badges; }, function(err){ console.log("Badge...
random_line_split
badgesService.js
(function() { 'use strict'; /** * @ngdoc function * @name app.service:badgesService * @description * # badgesService * Service of the app */ angular .module('badges') .factory('BadgesService', Badges); // Inject your dependencies as .$inject = ['$http', 'someSevide']; // function Name ($http,...
} })();
{ var badges = []; var url = "https://raw.githubusercontent.com/ltouroumov/amt-g4mify/master/client/app/assets/images/"; var req = { method: 'GET', url: 'http://localhost:8080/api/users/' + $rootScope.username +'/badges', headers: { 'Content-Type': 'application/json', 'Identity'...
identifier_body
badgesService.js
(function() { 'use strict'; /** * @ngdoc function * @name app.service:badgesService * @description * # badgesService * Service of the app */ angular .module('badges') .factory('BadgesService', Badges); // Inject your dependencies as .$inject = ['$http', 'someSevide']; // function Name ($http,...
vm.badges = badges; }, function(err){ console.log("Badges: ERROR"); vm.msg = "- An error occurred posting the event to the gamification platform"; vm.success = false; }); } } })();
{ var badge = { level: res.data[i].level, name: res.data[i].type.name, image: url + res.data[i].type.image }; console.log(badges); badges.push(badge); }
conditional_block
__init__.py
""" Copyright (c) 2020 Ad Schellevis <ad@opnsense.org> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, ...
def parse_flow(flow_line): tmp = flow_line.split() if flow_line.find(':') > 0 and len(tmp) > 8: # IPv6 layout return { 'BKT':tmp[0], 'Prot':tmp[1], 'flowid':tmp[2], 'Source':tmp[3], 'Destination':tmp[4], 'pkt':int(tmp[5]) if...
import re import datetime
random_line_split
__init__.py
""" Copyright (c) 2020 Ad Schellevis <ad@opnsense.org> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, ...
(flow_line): tmp = flow_line.split() if flow_line.find(':') > 0 and len(tmp) > 8: # IPv6 layout return { 'BKT':tmp[0], 'Prot':tmp[1], 'flowid':tmp[2], 'Source':tmp[3], 'Destination':tmp[4], 'pkt':int(tmp[5]) if tmp[5].isdigi...
parse_flow
identifier_name
__init__.py
""" Copyright (c) 2020 Ad Schellevis <ad@opnsense.org> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, ...
def trim_dict(payload): for key in payload: if type(payload[key]) == str: payload[key] = payload[key].strip() elif type(payload[key]) == dict: trim_dict(payload[key]) return payload def parse_ipfw_pipes(): result = dict() pipetxt = subprocess.run(['/sbin/ipfw'...
return re.match( r"q(?P<flow_set_nr>[0-9]*)(?P<queue_size>.*) (?P<flows>[0-9]*) flows" " \((?P<buckets>[0-9]*) buckets\) sched (?P<sched_nr>[0-9]*)" " weight (?P<weight>[0-9]*)" " lmax (?P<lmax>[0-9]*)" " pri (?P<pri>[0-9]*)" "(?P<queue_params>.*)", line )
identifier_body
__init__.py
""" Copyright (c) 2020 Ad Schellevis <ad@opnsense.org> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, ...
elif line.find('__Source') > 0: current_pipe_header = True elif current_pipe_header: flow_stats = parse_flow(line) if flow_stats: current_pipe['flows'].append(flow_stats) return trim_dict(result) def parse_ipfw_queues(): result = dict() ...
m = re.match( r" sched (?P<sched_nr>[0-9]*) type (?P<sched_type>.*) flags (?P<sched_flags>0x[0-9a-fA-F]*)" " (?P<sched_buckets>[0-9]*) buckets (?P<sched_active>[0-9]*) active", line ) if m: current_pipe['scheduler'] = m.groupdict()
conditional_block
reference.py
import os from .base import AnnotatedNineMLObject from nineml.exceptions import NineMLUsageError from nineml.base import DocumentLevelObject class BaseReference(AnnotatedNineMLObject): """ Base class for references to model components that are defined in the abstraction layer. Parameters -------...
@classmethod def unserialize_node(cls, node, **options): # @UnusedVariable name = node.attr('name', **options) url = node.attr('url', default=None, **options) return cls(name=name, document=node.document, url=url) def serialize_node_v1(self, node, **options): # @UnusedVariable ...
node.attr('url', self.url, **options)
conditional_block
reference.py
import os from .base import AnnotatedNineMLObject from nineml.exceptions import NineMLUsageError from nineml.base import DocumentLevelObject class BaseReference(AnnotatedNineMLObject): """ Base class for references to model components that are defined in the abstraction layer. Parameters -------...
node.attr('url', self.url, **options) @classmethod def unserialize_node(cls, node, **options): # @UnusedVariable name = node.attr('name', **options) url = node.attr('url', default=None, **options) return cls(name=name, document=node.document, url=url) def serialize_nod...
def serialize_node(self, node, **options): # @UnusedVariable name = self._target.name node.attr('name', name, **options) if self.url is not None and self.url != node.document.url:
random_line_split
reference.py
import os from .base import AnnotatedNineMLObject from nineml.exceptions import NineMLUsageError from nineml.base import DocumentLevelObject class BaseReference(AnnotatedNineMLObject): """ Base class for references to model components that are defined in the abstraction layer. Parameters -------...
(self): return self._target.name @property def url(self): return self._target.url @property def target(self): return self._target @property def key(self): return (self._target.key + self.url if self.url is not None else '') def __repr__(sel...
name
identifier_name
reference.py
import os from .base import AnnotatedNineMLObject from nineml.exceptions import NineMLUsageError from nineml.base import DocumentLevelObject class BaseReference(AnnotatedNineMLObject): """ Base class for references to model components that are defined in the abstraction layer. Parameters -------...
@property def name(self): return self._target.name @property def url(self): return self._target.url @property def target(self): return self._target @property def key(self): return (self._target.key + self.url if self.url is not None el...
super(BaseReference, self).__init__() if target is not None: assert isinstance(target, DocumentLevelObject) self._target = target if name is not None or url is not None or document is not None: raise NineMLUsageError( "'name', 'url' and 'do...
identifier_body
private-inferred-type-2.rs
// Copyright 2017 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 ...
m::Pub::static_method; //~ ERROR type `m::Priv` is private ext::Pub::static_method; //~ ERROR type `ext::Priv` is private }
} } fn main() { m::Pub::get_priv; //~ ERROR type `m::Priv` is private
random_line_split
private-inferred-type-2.rs
// Copyright 2017 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 ...
() {} } } fn main() { m::Pub::get_priv; //~ ERROR type `m::Priv` is private m::Pub::static_method; //~ ERROR type `m::Priv` is private ext::Pub::static_method; //~ ERROR type `ext::Priv` is private }
static_method
identifier_name
ipsec.py
## Copyright (C) 2007 Sadique Puthen <sputhenp@redhat.com> ### This program is free software; you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Software Foundation; either version 2 of the License, or ## (at your option) any later version. ## Thi...
(self): self.add_copy_specs([ "/etc/ipsec-tools.conf", "/etc/ipsec-tools.d", "/etc/default/setkey" ]) # vim: et ts=4 sw=4
setup
identifier_name
ipsec.py
## Copyright (C) 2007 Sadique Puthen <sputhenp@redhat.com> ### This program is free software; you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Software Foundation; either version 2 of the License, or ## (at your option) any later version. ## Thi...
class DebianIPSec(IPSec, DebianPlugin, UbuntuPlugin): """ipsec related information for Debian distributions """ files = ('/etc/ipsec-tools.conf',) def setup(self): self.add_copy_specs([ "/etc/ipsec-tools.conf", "/etc/ipsec-tools.d", "/etc/default/setkey" ...
self.add_copy_spec("/etc/racoon")
identifier_body
ipsec.py
## Copyright (C) 2007 Sadique Puthen <sputhenp@redhat.com> ### This program is free software; you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Software Foundation; either version 2 of the License, or ## (at your option) any later version. ## Thi...
files = ('/etc/racoon/racoon.conf',) def setup(self): self.add_copy_spec("/etc/racoon") class DebianIPSec(IPSec, DebianPlugin, UbuntuPlugin): """ipsec related information for Debian distributions """ files = ('/etc/ipsec-tools.conf',) def setup(self): self.add_copy_specs([ ...
class RedHatIpsec(IPSec, RedHatPlugin): """ipsec related information for Red Hat distributions """
random_line_split
propane.rs
// Lumol, an extensible molecular simulation engine // Copyright (C) 2015-2016 Lumol's contributors — BSD license #[macro_use] extern crate bencher; extern crate rand; extern crate lumol; extern crate lumol_input; use bencher::Bencher; use rand::Rng; use lumol::sys::EnergyCache; use lumol::types::Vector3D; mod util...
encher: &mut Bencher) { let mut system = utils::get_system("propane"); let mut cache = EnergyCache::new(); cache.init(&system); let mut rng = rand::weak_rng(); for molecule in system.molecules().to_owned() { let delta = Vector3D::new(rng.gen(), rng.gen(), rng.gen()); for i in molecu...
che_move_all_rigid_molecules(b
identifier_name
propane.rs
// Lumol, an extensible molecular simulation engine // Copyright (C) 2015-2016 Lumol's contributors — BSD license #[macro_use] extern crate bencher; extern crate rand; extern crate lumol; extern crate lumol_input; use bencher::Bencher; use rand::Rng; use lumol::sys::EnergyCache; use lumol::types::Vector3D; mod util...
benchmark_group!(energy_computation, energy, forces, virial); benchmark_group!(monte_carlo_cache, cache_move_particles, cache_move_all_rigid_molecules); benchmark_main!(energy_computation, monte_carlo_cache);
let mut system = utils::get_system("propane"); let mut cache = EnergyCache::new(); cache.init(&system); let mut rng = rand::weak_rng(); for molecule in system.molecules().to_owned() { let delta = Vector3D::new(rng.gen(), rng.gen(), rng.gen()); for i in molecule { system[...
identifier_body
propane.rs
// Lumol, an extensible molecular simulation engine // Copyright (C) 2015-2016 Lumol's contributors — BSD license #[macro_use] extern crate bencher; extern crate rand; extern crate lumol; extern crate lumol_input; use bencher::Bencher; use rand::Rng; use lumol::sys::EnergyCache; use lumol::types::Vector3D; mod util...
fn forces(bencher: &mut Bencher) { let system = utils::get_system("propane"); bencher.iter(||{ let _ = system.forces(); }) } fn virial(bencher: &mut Bencher) { let system = utils::get_system("propane"); bencher.iter(||{ let _ = system.virial(); }) } fn cache_move_particles(ben...
random_line_split
app.js
var fs = require('fs'); var path = require('path'); var http = require('http'); var yql = require('yql'); var express = require('express'); config = JSON.parse(fs.readFileSync('./config.json', 'utf-8')); api = JSON.parse(fs.readFileSync('./api.json', 'utf-8')); app = express(); app.configure(function() { app.set('p...
// within that template app.use(function(req, res, next) { res.locals.csrftoken = req.csrfToken(); next(); }); app.use(app.router); app.use(express.static(path.join(__dirname, 'public'))); app.set('jsonp callback', true); // Disable client socket pooling http.agent = false; }); // Routes app.get('^/$', f...
})); app.use(express.csrf()); // Everytime a Jade template is rendered // the CSRF token will be accessible as `csrftoken`
random_line_split
app.js
var fs = require('fs'); var path = require('path'); var http = require('http'); var yql = require('yql'); var express = require('express'); config = JSON.parse(fs.readFileSync('./config.json', 'utf-8')); api = JSON.parse(fs.readFileSync('./api.json', 'utf-8')); app = express(); app.configure(function() { app.set('p...
}); // Main loop http.createServer(app).listen(app.get('port'), function() { console.log("Express server listening on port " + app.get('port')); });
{ res.json({}); }
conditional_block
main.rs
// For random generation extern crate rand; // For fmt::Display use std::fmt; // For I/O (stdin, stdout, etc) use std::io::prelude::*; use rand::Rng; /// A simple struct for a board struct Board { /// The cells of the board cells: Vec<bool>, /// The size of the board size: usize, } // Functions for ...
(&self, rhs: &Board) -> bool { self.cells == rhs.cells } } // Implement the Display format, used with `print!("{}", &board);` impl fmt::Display for Board { // Example output: // 0 1 2 // 0 0 1 0 // 1 1 0 0 // 2 0 1 1 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { /...
eq
identifier_name
main.rs
// For random generation extern crate rand; // For fmt::Display use std::fmt; // For I/O (stdin, stdout, etc) use std::io::prelude::*; use rand::Rng;
cells: Vec<bool>, /// The size of the board size: usize, } // Functions for the Board struct impl Board { /// Generate a new, empty board, of size >= 1 /// /// Returns a Board in the "off" state, where all cells are 0. /// If a size of 0 is given, a Board of size 1 will be created instead. ...
/// A simple struct for a board struct Board { /// The cells of the board
random_line_split
main.rs
// For random generation extern crate rand; // For fmt::Display use std::fmt; // For I/O (stdin, stdout, etc) use std::io::prelude::*; use rand::Rng; /// A simple struct for a board struct Board { /// The cells of the board cells: Vec<bool>, /// The size of the board size: usize, } // Functions for ...
Err(_) => { println!( "Error: '{}': Unable to parse row or column number", input[1..].to_string() ); continue 'userinput; }...
{ // If we're within bounds, return the parsed number if x < size { x } else { println!( "Error: Must specify a row or column within siz...
conditional_block
main.rs
// For random generation extern crate rand; // For fmt::Display use std::fmt; // For I/O (stdin, stdout, etc) use std::io::prelude::*; use rand::Rng; /// A simple struct for a board struct Board { /// The cells of the board cells: Vec<bool>, /// The size of the board size: usize, } // Functions for ...
/// Generate a random board /// /// Returns a Board in a random state. /// If a size of 0 is given, a Board of size 1 will be created instead. /// /// ``` /// let target: Board = Board::random(3); /// ``` fn random<R: Rng>(rng: &mut R, size: usize) -> Board { // Ensure we m...
{ // Check constraints if col > self.size { return false; } // Loop through the vector column for i in 0..self.size { self.cells[col + i * self.size] = !self.cells[col + i * self.size]; } true }
identifier_body
screenshot.rs
extern crate kiss3d; extern crate nalgebra as na; use std::path::Path; use kiss3d::light::Light; use kiss3d::window::Window; use na::{UnitQuaternion, Vector3}; // Based on cube example. fn main()
{ let mut window = Window::new("Kiss3d: screenshot"); let mut c = window.add_cube(0.2, 0.2, 0.2); c.set_color(1.0, 0.0, 0.0); c.prepend_to_local_rotation(&UnitQuaternion::from_axis_angle(&Vector3::y_axis(), 0.785)); c.prepend_to_local_rotation(&UnitQuaternion::from_axis_angle( &Vector3::x_a...
identifier_body
screenshot.rs
extern crate kiss3d; extern crate nalgebra as na; use std::path::Path; use kiss3d::light::Light; use kiss3d::window::Window; use na::{UnitQuaternion, Vector3}; // Based on cube example. fn
() { let mut window = Window::new("Kiss3d: screenshot"); let mut c = window.add_cube(0.2, 0.2, 0.2); c.set_color(1.0, 0.0, 0.0); c.prepend_to_local_rotation(&UnitQuaternion::from_axis_angle(&Vector3::y_axis(), 0.785)); c.prepend_to_local_rotation(&UnitQuaternion::from_axis_angle( &Vector3::...
main
identifier_name
screenshot.rs
extern crate kiss3d; extern crate nalgebra as na; use std::path::Path; use kiss3d::light::Light; use kiss3d::window::Window; use na::{UnitQuaternion, Vector3}; // Based on cube example. fn main() { let mut window = Window::new("Kiss3d: screenshot"); let mut c = window.add_cube(0.2, 0.2, 0.2); c.set_colo...
while window.render() { let img = window.snap_image(); let img_path = Path::new("screenshot.png"); img.save(img_path).unwrap(); println!("Screeshot saved to `screenshot.png`"); break; } }
)); window.set_light(Light::StickToCamera);
random_line_split
semanticClassificationModules.ts
/// <reference path="fourslash.ts"/> ////module /*0*/M { //// export var v; //// export interface /*1*/I {
////} //// ////var x: /*2*/M./*3*/I = /*4*/M.v; ////var y = /*5*/M; const c = classification("original"); verify.semanticClassificationsAre("original", c.moduleName("M", test.marker("0").position), c.interfaceName("I", test.marker("1").position), c.moduleName("M", test.marker("2").position), ...
//// }
random_line_split
mask.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 crate::relay_directive::RelayDirective; use graphql_ir::{ FragmentDefinition, FragmentSpread, InlineFragment, OperationDe...
joined_arguments.insert(variable.name.item, variable); } for arg in self.current_reachable_arguments.drain(..) { match joined_arguments.entry(arg.name.item) { Entry::Vacant(entry) => { entry.insert(arg); } Entry:...
} fn join_current_arguments_to_fragment(&mut self, fragment: &mut FragmentDefinition) { let mut joined_arguments = JoinedArguments::default(); for variable in &fragment.used_global_variables {
random_line_split
mask.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 crate::relay_directive::RelayDirective; use graphql_ir::{ FragmentDefinition, FragmentSpread, InlineFragment, OperationDe...
fn transform_fragment( &mut self, fragment: &FragmentDefinition, ) -> Transformed<FragmentDefinition> { let result = self.default_transform_fragment(fragment); if self.current_reachable_arguments.is_empty() { result } else { Transformed::Replace(...
{ let result = self.default_transform_operation(operation); self.current_reachable_arguments.clear(); result }
identifier_body
mask.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 crate::relay_directive::RelayDirective; use graphql_ir::{ FragmentDefinition, FragmentSpread, InlineFragment, OperationDe...
} } } let range = RangeFull; fragment.used_global_variables = joined_arguments .drain(range) .map(|(_, v)| v) .cloned() .collect(); } } impl<'s> Transformer for Mask<'s> { const NAME: &'static str = "MaskTransf...
{ entry.insert(arg); }
conditional_block
mask.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 crate::relay_directive::RelayDirective; use graphql_ir::{ FragmentDefinition, FragmentSpread, InlineFragment, OperationDe...
(&mut self, fragment: &mut FragmentDefinition) { let mut joined_arguments = JoinedArguments::default(); for variable in &fragment.used_global_variables { joined_arguments.insert(variable.name.item, variable); } for arg in self.current_reachable_arguments.drain(..) { ...
join_current_arguments_to_fragment
identifier_name
word2vec.rs
extern crate vect; extern crate argparse; use vect::termcounts; use vect::ingestion; use vect::dictionary::Dictionary; use argparse::{ArgumentParser, Store}; use vect::huffman; use vect::base::split_words; use std::io; // This is labeled public to shut up the linter about dead code pub fn main() { let mut input_f...
{ for line in try!(ingestion::ingest_lines(&input_filename)) { let line = try!(line); let words = split_words(&line); for i in 0..words.len()-1 { dictionary.update_both(&words[i], &words[i+1]); } } Ok(()) }
identifier_body
word2vec.rs
extern crate vect; extern crate argparse; use vect::termcounts; use vect::ingestion; use vect::dictionary::Dictionary; use argparse::{ArgumentParser, Store}; use vect::huffman; use vect::base::split_words; use std::io;
// This is labeled public to shut up the linter about dead code pub fn main() { let mut input_filename = "word2vec_input".to_string(); let mut output_filename = "word2vec_termcounts".to_string(); { // Limit the scope of ap.refer() let mut ap = ArgumentParser::new(); ap.set_description("Crea...
random_line_split
word2vec.rs
extern crate vect; extern crate argparse; use vect::termcounts; use vect::ingestion; use vect::dictionary::Dictionary; use argparse::{ArgumentParser, Store}; use vect::huffman; use vect::base::split_words; use std::io; // This is labeled public to shut up the linter about dead code pub fn main() { let mut input_f...
(dictionary: &mut Dictionary, input_filename: &str) -> io::Result<()> { for line in try!(ingestion::ingest_lines(&input_filename)) { let line = try!(line); let words = split_words(&line); for i in 0..words.len()-1 { dictionary.update_both(&words[i], &words[i+1]); } } ...
train
identifier_name
annotations.py
import csv import json import numpy as np import os import pathlib import navpy from direct.showbase.ShowBase import ShowBase from panda3d.core import CardMaker, LPoint3, NodePath, Texture, TransparencyAttrib from direct.gui.DirectGui import * from tkinter import * class Annotations(): def __init__(self, render...
node.reparentTo(self.render) self.nodes.append(node)
random_line_split
annotations.py
import csv import json import numpy as np import os import pathlib import navpy from direct.showbase.ShowBase import ShowBase from panda3d.core import CardMaker, LPoint3, NodePath, Texture, TransparencyAttrib from direct.gui.DirectGui import * from tkinter import * class Annotations(): def __init__(self, render...
else: z = self.surface.get_elevation(x, y) result, comment = self.edit(self.next_id, [y, x, z], exists=False) if result == 'ok': id = self.next_id self.next_id += 1 self.add_marker( [y, x, z], comment, id ) dirt...
print("Found existing marker:", found) id = self.markers[found]['id'] ned = self.markers[found]['ned'] comment = self.markers[found]['comment'] result, comment = self.edit(id, ned, comment, exists=True) if result == 'ok': self.markers[found]['c...
conditional_block
annotations.py
import csv import json import numpy as np import os import pathlib import navpy from direct.showbase.ShowBase import ShowBase from panda3d.core import CardMaker, LPoint3, NodePath, Texture, TransparencyAttrib from direct.gui.DirectGui import * from tkinter import * class Annotations(): def __init__(self, render...
def edit(self, id, ned, comment="", exists=False): lla = self.ned2lla(ned[0], ned[1], ned[2]) new = Toplevel(self.tk_root) self.edit_result = "cancel" e = None def on_ok(): new.quit() new.withdraw() print('comment:', e.get()) ...
self.save_kml() filename = os.path.join(self.proj.analysis_dir, 'annotations.json') print('Saving annotations:', filename) lla_list = [] for m in self.markers: ned = m['ned'] lla = self.ned2lla( ned[0], ned[1], ned[2] ) jm = { 'lat_deg': lla[0], ...
identifier_body
annotations.py
import csv import json import numpy as np import os import pathlib import navpy from direct.showbase.ShowBase import ShowBase from panda3d.core import CardMaker, LPoint3, NodePath, Texture, TransparencyAttrib from direct.gui.DirectGui import * from tkinter import * class Annotations(): def __init__(self, render...
(self, n, e, d): lla = navpy.ned2lla( [n, e, d], self.ned_ref[0], self.ned_ref[1], self.ned_ref[2] ) # print(n, e, d, lla) return lla def add_marker(self, ned, comment, id): marker = { "ned": ned,...
ned2lla
identifier_name
arbitrary_self_types_pointers_and_wrappers.rs
// run-pass #![feature(arbitrary_self_types, unsize, coerce_unsized, dispatch_from_dyn)] #![feature(rustc_attrs)] use std::{ ops::{Deref, CoerceUnsized, DispatchFromDyn}, marker::Unsize, }; struct Ptr<T: ?Sized>(Box<T>); impl<T: ?Sized> Deref for Ptr<T> { type Target = T; fn deref(&self) -> &T { ...
}
random_line_split
arbitrary_self_types_pointers_and_wrappers.rs
// run-pass #![feature(arbitrary_self_types, unsize, coerce_unsized, dispatch_from_dyn)] #![feature(rustc_attrs)] use std::{ ops::{Deref, CoerceUnsized, DispatchFromDyn}, marker::Unsize, }; struct Ptr<T: ?Sized>(Box<T>); impl<T: ?Sized> Deref for Ptr<T> { type Target = T; fn deref(&self) -> &T
} impl<T: Unsize<U> + ?Sized, U: ?Sized> CoerceUnsized<Ptr<U>> for Ptr<T> {} impl<T: Unsize<U> + ?Sized, U: ?Sized> DispatchFromDyn<Ptr<U>> for Ptr<T> {} struct Wrapper<T: ?Sized>(T); impl<T: ?Sized> Deref for Wrapper<T> { type Target = T; fn deref(&self) -> &T { &self.0 } } impl<T: CoerceUnsi...
{ &*self.0 }
identifier_body
arbitrary_self_types_pointers_and_wrappers.rs
// run-pass #![feature(arbitrary_self_types, unsize, coerce_unsized, dispatch_from_dyn)] #![feature(rustc_attrs)] use std::{ ops::{Deref, CoerceUnsized, DispatchFromDyn}, marker::Unsize, }; struct Ptr<T: ?Sized>(Box<T>); impl<T: ?Sized> Deref for Ptr<T> { type Target = T; fn deref(&self) -> &T { ...
<T: ?Sized>(T); impl<T: ?Sized> Deref for Wrapper<T> { type Target = T; fn deref(&self) -> &T { &self.0 } } impl<T: CoerceUnsized<U>, U> CoerceUnsized<Wrapper<U>> for Wrapper<T> {} impl<T: DispatchFromDyn<U>, U> DispatchFromDyn<Wrapper<U>> for Wrapper<T> {} trait Trait { // This method isn'...
Wrapper
identifier_name
unboxed-closures-by-ref.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 ...
f() } fn main() { let mut x = 0u; let y = 2u; call_fn(|&:| assert_eq!(x, 0)); call_fn_mut(|&mut:| x += y); call_fn_once(|:| x += y); assert_eq!(x, y * 2); }
f() } fn call_fn_once<F: FnOnce()>(f: F) {
random_line_split
unboxed-closures-by-ref.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 ...
fn call_fn_once<F: FnOnce()>(f: F) { f() } fn main() { let mut x = 0u; let y = 2u; call_fn(|&:| assert_eq!(x, 0)); call_fn_mut(|&mut:| x += y); call_fn_once(|:| x += y); assert_eq!(x, y * 2); }
{ f() }
identifier_body
unboxed-closures-by-ref.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 ...
<F: FnMut()>(mut f: F) { f() } fn call_fn_once<F: FnOnce()>(f: F) { f() } fn main() { let mut x = 0u; let y = 2u; call_fn(|&:| assert_eq!(x, 0)); call_fn_mut(|&mut:| x += y); call_fn_once(|:| x += y); assert_eq!(x, y * 2); }
call_fn_mut
identifier_name
authserver.rs
pub struct AuthServer { cipher: Cipher } impl AuthServer { fn new(cipher: &Cipher) -> AuthServer { AuthServer { cipher: cipher } } fn authenticate(&self, auth_string: &Vec<u8>) -> Response { } } impl Receiver for AuthServer { fn receive(method: &str,...
fn encode(&self) -> Result<String, err::Error> { Ok(try!(url::encode(&vec![ ("email", &self.email), ("uid", self.uid), ("role", &format!("{:?}", self)]))) } fn decode(param_string: &str) -> Result<User, err::Error> { let params = try!(url::decode(&par...
{ User { email: email.clone(), uid: uid, role: role } }
identifier_body
authserver.rs
pub struct AuthServer { cipher: Cipher } impl AuthServer {
fn new(cipher: &Cipher) -> AuthServer { AuthServer { cipher: cipher } } fn authenticate(&self, auth_string: &Vec<u8>) -> Response { } } impl Receiver for AuthServer { fn receive(method: &str, data: &Vec<u8>) -> Response { match method { "a...
random_line_split
authserver.rs
pub struct
{ cipher: Cipher } impl AuthServer { fn new(cipher: &Cipher) -> AuthServer { AuthServer { cipher: cipher } } fn authenticate(&self, auth_string: &Vec<u8>) -> Response { } } impl Receiver for AuthServer { fn receive(method: &str, data: &Vec<u8>) -> Res...
AuthServer
identifier_name
font_collection.rs
// Copyright 2013 The Servo Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution. // // 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 http://opensource.org/licenses/MIT>, at ...
extern { /* * CTFontCollection.h */ static kCTFontCollectionRemoveDuplicatesOption: CFStringRef; //fn CTFontCollectionCreateCopyWithFontDescriptors(original: CTFontCollectionRef, // descriptors: CFArrayRef, // ...
{ unsafe { TCFType::wrap_under_create_rule(CTFontManagerCopyAvailableFontFamilyNames()) } }
identifier_body
font_collection.rs
// Copyright 2013 The Servo Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution. // // 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 http://opensource.org/licenses/MIT>, at ...
() -> CFArray { unsafe { TCFType::wrap_under_create_rule(CTFontManagerCopyAvailableFontFamilyNames()) } } extern { /* * CTFontCollection.h */ static kCTFontCollectionRemoveDuplicatesOption: CFStringRef; //fn CTFontCollectionCreateCopyWithFontDescriptors(original: CTFontCollectio...
get_family_names
identifier_name
font_collection.rs
// Copyright 2013 The Servo Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution. // // 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 http://opensource.org/licenses/MIT>, at ...
// this stupid function doesn't actually do any wildcard expansion; // it just chooses the best match. Use // CTFontDescriptorCreateMatchingDescriptors instead. fn CTFontCollectionCreateMatchingFontDescriptors(collection: CTFontCollectionRef) -> CFArrayRef; fn CTFontCollectionCreateWithFontDescript...
fn CTFontCollectionCreateFromAvailableFonts(options: CFDictionaryRef) -> CTFontCollectionRef;
random_line_split
font_collection.rs
// Copyright 2013 The Servo Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution. // // 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 http://opensource.org/licenses/MIT>, at ...
let matched_descs: CFArray = TCFType::wrap_under_create_rule(matched_descs); // I suppose one doesn't even need the CTFontCollection object at this point. // But we stick descriptors into and out of it just to provide a nice wrapper API. Some(new_from_descriptors(&matched_descs)) } ...
{ return None; }
conditional_block
AutoRoom.ts
import {setupRoomMemoryForMining} from '../../Common'; import {OperationProcess} from '../../lib/process/OperationProcess'; class OperationAutoLayoutRoom extends OperationProcess<IThaeOperationMemory> { public
() { this.log.debug(`Running Auto Layout Room Operation for { ${this.memory.room} }`); if (!this.room || !this.room.controller || !this.room.controller.my) { if (!this.memory.deadTime) { this.memory.deadTime = Game.time; } if (this.memory.deadTime + OP_DEAD_LIMIT <= Game.time) { ...
run
identifier_name
AutoRoom.ts
import {setupRoomMemoryForMining} from '../../Common'; import {OperationProcess} from '../../lib/process/OperationProcess'; class OperationAutoLayoutRoom extends OperationProcess<IThaeOperationMemory> { public run() { this.log.debug(`Running Auto Layout Room Operation for { ${this.memory.room} }`); if (!th...
room: this.room.name, }, 7).pid); this.missions.push(kernel.startProcess<IThaeCreepMissionMemory>(MissionImageNames.UPGRADING, { creeps: [], room: this.room.name, }, 13).pid); this.missions.push(kernel.startProcess<IThaeCreepMissionMemory>(MissionImageNames....
}, 11).pid); } this.missions.push(kernel.startProcess<IThaeCreepMissionMemory>(MissionImageNames.MELEE, { creeps: [],
random_line_split