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
scatter.js
import assert from './assert'; import Vertex from './vertex'; /** * 2D scattering algorithms. * @type {Object} */ const algorithms = { /** * Uniform-random scattering algorithm. * @param {Integer} width - the width of the scattering area * @param {Integer} height - the height of the scattering area * @...
(width, height, size) { var vertices = [], grid = [], x, y; for (var i = 0; i < size; i += 1) { // Generate a random position until one that isn't already occupied is found do { x = Math.floor(Math.random() * width); y = Math.floor(Math.random() * height); } while (grid[x] && grid[x][y]); ...
random
identifier_name
strand.rs
/* * strand.rs * * striking-db - Persistent key/value store for SSDs. * Copyright (c) 2017 Maxwell Duzen, Ammon Smith * * striking-db is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either versi...
} impl<'d> Strand<'d> { pub fn new( device: &'d Device, id: u16, start: u64, capacity: u64, read_strand: bool, ) -> Result<Self> { assert_eq!( start % PAGE_SIZE64, 0, "Start is not a multiple of the page size" ); ...
capacity: u64, offset: u64, pub stats: Mutex<Stats>,
random_line_split
strand.rs
/* * strand.rs * * striking-db - Persistent key/value store for SSDs. * Copyright (c) 2017 Maxwell Duzen, Ammon Smith * * striking-db is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either versi...
#[inline] pub fn push_offset(&mut self, amt: u64) { self.offset += amt; } #[inline] pub fn contains_ptr(&self, ptr: FilePointer) -> bool { self.start <= ptr && ptr <= self.end() } pub fn write_metadata(&mut self) -> Result<()> { let mut page = Page::default(); ...
{ self.offset }
identifier_body
strand.rs
/* * strand.rs * * striking-db - Persistent key/value store for SSDs. * Copyright (c) 2017 Maxwell Duzen, Ammon Smith * * striking-db is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either versi...
(&mut self) { self.write_metadata().expect("Error writing metadata"); } }
drop
identifier_name
strand.rs
/* * strand.rs * * striking-db - Persistent key/value store for SSDs. * Copyright (c) 2017 Maxwell Duzen, Ammon Smith * * striking-db is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either versi...
}; Ok(Strand { device: device, id: id, start: start, capacity: capacity, offset: offset, stats: Mutex::new(Stats::default()), }) } #[inline] pub fn id(&self) -> u16 { self.id } #[inline] p...
{ // Format strand let header = StrandHeader::new(id, capacity); header.write(&mut page)?; device.write(0, &page[..])?; PAGE_SIZE64 }
conditional_block
nuts.js
teamTwoTricks: {tricks: Array, points: number}, currentCards: Array, currentWinner: {}, trump: number, trumpPlayed: Array, round: number, renigs: Array, startRound: Function, shuffle: Function, deal: Function, cut: Function, takeTurn: Function, validateCard: Function, getCardRank: Function, validatePlayer: Function, g...
renig = true; }
conditional_block
nuts.js
strict'; /** * * @type {{teamOneTricks: {tricks: Array, points: number}, teamTwoTricks: {tricks: Array, points: number}, currentCards: Array, currentWinner: {}, trump: number, trumpPlayed: Array, round: number, renigs: Array, startRound: Function, shuffle: Function, deal: Function, cut: Function, takeTurn: Function,...
rnd = Math.floor(Math.random() * (80)) + 1;//1-80 if(deck.indexOf(rnd) < 0 && rnd < 81){//random can sometimes return outside the upper bounds so <81 deck.push(rnd); } } return deck; }, /** * * @param deck * @param dealInt * @param players * @returns {players} */ ...
while(deck.length < 80){
random_line_split
problem_041.py
""" Copyright 2014, March 21 Written by Pattarapol (Cheer) Iamngamsup E-mail: IAM.PATTARAPOL@GMAIL.COM Pandigital prime Problem 41 We shall say that an n-digit number is pandigital if it makes use of all the digits 1 to n exactly once. For example, 2143 is a 4-digit pandigital and is also prime...
################################################# # Main execution if __name__ == '__main__': # get starting date time startingDateTime = datetime.datetime.utcnow() print( 'startingDateTime = {0} UTC'.format( startingDateTime ) ) # call main function main() # get ending date time endingd...
largestPanDigitalPrimeNumber = 2 for digitNumber in xrange( 1, 10 ): for panDigitalNumber in MyMathSolver.getPanDigitalNumbersList( digitNumber ): if MyMathSolver.isPrimeNumber( panDigitalNumber ): largestPanDigitalPrimeNumber = panDigitalNumber print( 'answer = {0}'.format( largestPanDigitalPrimeNum...
identifier_body
problem_041.py
""" Copyright 2014, March 21 Written by Pattarapol (Cheer) Iamngamsup E-mail: IAM.PATTARAPOL@GMAIL.COM Pandigital prime Problem 41 We shall say that an n-digit number is pandigital if it makes use of all the digits 1 to n exactly once. For example, 2143 is a 4-digit pandigital and is also prime...
################################################# # Main function def main(): largestPanDigitalPrimeNumber = 2 for digitNumber in xrange( 1, 10 ): for panDigitalNumber in MyMathSolver.getPanDigitalNumbersList( digitNumber ): if MyMathSolver.isPrimeNumber( panDigitalNumber ): largestPanDigitalPr...
# Functions ################################################# # Classes
random_line_split
problem_041.py
""" Copyright 2014, March 21 Written by Pattarapol (Cheer) Iamngamsup E-mail: IAM.PATTARAPOL@GMAIL.COM Pandigital prime Problem 41 We shall say that an n-digit number is pandigital if it makes use of all the digits 1 to n exactly once. For example, 2143 is a 4-digit pandigital and is also prime...
(): largestPanDigitalPrimeNumber = 2 for digitNumber in xrange( 1, 10 ): for panDigitalNumber in MyMathSolver.getPanDigitalNumbersList( digitNumber ): if MyMathSolver.isPrimeNumber( panDigitalNumber ): largestPanDigitalPrimeNumber = panDigitalNumber print( 'answer = {0}'.format( largestPanDigita...
main
identifier_name
problem_041.py
""" Copyright 2014, March 21 Written by Pattarapol (Cheer) Iamngamsup E-mail: IAM.PATTARAPOL@GMAIL.COM Pandigital prime Problem 41 We shall say that an n-digit number is pandigital if it makes use of all the digits 1 to n exactly once. For example, 2143 is a 4-digit pandigital and is also prime...
startingDateTime = datetime.datetime.utcnow() print( 'startingDateTime = {0} UTC'.format( startingDateTime ) ) # call main function main() # get ending date time endingdateTime = datetime.datetime.utcnow() print( 'endingdateTime = {0} UTC'.format( endingdateTime ) ) # compute delta date time ...
conditional_block
records.controller.js
/** * @package omeka * @subpackage neatline * @copyright 2014 Rector and Board of Visitors, University of Virginia * @license http://www.apache.org/licenses/LICENSE-2.0.html */ Neatline.module('Editor.Exhibit.Records', function(Records) { Records.Controller = Neatline.Shared.Controller.extend({ ...
requests: [ 'getModel' ], /** * Create the router, collection, and view. */ init: function() { this.router = new Records.Router(); this.view = new Records.View({ slug: this.slug }); }, /** * Append the list to the editor container. * * @param {Obje...
random_line_split
demo.py
""" Author: Ali Hajimirza (ali@alihm.net) Copyright Ali Hajimirza, free for use under MIT license. """ import csv import os import sys import numpy as np import matplotlib.pyplot as plt from algorithm import EM import argparse def line_plot(data_arrays, xlabel, ylabel, labels, title, f):
None: Saves the plot to the disk. """ plt.suptitle(title, fontsize=14) plots = [] for data in data_arrays: plot, = plt.plot(data) plots.append(plot) plt.legend(plots, labels, loc=2) plt.xlabel(xlabel) plt.ylabel(ylabel) plt.savefig(f, format="png") plt.clf...
""" Plots a scatter chart. Parameters ---------- data_arrays: 2d numpy array Data to be plotted. This array consists of matrices of real values to be plotted. Each row of this matrix will be plotted as a line on the graph. xlabel: list of string The list of categories on for ...
identifier_body
demo.py
""" Author: Ali Hajimirza (ali@alihm.net) Copyright Ali Hajimirza, free for use under MIT license. """ import csv import os import sys import numpy as np import matplotlib.pyplot as plt from algorithm import EM import argparse def line_plot(data_arrays, xlabel, ylabel, labels, title, f): """ Plots a scatter c...
Saves the plot to the disk. """ plt.suptitle(title, fontsize=14) plots = [] for data in data_arrays: plot, = plt.plot(data) plots.append(plot) plt.legend(plots, labels, loc=2) plt.xlabel(xlabel) plt.ylabel(ylabel) plt.savefig(f, format="png") plt.clf() if __...
dest: string, optional Path to the directory to save the image Returns ------- None:
random_line_split
demo.py
""" Author: Ali Hajimirza (ali@alihm.net) Copyright Ali Hajimirza, free for use under MIT license. """ import csv import os import sys import numpy as np import matplotlib.pyplot as plt from algorithm import EM import argparse def
(data_arrays, xlabel, ylabel, labels, title, f): """ Plots a scatter chart. Parameters ---------- data_arrays: 2d numpy array Data to be plotted. This array consists of matrices of real values to be plotted. Each row of this matrix will be plotted as a line on the graph. xlabel: ...
line_plot
identifier_name
demo.py
""" Author: Ali Hajimirza (ali@alihm.net) Copyright Ali Hajimirza, free for use under MIT license. """ import csv import os import sys import numpy as np import matplotlib.pyplot as plt from algorithm import EM import argparse def line_plot(data_arrays, xlabel, ylabel, labels, title, f): """ Plots a scatter c...
plt.legend(plots, labels, loc=2) plt.xlabel(xlabel) plt.ylabel(ylabel) plt.savefig(f, format="png") plt.clf() if __name__ == '__main__': parser = argparse.ArgumentParser(description='Divides data into the categories by ') parser.add_argument('data', type=argparse.FileType("rb"), help='CSV...
plot, = plt.plot(data) plots.append(plot)
conditional_block
index.ts
import { EffectPluginBase, Exceptions, PluginPreRenderRequest, RenderRequest, Type, TypeDescriptor, } from '@ragg/delir-core' import * as Tooloud from 'tooloud' export default class
extends EffectPluginBase { public static async pluginDidLoad() { // ✋( ͡° ͜ʖ ͡°) インターフェースに誓って if (typeof window === 'undefined') { throw new Exceptions.PluginLoadFailException('this plugin only running on Electron') } } public static provideParameters(): TypeDescriptor ...
NoiseEffectPlugin
identifier_name
index.ts
import { EffectPluginBase, Exceptions, PluginPreRenderRequest, RenderRequest, Type, TypeDescriptor, } from '@ragg/delir-core' import * as Tooloud from 'tooloud' export default class NoiseEffectPlugin extends EffectPluginBase { public static async pluginDidLoad() { // ✋( ͡° ͜ʖ ͡°) イ...
Data, 0, 0) } }
< req.destCanvas.height; y++) { const head = canvas.width * y * 4 + x const value = Tooloud.Worley.Euclidean(x, y, 0) data[head + 0] = (value[0] * 255) | 0 data[head + 1] = (value[1] * 255) | 0 data[head + 2] = (value[2] * 255) | 0 ...
conditional_block
index.ts
import { EffectPluginBase, Exceptions, PluginPreRenderRequest, RenderRequest, Type, TypeDescriptor, } from '@ragg/delir-core' import * as Tooloud from 'tooloud' export default class NoiseEffectPlugin extends EffectPluginBase { public static async pluginDidLoad() { // ✋( ͡° ͜ʖ ͡°) イ...
const canvas = req.destCanvas const ctx = req.destCanvas.getContext('2d') if (ctx == null) { return } ctx.clearRect(0, 0, canvas.width, canvas.height) const imageData: ImageData = ctx.getImageData(0, 0, req.destCanvas.width, req.destCanvas.height) co...
public async beforeRender(preRenderRequest: PluginPreRenderRequest) {} public async render(req: RenderRequest) {
random_line_split
oxinfopopup.js
/** * This file is part of OXID eShop Community Edition. * * OXID eShop Community Edition is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your opt...
* but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OXID eShop Community Edition. If not, s...
* OXID eShop Community Edition is distributed in the hope that it will be useful,
random_line_split
awot.js
/* * grunt-awot * https://github.com/lasselukkari/grunt-awot * * Copyright (c) 2015 Lasse Lukkari * Licensed under the MIT license. */ 'use strict'; var ejs = require('ejs'); var path = require('path'); var mime = require('mime'); var zlib = require('zlib'); module.exports = function (grunt) { grunt.register...
} grunt.file.write(options.sketch, sketch); grunt.file.write(assetsRouter, generatedRoutes); var combinedSize = 0; commands.forEach(function (command) { combinedSize += command.size; }); grunt.log.writeln('Combined size of assets: ' + combinedSize + ' bytes'); done(); }); }...
var generatedRoutes = ejs.render(routesTemplate, {commands: commands}); if (sketch.indexOf('AssetRouter(' + options.appName + ');') < 0) { sketch = sketch.replace(options.needle, options.needle + '\n' + ' AssetRouter(' + options.appName + ');');
random_line_split
awot.js
/* * grunt-awot * https://github.com/lasselukkari/grunt-awot * * Copyright (c) 2015 Lasse Lukkari * Licensed under the MIT license. */ 'use strict'; var ejs = require('ejs'); var path = require('path'); var mime = require('mime'); var zlib = require('zlib'); module.exports = function (grunt) { grunt.register...
}).forEach(function (filepath) { var shortPath = filepath.replace(f.orig.cwd + '/', ''); var nameParts = path.basename(shortPath).split('.'); var camelCaseName = nameParts[0]; for (var i = 1; i < nameParts.length; i++) { camelCaseName += nameParts[i].charAt(0).toUpperCa...
{ return true; }
conditional_block
transaction.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use crate::errors; use crate::statecallback::StateCallback; use crate::transport::platformmonitor::Monitor; use ru...
timeout, ) .map_err(|_| errors::AuthenticatorError::Platform)?; Ok(Self { thread: Some(thread), }) } pub fn cancel(&mut self) { // This must never be None. self.thread.take().unwrap().cancel(); } }
random_line_split
transaction.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use crate::errors; use crate::statecallback::StateCallback; use crate::transport::platformmonitor::Monitor; use ru...
(&mut self) { // This must never be None. self.thread.take().unwrap().cancel(); } }
cancel
identifier_name
prelude.rs
// Copyright 2015 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 ...
//! The I/O Prelude //! //! The purpose of this module is to alleviate imports of many common I/O traits //! by adding a glob import to the top of I/O heavy modules: //! //! ``` //! # #![allow(unused_imports)] //! use std::io::prelude::*; //! ``` #![stable(feature = "rust1", since = "1.0.0")] pub use super::{Read, Wr...
random_line_split
depswriter.py
#!/usr/bin/env python # # Copyright 2009 The Closure Library Authors. 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. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 ...
(root, prefix=''): """Scans a top root directory for .js sources. Args: root: str, Root directory. prefix: str, Prefix for returned paths. Returns: dict, A map of relative paths (with prefix, if given), to source.Source objects. """ # Remember and restore the cwd when we're done. We work f...
_GetRelativePathToSourceDict
identifier_name
depswriter.py
#!/usr/bin/env python # # Copyright 2009 The Closure Library Authors. 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. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 ...
# Source paths for path in args: path_to_source[path] = source.Source(source.GetFileContents(path)) # Source paths with alternate deps paths for path_with_depspath in options.paths_with_depspath: srcpath, depspath = _GetPair(path_with_depspath) path_to_source[depspath] = source.Source(source.GetF...
root, prefix = _GetPair(root_and_prefix) path_to_source.update(_GetRelativePathToSourceDict(root, prefix=prefix))
conditional_block
depswriter.py
#!/usr/bin/env python # # Copyright 2009 The Closure Library Authors. 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. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 ...
action='append', help='A root directory to scan for JS source files, plus ' 'a prefix (if either contains a space, surround with ' 'quotes). Paths in generated deps file will be relative ' 'to the root, but preceded by ...
"""Get the options parser.""" parser = optparse.OptionParser(__doc__) parser.add_option('--output_file', dest='output_file', action='store', help=('If specified, write output to this path instead of ' 'writing to standard output...
identifier_body
depswriter.py
#!/usr/bin/env python # # Copyright 2009 The Closure Library Authors. 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. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 ...
main()
random_line_split
main.rs
use std::io::{self, Read, Write}; use std::env; fn main() { let content_length = env::var("CONTENT_LENGTH").unwrap_or("0".into()) .parse::<u64>().expect("Error parsing CONTENT_LENGTH"); let status = match handle(content_length) { Ok(_) => 0, Err(_) => 1, }; ::std::process::exit(...
(content_length: u64) -> io::Result<()> { let mut buffer = Vec::new(); io::stdin().take(content_length).read_to_end(&mut buffer)?; println!("Content-Type: text/html"); println!(); println!("<p>Hello, world!</p>"); println!("<ul>"); for (key, value) in ::std::env::vars() { println!("...
handle
identifier_name
main.rs
use std::io::{self, Read, Write}; use std::env; fn main() { let content_length = env::var("CONTENT_LENGTH").unwrap_or("0".into()) .parse::<u64>().expect("Error parsing CONTENT_LENGTH"); let status = match handle(content_length) { Ok(_) => 0, Err(_) => 1, }; ::std::process::exit(...
println!("<ul>"); for (key, value) in ::std::env::vars() { println!("<li>{}: {}</li>", key, value); } println!("</ul>"); println!("<p>"); io::stdout().write(&buffer[..])?; println!("</p>"); Ok(()) }
println!(); println!("<p>Hello, world!</p>");
random_line_split
main.rs
use std::io::{self, Read, Write}; use std::env; fn main()
fn handle(content_length: u64) -> io::Result<()> { let mut buffer = Vec::new(); io::stdin().take(content_length).read_to_end(&mut buffer)?; println!("Content-Type: text/html"); println!(); println!("<p>Hello, world!</p>"); println!("<ul>"); for (key, value) in ::std::env::vars() { ...
{ let content_length = env::var("CONTENT_LENGTH").unwrap_or("0".into()) .parse::<u64>().expect("Error parsing CONTENT_LENGTH"); let status = match handle(content_length) { Ok(_) => 0, Err(_) => 1, }; ::std::process::exit(status); }
identifier_body
Range.js
/** * @author Richard Davey <rich@photonstorm.com> * @copyright 2019 Photon Storm Ltd. * @license {@link https://opensource.org/licenses/MIT|MIT License} */ var GetValue = require('../object/GetValue'); var Shuffle = require('./Shuffle'); var BuildChunk = function (a, b, qty) { var out = []; ...
out.splice(max); } return out; }; module.exports = Range;
if (max) {
random_line_split
Range.js
/** * @author Richard Davey <rich@photonstorm.com> * @copyright 2019 Photon Storm Ltd. * @license {@link https://opensource.org/licenses/MIT|MIT License} */ var GetValue = require('../object/GetValue'); var Shuffle = require('./Shuffle'); var BuildChunk = function (a, b, qty) { var out = []; ...
else { // Work out how many repeats we need var total = (a.length * b.length) * qty; if (yoyo) { total *= 2; } repeat = Math.ceil(max / total); } } for (var i = 0; i <= repeat; i++) { ...
{ repeat = 0; }
conditional_block
font.rs
~[u8], style: &SpecifiedFontStyle) -> Result<FontHandle, ()> { let ft_ctx: FT_Library = fctx.ctx.borrow().ctx; if ft_ctx.is_null() { return Err(()); } let face_result = create_face_from_buffer(ft_ctx, buf.as_ptr(), buf.len(), style.pt_size); ...
{ return Err(()); }
conditional_block
font.rs
::TT_OS2; use std::cast; use std::ptr; use std::str; fn float_to_fixed_ft(f: f64) -> i32 { float_to_fixed(6, f) } fn fixed_to_float_ft(f: i32) -> f64 { fixed_to_float(6, f) } pub struct FontTable { bogus: () } impl FontTableMethods for FontTable { fn with_buffer(&self, _blk: |*u8, uint|) { ...
(&self) -> bool { unsafe { (*self.face).style_flags & FT_STYLE_FLAG_ITALIC != 0 } } fn boldness(&self) -> font_weight::T { let default_weight = font_weight::Weight400; if unsafe { (*self.face).style_flags & FT_STYLE_FLAG_BOLD == 0 } { default_weight } else { ...
is_italic
identifier_name
font.rs
2::TT_OS2; use std::cast;
float_to_fixed(6, f) } fn fixed_to_float_ft(f: i32) -> f64 { fixed_to_float(6, f) } pub struct FontTable { bogus: () } impl FontTableMethods for FontTable { fn with_buffer(&self, _blk: |*u8, uint|) { fail!() } } enum FontSource { FontSourceMem(~[u8]), FontSourceFile(~str) } pub ...
use std::ptr; use std::str; fn float_to_fixed_ft(f: f64) -> i32 {
random_line_split
font.rs
::TT_OS2; use std::cast; use std::ptr; use std::str; fn float_to_fixed_ft(f: f64) -> i32 { float_to_fixed(6, f) } fn fixed_to_float_ft(f: i32) -> f64 { fixed_to_float(6, f) } pub struct FontTable { bogus: () } impl FontTableMethods for FontTable { fn with_buffer(&self, _blk: |*u8, uint|) { ...
fn glyph_index(&self, codepoint: char) -> Option<GlyphIndex> { assert!(self.face.is_not_null()); unsafe { let idx = FT_Get_Char_Index(self.face, codepoint as FT_ULong); return if idx != 0 as FT_UInt { Some(idx as GlyphIndex) ...
{ match self.source { FontSourceMem(ref buf) => { FontHandleMethods::new_from_buffer(fctx, buf.clone(), style) } FontSourceFile(ref file) => { FontHandle::new_from_file(fctx, (*file).clone(), style) } } }
identifier_body
utils.py
# 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 agreed to in writing, software # distributed under t...
# under the License. from django.template.defaultfilters import filesizeformat from django.utils.translation import ugettext_lazy as _ from horizon import exceptions from openstack_dashboard.api import glance def get_available_images(request, project_id=None, images_cache=None): """Returns a list of images tha...
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations
random_line_split
utils.py
# 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 agreed to in writing, software # distributed under t...
except Exception: exceptions.handle(request, _("Unable to retrieve public images.")) # Preempt if we don't have a project_id yet. if project_id is None: images_by_project[project_id] = [] if project_id not in images_by_project: owner = {"pr...
"""Returns a list of images that are public or owned by the given project_id. If project_id is not specified, only public images are returned. :param images_cache: An optional dict-like object in which to cache public and per-project id image metadata. """ if images_cache is None: ima...
identifier_body
utils.py
# 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 agreed to in writing, software # distributed under t...
(request, project_id=None, images_cache=None): """Returns a list of images that are public or owned by the given project_id. If project_id is not specified, only public images are returned. :param images_cache: An optional dict-like object in which to cache public and per-project id image metadata...
get_available_images
identifier_name
utils.py
# 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 agreed to in writing, software # distributed under t...
public_images = images_cache.get('public_images', []) images_by_project = images_cache.get('images_by_project', {}) if 'public_images' not in images_cache: public = {"is_public": True, "status": "active"} try: images, _more, _prev = glance.image_list_detailed( ...
images_cache = {}
conditional_block
fu_poteng_bending.py
#------------------------------------------------------------------------- # # Copyright (c) 2009, IMB, RWTH Aachen. # All rights reserved. # # This software is provided without warranty under the terms of the BSD # license included in simvisage/LICENSE.txt and may be redistributed only # under the conditions described...
'''Get the derivatives with respect to individual displacements. ''' return self.forming_task.formed_object.V_du
identifier_body
fu_poteng_bending.py
#------------------------------------------------------------------------- # # Copyright (c) 2009, IMB, RWTH Aachen. # All rights reserved. # # This software is provided without warranty under the terms of the BSD # license included in simvisage/LICENSE.txt and may be redistributed only # under the conditions described...
(self, t=0): '''Get the bending energy of gravity. ''' return self.forming_task.formed_object.V def get_f_du(self, t=0): '''Get the derivatives with respect to individual displacements. ''' return self.forming_task.formed_object.V_du
get_f
identifier_name
fu_poteng_bending.py
#------------------------------------------------------------------------- # # Copyright (c) 2009, IMB, RWTH Aachen. # All rights reserved. # # This software is provided without warranty under the terms of the BSD # license included in simvisage/LICENSE.txt and may be redistributed only # under the conditions described...
'''Get the derivatives with respect to individual displacements. ''' return self.forming_task.formed_object.V_du
def get_f_du(self, t=0):
random_line_split
07_ExampleDoc.py
#ImportModules
MyParenter=SYS.ParenterClass( ).array( [ ['-Layers'], ['|First','|Second'], ['-Neurons'], ['|E','|I'] ] ).command( '+-.values+|.values', '#call:parent', _AfterWalkRigidBool=True ).command( '+-.values+|.values', { '#bound:recruit':lambda _InstanceVariable:_InstanceVariable[ '/Top/Neu...
import ShareYourSystem as SYS #define and get two children
random_line_split
imag_category.rs
// // imag - the personal information management suite for the commandline // Copyright (C) 2015-2020 Matthias Beyer <mail@beyermatthias.de> and contributors // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the F...
(tempdir: &TempDir) -> Command { crate::imag::binary(tempdir, "imag-category") } pub fn call(tmpdir: &TempDir, args: &[&str]) -> Vec<String> { let mut binary = binary(tmpdir); binary.stdin(std::process::Stdio::inherit()); binary.arg("--pipe-input"); binary.arg("--pipe-output"); binary.args(args...
binary
identifier_name
imag_category.rs
// // imag - the personal information management suite for the commandline // Copyright (C) 2015-2020 Matthias Beyer <mail@beyermatthias.de> and contributors // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the F...
use std::process::Command; use assert_fs::fixture::TempDir; pub fn binary(tempdir: &TempDir) -> Command { crate::imag::binary(tempdir, "imag-category") } pub fn call(tmpdir: &TempDir, args: &[&str]) -> Vec<String> { let mut binary = binary(tmpdir); binary.stdin(std::process::Stdio::inherit()); binar...
random_line_split
imag_category.rs
// // imag - the personal information management suite for the commandline // Copyright (C) 2015-2020 Matthias Beyer <mail@beyermatthias.de> and contributors // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the F...
#[test] fn test_new_entry_has_no_category() { crate::setup_logging(); let imag_home = crate::imag::make_temphome(); crate::imag_init::call(&imag_home); crate::imag_create::call(&imag_home, &["test"]); let (assert, stderr_output) = { let mut binary = binary(&imag_home); binary.stdi...
{ let mut binary = binary(tmpdir); binary.stdin(std::process::Stdio::inherit()); binary.arg("--pipe-input"); binary.arg("--pipe-output"); binary.args(args); debug!("Command = {:?}", binary); crate::imag::stdout_of_command(binary) }
identifier_body
non-exhaustive-pattern-witness.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 ...
() { match ((), false) { //~^ ERROR non-exhaustive patterns: `((), false)` not covered ((), true) => () } } fn main() {}
missing_nil
identifier_name
non-exhaustive-pattern-witness.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 ...
[Enum::Second(true), Enum::First] => (), [Enum::Second(true), Enum::Second(true)] => (), [Enum::Second(false), _] => (), [_, _, tail.., _] => () } } fn missing_nil() { match ((), false) { //~^ ERROR non-exhaustive patterns: `((), false)` not covered ((), true) => () ...
[_] => (), [Enum::First, _] => (),
random_line_split
__init__.py
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (C) 2011 Domsense srl (<http://www.domsense.com>) # Copyright (C) 2011-15 Agile Business Group sagl (<http://www.agilebg.com>)
# This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published # by the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that i...
#
random_line_split
main.rs
#![feature(macro_rules)] #![feature(globs)] #![feature(phase)] #![allow(missing_copy_implementations)] #[phase(plugin)] extern crate gl_generator; extern crate glfw; extern crate time; use glfw::{Glfw, Context, OpenGlProfileHint, WindowHint, WindowMode}; use std::rand::{task_rng, Rng}; use std::num::FloatMath; us...
particle.color.blue += particle.fade / 3.0; } // Replace dead particles for i in range(0u, particles.len()) { if particles[i].life < 0.05 { particles.remove(i); particles.insert(i, create_new_particle()); } } // Add new particles if missing let m...
particle.yi *= 0.999; particle.color.alpha = 1.0 * particle.life / MAX_LIFE; particle.color.red += particle.fade / 3.0; particle.color.green += particle.fade / 3.0;
random_line_split
main.rs
#![feature(macro_rules)] #![feature(globs)] #![feature(phase)] #![allow(missing_copy_implementations)] #[phase(plugin)] extern crate gl_generator; extern crate glfw; extern crate time; use glfw::{Glfw, Context, OpenGlProfileHint, WindowHint, WindowMode}; use std::rand::{task_rng, Rng}; use std::num::FloatMath; us...
} } // Add new particles if missing let mut i = 0i; loop { if particles.len() < MAX_PARTICLES { particles.push(create_new_particle()); i += 1 ; } else { break; } if i > 20 { break; } } }
{ // Move & decay existing particles for mut particle in particles.iter_mut() { particle.life -= particle.fade; particle.x += particle.xi; particle.y += particle.yi; particle.xi *= 0.999; particle.yi *= 0.999; particle.color.alpha = 1.0 * particle.life / MAX_LIFE...
identifier_body
main.rs
#![feature(macro_rules)] #![feature(globs)] #![feature(phase)] #![allow(missing_copy_implementations)] #[phase(plugin)] extern crate gl_generator; extern crate glfw; extern crate time; use glfw::{Glfw, Context, OpenGlProfileHint, WindowHint, WindowMode}; use std::rand::{task_rng, Rng}; use std::num::FloatMath; us...
{ red: f32, green: f32, blue: f32, alpha: f32 } struct Particle { life: f32, fade: f32, x: f32, y: f32, xi: f32, yi: f32, color: Color } static WINDOW_WIDTH: u32 = 800; static WINDOW_HEIGHT: u32 = 600; static MAX_PARTICLES: uint = 20000; static MAX_LIFE: f32 = 2.5; static...
Color
identifier_name
main.rs
#![feature(macro_rules)] #![feature(globs)] #![feature(phase)] #![allow(missing_copy_implementations)] #[phase(plugin)] extern crate gl_generator; extern crate glfw; extern crate time; use glfw::{Glfw, Context, OpenGlProfileHint, WindowHint, WindowMode}; use std::rand::{task_rng, Rng}; use std::num::FloatMath; us...
if i > 20 { break; } } }
{ break; }
conditional_block
Link.tsx
import * as React from 'react'; import clsx from 'clsx'; import { useRouter } from 'next/router'; import NextLink, { LinkProps as NextLinkProps } from 'next/link'; import MuiLink, { LinkProps as MuiLinkProps } from '@mui/material/Link'; import { styled } from '@mui/material/styles'; import { useUserLanguage } from 'doc...
as?: NextLinkProps['as']; href: NextLinkProps['href']; linkAs?: NextLinkProps['as']; // Useful when the as prop is shallow by styled(). noLinkStyle?: boolean; } & Omit<NextLinkComposedProps, 'to' | 'linkAs' | 'href'> & Omit<MuiLinkProps, 'href'>; // A styled version of the Next.js Link component: // https://...
activeClassName?: string;
random_line_split
Link.tsx
import * as React from 'react'; import clsx from 'clsx'; import { useRouter } from 'next/router'; import NextLink, { LinkProps as NextLinkProps } from 'next/link'; import MuiLink, { LinkProps as MuiLinkProps } from '@mui/material/Link'; import { styled } from '@mui/material/styles'; import { useUserLanguage } from 'doc...
return ( <MuiLink component={NextLinkComposed} linkAs={linkAs} className={className} ref={ref} to={href} {...other} /> ); }); export default Link;
{ return ( <NextLinkComposed className={className} ref={ref} to={href} linkAs={linkAs} {...other} /> ); }
conditional_block
hooks.ts
import { LOCKFILE_VERSION } from '@pnpm/constants' import { Lockfile } from '@pnpm/lockfile-file' import { prepareEmpty } from '@pnpm/prepare' import { addDependenciesToPackage, PackageManifest, } from '@pnpm/core' import sinon from 'sinon' import { addDistTag, testDefaults, } from '../utils' test('readPackage...
manifest.dependencies['dep-of-pkg-with-1-dep'] = '100.0.0' break } return manifest } const afterAllResolved = sinon.spy((lockfile: Lockfile) => { lockfile['foo'] = 'foo' // eslint-disable-line return lockfile }) await addDependenciesToPackage({}, ['pkg-with-1-dep'], await testDefa...
{ throw new Error('pkg-with-1-dep expected to have a dependencies field') }
conditional_block
hooks.ts
import { LOCKFILE_VERSION } from '@pnpm/constants' import { Lockfile } from '@pnpm/lockfile-file' import { prepareEmpty } from '@pnpm/prepare' import { addDependenciesToPackage, PackageManifest, } from '@pnpm/core' import sinon from 'sinon' import { addDistTag, testDefaults, } from '../utils' test('readPackage...
return lockfile }) await addDependenciesToPackage({}, ['pkg-with-1-dep'], await testDefaults({ hooks: { afterAllResolved, readPackage: readPackageHook, }, })) await project.storeHas('dep-of-pkg-with-1-dep', '100.0.0') expect(afterAllResolved.calledOnce).toBeTruthy() expect(afterAll...
random_line_split
hooks.ts
import { LOCKFILE_VERSION } from '@pnpm/constants' import { Lockfile } from '@pnpm/lockfile-file' import { prepareEmpty } from '@pnpm/prepare' import { addDependenciesToPackage, PackageManifest, } from '@pnpm/core' import sinon from 'sinon' import { addDistTag, testDefaults, } from '../utils' test('readPackage...
const afterAllResolved = sinon.spy((lockfile: Lockfile) => { lockfile['foo'] = 'foo' // eslint-disable-line return lockfile }) await addDependenciesToPackage({}, ['pkg-with-1-dep'], await testDefaults({ hooks: { afterAllResolved, readPackage: readPackageHook, }, })) await proje...
{ switch (manifest.name) { case 'pkg-with-1-dep': if (manifest.dependencies == null) { throw new Error('pkg-with-1-dep expected to have a dependencies field') } manifest.dependencies['dep-of-pkg-with-1-dep'] = '100.0.0' break } return manifest }
identifier_body
hooks.ts
import { LOCKFILE_VERSION } from '@pnpm/constants' import { Lockfile } from '@pnpm/lockfile-file' import { prepareEmpty } from '@pnpm/prepare' import { addDependenciesToPackage, PackageManifest, } from '@pnpm/core' import sinon from 'sinon' import { addDistTag, testDefaults, } from '../utils' test('readPackage...
(manifest: PackageManifest) { switch (manifest.name) { case 'pkg-with-1-dep': if (manifest.dependencies == null) { throw new Error('pkg-with-1-dep expected to have a dependencies field') } manifest.dependencies['dep-of-pkg-with-1-dep'] = '100.0.0' break } return manifest...
readPackageHook
identifier_name
codes test.py
# -*- coding: utf-8 -*- """ Éditeur de Spyder Ce script temporaire est sauvegardé ici : /home/poppy/.spyder2/.temp.py """ # bibliothèques nécessaires au fonctionnement de Poppy humanoide import pypot from poppy.creatures import PoppyHumanoid import kinematics as kin # démmarrer la simulation poppy dans vrep. Il f...
# Poppy dit oui for i in range(2): poppy.head_y.goal_position = -20 poppy.head_y.goal_position = +20 poppy.head_y.goal_position = 0 poppy.l_shoulder_y.goal_position = -45 poppy.l_shoulder_x.goal_position = 45
-----------" print "nom du moteur: ", m.name print "position actuelle du moteur: ", m.present_position, "degrès"
conditional_block
codes test.py
# -*- coding: utf-8 -*- """
# bibliothèques nécessaires au fonctionnement de Poppy humanoide import pypot from poppy.creatures import PoppyHumanoid import kinematics as kin # démmarrer la simulation poppy dans vrep. Il faut lancer V-rep avant d'executer le code. poppy = PoppyHumanoid(simulator='vrep') # Relancer la simulation poppy.reset_s...
Éditeur de Spyder Ce script temporaire est sauvegardé ici : /home/poppy/.spyder2/.temp.py """
random_line_split
loadstations.py
import argparse from osgb import osgb_to_lonlat from osgb.convert import eastnorth_to_osgb from utils.database import insert_into_db, empty_table, execute_sql # Loads data from here: https://data.gov.uk/dataset/naptan def read_stations(filename): with open(filename, 'r') as input_file: for line in inpu...
if __name__ == "__main__": parser = argparse.ArgumentParser(description='National Rail Data Collector') parser.add_argument('--filename', help='Input CSV file', default="data/RailReferences.csv") parser.add_argument('--db', help='SQLite DB Name', default="data/trains.db") args = parser.parse_args() ...
e = row["easting"] n = row["northing"] lon, lat = osgb_to_lonlat(eastnorth_to_osgb(e, n, digits=4)) row["latitude"] = lat row["longitude"] = lon return row
identifier_body
loadstations.py
import argparse from osgb import osgb_to_lonlat from osgb.convert import eastnorth_to_osgb from utils.database import insert_into_db, empty_table, execute_sql # Loads data from here: https://data.gov.uk/dataset/naptan def read_stations(filename): with open(filename, 'r') as input_file: for line in inpu...
if __name__ == "__main__": parser = argparse.ArgumentParser(description='National Rail Data Collector') parser.add_argument('--filename', help='Input CSV file', default="data/RailReferences.csv") parser.add_argument('--db', help='SQLite DB Name', default="data/trains.db") args = parser.parse_args() ...
return row
random_line_split
loadstations.py
import argparse from osgb import osgb_to_lonlat from osgb.convert import eastnorth_to_osgb from utils.database import insert_into_db, empty_table, execute_sql # Loads data from here: https://data.gov.uk/dataset/naptan def read_stations(filename): with open(filename, 'r') as input_file: for line in inpu...
(row): e = row["easting"] n = row["northing"] lon, lat = osgb_to_lonlat(eastnorth_to_osgb(e, n, digits=4)) row["latitude"] = lat row["longitude"] = lon return row if __name__ == "__main__": parser = argparse.ArgumentParser(description='National Rail Data Collector') parser.add_argume...
convert
identifier_name
loadstations.py
import argparse from osgb import osgb_to_lonlat from osgb.convert import eastnorth_to_osgb from utils.database import insert_into_db, empty_table, execute_sql # Loads data from here: https://data.gov.uk/dataset/naptan def read_stations(filename): with open(filename, 'r') as input_file: for line in inpu...
def convert(row): e = row["easting"] n = row["northing"] lon, lat = osgb_to_lonlat(eastnorth_to_osgb(e, n, digits=4)) row["latitude"] = lat row["longitude"] = lon return row if __name__ == "__main__": parser = argparse.ArgumentParser(description='National Rail Data Collector') par...
splits = line.strip().split(",") yield { "crs": splits[2], "name": splits[3], "easting": long(splits[6]), "northing": long(splits[7]) }
conditional_block
cli.rs
use structopt::StructOpt; #[derive(StructOpt)] #[structopt( name = "blog", after_help = "You can also run `blog SUBCOMMAND -h` to get more information about that subcommand." )] pub enum Cli { /// Create a new wonderfully delighting blog post #[structopt(name = "create_post")] CreatePost { ...
Register, }
random_line_split
cli.rs
use structopt::StructOpt; #[derive(StructOpt)] #[structopt( name = "blog", after_help = "You can also run `blog SUBCOMMAND -h` to get more information about that subcommand." )] pub enum
{ /// Create a new wonderfully delighting blog post #[structopt(name = "create_post")] CreatePost { /// The title of your post #[structopt(long = "title")] title: String, }, /// Fine-tune an existing post to reach 100% reader delight #[structopt(name = "edit_post")] ...
Cli
identifier_name
viewmixins.py
import inspect from django.utils.translation import activate class MenuItemMixin: """ This mixins injects attributes that start with the 'menu_' prefix into the context generated by the view it is applied to. This behavior can be used to highlight an item of a navigation component. """ def g...
activate("fr")
conditional_block
viewmixins.py
import inspect from django.utils.translation import activate class MenuItemMixin: """ This mixins injects attributes that start with the 'menu_' prefix into the context generated by the view it is applied to. This behavior can be used to highlight an item of a navigation component. """
menu_kwargs = dict(a for a in vattrs if a[0].startswith("menu_")) context.update(menu_kwargs) return context class ActivateLegacyLanguageViewMixin: """ """ def activate_legacy_language(self, *args, **kwargs): if "lang" in kwargs and kwargs["lang"] == "en" or self.request.GET.g...
def get_context_data(self, **kwargs): context = super(MenuItemMixin, self).get_context_data(**kwargs) vattrs = inspect.getmembers(self, lambda a: not (inspect.isroutine(a)))
random_line_split
viewmixins.py
import inspect from django.utils.translation import activate class MenuItemMixin: """ This mixins injects attributes that start with the 'menu_' prefix into the context generated by the view it is applied to. This behavior can be used to highlight an item of a navigation component. """ def
(self, **kwargs): context = super(MenuItemMixin, self).get_context_data(**kwargs) vattrs = inspect.getmembers(self, lambda a: not (inspect.isroutine(a))) menu_kwargs = dict(a for a in vattrs if a[0].startswith("menu_")) context.update(menu_kwargs) return context class ActivateL...
get_context_data
identifier_name
viewmixins.py
import inspect from django.utils.translation import activate class MenuItemMixin: """ This mixins injects attributes that start with the 'menu_' prefix into the context generated by the view it is applied to. This behavior can be used to highlight an item of a navigation component. """ def g...
if "lang" in kwargs and kwargs["lang"] == "en" or self.request.GET.get("lang") == "en": activate("en") else: activate("fr")
identifier_body
lib.rs
hyper::header::{ContentType, Headers}; use hyper::http::RawStatus; use hyper::method::Method; use hyper::mime::{Mime, Attr}; use ipc_channel::ipc::{self, IpcReceiver, IpcSender}; use msg::constellation_msg::{PipelineId}; use regex::Regex; use serde::{Deserializer, Serializer}; use url::Url; use util::mem::HeapSizeOf; ...
/// Data for passing between threads/processes to indicate a particular action to /// take on a provided network listener. #[derive(Deserialize, Serialize)] pub enum ResponseAction { /// Invoke headers_available HeadersAvailable(Metadata), /// Invoke data_available DataAvailable(Vec<u8>), /// Invoke...
/// The response is complete. If the provided status is an Err value, there is no guarantee /// that the response body was completely read. fn response_complete(&self, status: Result<(), String>); }
random_line_split
lib.rs
, Deserialize, Serialize, HeapSizeOf)] pub struct LoadData { pub url: Url, pub method: Method, #[ignore_heap_size_of = "Defined in hyper"] /// Headers that will apply to the initial request only pub headers: Headers, #[ignore_heap_size_of = "Defined in hyper"] /// Headers that will apply to ...
next
identifier_name
tablesorter.js
at // // http://www.apache.org/licenses/LICENSE-2.0 // // 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 languag...
* By default, the first row (index 0) is used. * Must be called before decorate() is called. * @param {number} index The row index. */ goog.ui.TableSorter.prototype.setSortableHeaderRowIndex = function(index) { if (this.isInDocument()) { throw Error(goog.ui.Component.Error.ALREADY_RENDERED); } this.sortab...
random_line_split
tablesorter.js
at // // http://www.apache.org/licenses/LICENSE-2.0 // // 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 languag...
this.sortableHeaderRowIndex_ = index; }; /** * Table sorter events. * @enum {string} */ goog.ui.TableSorter.EventType = { BEFORESORT: 'beforesort', SORT: 'sort' }; /** @override */ goog.ui.TableSorter.prototype.canDecorate = function(element) { return element.tagName == goog.dom.TagName.TABLE; }; /** ...
{ throw Error(goog.ui.Component.Error.ALREADY_RENDERED); }
conditional_block
link.rs
#![crate_name = "link"] /* * This file is part of the uutils coreutils package. * * (c) Michael Gehring <mg@ebfe.org> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ extern crate getopts; #[macro_use] extern crate uucore; use s...
#[allow(dead_code)] fn main() { std::process::exit(uumain(std::env::args().collect())); }
} }
random_line_split
link.rs
#![crate_name = "link"] /* * This file is part of the uutils coreutils package. * * (c) Michael Gehring <mg@ebfe.org> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ extern crate getopts; #[macro_use] extern crate uucore; use s...
if matches.opt_present("help") || matches.free.len() != 2 { let msg = format!("{0} {1} Usage: {0} [OPTIONS] FILE1 FILE2 Create a link named FILE2 to FILE1.", NAME, VERSION); println!("{}", opts.usage(&msg)); if matches.free.len() != 2 { return 1; } return 0...
{ println!("{} {}", NAME, VERSION); return 0; }
conditional_block
link.rs
#![crate_name = "link"] /* * This file is part of the uutils coreutils package. * * (c) Michael Gehring <mg@ebfe.org> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ extern crate getopts; #[macro_use] extern crate uucore; use s...
(args: Vec<String>) -> i32 { let mut opts = getopts::Options::new(); opts.optflag("h", "help", "display this help and exit"); opts.optflag("V", "version", "output version information and exit"); let matches = match opts.parse(&args[1..]) { Ok(m) => m, Err(err) => panic!("{}", err), ...
uumain
identifier_name
link.rs
#![crate_name = "link"] /* * This file is part of the uutils coreutils package. * * (c) Michael Gehring <mg@ebfe.org> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ extern crate getopts; #[macro_use] extern crate uucore; use s...
{0} [OPTIONS] FILE1 FILE2 Create a link named FILE2 to FILE1.", NAME, VERSION); println!("{}", opts.usage(&msg)); if matches.free.len() != 2 { return 1; } return 0; } let old = Path::new(&matches.free[0]); let new = Path::new(&matches.free[1]); match har...
{ let mut opts = getopts::Options::new(); opts.optflag("h", "help", "display this help and exit"); opts.optflag("V", "version", "output version information and exit"); let matches = match opts.parse(&args[1..]) { Ok(m) => m, Err(err) => panic!("{}", err), }; if matches.opt_pre...
identifier_body
compare_repositories.py
# -*- coding: utf-8; -*- # # This file is part of Superdesk. # # Copyright 2013, 2014 Sourcefabric z.u. and contributors. # # For the full copyright and license information, please see the # AUTHORS and LICENSE files distributed with this source code, or # at https://www.sourcefabric.org/superdesk/license import super...
if isinstance(dict_1[key], list): if not self.are_lists_equal(dict_1[key], dict_2[key]): differences.append(key) elif isinstance(dict_1[key], dict): differences.extend(self.compare_dicts(dict_1[key], dict_2[key])) else: ...
differences.append(key) continue
conditional_block
compare_repositories.py
# -*- coding: utf-8; -*- # # This file is part of Superdesk. # # Copyright 2013, 2014 Sourcefabric z.u. and contributors. # # For the full copyright and license information, please see the # AUTHORS and LICENSE files distributed with this source code, or # at https://www.sourcefabric.org/superdesk/license import super...
request.projection = json.dumps({'_etag': 1, '_updated': 1}) for x in range(0, no_of_buckets): skip = x * self.default_page_size print('Page : {}, skip: {}'.format(x + 1, skip)) # don't get any new records since the elastic items are retrieved cursor = ser...
random_line_split
compare_repositories.py
# -*- coding: utf-8; -*- # # This file is part of Superdesk. # # Copyright 2013, 2014 Sourcefabric z.u. and contributors. # # For the full copyright and license information, please see the # AUTHORS and LICENSE files distributed with this source code, or # at https://www.sourcefabric.org/superdesk/license import super...
def compare_dict_values(self, dict_1, dict_2, differences=None): if differences is None: differences = list() for key in dict_1.keys(): if key in differences: continue if key not in dict_2: differences.append(key) ...
if differences is None: differences = list() diff_keys = list(set(dict_1.keys()) ^ set(dict_2.keys())) if len(diff_keys) > 0: # there are differences in keys so report them differences.extend(diff_keys) self.compare_dict_values(dict_1, dict_2, differences) ...
identifier_body
compare_repositories.py
# -*- coding: utf-8; -*- # # This file is part of Superdesk. # # Copyright 2013, 2014 Sourcefabric z.u. and contributors. # # For the full copyright and license information, please see the # AUTHORS and LICENSE files distributed with this source code, or # at https://www.sourcefabric.org/superdesk/license import super...
(self, elasticsearch_index, elasticsearch_url): # get the all hits from elastic post_data = {'fields': ['_etag']} response = requests.get('{}/{}/{}'.format(elasticsearch_url, elasticsearch_index, '_search?size=5000&q=*:*'), params=post_data) ...
get_elastic_items
identifier_name
issue-14959.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 ...
} } impl<'a, 'b> Fn<(&'b mut Response+'b,),()> for SendFile<'a> { extern "rust-call" fn call(&self, (_res,): (&'b mut Response+'b,)) {} } impl<Rq: Request, Rs: Response> Ingot<Rq, Rs> for HelloWorld { fn enter(&mut self, _req: &mut Rq, res: &mut Rs, alloy: &mut Alloy) -> Status { let send_file = a...
impl Alloy { fn find<T>(&self) -> Option<T> { None
random_line_split
issue-14959.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 main() {}
{ let send_file = alloy.find::<SendFile>().unwrap(); send_file(res); Status::Continue }
identifier_body
issue-14959.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 ...
() {}
main
identifier_name
activity-bar.module.ts
/* * Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to ...
declarations: [ActivityBarComponent, ActivityTooltipPipe], exports: [ActivityBarComponent], imports: [CommonModule, CdCommonModule, RouterModule], }) export class ActivityBarModule {}
import { CdCommonModule } from 'cd-common'; import { ActivityTooltipPipe } from './activity-tooltip.pipe'; import { RouterModule } from '@angular/router'; @NgModule({
random_line_split
activity-bar.module.ts
/* * Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to ...
{}
ActivityBarModule
identifier_name
net.rs
= cvt(unsafe { netc::readv( self.fd, bufs.as_ptr() as *const netc::iovec, cmp::min(bufs.len(), max_iov()) as c_int, ) })?; Ok(ret as usize) } #[inline] fn is_read_vectored(&self) -> bool { true } fn wr...
/// Just to provide the same interface as sys/unix/net.rs pub fn cvt_r<T, F>(mut f: F) -> io::Result<T> where T: IsMinusOne, F: FnMut() -> T, { cvt(f()) } /// Returns the last error from the network subsystem. fn last_error() -> io::Error { io::Error::from_raw_os_error(unsafe { netc::SOLID_NET_GetLas...
{ if err == 0 { Ok(()) } else { let msg: &dyn crate::fmt::Display = match err { netc::EAI_NONAME => &"name or service not known", netc::EAI_SERVICE => &"service not supported", netc::EAI_FAIL => &"non-recoverable failure in name resolution", netc::...
identifier_body
net.rs
= cvt(unsafe { netc::readv( self.fd, bufs.as_ptr() as *const netc::iovec, cmp::min(bufs.len(), max_iov()) as c_int, ) })?; Ok(ret as usize) } #[inline] fn is_read_vectored(&self) -> bool { true } fn wr...
F: FnMut() -> T, { cvt(f()) } /// Returns the last error from the network subsystem. fn last_error() -> io::Error { io::Error::from_raw_os_error(unsafe { netc::SOLID_NET_GetLastError() }) } pub(super) fn error_name(er: abi::ER) -> Option<&'static str> { unsafe { CStr::from_ptr(netc::strerror(er)) }.to...
/// Just to provide the same interface as sys/unix/net.rs pub fn cvt_r<T, F>(mut f: F) -> io::Result<T> where T: IsMinusOne,
random_line_split
net.rs
Result<()> { if err == 0 { Ok(()) } else { let msg: &dyn crate::fmt::Display = match err { netc::EAI_NONAME => &"name or service not known", netc::EAI_SERVICE => &"service not supported", netc::EAI_FAIL => &"non-recoverable failure in name resolution", ...
timeout
identifier_name
main.py
import json import random import ssl import string import threading import time import websocket import settings from player import Player class WebsocketPlayerControl(object): def __init__(self, player, server=settings.WS_SERVER): websocket.enableTrace(settings.DEBUG) rand_chars = string.ascii_...
def on_message(self, ws, message): if settings.DEBUG: print('message received:', message) data = json.loads(message) if data['action'] == 'play': self.player.play() elif data['action'] == 'pause': self.player.pause() elif data['action'] ...
try: name = settings.CLIENT_NAME except AttributeError: name = 'Client' data = { 'action': 'register', 'player': self.player_id, 'key': settings.CLIENT_TOKEN, 'playlist': settings.PLAYLIST_ID, 'name': name }...
identifier_body
main.py
import json import random import ssl import string import threading import time import websocket import settings from player import Player class WebsocketPlayerControl(object): def __init__(self, player, server=settings.WS_SERVER): websocket.enableTrace(settings.DEBUG) rand_chars = string.ascii_...
main()
conditional_block
main.py
import json import random import ssl import string import threading import time import websocket import settings from player import Player class WebsocketPlayerControl(object): def __init__(self, player, server=settings.WS_SERVER): websocket.enableTrace(settings.DEBUG) rand_chars = string.ascii_...
} ws.send(json.dumps(data)) def on_message(self, ws, message): if settings.DEBUG: print('message received:', message) data = json.loads(message) if data['action'] == 'play': self.player.play() elif data['action'] == 'pause': s...
'playlist': settings.PLAYLIST_ID, 'name': name
random_line_split
main.py
import json import random import ssl import string import threading import time import websocket import settings from player import Player class WebsocketPlayerControl(object): def __init__(self, player, server=settings.WS_SERVER): websocket.enableTrace(settings.DEBUG) rand_chars = string.ascii_...
(self, ws, message): if settings.DEBUG: print('message received:', message) data = json.loads(message) if data['action'] == 'play': self.player.play() elif data['action'] == 'pause': self.player.pause() elif data['action'] == 'update_playlist'...
on_message
identifier_name
jquery.contextmenu.js
/** * jQuery plugin for Pretty looking right click context menu. * * Requires popup.js and popup.css to be included in your page. And jQuery, obviously. * * Usage: * * $('.something').contextPopup({ * title: 'Some title', * items: [ * {label:'My Item', icon:'/some/icon1.png', action:function()...
row.find('a').click(function(){ item.action(e); }); } } else { $('<li class="' + settings.seperatorClass + '"></li>').appendTo(menu); } }); menu.find('.' + settings.headerClass ).text(settings.title); return menu; } // On contextmenu event (right click) this.bin...
{ var menu = $('<ul class="' + settings.contextMenuClass + '"><div class="' + settings.gutterLineClass + '"></div></ul>') .appendTo(document.body); if (settings.title) { $('<li class="' + settings.headerClass + '"></li>').text(settings.title).appendTo(menu); } settings.items.forEach(function...
identifier_body
jquery.contextmenu.js
/** * jQuery plugin for Pretty looking right click context menu. * * Requires popup.js and popup.css to be included in your page. And jQuery, obviously. * * Usage: * * $('.something').contextPopup({ * title: 'Some title', * items: [ * {label:'My Item', icon:'/some/icon1.png', action:function()...
menu.remove(); return false; }); // When clicking on a link in menu: clean up (in addition to handlers on link already) menu.find('a').click(function() { bg.remove(); menu.remove(); }); // Cancel event, so real browser popup doesn't appear. return false; }); ...
.bind('contextmenu click', function() { // If click or right click anywhere else on page: remove clean up. bg.remove();
random_line_split