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
directory.rs
use std::collections::HashMap; use std::fmt::{self, Debug, Formatter}; use std::fs::File; use std::io::Read; use std::path::{Path, PathBuf}; use hex::ToHex; use serde_json; use core::{Package, PackageId, Summary, SourceId, Source, Dependency, Registry}; use sources::PathSource; use util::{Config, Sha256}; use util::...
only_dotfile = false; } if only_dotfile { continue } let mut src = PathSource::new(&path, &self.source_id, self.config); src.update()?; let pkg = src.root_package()?; let cksum_file = path.join(".cargo-...
}
random_line_split
directory.rs
use std::collections::HashMap; use std::fmt::{self, Debug, Formatter}; use std::fs::File; use std::io::Read; use std::path::{Path, PathBuf}; use hex::ToHex; use serde_json; use core::{Package, PackageId, Summary, SourceId, Source, Dependency, Registry}; use sources::PathSource; use util::{Config, Sha256}; use util::...
} impl<'cfg> Debug for DirectorySource<'cfg> { fn fmt(&self, f: &mut Formatter) -> fmt::Result { write!(f, "DirectorySource {{ root: {:?} }}", self.root) } } impl<'cfg> Registry for DirectorySource<'cfg> { fn query(&mut self, dep: &Dependency, f: &mut FnMut(Summary)) -> ...
{ DirectorySource { source_id: id.clone(), root: path.to_path_buf(), config: config, packages: HashMap::new(), } }
identifier_body
FrameView.js
/** * The most basic version of a Label control * It holds simple text (with line wrapping) * and is not user editable. */ sk.stsc.view.FrameView = sk.stsc.view.ControlView.extend({ label: null, bgColor: '#353535', initialize: function(options) { this._super('initialize', options); this.setupLabel(); ...
this.drawLabel(); } }, drawBackground: function() { var rgba = 'rgba(160, 160, 160, 0.1)'; var background = new createjs.Shape(); background.graphics.beginFill(this.bgColor) .drawRoundRect(1, 1, this.model.get('width') - 2, this.model.get('height') - 2, 5); this.container['background'].addChild(b...
} if (this.model.get('hasLabel')) {
random_line_split
FrameView.js
/** * The most basic version of a Label control * It holds simple text (with line wrapping) * and is not user editable. */ sk.stsc.view.FrameView = sk.stsc.view.ControlView.extend({ label: null, bgColor: '#353535', initialize: function(options) { this._super('initialize', options); this.setupLabel(); ...
if (this.model.get('hasLabel')) { this.drawLabel(); } }, drawBackground: function() { var rgba = 'rgba(160, 160, 160, 0.1)'; var background = new createjs.Shape(); background.graphics.beginFill(this.bgColor) .drawRoundRect(1, 1, this.model.get('width') - 2, this.model.get('height') - 2, 5); th...
{ this.drawBackground(); }
conditional_block
foundation-sites-tests.ts
// Tests for type definitions for Foundation Sites v6.0.4 // Project: http://foundation.zurb.com/ // Definitions by: Sam Vloeberghs <https://github.com/samvloeberghs/> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// <reference path="../jquery/jquery.d.ts" /> /// <reference path="foundation-sites...
Foundation.AccordionMenu($('.selector')); Foundation.AccordionMenu($('.selector'), {}); Foundation.DrillDown($('.selector')); Foundation.DrillDown($('.selector'), {}); Foundation.Dropdown($('.selector')); Foundation.Dropdown($('.selector'), {}); Foundation.DropdownMenu($('.selector')); Foundation.DropdownMenu($('.se...
random_line_split
0001_initial.py
# -*- coding: utf-8 -*- # Generated by Django 1.11.4 on 2017-09-04 09:48 from __future__ import unicode_literals import api.utils from django.conf import settings from django.db import migrations, models import django.db.models.deletion class
(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='DateMixin', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, s...
Migration
identifier_name
0001_initial.py
# -*- coding: utf-8 -*- # Generated by Django 1.11.4 on 2017-09-04 09:48 from __future__ import unicode_literals import api.utils from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration):
('name', models.CharField(max_length=255)), ('_file', models.FileField(upload_to='files')), ('owner', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='files', to=settings.AUTH_USER_MODEL)), ], bases=('api.datemixin',), ...
initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='DateMixin', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name=...
identifier_body
0001_initial.py
# -*- coding: utf-8 -*- # Generated by Django 1.11.4 on 2017-09-04 09:48 from __future__ import unicode_literals import api.utils from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [...
('file_id', models.CharField(default=api.utils.generate_uid, max_length=20)), ('name', models.CharField(max_length=255)), ('_file', models.FileField(upload_to='files')), ('owner', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name=...
name='File', fields=[ ('datemixin_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='api.DateMixin')),
random_line_split
index.js
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to ...
({ pageAttachment = {} }) { const { displayLinkGuidelines, pageAttachmentContainer, setPageAttachmentContainer, } = useCanvas((state) => ({ displayLinkGuidelines: state.state.displayLinkGuidelines, pageAttachmentContainer: state.state.pageAttachmentContainer, setPageAttachmentContainer: stat...
PageAttachment
identifier_name
index.js
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to ...
width: 24px; vertical-align: middle; background-size: cover; background-repeat: no-repeat; background-position: 50%; border-radius: 50%; background-image: url('${({ icon }) => icon}') !important; `; const spacing = { x: 8 }; const LIGHT_COLOR = '#FFFFFF'; const DARK_COLOR = '#000000'; function PageAtta...
random_line_split
index.js
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to ...
const bgColor = theme === OUTLINK_THEME.DARK ? DARK_COLOR : LIGHT_COLOR; const fgColor = theme === OUTLINK_THEME.DARK ? LIGHT_COLOR : DARK_COLOR; return ( <> {(displayLinkGuidelines || hasInvalidLinkSelected) && <Guideline />} <Wrapper role="presentation" ref={setPageAttachmentContainer}> ...
{ const { displayLinkGuidelines, pageAttachmentContainer, setPageAttachmentContainer, } = useCanvas((state) => ({ displayLinkGuidelines: state.state.displayLinkGuidelines, pageAttachmentContainer: state.state.pageAttachmentContainer, setPageAttachmentContainer: state.actions.setPageAttachmen...
identifier_body
scenarios.js
describe('In class End to End Exercise', function() { 'use strict' beforeEach(function() { browser.get('e2e/index.html') }) it('should work and have header text', function() { expect(element.all(by.css('h1')).first().getText()).toMatch("Dummy Server Example") }) function login() { // grab...
(value) { // find the new status input // type in the new "value" // click the update button } it('should update the status and then set it back', function() { login() // validate the current status message in the <span> var newStatus = "A new status message" setStatus(newStatus) // va...
setStatus
identifier_name
scenarios.js
describe('In class End to End Exercise', function() { 'use strict' beforeEach(function() { browser.get('e2e/index.html') }) it('should work and have header text', function() { expect(element.all(by.css('h1')).first().getText()).toMatch("Dummy Server Example") }) function login() { // grab...
it('should update the status and then set it back', function() { login() // validate the current status message in the <span> var newStatus = "A new status message" setStatus(newStatus) // validate the new status message in the <span> // revert back to the old status message // setStatus...
{ // find the new status input // type in the new "value" // click the update button }
identifier_body
scenarios.js
describe('In class End to End Exercise', function() { 'use strict' beforeEach(function() { browser.get('e2e/index.html') }) it('should work and have header text', function() { expect(element.all(by.css('h1')).first().getText()).toMatch("Dummy Server Example") }) function login() { // grab...
var newStatus = "A new status message" setStatus(newStatus) // validate the new status message in the <span> // revert back to the old status message // setStatus(status) // validate it is correctly reverted in the <span> logout() }) })
login() // validate the current status message in the <span>
random_line_split
main.py
from umqtt.simple import MQTTClient from machine import Pin import ubinascii import machine import time import network # Default MQTT server to connect to SERVER = "m11.cloudmqtt.com" PORT = 15034 CLIENT_ID = ubinascii.hexlify(machine.unique_id()) TOPIC = b"hello/world" USER = "oyqmvonl" PASSWORD = "eCPIJkxVFWBU" ...
time.sleep(2) finally: c.disconnect() if __name__ == "__main__": main()
try: print('try reconnect...') c.connect(False) break except: print('error on reconnect...') time.sleep(2)
conditional_block
main.py
from umqtt.simple import MQTTClient from machine import Pin import ubinascii import machine import time import network # Default MQTT server to connect to SERVER = "m11.cloudmqtt.com" PORT = 15034 CLIENT_ID = ubinascii.hexlify(machine.unique_id()) TOPIC = b"hello/world" USER = "oyqmvonl" PASSWORD = "eCPIJkxVFWBU" ...
print('error on reconnect...') time.sleep(2) time.sleep(2) finally: c.disconnect() if __name__ == "__main__": main()
print('try reconnect...') c.connect(False) break except:
random_line_split
main.py
from umqtt.simple import MQTTClient from machine import Pin import ubinascii import machine import time import network # Default MQTT server to connect to SERVER = "m11.cloudmqtt.com" PORT = 15034 CLIENT_ID = ubinascii.hexlify(machine.unique_id()) TOPIC = b"hello/world" USER = "oyqmvonl" PASSWORD = "eCPIJkxVFWBU" ...
(): do_connect_wifi() c = MQTTClient(CLIENT_ID, SERVER, PORT, USER, PASSWORD) # Subscribed messages will be delivered to this callback c.set_callback(sub_cb) c.connect(clean_session=False) c.subscribe(TOPIC,qos=1) print("Connected to %s, subscribed to %s topic" % (SERVER, TOPIC)) ...
main
identifier_name
main.py
from umqtt.simple import MQTTClient from machine import Pin import ubinascii import machine import time import network # Default MQTT server to connect to SERVER = "m11.cloudmqtt.com" PORT = 15034 CLIENT_ID = ubinascii.hexlify(machine.unique_id()) TOPIC = b"hello/world" USER = "oyqmvonl" PASSWORD = "eCPIJkxVFWBU" ...
def sub_cb(topic, msg): print((topic, msg)) if msg == b"0": led.value(0) elif msg == b"1": led.value(1) def main(): do_connect_wifi() c = MQTTClient(CLIENT_ID, SERVER, PORT, USER, PASSWORD) # Subscribed messages will be delivered to this callback c.set_callback(sub...
sta_if = network.WLAN(network.STA_IF) if not sta_if.isconnected(): print('connecting to network...') sta_if.active(True) sta_if.connect('SSID_GO_HERE', 'PASS_HERE') while not sta_if.isconnected(): pass print('network config:', sta_if.ifconfig())
identifier_body
getRenderProperties.js
/* global HTMLImageElement */ /* global HTMLCanvasElement */ /* global SVGElement */ import getOptionsFromElement from "./getOptionsFromElement.js"; import renderers from "../renderers"; import {InvalidElementException} from "../exceptions/exceptions.js"; // Takes an element and returns an object with information ab...
// If the element is a string, query select call again if(typeof element === "string"){ return querySelectedRenderProperties(element); } // If element is array. Recursivly call with every object in the array else if(Array.isArray(element)){ var returnArray = []; for(let i = 0; i < element.length; i++){ re...
// } function getRenderProperties(element){
random_line_split
getRenderProperties.js
/* global HTMLImageElement */ /* global HTMLCanvasElement */ /* global SVGElement */ import getOptionsFromElement from "./getOptionsFromElement.js"; import renderers from "../renderers"; import {InvalidElementException} from "../exceptions/exceptions.js"; // Takes an element and returns an object with information ab...
} function querySelectedRenderProperties(string){ var selector = document.querySelectorAll(string); if(selector.length === 0){ return undefined; } else{ let returnArray = []; for(let i = 0; i < selector.length; i++){ returnArray.push(getRenderProperties(selector[i])); } return returnArray; } } fun...
{ throw new InvalidElementException(); }
conditional_block
getRenderProperties.js
/* global HTMLImageElement */ /* global HTMLCanvasElement */ /* global SVGElement */ import getOptionsFromElement from "./getOptionsFromElement.js"; import renderers from "../renderers"; import {InvalidElementException} from "../exceptions/exceptions.js"; // Takes an element and returns an object with information ab...
(imgElement){ var canvas = document.createElement('canvas'); return { element: canvas, options: getOptionsFromElement(imgElement), renderer: renderers.CanvasRenderer, afterRender: function(){ imgElement.setAttribute("src", canvas.toDataURL()); } }; } export default getRenderProperties;
newCanvasRenderProperties
identifier_name
getRenderProperties.js
/* global HTMLImageElement */ /* global HTMLCanvasElement */ /* global SVGElement */ import getOptionsFromElement from "./getOptionsFromElement.js"; import renderers from "../renderers"; import {InvalidElementException} from "../exceptions/exceptions.js"; // Takes an element and returns an object with information ab...
export default getRenderProperties;
{ var canvas = document.createElement('canvas'); return { element: canvas, options: getOptionsFromElement(imgElement), renderer: renderers.CanvasRenderer, afterRender: function(){ imgElement.setAttribute("src", canvas.toDataURL()); } }; }
identifier_body
achievementIcons.spec.ts
import { expect } from 'chai'; import { BadgeUp } from './../src'; const bup = new BadgeUp({ apiKey: 'eyJhY2NvdW50SWQiOiJ0aGViZXN0IiwiYXBwbGljYXRpb25JZCI6IjEzMzciLCJrZXkiOiJpY2VjcmVhbWFuZGNvb2tpZXN5dW0ifQ==' }); describe('achievement icons', function() { it('should get all achievement icons', async function() ...
function _validate(options) { expect(options.method).to.equal('DELETE'); expect(options.url).to.equal('/v2/apps/1337/achievementicons/myIcon.png'); } await bup.achievementIcons.remove('myIcon.png', { _payload, _validate }); }); });
{ return Promise.resolve({ url: 'url', fileName: 'myIcon.png' }); }
identifier_body
achievementIcons.spec.ts
import { expect } from 'chai'; import { BadgeUp } from './../src'; const bup = new BadgeUp({ apiKey: 'eyJhY2NvdW50SWQiOiJ0aGViZXN0IiwiYXBwbGljYXRpb25JZCI6IjEzMzciLCJrZXkiOiJpY2VjcmVhbWFuZGNvb2tpZXN5dW0ifQ==' }); describe('achievement icons', function() { it('should get all achievement icons', async function() ...
(options) { expect(options.method).to.equal('DELETE'); expect(options.url).to.equal('/v2/apps/1337/achievementicons/myIcon.png'); } await bup.achievementIcons.remove('myIcon.png', { _payload, _validate }); }); });
_validate
identifier_name
achievementIcons.spec.ts
import { expect } from 'chai'; import { BadgeUp } from './../src'; const bup = new BadgeUp({ apiKey: 'eyJhY2NvdW50SWQiOiJ0aGViZXN0IiwiYXBwbGljYXRpb25JZCI6IjEzMzciLCJrZXkiOiJpY2VjcmVhbWFuZGNvb2tpZXN5dW0ifQ==' }); describe('achievement icons', function() { it('should get all achievement icons', async function() ...
await bup.achievementIcons.remove('myIcon.png', { _payload, _validate }); }); });
expect(options.url).to.equal('/v2/apps/1337/achievementicons/myIcon.png'); }
random_line_split
texttrackcue.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 https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::cell::DomRefCell; use crate::dom::bindings::codegen::Bindings::TextTrackCueBinding::{se...
(&self, value: DOMString) { *self.id.borrow_mut() = value; } // https://html.spec.whatwg.org/multipage/#dom-texttrackcue-track fn GetTrack(&self) -> Option<DomRoot<TextTrack>> { self.get_track() } // https://html.spec.whatwg.org/multipage/#dom-texttrackcue-starttime fn StartTim...
SetId
identifier_name
texttrackcue.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 https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::cell::DomRefCell; use crate::dom::bindings::codegen::Bindings::TextTrackCueBinding::{se...
// https://html.spec.whatwg.org/multipage/#handler-texttrackcue-onenter event_handler!(enter, GetOnenter, SetOnenter); // https://html.spec.whatwg.org/multipage/#handler-texttrackcue-onexit event_handler!(exit, GetOnexit, SetOnexit); }
}
random_line_split
texttrackcue.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 https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::cell::DomRefCell; use crate::dom::bindings::codegen::Bindings::TextTrackCueBinding::{se...
pub fn get_track(&self) -> Option<DomRoot<TextTrack>> { self.track.as_ref().map(|t| DomRoot::from_ref(&**t)) } } impl TextTrackCueMethods for TextTrackCue { // https://html.spec.whatwg.org/multipage/#dom-texttrackcue-id fn Id(&self) -> DOMString { self.id() } // https://html....
{ self.id.borrow().clone() }
identifier_body
legacy.py
#!/usr/bin/env python3 # -*- coding: UTF-8 -*- # # Easy AVR USB Keyboard Firmware Keymapper # Copyright (C) 2018 David Howland # # 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 ...
(Exception): """Raised when an error is encountered while loading a legacy layout file.""" pass def load_legacy(user_data, datfile): """Load the legacy .dat save file from the path given by `datfile` and populate the UserData object given by `user_data`. """ legacy_data = open_legacy(datfile) ...
LegacySaveFileException
identifier_name
legacy.py
#!/usr/bin/env python3 # -*- coding: UTF-8 -*- # # Easy AVR USB Keyboard Firmware Keymapper # Copyright (C) 2018 David Howland # # 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 ...
map = Map(legacy_data['maps'][layer][ri][ci], key_mode_map[legacy_data['modes'][layer][ri][ci]], legacy_data['actions'][layer][ri][ci], legacy_data['wmods'][layer][ri][ci]) user_data.keymap[...
"""Converts the data from a legacy save file into a `user_data` object. `user_data` should be a fresh instance of UserData and `legacy_data` is the output from a successful call to open_legacy(). """ # can't save to legacy file user_data.path = None # get good defaults to start from user_da...
identifier_body
legacy.py
#!/usr/bin/env python3 # -*- coding: UTF-8 -*- # # Easy AVR USB Keyboard Firmware Keymapper # Copyright (C) 2018 David Howland # # 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 ...
the UserData object given by `user_data`. """ legacy_data = open_legacy(datfile) convert_legacy(user_data, legacy_data) def open_legacy(datfile): """Opens and decodes the pickled data in a legacy .dat save file. `datfile` is a path to the file. The function returns a dictionary with an item ...
pass def load_legacy(user_data, datfile): """Load the legacy .dat save file from the path given by `datfile` and populate
random_line_split
legacy.py
#!/usr/bin/env python3 # -*- coding: UTF-8 -*- # # Easy AVR USB Keyboard Firmware Keymapper # Copyright (C) 2018 David Howland # # 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 ...
if len(data) > 13: ledlayers = data[13] else: ledlayers = [0, 0, 0, 0, 0] # fixes for older versions (renamed layers) for kmap in (maps, actions, modes, wmods): if 'Fn' in kmap: kmap['Layer 1'] = kmap['Fn'] del kmap['Fn'] # fixes for o...
advancedleds = [(255, 0)] * len(led_assignments) useadvancedleds = False
conditional_block
dijkstra.rs
use std::hash::Hash; use collections::hashmap::HashMap; use collections::hashmap::HashSet; /// Build a Dijkstra map starting from the goal nodes and using the neighbors /// function to define the graph to up to limit distance. pub fn
<N: Hash + Eq + Clone>( goals: ~[N], neighbors: |&N| -> ~[N], limit: uint) -> HashMap<N, uint> { assert!(goals.len() > 0); let mut ret = HashMap::new(); // Init goal nodes to zero score. for k in goals.iter() { ret.insert(k.clone(), 0); } let mut edge = ~HashSet::new(); for k ...
build_map
identifier_name
dijkstra.rs
use std::hash::Hash; use collections::hashmap::HashMap; use collections::hashmap::HashSet; /// Build a Dijkstra map starting from the goal nodes and using the neighbors /// function to define the graph to up to limit distance. pub fn build_map<N: Hash + Eq + Clone>( goals: ~[N], neighbors: |&N| -> ~[N], limit: uin...
} } edge = new_edge; } ret }
{ new_edge.insert(n.clone()); }
conditional_block
dijkstra.rs
use std::hash::Hash; use collections::hashmap::HashMap; use collections::hashmap::HashSet; /// Build a Dijkstra map starting from the goal nodes and using the neighbors /// function to define the graph to up to limit distance. pub fn build_map<N: Hash + Eq + Clone>( goals: ~[N], neighbors: |&N| -> ~[N], limit: uin...
// Init goal nodes to zero score. for k in goals.iter() { ret.insert(k.clone(), 0); } let mut edge = ~HashSet::new(); for k in goals.iter() { for n in neighbors(k).iter() { // XXX: Extra clone op here, should just shuffle references until // things get clon...
assert!(goals.len() > 0); let mut ret = HashMap::new();
random_line_split
dijkstra.rs
use std::hash::Hash; use collections::hashmap::HashMap; use collections::hashmap::HashSet; /// Build a Dijkstra map starting from the goal nodes and using the neighbors /// function to define the graph to up to limit distance. pub fn build_map<N: Hash + Eq + Clone>( goals: ~[N], neighbors: |&N| -> ~[N], limit: uin...
for k in edge.iter() { ret.insert(k.clone(), dist); } let mut new_edge = ~HashSet::new(); for k in edge.iter() { for n in neighbors(k).iter() { if !ret.contains_key(n) { new_edge.insert(n.clone()); } } } edge = new_edg...
{ assert!(goals.len() > 0); let mut ret = HashMap::new(); // Init goal nodes to zero score. for k in goals.iter() { ret.insert(k.clone(), 0); } let mut edge = ~HashSet::new(); for k in goals.iter() { for n in neighbors(k).iter() { // XXX: Extra clone op here, s...
identifier_body
app.ts
import "reflect-metadata"; import {ConnectionOptions, createConnection} from "../../src/index"; import {Post} from "./entity/Post"; import {Author} from "./entity/Author"; const options: ConnectionOptions = { type: "mysql", host: "localhost", port: 3306, username: "root", password: "admin", dat...
host: "localhost", port: 3306, username: "test", password: "test", database: "test", logging: ["query", "error"], entities: [ Post, Author ], migrations: [ __dirname + "/migrations/*{.js,.ts}" ] }); ...
// now create a new connection connection = await createConnection({ type: "mysql", name: "mysql",
random_line_split
state.rs
// Copyleft (ↄ) meh. <meh@schizofreni.co> | http://meh.schizofreni.co // // This file is part of cancer. // // cancer 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 // (a...
/// The current margins. pub fn margin(&self) -> &Margin { &self.margin } /// Resize the state. pub fn resize(&mut self, width: u32, height: u32) { let (m, s) = (self.config.style().margin(), self.config.style().spacing()); self.margin.horizontal = m + ((width - (m * 2)) % self.font.width()) / 2; sel...
(self.width - (self.margin.horizontal * 2)) / self.font.width() }
identifier_body
state.rs
// Copyleft (ↄ) meh. <meh@schizofreni.co> | http://meh.schizofreni.co // // This file is part of cancer. // // cancer 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 // (a...
lse { 0 }) } }
1 } e
conditional_block
state.rs
// Copyleft (ↄ) meh. <meh@schizofreni.co> | http://meh.schizofreni.co // // This file is part of cancer. // // cancer 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 // (a...
mut self, width: u32, height: u32) { let (m, s) = (self.config.style().margin(), self.config.style().spacing()); self.margin.horizontal = m + ((width - (m * 2)) % self.font.width()) / 2; self.margin.vertical = m + ((height - (m * 2)) % (self.font.height() + s)) / 2; self.width = width; self.height =...
size(&
identifier_name
state.rs
// Copyleft (ↄ) meh. <meh@schizofreni.co> | http://meh.schizofreni.co // // This file is part of cancer. // // cancer 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 // (a...
.saturating_sub(h.saturating_sub(self.width - (region.x + region.width))) as f32; // Remove margins from height. let h = region.height .saturating_sub(v.saturating_sub(region.y)) .saturating_sub(v.saturating_sub(self.height - (region.y + region.height))) as f32; let x = (x / width).floor() as u32; le...
random_line_split
func_unused_overridden_argument.py
# pylint: disable=R0903, print-statement """for Sub.inherited, only the warning for "aay" is desired. The warnings for "aab" and "aac" are most likely false positives though, because there could be another subclass that overrides the same method and does use the arguments (eg Sub2) """ __revision__ = 'thx to M...
"parent" def inherited(self, aaa, aab, aac): "abstract method" raise NotImplementedError class Sub(Base): "child 1" def inherited(self, aaa, aab, aac): "overridden method, though don't use every argument" return aaa def newmethod(self, aax, aay): ...
random_line_split
func_unused_overridden_argument.py
# pylint: disable=R0903, print-statement """for Sub.inherited, only the warning for "aay" is desired. The warnings for "aab" and "aac" are most likely false positives though, because there could be another subclass that overrides the same method and does use the arguments (eg Sub2) """ __revision__ = 'thx to M...
"overridden method, use every argument" return aaa + aab + aac
identifier_body
func_unused_overridden_argument.py
# pylint: disable=R0903, print-statement """for Sub.inherited, only the warning for "aay" is desired. The warnings for "aab" and "aac" are most likely false positives though, because there could be another subclass that overrides the same method and does use the arguments (eg Sub2) """ __revision__ = 'thx to M...
(self, aaa, aab, aac): "abstract method" raise NotImplementedError class Sub(Base): "child 1" def inherited(self, aaa, aab, aac): "overridden method, though don't use every argument" return aaa def newmethod(self, aax, aay): "another method, warning for a...
inherited
identifier_name
index.js
/** * Copyright 2014 Shape Security, Inc. * * 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 a...
{ return ScopeAnalyzer.analyze(script); }
identifier_body
index.js
/** * Copyright 2014 Shape Security, Inc. * * 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 a...
(script) { return ScopeAnalyzer.analyze(script); }
analyze
identifier_name
index.js
/** * Copyright 2014 Shape Security, Inc. * * 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 a...
export {DeclarationType} from "./declaration"; export {Accessibility} from "./reference"; export default function analyze(script) { return ScopeAnalyzer.analyze(script); }
require('es6-symbol/implement'); import ScopeAnalyzer from "./scope-analyzer"; export {ScopeType} from "./scope";
random_line_split
size_of_in_element_count.rs
//! Lint on use of `size_of` or `size_of_val` of T in an expression //! expecting a count of T use clippy_utils::diagnostics::span_lint_and_help; use clippy_utils::{match_def_path, paths}; use if_chain::if_chain; use rustc_hir::BinOpKind; use rustc_hir::{Expr, ExprKind}; use rustc_lint::{LateContext, LateLintPass}; us...
(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) -> Option<(Ty<'tcx>, &'tcx Expr<'tcx>)> { const FUNCTIONS: [&[&str]; 8] = [ &paths::PTR_COPY_NONOVERLAPPING, &paths::PTR_COPY, &paths::PTR_WRITE_BYTES, &paths::PTR_SWAP_NONOVERLAPPING, &paths::PTR_SLICE_FROM_RAW_PARTS, &p...
get_pointee_ty_and_count_expr
identifier_name
size_of_in_element_count.rs
//! Lint on use of `size_of` or `size_of_val` of T in an expression //! expecting a count of T use clippy_utils::diagnostics::span_lint_and_help; use clippy_utils::{match_def_path, paths}; use if_chain::if_chain; use rustc_hir::BinOpKind; use rustc_hir::{Expr, ExprKind}; use rustc_lint::{LateContext, LateLintPass}; us...
count_expr.span, LINT_MSG, None, HELP_MSG ); } }; } }
{ const HELP_MSG: &str = "use a count of elements instead of a count of bytes\ , it already gets multiplied by the size of the type"; const LINT_MSG: &str = "found a count of bytes \ instead of a count of elements of `T`"; if_chain! { // Find calls to funct...
identifier_body
size_of_in_element_count.rs
//! Lint on use of `size_of` or `size_of_val` of T in an expression //! expecting a count of T use clippy_utils::diagnostics::span_lint_and_help; use clippy_utils::{match_def_path, paths}; use if_chain::if_chain; use rustc_hir::BinOpKind; use rustc_hir::{Expr, ExprKind}; use rustc_lint::{LateContext, LateLintPass}; us...
); } }; } }
None, HELP_MSG
random_line_split
crypto.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any lat...
let cipher = match (cipher, cipherparams) { (Some(CipherSer::Aes128Ctr), Some(CipherSerParams::Aes128Ctr(params))) => Cipher::Aes128Ctr(params), (None, _) => return Err(V::Error::missing_field("cipher")), (Some(_), None) => return Err(V::Error::missing_field("cipherparams")), }; let ciphertext = match c...
}
random_line_split
crypto.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any lat...
fn visit_map<V>(self, mut visitor: V) -> Result<Self::Value, V::Error> where V: MapVisitor { let mut cipher = None; let mut cipherparams = None; let mut ciphertext = None; let mut kdf = None; let mut kdfparams = None; let mut mac = None; loop { match visitor.visit_key()? { Some(CryptoField::...
{ write!(formatter, "a valid vault crypto object") }
identifier_body
crypto.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any lat...
<E>(self, value: &str) -> Result<Self::Value, E> where E: Error { match value { "cipher" => Ok(CryptoField::Cipher), "cipherparams" => Ok(CryptoField::CipherParams), "ciphertext" => Ok(CryptoField::CipherText), "kdf" => Ok(CryptoField::Kdf), "kdfparams" => Ok(CryptoField::KdfParams), "mac" => Ok(...
visit_str
identifier_name
directive.rs
use std::collections::hash_map::Entry; use syn::parse; use syn::Token; use quote::quote; use proc_macro_error::emit_error; use crate::common::{Stmt, Size, delimited}; use crate::arch; use crate::DynasmContext; use crate::parse_helpers::ParseOptExt; pub(crate) fn evaluate_directive(invocation_context: &mut DynasmCont...
} Ok(()) } /// In case a directive is unknown, try to skip up to the next ; and resume parsing. fn skip_until_semicolon(input: parse::ParseStream) { let _ = input.step(|cursor| { let mut rest = *cursor; while let Some((tt, next)) = rest.token_tree() { match tt { ...
{ let expr: syn::Expr = input.parse()?; stmts.push(Stmt::ExprSigned(delimited(expr), size)); }
conditional_block
directive.rs
use std::collections::hash_map::Entry; use syn::parse; use syn::Token; use quote::quote; use proc_macro_error::emit_error; use crate::common::{Stmt, Size, delimited}; use crate::arch; use crate::DynasmContext; use crate::parse_helpers::ParseOptExt; pub(crate) fn evaluate_directive(invocation_context: &mut DynasmCont...
"byte" => directive_const(invocation_context, stmts, input, Size::BYTE)?, "word" => directive_const(invocation_context, stmts, input, Size::WORD)?, "dword" => directive_const(invocation_context, stmts, input, Size::DWORD)?, "qword" => directive_const(invocation_context, stmts, input, S...
invocation_context.current_arch.set_features(&features); }, // ; .byte (expr ("," expr)*)?
random_line_split
directive.rs
use std::collections::hash_map::Entry; use syn::parse; use syn::Token; use quote::quote; use proc_macro_error::emit_error; use crate::common::{Stmt, Size, delimited}; use crate::arch; use crate::DynasmContext; use crate::parse_helpers::ParseOptExt; pub(crate) fn evaluate_directive(invocation_context: &mut DynasmCont...
while input.peek(Token![,]) { let _: Token![,] = input.parse()?; let ident: syn::Ident = input.parse()?; features.push(ident); } // ;.feature none cancels all features if features.len() == 1 && features[0] == "none" { ...
{ let directive: syn::Ident = input.parse()?; match directive.to_string().as_str() { // TODO: oword, qword, float, double, long double "arch" => { // ; .arch ident let arch: syn::Ident = input.parse()?; if let Some(a) = arch::from_str(arch.to_string().as_str...
identifier_body
directive.rs
use std::collections::hash_map::Entry; use syn::parse; use syn::Token; use quote::quote; use proc_macro_error::emit_error; use crate::common::{Stmt, Size, delimited}; use crate::arch; use crate::DynasmContext; use crate::parse_helpers::ParseOptExt; pub(crate) fn
(invocation_context: &mut DynasmContext, stmts: &mut Vec<Stmt>, input: parse::ParseStream) -> parse::Result<()> { let directive: syn::Ident = input.parse()?; match directive.to_string().as_str() { // TODO: oword, qword, float, double, long double "arch" => { // ; .arch ident ...
evaluate_directive
identifier_name
useDateTimePickerAdapter.ts
/* eslint-disable class-methods-use-this */ import DayjsAdapter from '@date-io/dayjs'; import dayjs from 'dayjs'; import { equals, isNil } from 'ramda'; import { useAtomValue } from 'jotai/utils'; import { useLocaleDateTimeFormat } from '@centreon/ui'; import { userAtom } from '@centreon/ui-context'; interface UseDat...
extends DayjsAdapter { public formatByString = (value, formatKey: string): string => { return format({ date: value.tz(timezone), formatString: formatKey }); }; public isEqual = (value, comparing): boolean => { if (value === null && comparing === null) { return true; } retu...
Adapter
identifier_name
useDateTimePickerAdapter.ts
/* eslint-disable class-methods-use-this */ import DayjsAdapter from '@date-io/dayjs'; import dayjs from 'dayjs'; import { equals, isNil } from 'ramda'; import { useAtomValue } from 'jotai/utils'; import { useLocaleDateTimeFormat } from '@centreon/ui'; import { userAtom } from '@centreon/ui-context'; interface UseDat...
return equals( format({ date: value, formatString: 'LT' }), format({ date: comparing, formatString: 'LT' }), ); }; public getHours = (date): number => { return date.tz(timezone).get('hour'); }; public setHours = (date: dayjs.Dayjs, count: number): dayjs.Dayjs => { ...
{ return true; }
conditional_block
useDateTimePickerAdapter.ts
/* eslint-disable class-methods-use-this */ import DayjsAdapter from '@date-io/dayjs'; import dayjs from 'dayjs'; import { equals, isNil } from 'ramda'; import { useAtomValue } from 'jotai/utils'; import { useLocaleDateTimeFormat } from '@centreon/ui'; import { userAtom } from '@centreon/ui-context'; interface UseDat...
}; class Adapter extends DayjsAdapter { public formatByString = (value, formatKey: string): string => { return format({ date: value.tz(timezone), formatString: formatKey }); }; public isEqual = (value, comparing): boolean => { if (value === null && comparing === null) { return true...
const day = value.substring(3, 5); const newValue = `${day}/${month}/${value.substring(6, 16)}`; return newValue;
random_line_split
upgrade.js
/* eslint-disable */ /* global MessageBus, bootbox */ import Repo from "manager-client/models/repo"; import Controller from "@ember/controller"; import { equal } from "@ember/object/computed"; import { computed } from "@ember/object"; export default Controller.extend({ output: null, init() { this._super(); ...
() { MessageBus.subscribe("/docker/upgrade", (msg) => { this.messageReceived(msg); }); }, stopBus() { MessageBus.unsubscribe("/docker/upgrade"); }, reset() { this.setProperties({ output: "", status: null, percent: 0 }); }, actions: { start() { this.reset(); if (this...
startBus
identifier_name
upgrade.js
/* eslint-disable */ /* global MessageBus, bootbox */ import Repo from "manager-client/models/repo"; import Controller from "@ember/controller"; import { equal } from "@ember/object/computed"; import { computed } from "@ember/object"; export default Controller.extend({ output: null, init()
, complete: equal("status", "complete"), failed: equal("status", "failed"), multiUpgrade: computed("model.length", function () { return this.get("model.length") !== 1; }), title: computed("model.@each.name", function () { return this.get("multiUpgrade") ? "All" : this.get("model")[0].get("name"); ...
{ this._super(); this.reset(); }
identifier_body
upgrade.js
/* eslint-disable */ /* global MessageBus, bootbox */ import Repo from "manager-client/models/repo"; import Controller from "@ember/controller"; import { equal } from "@ember/object/computed"; import { computed } from "@ember/object"; export default Controller.extend({ output: null, init() { this._super(); ...
}), startBus() { MessageBus.subscribe("/docker/upgrade", (msg) => { this.messageReceived(msg); }); }, stopBus() { MessageBus.unsubscribe("/docker/upgrade"); }, reset() { this.setProperties({ output: "", status: null, percent: 0 }); }, actions: { start() { this.reset(...
{ return "Start Upgrading"; }
conditional_block
upgrade.js
/* eslint-disable */ /* global MessageBus, bootbox */ import Repo from "manager-client/models/repo"; import Controller from "@ember/controller"; import { equal } from "@ember/object/computed"; import { computed } from "@ember/object"; export default Controller.extend({ output: null, init() { this._super(); ...
MessageBus.unsubscribe("/docker/upgrade"); }, reset() { this.setProperties({ output: "", status: null, percent: 0 }); }, actions: { start() { this.reset(); if (this.get("multiUpgrade")) { this.get("model") .filter((repo) => !repo.get("upToDate")) .forEach((...
stopBus() {
random_line_split
Plane.ts
import {Primitive} from "./Primitive"; import {Vec3f} from "./Vec3f"; import {Ray} from "./Ray"; import {Intersection} from "./Intersection"; import {Config} from "../Config"; export class Plane extends Primitive { public normal:Vec3f; constructor(pos:Vec3f, normal:Vec3f) { super(pos); this.t...
if (t < Config.epsilon) return null; var x:Intersection = new Intersection(); x.setPos(r.getPos().add(r.getDir().scale(t))); x.setNorm(this.normal.normalize()); x.setT(t); return x; } static cast(obj):Plane{ var plane:Plane = new Plane(new ...
t = P.dot(this.normal) / d;
random_line_split
Plane.ts
import {Primitive} from "./Primitive"; import {Vec3f} from "./Vec3f"; import {Ray} from "./Ray"; import {Intersection} from "./Intersection"; import {Config} from "../Config"; export class
extends Primitive { public normal:Vec3f; constructor(pos:Vec3f, normal:Vec3f) { super(pos); this.type = "plane"; this.normal = normal; } intersect(r:Ray):Intersection { var P:Vec3f; var d:number; var t:number; P = this.vertices[0].sub(r.getPos...
Plane
identifier_name
en-ca.js
/* */ "format cjs"; (function(factory) { if (typeof define === 'function' && define.amd) { define(["moment"], factory); } else if (typeof exports === 'object') { module.exports = factory(require("../moment")); } else { factory((typeof global !== 'undefined' ? global : this).moment); } }(function(mo...
var b = number % 10, output = (~~(number % 100 / 10) === 1) ? 'th' : (b === 1) ? 'st' : (b === 2) ? 'nd' : (b === 3) ? 'rd' : 'th'; return number + output; } }); }));
y: 'a year', yy: '%d years' }, ordinalParse: /\d{1,2}(st|nd|rd|th)/, ordinal: function(number) {
random_line_split
utils.js
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var Cookie = exports.Cookie = { createCookie: function createCookie(name, value, expireTime) { expireTime = !!expireTime ? expireTime : 15 * 60 * 1000; // Default 15 min var date = new Date(); date.setTime(date...
}, deleteCookie: function deleteCookie(name) { document.cookie = name + '=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;'; } };
{ return parts.pop().split(";").shift(); }
conditional_block
utils.js
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var Cookie = exports.Cookie = { createCookie: function createCookie(name, value, expireTime) { expireTime = !!expireTime ? expireTime : 15 * 60 * 1000; // Default 15 min var date = new Date(); date.setTime(date...
if (parts.length == 2) { return parts.pop().split(";").shift(); } }, deleteCookie: function deleteCookie(name) { document.cookie = name + '=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;'; } };
getCookie: function getCookie(name) { var value = "; " + document.cookie; var parts = value.split("; " + name + "=");
random_line_split
L0MSBuildLocation.ts
import ma = require('vsts-task-lib/mock-answer'); import tmrm = require('vsts-task-lib/mock-run'); import path = require('path'); import os = require('os'); let taskPath = path.join(__dirname, '..', 'xamarinios.js'); let tr: tmrm.TaskMockRunner = new tmrm.TaskMockRunner(taskPath);
tr.setInput('args', ''); tr.setInput('clean', 'true'); tr.setInput('packageApp', ''); //boolean tr.setInput('forSimulator', ''); //boolean tr.setInput('runNugetRestore', 'true'); //boolean tr.setInput('iosSigningIdentity', ''); tr.setInput('provProfileUuid', ''); tr.setInput('buildToolLocation', '/home/bin/msbuild'); ...
process.env['HOME']='/user/home'; //replace with mock of setVariable when task-lib has the support tr.setInput('solution', 'src/project.sln'); //path tr.setInput('configuration', 'Release');
random_line_split
main.rs
use std::env; use std::path::Path; use std::process::{Command, Output}; fn check_html_file(file: &Path) -> usize { let to_mute = &[ // "disabled" on <link> or "autocomplete" on <select> emit this warning "PROPRIETARY_ATTRIBUTE", // It complains when multiple in the same page link to the sam...
() -> Result<(), String> { let args = env::args().collect::<Vec<_>>(); if args.len() != 2 { return Err(format!("Usage: {} <doc folder>", args[0])); } println!("Running HTML checker..."); let (files_read, errors) = find_all_html_files(&Path::new(&args[1])); println!("Done! Read {} files...
main
identifier_name
main.rs
use std::env; use std::path::Path; use std::process::{Command, Output}; fn check_html_file(file: &Path) -> usize { let to_mute = &[ // "disabled" on <link> or "autocomplete" on <select> emit this warning "PROPRIETARY_ATTRIBUTE", // It complains when multiple in the same page link to the sam...
.to_str() .map(|s| DOCS_TO_CHECK.into_iter().any(|d| *d == s)) .unwrap_or(false) }) { let entry = entry.expect("failed to read file"); if !entry.file_type().is_file() { continue; } let entry = entry.path(); if entry....
let mut errors = 0; for entry in walkdir::WalkDir::new(dir).into_iter().filter_entry(|e| { e.depth() != 1 || e.file_name()
random_line_split
main.rs
use std::env; use std::path::Path; use std::process::{Command, Output}; fn check_html_file(file: &Path) -> usize { let to_mute = &[ // "disabled" on <link> or "autocomplete" on <select> emit this warning "PROPRIETARY_ATTRIBUTE", // It complains when multiple in the same page link to the sam...
} (files_read, errors) } fn main() -> Result<(), String> { let args = env::args().collect::<Vec<_>>(); if args.len() != 2 { return Err(format!("Usage: {} <doc folder>", args[0])); } println!("Running HTML checker..."); let (files_read, errors) = find_all_html_files(&Path::new(&ar...
{ let mut files_read = 0; let mut errors = 0; for entry in walkdir::WalkDir::new(dir).into_iter().filter_entry(|e| { e.depth() != 1 || e.file_name() .to_str() .map(|s| DOCS_TO_CHECK.into_iter().any(|d| *d == s)) .unwrap_or(false) }) { ...
identifier_body
main.rs
use std::env; use std::path::Path; use std::process::{Command, Output}; fn check_html_file(file: &Path) -> usize { let to_mute = &[ // "disabled" on <link> or "autocomplete" on <select> emit this warning "PROPRIETARY_ATTRIBUTE", // It complains when multiple in the same page link to the sam...
} (files_read, errors) } fn main() -> Result<(), String> { let args = env::args().collect::<Vec<_>>(); if args.len() != 2 { return Err(format!("Usage: {} <doc folder>", args[0])); } println!("Running HTML checker..."); let (files_read, errors) = find_all_html_files(&Path::new(&ar...
{ errors += check_html_file(&entry); files_read += 1; }
conditional_block
sorting.rs
#![feature(test)] extern crate test; extern crate rand; extern crate algs4; use test::Bencher; use rand::{thread_rng, Rng}; use algs4::sorting::*; use algs4::sorting::quicksort::{quick_sort_3way, quick_sort_orig};
// for small array // static SIZE: usize = 10; macro_rules! defbench( ($name:ident, $func:ident) => ( defbench!($name, $func, f64, SIZE); ); ($name:ident, $func:ident, $typ:ty) => ( defbench!($name, $func, $typ, SIZE); ); ($name:ident, $func:ident, $typ:ty, $size:expr) => ( ...
use algs4::fundamentals::knuth_shuffle; static SIZE: usize = 1000;
random_line_split
sorting.rs
#![feature(test)] extern crate test; extern crate rand; extern crate algs4; use test::Bencher; use rand::{thread_rng, Rng}; use algs4::sorting::*; use algs4::sorting::quicksort::{quick_sort_3way, quick_sort_orig}; use algs4::fundamentals::knuth_shuffle; static SIZE: usize = 1000; // for small array // static SIZE: ...
{ let array = thread_rng().gen_iter().take(SIZE).collect::<Vec<f64>>(); b.iter(|| { let mut array = array.clone(); knuth_shuffle(&mut array); }); }
identifier_body
sorting.rs
#![feature(test)] extern crate test; extern crate rand; extern crate algs4; use test::Bencher; use rand::{thread_rng, Rng}; use algs4::sorting::*; use algs4::sorting::quicksort::{quick_sort_3way, quick_sort_orig}; use algs4::fundamentals::knuth_shuffle; static SIZE: usize = 1000; // for small array // static SIZE: ...
(b: &mut Bencher) { let array = thread_rng().gen_iter().take(SIZE).collect::<Vec<f64>>(); b.iter(|| { let mut array = array.clone(); knuth_shuffle(&mut array); }); }
bench_knuth_shuffle
identifier_name
ui-tile.js
/** * @class UITile * @extends UIElement * 是瓦片游戏地图控件,只需要放一个UITile到场景中,地图自动与场景关联。UITile支持由Map Editor Tiled制作的地图。场景中有多个地图时,可以通过UITile的setEnable函数,或用场景的setMap来设置场景当前的地图。 * * 注意: * * 1.在新建地图时请选择CSV格式作为tile layer format,保存时使用JSON格式保存,图片与数据放在同一目录下。 * * 2.启用物理引擎的方法:在tiled中新建立一个图层,给图层加几个自定义的属性。physics为true表示启用物理引擎,fri...
/** * @method getLayerByIndex * 获取地图某层的数据。 * @param {Number} index 层数索引。 * @return {Object} 返回地图某层的数据。layer.info里是tiled生成的原始数据。 * */ /** * @method setClipRegion * 只显示指定区域的地图。有的游戏中只显示玩家视力范围类的地图,这时可以用本函数实现。 * @param {Array} rects * @return {UIElement} 返回控件本身。 * * @example small frame * var tile = t...
* */
random_line_split
models.py
# -*- coding: utf-8 -*- # # Copyright (c) 2013 Clione Software # Copyright (c) 2010-2013 Cidadania S. Coop. Galega # # 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.or...
class Meta: ordering = ['event_date'] verbose_name = _('Event') verbose_name_plural = _('Events') get_latest_by = 'event_date' permissions = ( ('view_event', 'Can view this event'), ('admin_event', 'Can administrate this event'), ('mod_ev...
return False
conditional_block
models.py
# -*- coding: utf-8 -*- # # Copyright (c) 2013 Clione Software # Copyright (c) 2010-2013 Cidadania S. Coop. Galega # # 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.or...
(self): return self.name @models.permalink def get_absolute_url(self): return ('space-index', (), { 'space_url': self.url}) class Entity(models.Model): """ This model stores the name of the entities responsible for the creation of the space or supporting it. "...
__unicode__
identifier_name
models.py
# -*- coding: utf-8 -*- # # Copyright (c) 2013 Clione Software # Copyright (c) 2010-2013 Cidadania S. Coop. Galega # # 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.or...
user = models.ForeignKey(User) space = models.ForeignKey(Space) token = models.CharField(max_length=32) requested_on = models.DateTimeField(auto_now_add=True) def get_approve_url(self): site = Site.objects.all()[0] return "http://%s%sintent/approve/%s" % (site.domain, self.space.get...
.. versionadded: 0.1.5 """
random_line_split
models.py
# -*- coding: utf-8 -*- # # Copyright (c) 2013 Clione Software # Copyright (c) 2010-2013 Cidadania S. Coop. Galega # # 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.or...
class Meta: ordering = ['pub_date'] verbose_name = _('Document') verbose_name_plural = _('Documents') get_latest_by = 'pub_date' # There is no 'view-document' view, so I'll leave the get_absolute_url # method without permalink. Remember that the document files are accesed ...
if self.docfile.size < 1023: return str(self.docfile.size) + " Bytes" elif self.docfile.size >= 1024 and self.docfile.size <= 1048575: return str(round(self.docfile.size / 1024.0, 2)) + " KB" elif self.docfile.size >= 1048576: return str(round(self.docfile.size / 1024...
identifier_body
index.js
module.exports = parse /** * expected argument lengths * @type {Object} */ var length = {a: 7, c: 6, h: 1, l: 2, m: 2, q: 4, s: 4, t: 2, v: 1, z: 0} /** * segment pattern * @type {RegExp} */ var segment = /([astvzqmhlc])([^astvzqmhlc]*)/ig /** * parse an svg path data string. Generates an Array * of comman...
function parse(path) { var data = [] path.replace(segment, function(_, command, args){ var type = command.toLowerCase() args = parseValues(args) // overloaded moveTo if (type == 'm' && args.length > 2) { data.push([command].concat(args.splice(0, 2))) type = 'l' command = command == 'm' ? 'l' : 'L' ...
* @param {String} path * @return {Array} */
random_line_split
index.js
module.exports = parse /** * expected argument lengths * @type {Object} */ var length = {a: 7, c: 6, h: 1, l: 2, m: 2, q: 4, s: 4, t: 2, v: 1, z: 0} /** * segment pattern * @type {RegExp} */ var segment = /([astvzqmhlc])([^astvzqmhlc]*)/ig /** * parse an svg path data string. Generates an Array * of comma...
(args) { var numbers = args.match(number) return numbers ? numbers.map(Number) : [] }
parseValues
identifier_name
index.js
module.exports = parse /** * expected argument lengths * @type {Object} */ var length = {a: 7, c: 6, h: 1, l: 2, m: 2, q: 4, s: 4, t: 2, v: 1, z: 0} /** * segment pattern * @type {RegExp} */ var segment = /([astvzqmhlc])([^astvzqmhlc]*)/ig /** * parse an svg path data string. Generates an Array * of comma...
} }) return data } var number = /-?[0-9]*\.?[0-9]+(?:e[-+]?\d+)?/ig function parseValues(args) { var numbers = args.match(number) return numbers ? numbers.map(Number) : [] }
{ var data = [] path.replace(segment, function(_, command, args){ var type = command.toLowerCase() args = parseValues(args) // overloaded moveTo if (type == 'm' && args.length > 2) { data.push([command].concat(args.splice(0, 2))) type = 'l' command = command == 'm' ? 'l' : 'L' } while (true) { ...
identifier_body
index.js
module.exports = parse /** * expected argument lengths * @type {Object} */ var length = {a: 7, c: 6, h: 1, l: 2, m: 2, q: 4, s: 4, t: 2, v: 1, z: 0} /** * segment pattern * @type {RegExp} */ var segment = /([astvzqmhlc])([^astvzqmhlc]*)/ig /** * parse an svg path data string. Generates an Array * of comma...
}) return data } var number = /-?[0-9]*\.?[0-9]+(?:e[-+]?\d+)?/ig function parseValues(args) { var numbers = args.match(number) return numbers ? numbers.map(Number) : [] }
{ if (args.length == length[type]) { args.unshift(command) return data.push(args) } if (args.length < length[type]) throw new Error('malformed path data') data.push([command].concat(args.splice(0, length[type]))) }
conditional_block
errors.rs
#[cfg(not(target_os = "macos"))] use std::env; use std::io; use std::num; use std::path; use app_dirs; use reqwest; use serde_json; #[cfg(target_os = "macos")] use walkdir; #[derive(Debug, ErrorChain)] #[error_chain(backtrace = "false")] pub enum
{ Msg(String), #[error_chain(foreign)] AppDirs(app_dirs::AppDirsError), #[cfg(not(target_os = "macos"))] #[error_chain(foreign)] EnvVar(env::VarError), #[error_chain(foreign)] Io(io::Error), #[error_chain(foreign)] Parse(num::ParseIntError), #[error_chain(foreign)] Prefix(path::Str...
ErrorKind
identifier_name
errors.rs
#[cfg(not(target_os = "macos"))] use std::env; use std::io; use std::num; use std::path; use app_dirs; use reqwest; use serde_json; #[cfg(target_os = "macos")] use walkdir; #[derive(Debug, ErrorChain)] #[error_chain(backtrace = "false")] pub enum ErrorKind { Msg(String), #[error_chain(foreign)] AppDirs(app_d...
#[error_chain(foreign)] Io(io::Error), #[error_chain(foreign)] Parse(num::ParseIntError), #[error_chain(foreign)] Prefix(path::StripPrefixError), #[error_chain(foreign)] Reqwest(reqwest::Error), #[error_chain(foreign)] SerdeJSON(serde_json::Error), #[cfg(target_os = "macos")] #[error_ch...
#[cfg(not(target_os = "macos"))] #[error_chain(foreign)] EnvVar(env::VarError),
random_line_split
eventum.js
/*jslint indent: 2, unparam: true*/ /*global $: false, document: false, togglbutton: false*/ 'use strict'; togglbutton.render('.issue_view:not(.toggl)', {}, function (elem) { var projectSelect, project, link, container, spanTag, issue_id = $('#issue_overview', elem).getAttribute('data-issue-id'), descri...
container = $('div#issue_menu', elem); spanTag = document.createElement("span"); container.parentNode.appendChild(spanTag.appendChild(link)); });
className: 'eventum', description: '#' + issue_id + ' ' + description, projectName: project });
random_line_split
graph.js
$(function(){ // on dom ready $('#cy').cytoscape({ layout: { name: 'cose', padding: 10 }, style: cytoscape.stylesheet() .selector('node') .css({ 'shape': 'ellipse', 'width': 32, 'content': 'data(name)', 'text-valign': 'center', 't...
{ data: { source: 'k', target: 'g', faveColor: '#86B342', strength: 100 , name:'likes'} }, { data: { source: 'g', target: 'j', faveColor: '#F5A45D', strength: 90 , name:'likes'} } ] }, ready: function(){ window.cy = this; } }); });
random_line_split
Array Helpers.js
// Description: // This kata is designed to test your ability to extend the functionality of built-in ruby classes. In this case, we want you to extend the built-in Array class with the following methods: square(), cube(), average(), sum(), even() and odd(). // Explanation: // square() must return a copy of the arra...
Array.prototype.cube = function(){ return this.map(x=>Math.pow(x,3)) } Array.prototype.sum = function(){ return this.reduce((x,y)=>x+y,0) } Array.prototype.average = function(){ return (this.sum()/this.length) } Array.prototype.even = function(){ return this.filter(x=> x%2 == 0?x:''); } Array.prototype.odd...
return this.map(x=>Math.pow(x,2)) }
random_line_split
reference.rs
use serde::{ser}; use std::mem::transmute; use byteorder::{ByteOrder, LittleEndian, WriteBytesExt}; use std::fmt::{Display,Debug}; use std::fmt; use serialize::{ serialize_u64 }; // Option to display references as nested pub static mut NESTED_REFERENCE: bool = false; #[derive(Serialize, Debug)] pub struct MftEnum...
else { // Just serialize the u64 version serialize_u64(&self.0,serializer) } } } #[test] fn test_mft_reference() { use std::mem; let raw_reference: &[u8] = &[0x73,0x00,0x00,0x00,0x00,0x00,0x68,0x91]; let mft_reference = MftReference( LittleEndian::read_u64(&raw...
{ serializer.serialize_newtype_struct("mft_reference",&self.get_enum_ref()) }
conditional_block
reference.rs
use serde::{ser}; use std::mem::transmute; use byteorder::{ByteOrder, LittleEndian, WriteBytesExt}; use std::fmt::{Display,Debug}; use std::fmt; use serialize::{ serialize_u64 }; // Option to display references as nested pub static mut NESTED_REFERENCE: bool = false; #[derive(Serialize, Debug)] pub struct MftEnum...
} impl Display for MftReference { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f,"{}",self.0) } } impl Debug for MftReference { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f,"{}",self.0) } } impl ser::Serialize for MftReference { fn serialize<S>(&s...
{ let mut raw_buffer = vec![]; raw_buffer.write_u64::<LittleEndian>(self.0).unwrap(); LittleEndian::read_u64( &[&raw_buffer[0..6], &[0,0]].concat() ) }
identifier_body
reference.rs
use serde::{ser}; use std::mem::transmute; use byteorder::{ByteOrder, LittleEndian, WriteBytesExt}; use std::fmt::{Display,Debug}; use std::fmt; use serialize::{ serialize_u64 }; // Option to display references as nested pub static mut NESTED_REFERENCE: bool = false; #[derive(Serialize, Debug)] pub struct MftEnum...
(pub u64); impl MftReference{ pub fn from_entry_and_seq(&mut self, entry: u64, sequence: u16){ let entry_buffer: [u8; 8] = unsafe { transmute(entry.to_le()) }; let seq_buffer: [u8; 2] = unsafe { transmute(sequence.to_le()) }; let mut ref_buffer = vec![...
MftReference
identifier_name
reference.rs
use serde::{ser}; use std::mem::transmute; use byteorder::{ByteOrder, LittleEndian, WriteBytesExt}; use std::fmt::{Display,Debug}; use std::fmt; use serialize::{ serialize_u64 }; // Option to display references as nested pub static mut NESTED_REFERENCE: bool = false; #[derive(Serialize, Debug)] pub struct MftEnum...
reference: LittleEndian::read_u64(&raw_buffer[0..8]), entry: LittleEndian::read_u64( &[&raw_buffer[0..6], &[0,0]].concat() ), sequence: LittleEndian::read_u16(&raw_buffer[6..8]) } } pub fn get_entry_number(&self)->u64{ let mut raw_b...
MftEnumReference{
random_line_split
remote_relay.py
from . import terrariumRelay, terrariumRelayDimmer, terrariumRelayLoadingException from terrariumUtils import terrariumUtils class terrariumRelayRemote(terrariumRelay): HARDWARE = 'remote' NAME = 'Remote power switch (API)' def _load_hardware(self): if terrariumUtils.parse_url(self.address): return se...
data = float(data) return data
return None
conditional_block
remote_relay.py
from . import terrariumRelay, terrariumRelayDimmer, terrariumRelayLoadingException from terrariumUtils import terrariumUtils
HARDWARE = 'remote' NAME = 'Remote power switch (API)' def _load_hardware(self): if terrariumUtils.parse_url(self.address): return self.address raise terrariumRelayLoadingException(f'Invalid url for relay {self}') # Overrule the main set_hardware_state function, as this is not yet possible (may...
class terrariumRelayRemote(terrariumRelay):
random_line_split
remote_relay.py
from . import terrariumRelay, terrariumRelayDimmer, terrariumRelayLoadingException from terrariumUtils import terrariumUtils class terrariumRelayRemote(terrariumRelay): HARDWARE = 'remote' NAME = 'Remote power switch (API)' def _load_hardware(self):
# Overrule the main set_hardware_state function, as this is not yet possible (maybe a post action) def set_hardware_state(self, state, force = False): pass def _get_hardware_value(self): data = terrariumUtils.get_remote_data(self.device) if data is None: return None data = float(data) ...
if terrariumUtils.parse_url(self.address): return self.address raise terrariumRelayLoadingException(f'Invalid url for relay {self}')
identifier_body
remote_relay.py
from . import terrariumRelay, terrariumRelayDimmer, terrariumRelayLoadingException from terrariumUtils import terrariumUtils class terrariumRelayRemote(terrariumRelay): HARDWARE = 'remote' NAME = 'Remote power switch (API)' def _load_hardware(self): if terrariumUtils.parse_url(self.address): return se...
(self, state, force = False): pass def _get_hardware_value(self): data = terrariumUtils.get_remote_data(self.device) if data is None: return None data = float(data) return data class terrariumRelayDimmerRemote(terrariumRelayDimmer): HARDWARE = 'remote-dimmer' NAME = 'Remote dimmer (AP...
set_hardware_state
identifier_name
cp.rs
#![crate_name = "cp"] /* * This file is part of the uutils coreutils package. * * (c) Jordy Dickinson <jordy.dickinson@gmail.com> * * For the full copyright and license information, please view the LICENSE file * that was distributed with this source code. */ extern crate getopts; use getopts::Options; use st...
} else { if !dest.uu_is_dir() { show_error!("TARGET must be a directory"); panic!(); } for src in sources.iter() { let source = Path::new(&src); if !source.uu_is_file() { show_error!("\"{}\" is not a file", source.display());...
{ show_error!("{}", err); panic!(); }
conditional_block