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
index.tsx
import * as React from 'react' import * as ConfigGen from '../actions/config-gen' import * as SettingsGen from '../actions/settings-gen' import * as Constants from '../constants/settings' import * as RouteTreeGen from '../actions/route-tree-gen' import SettingsContainer from './render' import * as Container from '../ut...
if (ownProps.routeSelected === Constants.accountTab && tab !== Constants.accountTab) { dispatch(SettingsGen.createClearAddedEmail()) } dispatch(RouteTreeGen.createNavigateAppend({path: [tab]})) }, }), (stateProps, dispatchProps, ownProps: OwnProps) => ({ badgeNotifications: stateP...
{ dispatch(RouteTreeGen.createNavigateAppend({path: ['walletOnboarding']})) return }
conditional_block
index.tsx
import * as React from 'react' import * as ConfigGen from '../actions/config-gen' import * as SettingsGen from '../actions/settings-gen' import * as Constants from '../constants/settings' import * as RouteTreeGen from '../actions/route-tree-gen' import SettingsContainer from './render' import * as Container from '../ut...
onTabChange: (tab: Constants.SettingsTab) => dispatchProps.onTabChange(tab, stateProps._walletsAcceptedDisclaimer), selectedTab: ownProps.routeSelected, }) )(SettingsContainer) export default Connected
contactsLabel: stateProps._contactImportEnabled ? 'Phone contacts' : 'Import phone contacts', hasRandomPW: stateProps.hasRandomPW || undefined, loadHasRandomPW: dispatchProps.loadHasRandomPW, logoutInProgress: stateProps.logoutInProgress, onLogout: dispatchProps.onLogout,
random_line_split
cloudFoundryDestroyAsgStage.module.ts
import type { IStage } from '@spinnaker/core'; import { Registry } from '@spinnaker/core'; import { CloudFoundryAsgStageConfig } from '../../../presentation'; Registry.pipeline.registerStage({ accountExtractor: (stage: IStage) => [stage.context.credentials], cloudProvider: 'cloudfoundry', component: CloudFoundry...
validators: [ { type: 'cfTargetImpedance', message: 'This pipeline will attempt to destroy a server group without deploying a new version into the same cluster.', }, { type: 'requiredField', fieldName: 'cluster' }, { type: 'requiredField', fieldName: 'target' }, { type: 'requir...
key: 'destroyServerGroup', provides: 'destroyServerGroup',
random_line_split
game.js
'use strict'; const Input = require('./input'), Level = require('./level'), StartScreen = require('./start-screen'), LevelEnding = require('./level-ending'), GameEnding = require('./game-ending'), Sound = require('./sound'), FpsCounter = require('./fps-counter'); const ...
break; case 'level-ending': this._levelEnding.step(elapsed); break; case 'game-ending': this._gameEnding.step(elapsed); break; } this._sound.step(elapsed); this._fpsCounter.step(elapsed); ...
{ eventBus.fire({ name: 'event.level.end' }); }
conditional_block
game.js
'use strict'; const Input = require('./input'), Level = require('./level'), StartScreen = require('./start-screen'), LevelEnding = require('./level-ending'), GameEnding = require('./game-ending'), Sound = require('./sound'), FpsCounter = require('./fps-counter'); const ...
return b.z - a.z; } }); } } module.exports = Game; /** * Fischer-Yates Algorithm * http://stackoverflow.com/a/6274398/738081 */ function shuffleArray(arr) { var counter = arr.length, temp, index; // While there are elements in the array while (counter > 0) { ...
} else {
random_line_split
game.js
'use strict'; const Input = require('./input'), Level = require('./level'), StartScreen = require('./start-screen'), LevelEnding = require('./level-ending'), GameEnding = require('./game-ending'), Sound = require('./sound'), FpsCounter = require('./fps-counter'); const ...
/** * Re-sort the stage children to their z-order, if any. * @private */ _resortStageChildren() { this._stage.children.sort((a, b) => { if (a.z === undefined || a.z === null) { return -1; } else if (b.z === undefined || b.z === null) { ...
{ let elapsed = Date.now() - this._lastStep; if (elapsed > 1000) { elapsed = 1000; // enforce speed limit } this._lastStep = Date.now(); return elapsed; }
identifier_body
game.js
'use strict'; const Input = require('./input'), Level = require('./level'), StartScreen = require('./start-screen'), LevelEnding = require('./level-ending'), GameEnding = require('./game-ending'), Sound = require('./sound'), FpsCounter = require('./fps-counter'); const ...
(arr) { var counter = arr.length, temp, index; // While there are elements in the array while (counter > 0) { // Pick a random index index = Math.floor(Math.random() * counter); // Decrease counter by 1 counter--; // And swap the last element with it temp =...
shuffleArray
identifier_name
instruction.js
/* Copyright (c) 2011 Cimaron Shanahan Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute...
} else if (this.swizzle.length != size) { throw new Error(util.format("Cannot coerce operand to size %s", size)); } }; /** * toString method * * @return string */ IrOperand.prototype.toString = function() { var str; if (this.raw) { str = this.raw; } else { str = this.neg + this.name + ("@" + this.add...
this.swizzle = "xyzw".substring(0, size);
random_line_split
instruction.js
/* Copyright (c) 2011 Cimaron Shanahan Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute...
(str, raw) { this.full = ""; this.neg = ""; this.name = ""; this.address = ""; this.swizzle = ""; this.number = ""; this.raw = ""; this.index = ""; if (raw) { this.full = str; this.raw = str; } else { this.parse(str); } } /** * Parses operand string * * @param string string that represents a...
IrOperand
identifier_name
instruction.js
/* Copyright (c) 2011 Cimaron Shanahan Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute...
/** * Parses operand string * * @param string string that represents a single variable */ IrOperand.prototype.parse = function(str) { var parts, regex; if (!str) { return; } if (!isNaN(parseFloat(str))) { this.raw = str; return; } //neg regex = "(\-)?"; //name (include '%' for our code subs...
{ this.full = ""; this.neg = ""; this.name = ""; this.address = ""; this.swizzle = ""; this.number = ""; this.raw = ""; this.index = ""; if (raw) { this.full = str; this.raw = str; } else { this.parse(str); } }
identifier_body
instruction.js
/* Copyright (c) 2011 Cimaron Shanahan Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute...
}; /** * Set the swizzle components on all operands * * @param string The swizzle to set */ IrInstruction.prototype.setSwizzle = function(swz) { var i, o; for (i = 0; i < IrInstruction.operands.length; i++) { o = IrInstruction.operands[i]; if (this[o] && !this[o].swizzle) { this[o].swizzle = swz; ...
{ o = IrInstruction.operands[i]; if (this[o]) { this[o].addOffset(offset); } }
conditional_block
Wiltron360SS69.py
from ..GenericInstrument import GenericInstrument from .helper import SignalGenerator, amplitudelimiter class Wiltron360SS69(GenericInstrument, SignalGenerator): """Wiltron 360SS69 10e6, 40e9. .. figure:: images/SignalGenerator/Wiltron360SS69.jpg """ def
(self, instrument): """.""" super().__init__(instrument) # self.log = logging.getLogger(__name__) # self.log.info('Creating an instance of\t' + str(__class__)) self.amps = [-140, 17] self.freqs = [10e6, 40e9] # self.siggen.write("*CLS") # clear error status ...
__init__
identifier_name
Wiltron360SS69.py
from ..GenericInstrument import GenericInstrument from .helper import SignalGenerator, amplitudelimiter class Wiltron360SS69(GenericInstrument, SignalGenerator): """Wiltron 360SS69 10e6, 40e9. .. figure:: images/SignalGenerator/Wiltron360SS69.jpg """ def __init__(self, instrument): """.""" ...
@property def amplitude(self): """.""" return(self.query("OL0")) @amplitude.setter @amplitudelimiter def amplitude(self, amplitude): self.write(f"L0{amplitude:.2f}DM") '''@property def output(self): if self.query("OUTPut:STATe?") == "1": return...
self.write(f"F0{frequency:.2f}GH")
identifier_body
Wiltron360SS69.py
from ..GenericInstrument import GenericInstrument from .helper import SignalGenerator, amplitudelimiter class Wiltron360SS69(GenericInstrument, SignalGenerator): """Wiltron 360SS69 10e6, 40e9. .. figure:: images/SignalGenerator/Wiltron360SS69.jpg """ def __init__(self, instrument): """.""" ...
return(self.query("OF0")) @frequency.setter def frequency(self, frequency): self.write(f"F0{frequency:.2f}GH") @property def amplitude(self): """.""" return(self.query("OL0")) @amplitude.setter @amplitudelimiter def amplitude(self, amplitude): self....
def frequency(self): """."""
random_line_split
basic_types.rs
// Copyright 2015, 2016 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 la...
//! Ethcore basic typenames. use util::hash::H2048; /// Type for a 2048-bit log-bloom, as used by our blocks. pub type LogBloom = H2048; /// Constant 2048-bit datum for 0. Often used as a default. pub static ZERO_LOGBLOOM: LogBloom = H2048([0x00; 256]); #[cfg_attr(feature="dev", allow(enum_variant_names))] /// Sema...
random_line_split
basic_types.rs
// Copyright 2015, 2016 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 la...
{ /// The seal/signature is included. With, /// The seal/signature is not included. Without, }
Seal
identifier_name
MessageArea.py
# Copyright (C) 2008 Valmantas Paliksa <walmis at balticum-tv dot lt> # # Licensed under the GNU General Public License Version 3 # # 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...
(wg): if isinstance(wg, gtk.Container): for w in wg: if not isinstance(w, gtk.Button): _set_style(w) wg.set_style(style) _set_style(self) self.anim.color = self.hbox.style.base[0] self.queue_draw() self.setting_style = False def on_close(self, button): def on_finished(anim):...
_set_style
identifier_name
MessageArea.py
# Copyright (C) 2008 Valmantas Paliksa <walmis at balticum-tv dot lt> # # Licensed under the GNU General Public License Version 3 # # 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...
def style_set(self, widget, prev_style): if self.setting_style: return #This is a hack needed to use the tooltip background color window = gtk.Window(gtk.WINDOW_POPUP) window.set_name("gtk-tooltip") window.ensure_style() style = window.get_style() window.destroy() self.setting_style = True...
d = gtk.MessageDialog(parent=None, flags=0, type=gtk.MESSAGE_INFO, buttons=gtk.BUTTONS_CLOSE) d.props.text = self.text d.run() d.destroy()
identifier_body
MessageArea.py
# Copyright (C) 2008 Valmantas Paliksa <walmis at balticum-tv dot lt> # # Licensed under the GNU General Public License Version 3 # # 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...
@staticmethod def show_message(*args): MessageArea._inst_._show_message(*args) def _show_message(self, text, icon=gtk.STOCK_DIALOG_WARNING): self.text = text self.label.set_tooltip_text(text) self.icon.set_from_stock(icon, gtk.ICON_SIZE_MENU) if icon == gtk.STOCK_DIALOG_WARNING: self.hl_anim.c...
def close(): MessageArea._inst_.on_close(None)
random_line_split
MessageArea.py
# Copyright (C) 2008 Valmantas Paliksa <walmis at balticum-tv dot lt> # # Licensed under the GNU General Public License Version 3 # # 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...
else: self.hl_anim.color = gtk.gdk.Color(0,0,65535) def on_finished(anim): anim.disconnect(sig) anim.freeze() if not self.props.visible: sig = self.anim.connect("animation-finished", on_finished) self.anim.thaw() self.show() self.anim.animate(start=0.0, end=1.0, duration=500)...
self.hl_anim.color = gtk.gdk.Color(65535,0,0)
conditional_block
models.py
# -*- coding: utf-8 -*- from django.db import models from datetime import datetime class Place(models.Model): """ Holder object for basic info about the rooms in the university. """ room_place = models.CharField(max_length=255) floor = models.IntegerField() def __unicode__(self): ...
k=True, default=None, null=True) event = models.ForeignKey(Event, blank=True, default=None, null=True) start_date = models.DateField() end_date = models.DateField() dtstamp = models.DateField(default=datetime.now()) desc = models.TextField()
ey(Student, blan
identifier_body
models.py
# -*- coding: utf-8 -*- from django.db import models from datetime import datetime class Place(models.Model): """ Holder object for basic info about the rooms in the university. """ room_place = models.CharField(max_length=255) floor = models.IntegerField() def __unicode__(self): ...
(WEEKLY, u'Седмично'), ) type_value = models.CharField(max_length=255, null=True, blank=True, default=None) inserted = models.DateField(default=datetime.now()) name = models.CharField(max_length=255) place = models.ForeignKey(Place, blank=True, default=None, null=True) date_start = mode...
WEEKLY = 'WKL' TYPES = (
random_line_split
models.py
# -*- coding: utf-8 -*- from django.db import models from datetime import datetime class Place(models.Model): """ Holder object for basic info about the rooms in the university. """ room_place = models.CharField(max_length=255) floor = models.IntegerField() def __unicode__(self): ...
lue, self.year.value+u' курс']) def __unicode__(self): return self.name class Department(models.Model): """ Group representing a set of lecturers grouped by field of teaching. """ name = models.CharField(max_length=255) def __unicode__(self): return self.name class Teac...
year.parent.va
identifier_name
models.py
# -*- coding: utf-8 -*- from django.db import models from datetime import datetime class Place(models.Model): """ Holder object for basic info about the rooms in the university. """ room_place = models.CharField(max_length=255) floor = models.IntegerField() def __unicode__(self): ...
return HierarchyUnit.objects.filter(parent=self) def __unicode__(self): return self.get_all_info_for_parents() class Block(models.Model): """ Group representing a set of optional subjects. Example: Core of Computer Science. """ name = models.CharField(max_length=255) def ...
arent.parent.value, self.parent.value+u' курс', self.value+u' група']) def get_all_childs(self):
conditional_block
dbms.py
query = self._get_and_validate_select_query(design, query_history) hql = 'CREATE TABLE `%s`.`%s` AS %s' % (target_database, target_table, query) query_history = self.execute_statement(hql) else: # FYI: this path is dead since moving to HiveServer2 # # Case 2: The results are in s...
log = db.get_log(exc)
conditional_block
dbms.py
= SERVER_CONN_TIMEOUT.get() handle = self.execute_and_wait(query, timeout_sec=timeout) if handle: result = self.fetch(handle, rows=5000) self.close(handle) return [name for database in result.rows() for name in database] else: return [] def get_database(self, database): re...
for table in tables: if table.is_view: hql.append("DROP VIEW `%s`.`%s`" % (database, table.name
def drop_tables(self, database, tables, design): hql = []
random_line_split
dbms.py
: if table.is_view: hql.append("DROP VIEW `%s`.`%s`" % (database, table.name,)) else: hql.append("DROP TABLE `%s`.`%s`" % (database, table.name,)) query = hql_query(';'.join(hql), database) design.data = query.dumps() design.save() return self.execute_query(query, design) ...
get_results_metadata
identifier_name
dbms.py
= SERVER_CONN_TIMEOUT.get() handle = self.execute_and_wait(query, timeout_sec=timeout) if handle: result = self.fetch(handle, rows=5000) self.close(handle) return [name for database in result.rows() for name in database] else: return [] def get_database(self, database): re...
def get_column(self, database, table_name, column_name): table = self.client.get_table(database, table_name) for col in table.cols: if col.name == column_name: return col return None def execute_query(self, query, design): return self.execute_and_watch(query, design=design) de...
return self.client.get_table(database, table_name)
identifier_body
Entity.js
import Joi from 'joi' export default class EventsEntity { constructor(deps = {}) { this.Adapter = deps.Adapter || require('./Adapter').default } createValidation(input){ return new Promise((resolve, reject) => { let schema = Joi.object().keys({ game: Joi.string().required(), ...
else { let outputMessage = { name: 'ValidationError', messages: result.error.details.map(e => e.message) } reject(outputMessage) } }) } update(body){ let adapter = new this.Adapter return adap...
{ resolve(result.value) }
conditional_block
Entity.js
import Joi from 'joi' export default class EventsEntity { constructor(deps = {}) { this.Adapter = deps.Adapter || require('./Adapter').default } createValidation(input){ return new Promise((resolve, reject) => { let schema = Joi.object().keys({ game: Joi.string().required(), ...
}
random_line_split
Entity.js
import Joi from 'joi' export default class EventsEntity {
(deps = {}) { this.Adapter = deps.Adapter || require('./Adapter').default } createValidation(input){ return new Promise((resolve, reject) => { let schema = Joi.object().keys({ game: Joi.string().required(), time: Joi.number().required(), participants: Joi.arr...
constructor
identifier_name
websockets_chat_async.py
#!./uwsgi --http-socket :9090 --async 100 ... # same chat example but using uwsgi async api # for pypy + continulets just run: # uwsgi --http-socket :9090 --pypy-home /opt/pypy --pypy-wsgi-file tests/websockets_chat_async.py --pypy-eval "uwsgi_pypy_setup_continulets()" --async 100 import uwsgi import time import redis ...
(env, sr): ws_scheme = 'ws' if 'HTTPS' in env or env['wsgi.url_scheme'] == 'https': ws_scheme = 'wss' if env['PATH_INFO'] == '/': sr('200 OK', [('Content-Type', 'text/html')]) output = """ <html> <head> <script language="Javascript"> var s = new WebS...
application
identifier_name
websockets_chat_async.py
#!./uwsgi --http-socket :9090 --async 100 ... # same chat example but using uwsgi async api # for pypy + continulets just run: # uwsgi --http-socket :9090 --pypy-home /opt/pypy --pypy-wsgi-file tests/websockets_chat_async.py --pypy-eval "uwsgi_pypy_setup_continulets()" --async 100 import uwsgi import time import redis ...
if msg[0] == t: uwsgi.websocket_send("[%s] %s" % (time.time(), msg)) else: # on timeout call websocket_recv_nb again to manage ping/pong msg = uwsgi.websocket_recv_nb() if msg: r.publish('foobar',...
# only interested in user messages t = 'message' if sys.version_info[0] > 2: t = b'message'
random_line_split
websockets_chat_async.py
#!./uwsgi --http-socket :9090 --async 100 ... # same chat example but using uwsgi async api # for pypy + continulets just run: # uwsgi --http-socket :9090 --pypy-home /opt/pypy --pypy-wsgi-file tests/websockets_chat_async.py --pypy-eval "uwsgi_pypy_setup_continulets()" --async 100 import uwsgi import time import redis ...
s.onerror = function(e) { alert(e); } s.onclose = function(e) { alert("connection closed"); } function invia() { var value = document.getElementById('testo').value; s.send(value); }...
ws_scheme = 'ws' if 'HTTPS' in env or env['wsgi.url_scheme'] == 'https': ws_scheme = 'wss' if env['PATH_INFO'] == '/': sr('200 OK', [('Content-Type', 'text/html')]) output = """ <html> <head> <script language="Javascript"> var s = new WebSocket("%s://%s/f...
identifier_body
websockets_chat_async.py
#!./uwsgi --http-socket :9090 --async 100 ... # same chat example but using uwsgi async api # for pypy + continulets just run: # uwsgi --http-socket :9090 --pypy-home /opt/pypy --pypy-wsgi-file tests/websockets_chat_async.py --pypy-eval "uwsgi_pypy_setup_continulets()" --async 100 import uwsgi import time import redis ...
msg = channel.parse_response() print(msg) # only interested in user messages t = 'message' if sys.version_info[0] > 2: t = b'message' if msg[0] == t: uw...
uwsgi.websocket_handshake(env['HTTP_SEC_WEBSOCKET_KEY'], env.get('HTTP_ORIGIN', '')) print("websockets...") r = redis.StrictRedis(host='localhost', port=6379, db=0) channel = r.pubsub() channel.subscribe('foobar') websocket_fd = uwsgi.connection_fd() redis_fd = channel.c...
conditional_block
img.rs
use std::default::{Default}; use std::cmp::{min, max}; use std::convert::{Into}; use image::{Primitive, GenericImage, Pixel, ImageBuffer, Rgba}; use geom::{V2, Rect}; use rgb; /// Set alpha channel to transparent if pixels have a specific color. pub fn color_key<P: Pixel<Subpixel=u8>, I: GenericImage<Pixel=P>, C: Into...
<T, P, I, J>(image: &I, target: &mut J, offset: V2<i32>) where T: Primitive+Default, P: Pixel<Subpixel=T>, I: GenericImage<Pixel=P>, J: GenericImage<Pixel=P> { let (w, h) = image.dimensions(); // TODO: Check for going over bounds. for y in 0..(h) { for x in 0..(w) {...
blit
identifier_name
img.rs
use std::default::{Default}; use std::cmp::{min, max}; use std::convert::{Into}; use image::{Primitive, GenericImage, Pixel, ImageBuffer, Rgba}; use geom::{V2, Rect}; use rgb; /// Set alpha channel to transparent if pixels have a specific color.
let (w, h) = image.dimensions(); let srgba = color.into(); ImageBuffer::from_fn(w, h, |x, y| { let (pr, pg, pb, mut pa) = image.get_pixel(x, y).to_rgba().channels4(); if pr == srgba.r && pg == srgba.g && pb == srgba.b { pa = Default::default(); } Pixel::from_chann...
pub fn color_key<P: Pixel<Subpixel=u8>, I: GenericImage<Pixel=P>, C: Into<rgb::SRgba>>( image: &I, color: C) -> ImageBuffer<Rgba<u8>, Vec<u8>> {
random_line_split
img.rs
use std::default::{Default}; use std::cmp::{min, max}; use std::convert::{Into}; use image::{Primitive, GenericImage, Pixel, ImageBuffer, Rgba}; use geom::{V2, Rect}; use rgb; /// Set alpha channel to transparent if pixels have a specific color. pub fn color_key<P: Pixel<Subpixel=u8>, I: GenericImage<Pixel=P>, C: Into...
// Empty image. else { Rect(p1, p2 - p1) } } pub fn blit<T, P, I, J>(image: &I, target: &mut J, offset: V2<i32>) where T: Primitive+Default, P: Pixel<Subpixel=T>, I: GenericImage<Pixel=P>, J: GenericImage<Pixel=P> { let (w, h) = image.dimensions(); // TODO: Check for goin...
{ Rect(V2(0, 0), V2(0, 0)) }
conditional_block
img.rs
use std::default::{Default}; use std::cmp::{min, max}; use std::convert::{Into}; use image::{Primitive, GenericImage, Pixel, ImageBuffer, Rgba}; use geom::{V2, Rect}; use rgb; /// Set alpha channel to transparent if pixels have a specific color. pub fn color_key<P: Pixel<Subpixel=u8>, I: GenericImage<Pixel=P>, C: Into...
{ let (w, h) = image.dimensions(); // TODO: Check for going over bounds. for y in 0..(h) { for x in 0..(w) { target.put_pixel(x + offset.0 as u32, y + offset.1 as u32, image.get_pixel(x, y)); } } }
identifier_body
lib.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/. */ extern crate hashglobe; extern crate smallvec; #[cfg(feature = "known_system_malloc")] use hashglobe::alloc; use...
if new_ptr.is_null() { return Err(FailedAllocationError::new( "out of memory when allocating SmallVec", )); } let new_vec = unsafe { Vec::from_raw_parts(new_ptr as *mut T::Item, old_len, new_cap) }; let new_svec = SmallVec::from_vec(new_vec); mem::forget(mem::replace(s...
random_line_split
lib.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/. */ extern crate hashglobe; extern crate smallvec; #[cfg(feature = "known_system_malloc")] use hashglobe::alloc; use...
} // Double the capacity of |vec|, or fail to do so due to lack of memory. // Returns Ok(()) on success, Err(..) on failure. #[cfg(feature = "known_system_malloc")] #[inline(never)] #[cold] fn try_double_vec<T>(vec: &mut Vec<T>) -> Result<(), FailedAllocationError> { use std::mem; let old_ptr = vec.as_mut_pt...
{ #[cfg(feature = "known_system_malloc")] { if self.capacity() == self.len() { try_double_vec(self)?; debug_assert!(self.capacity() > self.len()); } } self.push(val); Ok(()) }
identifier_body
lib.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/. */ extern crate hashglobe; extern crate smallvec; #[cfg(feature = "known_system_malloc")] use hashglobe::alloc; use...
(&mut self, val: T::Item) -> Result<(), FailedAllocationError> { #[cfg(feature = "known_system_malloc")] { if self.capacity() == self.len() { try_double_small_vec(self)?; debug_assert!(self.capacity() > self.len()); } } self.push(va...
try_push
identifier_name
lib.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/. */ extern crate hashglobe; extern crate smallvec; #[cfg(feature = "known_system_malloc")] use hashglobe::alloc; use...
else { old_cap .checked_mul(2) .ok_or(FailedAllocationError::new("capacity overflow for SmallVec"))? }; // This surely shouldn't fail, if |old_cap| was previously accepted as a // valid value. But err on the side of caution. let old_size_bytes = old_cap .checke...
{ 4 }
conditional_block
OneFichierCom.py
# -*- coding: utf-8 -*- import re import time import pycurl from module.network.HTTPRequest import BadHeader from ..internal.Account import Account class OneFichierCom(Account): __name__ = "OneFichierCom" __type__ = "account" __version__ = "0.23" __status__ = "testing" __description__ = """1fi...
return {'validuntil': validuntil, 'trafficleft': trafficleft, 'premium': premium or False} def signin(self, user, password, data): self.req.http.c.setopt( pycurl.REFERER, "https://1fichier.com/login.pl?lg=en") try: html = self.load("htt...
premium = True
conditional_block
OneFichierCom.py
# -*- coding: utf-8 -*- import re import time import pycurl from module.network.HTTPRequest import BadHeader from ..internal.Account import Account class OneFichierCom(Account): __name__ = "OneFichierCom" __type__ = "account" __version__ = "0.23" __status__ = "testing" __description__ = """1fi...
raise
self.req.http.c.setopt( pycurl.REFERER, "https://1fichier.com/login.pl?lg=en") try: html = self.load("https://1fichier.com/login.pl?lg=en", post={'mail': user, 'pass': password, ...
identifier_body
OneFichierCom.py
# -*- coding: utf-8 -*- import re import time import pycurl from module.network.HTTPRequest import BadHeader from ..internal.Account import Account class OneFichierCom(Account): __name__ = "OneFichierCom" __type__ = "account" __version__ = "0.23" __status__ = "testing" __description__ = """1fi...
(self, user, password, data): self.req.http.c.setopt( pycurl.REFERER, "https://1fichier.com/login.pl?lg=en") try: html = self.load("https://1fichier.com/login.pl?lg=en", post={'mail': user, 'pass': passw...
signin
identifier_name
OneFichierCom.py
# -*- coding: utf-8 -*- import re import time import pycurl from module.network.HTTPRequest import BadHeader from ..internal.Account import Account class OneFichierCom(Account): __name__ = "OneFichierCom" __type__ = "account" __version__ = "0.23" __status__ = "testing" __description__ = """1fi...
expiredate = m.group(1) self.log_debug("Expire date: " + expiredate) try: validuntil = time.mktime(time.strptime(expiredate, "%Y-%m-%d")) except Exception, e: self.log_error(e, trace=True) else: premium = True...
if m is not None:
random_line_split
observation_preprocessor_test.py
. # See the License for the specific language governing permissions and # limitations under the License. # Lint as: python3 """Tests for observation_preprocessor.""" import math from absl.testing import absltest from absl.testing import parameterized from google.protobuf import text_format from learner import test_d...
(feelers_version): return dict( always_compute_egocentric=True, feelers_version=feelers_version, feelers_v2_output_channels=3, feelers_v2_kernel_size=5) class ObservationPreprocessorTest(parameterized.TestCase): @parameterized.parameters([ ('v1', 'default'), ('v2', 'default'), ('v2', 'wrap')]) ...
get_hparams
identifier_name
observation_preprocessor_test.py
('v2', 'wrap')]) def test_preproc(self, feelers_version, yaw_range): spec_proto = test_data.brain_spec() if yaw_range == 'wrap': # Force yaw_angles to loop around 360 degrees. for field in spec_proto.observation_spec.player.entity_fields: if field.HasField('feeler'): for i, yaw ...
want = [math.sqrt(3)] # diagonal of the unit cube. self.assertSequenceAlmostEqual(want, preprocessed, delta=0.05) else:
random_line_split
observation_preprocessor_test.py
. # See the License for the specific language governing permissions and # limitations under the License. # Lint as: python3 """Tests for observation_preprocessor.""" import math from absl.testing import absltest from absl.testing import parameterized from google.protobuf import text_format from learner import test_d...
data.camera.position.y = data.player.position.y data.camera.position.z = data.player.position.z data.camera.rotation.x = 0 data.camera.rotation.y = 0 data.camera.rotation.z = 1 # 180 degrees rotated around z data.camera.rotation.w = 0 tfa_val = spec.observation_spec.tfa_value(data) # ...
@parameterized.parameters([ ('v1', 'default'), ('v2', 'default'), ('v2', 'wrap')]) def test_preproc(self, feelers_version, yaw_range): spec_proto = test_data.brain_spec() if yaw_range == 'wrap': # Force yaw_angles to loop around 360 degrees. for field in spec_proto.observation_spec.player.en...
identifier_body
observation_preprocessor_test.py
spec_proto.observation_spec.player.entity_fields: if field.HasField('feeler'): for i, yaw in enumerate( np.linspace(0, math.pi, len(field.feeler.yaw_angles))): field.feeler.yaw_angles[i] = yaw spec = tfa_specs.BrainSpec(spec_proto) obs_preproc = observation_preproc...
absltest.main()
conditional_block
searchView.py
#! /usr/bin/env python # -*- coding: utf-8 -*- # Copyright (C) 2011 Deepin, Inc. # 2011 Wang Yong # # Author: Wang Yong <lazycat.manatee@gmail.com> # Maintainer: Wang Yong <lazycat.manatee@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of th...
appInstalledLabel = appInstalledDynamicLabel.getLabel() buttonImage = appTheme.getDynamicPixbuf("cell/update_hover.png").getPixbuf() appInstalledLabel.set_size_request(buttonImage.get_width(), buttonImage.get_height()) actionButtonBox.pack_start(appInstall...
appTheme.getDynamicColor("installed"), LABEL_FONT_SIZE, )
random_line_split
searchView.py
#! /usr/bin/env python # -*- coding: utf-8 -*- # Copyright (C) 2011 Deepin, Inc. # 2011 Wang Yong # # Author: Wang Yong <lazycat.manatee@gmail.com> # Maintainer: Wang Yong <lazycat.manatee@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of th...
(self, widget, event): '''Click item.''' if utils.isDoubleClick(event): self.entryDetailView() else: self.setSelectIndex(self.index) def initAdditionStatus(self): '''Add addition status.''' status = self.appInfo.status if status in [AP...
clickItem
identifier_name
searchView.py
#! /usr/bin/env python # -*- coding: utf-8 -*- # Copyright (C) 2011 Deepin, Inc. # 2011 Wang Yong # # Author: Wang Yong <lazycat.manatee@gmail.com> # Maintainer: Wang Yong <lazycat.manatee@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of th...
elif status == APP_STATE_DOWNLOADING: self.initDownloadingStatus(self.appAdditionBox) elif status == APP_STATE_DOWNLOAD_PAUSE: self.initDownloadPauseStatus(self.appAdditionBox) elif status == APP_STATE_INSTALLING: self.initInstallingStatus() elif stat...
self.initNormalStatus()
conditional_block
searchView.py
#! /usr/bin/env python # -*- coding: utf-8 -*- # Copyright (C) 2011 Deepin, Inc. # 2011 Wang Yong # # Author: Wang Yong <lazycat.manatee@gmail.com> # Maintainer: Wang Yong <lazycat.manatee@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of th...
def updateSearch(self, appNum): '''Update view.''' self.appNum = appNum self.calculateMaxPageIndex() self.pageIndex = 1 self.show() def createAppList(self, appList): '''Create application list.''' # Init. itemPaddingY = 5 box = gt...
'''Search view.''' def __init__(self, appNum, getListFunc, switchStatus, downloadQueue, entryDetailCallback, sendVoteCallback, fetchVoteCallback, launchApplicationCallback): '''Init for search view.''' appView.AppView.__init__(self, appNum, PAGE_REPO, True) ...
identifier_body
coercion.rs
've opted to leave it for later---after all //! we may want to adjust precisely when coercions occur. use check::{autoderef, FnCtxt, LvaluePreference, UnresolvedTypeAction}; use middle::infer::{self, Coercion}; use middle::traits::{self, ObligationCause}; use middle::traits::{predicate_for_trait_def, report_selection...
<'a, 'tcx: 'a> { fcx: &'a FnCtxt<'a, 'tcx>, origin: infer::TypeOrigin, unsizing_obligations: RefCell<Vec<traits::PredicateObligation<'tcx>>>, } type CoerceResult<'tcx> = RelateResult<'tcx, Option<ty::AutoAdjustment<'tcx>>>; impl<'f, 'tcx> Coerce<'f, 'tcx> { fn tcx(&self) -> &ty::ctxt<'tcx> { s...
Coerce
identifier_name
coercion.rs
've opted to leave it for later---after all //! we may want to adjust precisely when coercions occur. use check::{autoderef, FnCtxt, LvaluePreference, UnresolvedTypeAction}; use middle::infer::{self, Coercion}; use middle::traits::{self, ObligationCause}; use middle::traits::{predicate_for_trait_def, report_selection...
} ty::TyBareFn(None, a_f) => { // We permit coercion of fn pointers to drop the // unsafe qualifier. self.coerce_from_fn_pointer(a, a_f, b) } _ => { // Otherwise, just use subt...
// type; function pointers are not (that would // require double indirection). self.coerce_from_fn_item(a, a_f, b)
random_line_split
coercion.rs
-> CoerceResult<'tcx> { debug!("coerce_borrowed_pointer(a={:?}, b={:?})", a, b); // If we have a parameter of type `&M T_a` and the value // provided is `expr`, we will be adding an implicit borrow, // meaning that we convert ...
{ /*! * Attempts to coerce from the type of a Rust function item * into a closure or a `proc`. */ self.unpack_actual_value(b, |b| { debug!("coerce_from_fn_item(a={:?}, b={:?})", a, b); match b.sty { ty::TyBareFn(None...
identifier_body
viewport.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 cssparser::{Parser, ToCss}; use euclid::scale_factor::ScaleFactor; use euclid::size::TypedSize2D; use std::asc...
<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { match *self { Zoom::Number(number) => write!(dest, "{}", number), Zoom::Percentage(percentage) => write!(dest, "{}%", percentage * 100.), Zoom::Auto => write!(dest, "auto") } } } impl Zoom ...
to_css
identifier_name
viewport.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 cssparser::{Parser, ToCss}; use euclid::scale_factor::ScaleFactor; use euclid::size::TypedSize2D; use std::asc...
} } #[inline] pub fn to_f32(&self) -> Option<f32> { match *self { Zoom::Number(number) => Some(number as f32), Zoom::Percentage(percentage) => Some(percentage as f32), Zoom::Auto => None } } }
random_line_split
product.utility.ts
"use strict"; import {IProduct} from "./crawler.interface"; export let deduplicateStringArrays = (existingResult: string[], newResult: string[]): string[] => { let result: string[] = existingResult.slice(0); let hash = {}; existingResult.forEach((value: string) => { hash[value] = true; }); ...
// do actual dedupe newResult.forEach((value) => { if (!hash[value.uniqueIdInShop]) { hash[value.uniqueIdInShop] = true; result.push(value); } }); return result; };
random_line_split
product.utility.ts
"use strict"; import {IProduct} from "./crawler.interface"; export let deduplicateStringArrays = (existingResult: string[], newResult: string[]): string[] => { let result: string[] = existingResult.slice(0); let hash = {}; existingResult.forEach((value: string) => { hash[value] = true; }); ...
}); return result; }; export let deduplicateProducts = (existingResult: IProduct[], newResult: IProduct[]): IProduct[] => { let result: IProduct[] = existingResult.slice(0); let hash: {}; existingResult.forEach((value: IProduct) => { hash[value.uniqueIdInShop] = true; }); ...
{ hash[value] = true; result.push(value); }
conditional_block
roundrobin.py
# -*- coding: utf-8 -*- """Round-robin scheduling.""" # Copyright (C) 2015 Alexander Jones # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published # by the Free Software Foundation, either version 3 of the License, or # (at yo...
def _generate_schedule_round(self, matches): """Fully generate a round for a schedule.""" for ___ in range(10): next_round = self.generate_round(matches) if next_round: return next_round else: raise ScheduleGenerationFailed('Schedule gene...
"""Generate a round. @param matches: The generated matches @type matches: list @return: The generated round @rtype: list """ round = [] try: random.shuffle(matches) round.append(matches.pop(0)) poss = copy.copy(matches) ...
identifier_body
roundrobin.py
# -*- coding: utf-8 -*- """Round-robin scheduling.""" # Copyright (C) 2015 Alexander Jones # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published # by the Free Software Foundation, either version 3 of the License, or # (at yo...
for team in self.teams for opp in self.teams if team != opp] * evens def _generate_odd_matches(self, home_teams=None): """Generate a list of matches for odd meeting counts.""" matrix = self.generate_matrix(home_teams=home_teams) matches = [] ...
return matrix def _generate_even_matches(self, evens): """Generate a list of matches for even meeting counts.""" return [(team, opp)
random_line_split
roundrobin.py
# -*- coding: utf-8 -*- """Round-robin scheduling.""" # Copyright (C) 2015 Alexander Jones # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published # by the Free Software Foundation, either version 3 of the License, or # (at yo...
except ValueError: # Recurse return self.generate_matrix(home_teams=home_teams) return matrix def _generate_even_matches(self, evens): """Generate a list of matches for even meeting counts.""" return [(team, opp) for team in self.teams ...
is_home = opp in home_opps matrix[i][opp] = is_home matrix[opp][i] = not is_home
conditional_block
roundrobin.py
# -*- coding: utf-8 -*- """Round-robin scheduling.""" # Copyright (C) 2015 Alexander Jones # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published # by the Free Software Foundation, either version 3 of the License, or # (at yo...
(self, teams): """Constructor. @param teams: A list of teams or the number of teams @type teams: list or int """ super(QuadrupleRoundRobinScheduler, self).__init__(teams, meetings=4)
__init__
identifier_name
SmoothScroll.js
} if ( // If the character is in the range [\1-\1F] (U+0001 to U+001F) or is // U+007F, […] (codeUnit >= 0x0001 && codeUnit <= 0x001F) || codeUnit == 0x007F || // If the character is the first character and is in the range [0-9] ...
random_line_split
SmoothScroll.js
* time : 1 - 8 * (--time) * time * time * time; // acceleration until halfway, then deceleration if (settings.easing === 'easeInQuint') pattern = time * time * time * time * time; // accelerating from zero velocity if (settings.easing === 'easeOutQuint') pattern = 1 + (--time) * time * time * time * ti...
timestamp; }
conditional_block
numberwidget.py
import os from PyQt4.QtCore import pyqtSignal from PyQt4.QtGui import QComboBox, QDoubleValidator from configmanager.editorwidgets.core import ConfigWidget from configmanager.editorwidgets.uifiles.ui_numberwidget_config import Ui_Form class NumberWidgetConfig(Ui_Form, ConfigWidget): description = 'Number entry w...
def setconfig(self, config): self.blockSignals(True) max = config.get('max', '') min = config.get('min', '') prefix = config.get('prefix', '') suffix = config.get('suffix', '') self.minEdit.setText(min) self.maxEdit.setText(max) self.prefixEdit.setTe...
config = {} config['max'] = self.maxEdit.text() config['min'] = self.minEdit.text() config['prefix'] = self.prefixEdit.text() config['suffix'] = self.suffixEdit.text() return config
identifier_body
numberwidget.py
import os from PyQt4.QtCore import pyqtSignal from PyQt4.QtGui import QComboBox, QDoubleValidator from configmanager.editorwidgets.core import ConfigWidget from configmanager.editorwidgets.uifiles.ui_numberwidget_config import Ui_Form class NumberWidgetConfig(Ui_Form, ConfigWidget): description = 'Number entry w...
(self, parent=None): super(NumberWidgetConfig, self).__init__(parent) self.setupUi(self) self.minEdit.setValidator( QDoubleValidator() ) self.maxEdit.setValidator( QDoubleValidator() ) self.minEdit.textChanged.connect(self.widgetchanged) self.maxEdit.textChanged.connect(...
__init__
identifier_name
numberwidget.py
import os from PyQt4.QtCore import pyqtSignal from PyQt4.QtGui import QComboBox, QDoubleValidator from configmanager.editorwidgets.core import ConfigWidget from configmanager.editorwidgets.uifiles.ui_numberwidget_config import Ui_Form class NumberWidgetConfig(Ui_Form, ConfigWidget): description = 'Number entry w...
self.minEdit.setText(min) self.maxEdit.setText(max) self.prefixEdit.setText(prefix) self.suffixEdit.setText(suffix) self.blockSignals(False)
suffix = config.get('suffix', '')
random_line_split
formatter.js
'use strict'; // Oracle Formatter // ------ module.exports = function(client) { var Formatter = require('../../formatter'); var inherits = require('inherits'); // The "formatter" is used to ensure all output is properly // escaped & parameterized. function Formatter_Oracle()
inherits(Formatter_Oracle, Formatter); Formatter_Oracle.prototype.operators = [ '=', '<', '>', '<=', '>=', '<>', '!=', 'like', 'not like', 'between', 'ilike', '&', '|', '^', '<<', '>>', 'rlike', 'regexp', 'not regexp' ]; // Wraps a value (column, tableName) with the correct ticks. Formatter_Oracle.prototype....
{ this.client = client; Formatter.apply(this, arguments); }
identifier_body
formatter.js
'use strict'; // Oracle Formatter // ------ module.exports = function(client) { var Formatter = require('../../formatter'); var inherits = require('inherits'); // The "formatter" is used to ensure all output is properly // escaped & parameterized. function Formatter_Oracle() { this.client = client; Formatter.ap...
} return sql; }; // Assign the formatter to the the client. client.Formatter = Formatter_Oracle; };
{ sql = '(' + sql + ')'; if (compiled.as) sql += ' ' + this.wrap(compiled.as); }
conditional_block
formatter.js
'use strict'; // Oracle Formatter // ------ module.exports = function(client) { var Formatter = require('../../formatter'); var inherits = require('inherits'); // The "formatter" is used to ensure all output is properly // escaped & parameterized. function Formatter_Oracle() { this.client = client; Formatter.ap...
} return wrapped.join('.'); }; // Memoize the calls to "wrap" for a little extra perf. var wrapperMemo = (function(){ var memo = Object.create(null); return function(key) { if (memo[key] === void 0) { memo[key] = this._wrapString(key); } return memo[key]; }; }()); Formatter_Oracle.prototyp...
}
random_line_split
formatter.js
'use strict'; // Oracle Formatter // ------ module.exports = function(client) { var Formatter = require('../../formatter'); var inherits = require('inherits'); // The "formatter" is used to ensure all output is properly // escaped & parameterized. function
() { this.client = client; Formatter.apply(this, arguments); } inherits(Formatter_Oracle, Formatter); Formatter_Oracle.prototype.operators = [ '=', '<', '>', '<=', '>=', '<>', '!=', 'like', 'not like', 'between', 'ilike', '&', '|', '^', '<<', '>>', 'rlike', 'regexp', 'not regexp' ]; // Wraps a value (colu...
Formatter_Oracle
identifier_name
bitpacker.rs
use std::io::Write; use std::io; use common::serialize::BinarySerializable; use std::mem; /// Computes the number of bits that will be used for bitpacking. /// /// In general the target is the minimum number of bits /// required to express the amplitude given in argument. /// /// e.g. If the amplitude is 10, we can s...
<TWrite: Write>(&mut self, output: &mut TWrite) -> io::Result<()> { if self.mini_buffer_written > 0 { let num_bytes = (self.mini_buffer_written + 7) / 8; let arr: [u8; 8] = unsafe { mem::transmute::<u64, [u8; 8]>(self.mini_buffer) }; output.write_all(&arr[..num_bytes])?; ...
flush
identifier_name
bitpacker.rs
use std::io::Write; use std::io; use common::serialize::BinarySerializable; use std::mem; /// Computes the number of bits that will be used for bitpacking. /// /// In general the target is the minimum number of bits /// required to express the amplitude given in argument. /// /// e.g. If the amplitude is 10, we can s...
) .collect(); for &val in &vals { bitpacker.write(val, &mut data).unwrap(); } let num_bytes = bitpacker.close(&mut data).unwrap(); assert_eq!(num_bytes, (num_bits * len + 7) / 8 + 7); assert_eq!(data.len(), num_bytes); let bitunpacker = BitUnpacker...
{ i % max_val }
conditional_block
bitpacker.rs
use std::io::Write; use std::io; use common::serialize::BinarySerializable; use std::mem; /// Computes the number of bits that will be used for bitpacking. /// /// In general the target is the minimum number of bits /// required to express the amplitude given in argument. /// /// e.g. If the amplitude is 10, we can s...
data_ptr: data.as_ptr(), data_len: data.len(), } } pub fn get(&self, idx: usize) -> u64 { if self.num_bits == 0 { return 0; } let addr = (idx * self.num_bits) / 8; let bit_shift = idx * self.num_bits - addr * 8; let val_unshift...
random_line_split
regions-close-over-type-parameter-2.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 repeater3<'a,A:'a>(v: A) -> Box<Foo+'a> { box v as Box<Foo+'a> } fn main() { // Error results because the type of is inferred to be // ~Repeat<&'blk isize> where blk is the lifetime of the block below. let _ = { let tmp0 = 3; let tmp1 = &tmp0; //~ ERROR `tmp0` does not live long...
{ }
identifier_body
regions-close-over-type-parameter-2.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
}
let _ = { let tmp0 = 3; let tmp1 = &tmp0; //~ ERROR `tmp0` does not live long enough repeater3(tmp1) };
random_line_split
regions-close-over-type-parameter-2.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 ...
() { // Error results because the type of is inferred to be // ~Repeat<&'blk isize> where blk is the lifetime of the block below. let _ = { let tmp0 = 3; let tmp1 = &tmp0; //~ ERROR `tmp0` does not live long enough repeater3(tmp1) }; }
main
identifier_name
lin_reg.rs
use rm::linalg::Matrix; use rm::linalg::Vector; use rm::learning::SupModel; use rm::learning::lin_reg::LinRegressor; use libnum::abs; #[test] fn test_optimized_regression() { let mut lin_mod = LinRegressor::default(); let inputs = Matrix::new(3, 1, vec![2.0, 3.0, 4.0]); let targets = Vector::new(vec![5.0, ...
() { let inputs = Matrix::new(0, 1, vec![]); let targets = Vector::new(vec![]); let mut lin_mod = LinRegressor::default(); let res = lin_mod.train(&inputs, &targets); assert!(res.is_err()); }
test_train_no_data
identifier_name
lin_reg.rs
use rm::linalg::Matrix; use rm::linalg::Vector; use rm::learning::SupModel; use rm::learning::lin_reg::LinRegressor; use libnum::abs; #[test] fn test_optimized_regression() { let mut lin_mod = LinRegressor::default(); let inputs = Matrix::new(3, 1, vec![2.0, 3.0, 4.0]); let targets = Vector::new(vec![5.0, ...
#[test] #[ignore = "FIXME #183 fails nondeterministically"] fn test_train_no_data() { let inputs = Matrix::new(0, 1, vec![]); let targets = Vector::new(vec![]); let mut lin_mod = LinRegressor::default(); let res = lin_mod.train(&inputs, &targets); assert!(res.is_err()); }
{ use rm::datasets::trees; let trees = trees::load(); let mut lin_mod = LinRegressor::default(); lin_mod.train(&trees.data(), &trees.target()).unwrap(); let params = lin_mod.parameters().unwrap(); assert_eq!(params, &Vector::new(vec![-57.98765891838409, 4.708160503017506, 0.3392512342447438]));...
identifier_body
lin_reg.rs
use rm::linalg::Matrix; use rm::linalg::Vector; use rm::learning::SupModel; use rm::learning::lin_reg::LinRegressor; use libnum::abs; #[test] fn test_optimized_regression() { let mut lin_mod = LinRegressor::default(); let inputs = Matrix::new(3, 1, vec![2.0, 3.0, 4.0]); let targets = Vector::new(vec![5.0, ...
let lin_mod = LinRegressor::default(); let inputs = Matrix::new(3, 2, vec![1.0, 2.0, 1.0, 3.0, 1.0, 4.0]); let _ = lin_mod.predict(&inputs).unwrap(); } #[cfg(feature = "datasets")] #[test] fn test_regression_datasets_trees() { use rm::datasets::trees; let trees = trees::load(); let mut lin_mo...
fn test_no_train_predict() {
random_line_split
gitignore.js
/* @flow */ import type { CreateTemplate } from '../../types'; module.exports = (createTemplate: CreateTemplate) => createTemplate` # Gluestick autogenerated files gluestick/entries.js gluestick/clientEntryInit # Logs logs *.log npm-debug.log* # Runtime data pids *.pid *.seed # Directory for instrumented libs gener...
# node-waf configuration .lock-wscript # Compiled binary addons (http://nodejs.org/api/addons.html) build _build # Dependency directory # https://docs.npmjs.com/misc/faq#should-i-check-my-node-modules-folder-into-git node_modules # Optional npm cache directory .npm # Optional REPL history .node_repl_history `;
random_line_split
watch.js
module.exports = { livereload: { options: { livereload: '<%= express.options.livereload %>' }, files: [
'<%= yeoman.src %>/{,*/}*.js', '<%= yeoman.src %>/{,*/}*.css', '<%= yeoman.src %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}' ] }, test: { options: { livereload: { port: 35728 } }, files: [ '<%...
'<%= yeoman.currentDir %>', '<%= yeoman.demo %>/**/*.html', '<%= yeoman.demo %>/**/*.js', '<%= yeoman.styles %>/{,*/}*.css', '<%= yeoman.src %>/**/*.html',
random_line_split
decompressor.rs
use ll; use parse_code; use std::io; struct DecoderContext { c: *mut ll::ZSTD_DCtx, } impl Default for DecoderContext { fn default() -> Self { DecoderContext { c: unsafe { ll::ZSTD_createDCtx() }, } } } impl Drop for DecoderContext { fn drop(&mut self) { let code ...
self.dict.len(), ) }; parse_code(code) } /// Decompress a block of data, and return the decompressed result in a `Vec<u8>`. /// /// The decompressed data should be less than `capacity` bytes, /// or an error will be returned. pub fn decompress( ...
random_line_split
decompressor.rs
use ll; use parse_code; use std::io; struct DecoderContext { c: *mut ll::ZSTD_DCtx, } impl Default for DecoderContext { fn
() -> Self { DecoderContext { c: unsafe { ll::ZSTD_createDCtx() }, } } } impl Drop for DecoderContext { fn drop(&mut self) { let code = unsafe { ll::ZSTD_freeDCtx(self.c) }; parse_code(code).unwrap(); } } /// Allows to decompress independently multiple blocks of...
default
identifier_name
decompressor.rs
use ll; use parse_code; use std::io; struct DecoderContext { c: *mut ll::ZSTD_DCtx, } impl Default for DecoderContext { fn default() -> Self
} impl Drop for DecoderContext { fn drop(&mut self) { let code = unsafe { ll::ZSTD_freeDCtx(self.c) }; parse_code(code).unwrap(); } } /// Allows to decompress independently multiple blocks of data. /// /// This reduces memory usage compared to calling `decompress` multiple times. #[derive(Def...
{ DecoderContext { c: unsafe { ll::ZSTD_createDCtx() }, } }
identifier_body
Example.tsx
import React, { useState, useCallback } from 'react'; import { Tooltip, TooltipWithBounds, useTooltip, useTooltipInPortal, defaultStyles, } from '@visx/tooltip'; export type TooltipProps = { width: number; height: number; showControls?: boolean; }; type TooltipData = string; const positionIndicatorSi...
); }
line-height: 1.2em; } `}</style> </>
random_line_split
Expression.js
import GLBoost from '../../globals'; import GLBoostObject from '../../low_level/core/GLBoostObject'; export default class Expression extends GLBoostObject {
(glBoostContext) { super(glBoostContext); this._renderPasses = []; } addRenderPasses(renderPasses) { renderPasses.forEach((renderPass)=>{ renderPass._expression = this; }); this._renderPasses = this._renderPasses.concat(renderPasses); } addRenderPass(renderPass) { renderPat...
constructor
identifier_name
Expression.js
import GLBoost from '../../globals'; import GLBoostObject from '../../low_level/core/GLBoostObject'; export default class Expression extends GLBoostObject { constructor(glBoostContext) { super(glBoostContext); this._renderPasses = []; } addRenderPasses(renderPasses) { renderPasses.forEach((renderP...
} } prepareToRender() { this._renderPasses.forEach((renderPass, index)=>{ renderPass.prepareToRender(this); }); } } GLBoost['Expression'] = Expression;
{ renderPass.scene.setCurrentAnimationValue(inputName, inputValue); }
conditional_block
Expression.js
import GLBoost from '../../globals'; import GLBoostObject from '../../low_level/core/GLBoostObject'; export default class Expression extends GLBoostObject { constructor(glBoostContext) { super(glBoostContext); this._renderPasses = []; } addRenderPasses(renderPasses) { renderPasses.forEach((renderP...
} GLBoost['Expression'] = Expression;
{ this._renderPasses.forEach((renderPass, index)=>{ renderPass.prepareToRender(this); }); }
identifier_body
Expression.js
import GLBoost from '../../globals'; import GLBoostObject from '../../low_level/core/GLBoostObject'; export default class Expression extends GLBoostObject { constructor(glBoostContext) { super(glBoostContext); this._renderPasses = []; } addRenderPasses(renderPasses) { renderPasses.forEach((renderP...
if (renderPass.scene) { renderPass.scene.setCurrentAnimationValue(inputName, inputValue); } } } prepareToRender() { this._renderPasses.forEach((renderPass, index)=>{ renderPass.prepareToRender(this); }); } } GLBoost['Expression'] = Expression;
for (let renderPass of this.renderPasses) {
random_line_split
mod.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 servo::config::opts; use std::ptr; use std::thread; use std::time::Duration; pub fn deinit() { // An unf...
else { println!("All threads have shutdown (good)."); } } #[link_section = "__TEXT,__info_plist"] #[no_mangle] pub static INFO_PLIST: [u8; 619] = *include_bytes!("Info.plist"); #[link(name = "count_threads")] extern { fn macos_count_running_threads() -> i32; }
{ println!("{} threads are still running after shutdown (bad).", thread_count); if opts::get().clean_shutdown { println!("Waiting until all threads have shutdown"); loop { let thread_count = unsafe { macos_count_running_threads() ...
conditional_block
mod.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 servo::config::opts; use std::ptr; use std::thread; use std::time::Duration; pub fn deinit() { // An unf...
} } #[link_section = "__TEXT,__info_plist"] #[no_mangle] pub static INFO_PLIST: [u8; 619] = *include_bytes!("Info.plist"); #[link(name = "count_threads")] extern { fn macos_count_running_threads() -> i32; }
println!("{} threads are still running.", thread_count); } } } else { println!("All threads have shutdown (good).");
random_line_split
mod.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 servo::config::opts; use std::ptr; use std::thread; use std::time::Duration; pub fn
() { // An unfortunate hack to make sure the linker's dead code stripping doesn't strip our // `Info.plist`. unsafe { ptr::read_volatile(&INFO_PLIST[0]); } let thread_count = unsafe { macos_count_running_threads() }; if thread_count != 1 { println!("{} threads are s...
deinit
identifier_name
mod.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 servo::config::opts; use std::ptr; use std::thread; use std::time::Duration; pub fn deinit()
break; } thread::sleep(Duration::from_millis(1000)); println!("{} threads are still running.", thread_count); } } } else { println!("All threads have shutdown (good)."); } } #[link_section = "__TEXT,__info_plist"] ...
{ // An unfortunate hack to make sure the linker's dead code stripping doesn't strip our // `Info.plist`. unsafe { ptr::read_volatile(&INFO_PLIST[0]); } let thread_count = unsafe { macos_count_running_threads() }; if thread_count != 1 { println!("{} threads are stil...
identifier_body
index.js
/** * Created by gjrwcs on 10/25/2016. */ 'use strict'; /** * Game Behavior and Logic for Warp * @module pulsar.warp */ var warp = require('angular').module('pulsar.warp', []); const ADT = require('../app.dependency-tree.js').ADT; ADT.warp = { Level: 'warp.Level', WarpField: 'warp.WarpField', Bar: 'w...
module.exports = warp;
require('./warp-field-cache.svc'); require('./warp-field-draw.svc'); require('./state.svc');
random_line_split
dialog.d.ts
import { BlockScrollStrategy, Overlay, ScrollStrategy } from '@angular/cdk/overlay'; import { ComponentType } from '@angular/cdk/portal'; import { Location } from '@angular/common'; import { InjectionToken, Injector, TemplateRef } from '@angular/core'; import { Observable } from 'rxjs/Observable'; import { Subject } fr...
{ private _overlay; private _injector; private _scrollStrategy; private _parentDialog; private _openDialogsAtThisLevel; private _afterAllClosedAtThisLevel; private _afterOpenAtThisLevel; /** Keeps track of the currently-open dialogs. */ readonly openDialogs: MatDialogRef<any>[]; ...
MatDialog
identifier_name