file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
39k
suffix
large_stringlengths
0
36.1k
middle
large_stringlengths
0
29.4k
fim_type
large_stringclasses
4 values
experiment.py
#!/usr/bin/env python """ Manage and display experimental results. """ __license__ = 'MIT License <http://www.opensource.org/licenses/mit-license.php>' __author__ = 'Lucas Theis <lucas@theis.io>' __docformat__ = 'epytext' __version__ = '0.4.3' import sys import os import numpy import random import scipy import socke...
else: self.wfile.write('No running experiments.') self.wfile.write('<h2>Saved</h2>') # display saved experiments if ExperimentRequestHandler.finished: self.wfile.write('<table>') self.wfile.write('<tr>') self.wfile.write('<th>Results</th>') self.wfile.write('<th>Status</th>') sel...
self.wfile.write('<table>') self.wfile.write('<tr>') self.wfile.write('<th>Experiment</th>') self.wfile.write('<th>Hostname</th>') self.wfile.write('<th>Status</th>') self.wfile.write('<th>Progress</th>') self.wfile.write('<th>Start</th>') self.wfile.write('<th>Comment</th>') self.wfile....
conditional_block
experiment.py
#!/usr/bin/env python """ Manage and display experimental results. """ __license__ = 'MIT License <http://www.opensource.org/licenses/mit-license.php>' __author__ = 'Lucas Theis <lucas@theis.io>' __docformat__ = 'epytext' __version__ = '0.4.3' import sys import os import numpy import random import scipy import socke...
instance = ExperimentRequestHandler.running[id] num_bars = int(instance['progress']) * max_bars / 100 self.wfile.write('<tr>') self.wfile.write('<td class="filepath"><a href="/running/{1}/">{0}</a></td>'.format( instance['script_path'], instance['id'])) self.wfile.write('<td>{0}</td>'.fo...
ids = ExperimentRequestHandler.running.keys() ids = [ids[i] for i in argsort(times)][::-1] for id in ids:
random_line_split
general.py
import discord from discord.ext import commands from .utils.chat_formatting import escape_mass_mentions, italics, pagify from random import randint from random import choice from enum import Enum from urllib.parse import quote_plus import datetime import time import aiohttp import asyncio settings = {"POLL...
try: if len(search_terms) > 1: pos = int(search_terms[-1]) - 1 search_terms = search_terms[:-1] else: pos = 0 if pos not in range(0, 11): # API only provides the pos = 0 # top 10 definition...
search_terms = search_terms.split(" ")
random_line_split
general.py
import discord from discord.ext import commands from .utils.chat_formatting import escape_mass_mentions, italics, pagify from random import randint from random import choice from enum import Enum from urllib.parse import quote_plus import datetime import time import aiohttp import asyncio settings = {"POLL...
0] msg.remove(self.question) self.answers = {} i = 1 for answer in msg: # {id : {answer, votes}} self.answers[i] = {"ANSWER" : answer, "VOTES" : 0} i += 1 async def start(self): msg = "**POLL STARTED!**\n\n{}\n\n".format(self.question) ...
dy_voted = [] self.question = msg[
conditional_block
general.py
import discord from discord.ext import commands from .utils.chat_formatting import escape_mass_mentions, italics, pagify from random import randint from random import choice from enum import Enum from urllib.parse import quote_plus import datetime import time import aiohttp import asyncio settings = {"POLL...
0341705637888" and server.id == "133049272517001216": return datetime.datetime(2016, 1, 10, 6, 8, 4, 443000) else: return user.joined_at class NewPoll(): def __init__(self, message, text, main): self.channel = message.channel self.author = message.author.id ...
ser.id == "9613
identifier_name
general.py
import discord from discord.ext import commands from .utils.chat_formatting import escape_mass_mentions, italics, pagify from random import randint from random import choice from enum import Enum from urllib.parse import quote_plus import datetime import time import aiohttp import asyncio settings = {"POLL...
annel == message.channel: return poll return False async def check_poll_votes(self, message): if message.author.id != self.bot.user.id: if self.getPollByChannel(message): self.getPollByChannel(message).checkAnswer(message) def fetch_join...
= message.author.id: # or isMemberAdmin(message) await self.getPollByChannel(message).endPoll() else: await self.bot.say("Only admins and the author can stop the poll.") else: await self.bot.say("There's no poll ongoing in this channel.") def g...
identifier_body
runLCWeekly.py
import sys from fermipy import utils utils.init_matplotlib_backend() from fermipy.gtanalysis import GTAnalysis from fermipy.utils import * import yaml import pprint import numpy import argparse from fermipy.gtanalysis import GTAnalysis def main(): usage = "usage: %(prog)s [config file]" description =...
gta.setup() gta.optimize() loc = gta.localize(src_name, free_radius=1.0, update=True, make_plots=True) model = {'Index' : 2.0, 'SpatialModel' : 'PointSource'} srcs = gta.find_sources(model=model, sqrt_ts_threshold=5.0, min_separation=0.5) sed = gta.sed(src_na...
src_name = gta.roi.sources[0].name
conditional_block
runLCWeekly.py
import sys from fermipy import utils utils.init_matplotlib_backend() from fermipy.gtanalysis import GTAnalysis from fermipy.utils import * import yaml import pprint import numpy import argparse from fermipy.gtanalysis import GTAnalysis def
(): usage = "usage: %(prog)s [config file]" description = "Run fermipy analysis chain." parser = argparse.ArgumentParser(usage=usage,description=description) parser.add_argument('--config', default = 'sample_config.yaml') parser.add_argument('--source', default = None) args = parser.p...
main
identifier_name
runLCWeekly.py
import sys from fermipy import utils utils.init_matplotlib_backend() from fermipy.gtanalysis import GTAnalysis from fermipy.utils import * import yaml import pprint import numpy import argparse from fermipy.gtanalysis import GTAnalysis def main(): usage = "usage: %(prog)s [config file]" description =...
lc = gta.lightcurve(src_name, binsz=86400.*7.0, free_radius=3.0, use_scaled_srcmap=True, multithread=False) if __name__ == "__main__": main()
gta.write_roi('fit0')
random_line_split
runLCWeekly.py
import sys from fermipy import utils utils.init_matplotlib_backend() from fermipy.gtanalysis import GTAnalysis from fermipy.utils import * import yaml import pprint import numpy import argparse from fermipy.gtanalysis import GTAnalysis def main():
if __name__ == "__main__": main()
usage = "usage: %(prog)s [config file]" description = "Run fermipy analysis chain." parser = argparse.ArgumentParser(usage=usage,description=description) parser.add_argument('--config', default = 'sample_config.yaml') parser.add_argument('--source', default = None) args = parser.parse_args() g...
identifier_body
weather_list.js
import React, { Component } from 'react'; import { connect } from 'react-redux'; import Chart from '../components/chart'; import GoogleMap from '../components/google_map' //npm i --save react-sparklines@1.6.0 class WeatherList extends Component { renderWeather(cityData){ const name = cityData.city.name...
<th> Humidity (%) </th> </tr> </thead> <tbody> {this.props.weather.map(this.renderWeather)} </tbody> </table> )}; } function mapStateToProps (state){ return { weather: state.weather};...
<th> Temperature (°C) </th> <th> Pressure (hPa) </th>
random_line_split
weather_list.js
import React, { Component } from 'react'; import { connect } from 'react-redux'; import Chart from '../components/chart'; import GoogleMap from '../components/google_map' //npm i --save react-sparklines@1.6.0 class WeatherList extends Component { renderWeather(cityData){ const name = cityData.city.name...
state){ return { weather: state.weather}; } export default connect (mapStateToProps)(WeatherList);
pStateToProps (
identifier_name
weather_list.js
import React, { Component } from 'react'; import { connect } from 'react-redux'; import Chart from '../components/chart'; import GoogleMap from '../components/google_map' //npm i --save react-sparklines@1.6.0 class WeatherList extends Component { renderWeather(cityData){ const name = cityData.city.name...
export default connect (mapStateToProps)(WeatherList);
return { weather: state.weather}; }
identifier_body
instances.controller.ts
/* * Copyright (C) 2015 The Gravitee team (http://gravitee.io) * * 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 requi...
() { return this.instances.length === 0; } } export default InstancesController;
displayEmptyMode
identifier_name
instances.controller.ts
/* * Copyright (C) 2015 The Gravitee team (http://gravitee.io) * * 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 requi...
$onInit() { this.searchGatewayInstances = ''; this.startedInstances = _.filter(this.instances, { 'state': 'started'}); this._displayEmptyMode = this.startedInstances.length === 0; this.$scope.displayAllInstances = false; let that = this; this.$scope.switchDisplayInstances = function() { ...
{ 'ngInject'; }
identifier_body
instances.controller.ts
/* * Copyright (C) 2015 The Gravitee team (http://gravitee.io) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at
* * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language...
random_line_split
Header.js
import React from 'react'; import PropTypes from 'prop-types'; import { Link } from 'react-router-dom'; import { FormattedMessage } from 'react-intl'; // Import Style import styles from './Header.css'; export function Header(props, context) { const languageNodes = props.intl.enabledLanguages.map( lang => <li ke...
</div> <div className={styles.content}> <h1 className={styles['site-title']}> <Link to="/" ><FormattedMessage id="siteTitle" /></Link> </h1> { renderAddPostButton ? <a className={styles['add-post-button']} href="#" onClick={props.toggleAddPost}><Format...
<li><FormattedMessage id="switchLanguage" /></li> {languageNodes} </ul>
random_line_split
Header.js
import React from 'react'; import PropTypes from 'prop-types'; import { Link } from 'react-router-dom'; import { FormattedMessage } from 'react-intl'; // Import Style import styles from './Header.css'; export function Header(props, context)
Header.contextTypes = { router: PropTypes.object, }; Header.propTypes = { toggleAddPost: PropTypes.func.isRequired, switchLanguage: PropTypes.func.isRequired, intl: PropTypes.object.isRequired, }; export default Header;
{ const languageNodes = props.intl.enabledLanguages.map( lang => <li key={lang} onClick={() => props.switchLanguage(lang)} className={lang === props.intl.locale ? styles.selected : ''}>{lang}</li> ); const renderAddPostButton = context.router.isActive ? context.router.isActive() : ...
identifier_body
Header.js
import React from 'react'; import PropTypes from 'prop-types'; import { Link } from 'react-router-dom'; import { FormattedMessage } from 'react-intl'; // Import Style import styles from './Header.css'; export function
(props, context) { const languageNodes = props.intl.enabledLanguages.map( lang => <li key={lang} onClick={() => props.switchLanguage(lang)} className={lang === props.intl.locale ? styles.selected : ''}>{lang}</li> ); const renderAddPostButton = context.router.isActive ? context.router.isActive() : ...
Header
identifier_name
create.py
"""Creates a user """ # :license: MIT, see LICENSE for more details. import json import string import sys import click import SoftLayer from SoftLayer.CLI import environment from SoftLayer.CLI import exceptions from SoftLayer.CLI import formatting from SoftLayer.CLI import helpers @click.command() @click.argument(...
(env, username, email, password, from_user, template): """Creates a user Users. Remember to set the permissions and access for this new user. Example:: slcli user create my@email.com -e my@email.com -p generate -a -t '{"firstName": "Test", "lastName": "Testerson"}' """ mgr = Sof...
cli
identifier_name
create.py
"""Creates a user """ # :license: MIT, see LICENSE for more details. import json import string import sys
import click import SoftLayer from SoftLayer.CLI import environment from SoftLayer.CLI import exceptions from SoftLayer.CLI import formatting from SoftLayer.CLI import helpers @click.command() @click.argument('username') @click.option('--email', '-e', required=True, help="Email address for this user. R...
random_line_split
create.py
"""Creates a user """ # :license: MIT, see LICENSE for more details. import json import string import sys import click import SoftLayer from SoftLayer.CLI import environment from SoftLayer.CLI import exceptions from SoftLayer.CLI import formatting from SoftLayer.CLI import helpers @click.command() @click.argument(...
else: from_user_id = helpers.resolve_id(mgr.resolve_ids, from_user, 'username') user_template = mgr.get_user(from_user_id, objectmask=user_mask) # If we send the ID back to the API, an exception will be thrown del user_template['id'] if template is not None: try: te...
user_template = mgr.get_current_user(objectmask=user_mask) from_user_id = user_template['id']
conditional_block
create.py
"""Creates a user """ # :license: MIT, see LICENSE for more details. import json import string import sys import click import SoftLayer from SoftLayer.CLI import environment from SoftLayer.CLI import exceptions from SoftLayer.CLI import formatting from SoftLayer.CLI import helpers @click.command() @click.argument(...
"""Returns a 23 character random string, with 3 special characters at the end""" if sys.version_info > (3, 6): import secrets # pylint: disable=import-error,import-outside-toplevel alphabet = string.ascii_letters + string.digits password = ''.join(secrets.choice(alphabet) for i in range(20)...
identifier_body
main.py
#coding: utf-8 #!/usr/bin/env python3 #Initial test code for MiSynth Wave Generator #Opens Wave Files And Cuts And Plays Them As The FPGA will #Synth plays back 2048 samples at frequency of note #Effective sample rate is 901,120Hz @ 440Hz #CURRENTLY A DRAWING LOOP TO BE SOLVED, THANKS WX/PYTHON FOR YOUR #COMPLETE LACK...
def OnOpenButton(self, evt): #Open file with wx.FileDialog(self, "Open .wav file.", wildcard="WAV files (*.wav)|*.wav", style=wx.FD_OPEN | wx.FD_FILE_MUST_EXIST) as fileDialog: if fileDialog.ShowModal() == wx.ID_CANCEL: return # the user chan...
if self.wavepanel.mouseOver: if self.wavepanel.ctrlDown: if event.GetWheelRotation() > 0: if(self.scale > 1): self.scale = self.scale >> 1 else: if(self.scale < 2097151): self.scale = self...
identifier_body
main.py
#coding: utf-8 #!/usr/bin/env python3 #Initial test code for MiSynth Wave Generator #Opens Wave Files And Cuts And Plays Them As The FPGA will #Synth plays back 2048 samples at frequency of note #Effective sample rate is 901,120Hz @ 440Hz #CURRENTLY A DRAWING LOOP TO BE SOLVED, THANKS WX/PYTHON FOR YOUR #COMPLETE LACK...
if self.mouseOver: x, y = self.ScreenToClient(wx.GetMousePosition()) sector = abs(x // (2048 / self.getter())) self.sender(sector) def onMouseOver(self, event): self.mouseOver = True def onMouseLeave(self, event): self.mouseOver = False def onKe...
def onMouseClick(self, event):
random_line_split
main.py
#coding: utf-8 #!/usr/bin/env python3 #Initial test code for MiSynth Wave Generator #Opens Wave Files And Cuts And Plays Them As The FPGA will #Synth plays back 2048 samples at frequency of note #Effective sample rate is 901,120Hz @ 440Hz #CURRENTLY A DRAWING LOOP TO BE SOLVED, THANKS WX/PYTHON FOR YOUR #COMPLETE LACK...
self.Refresh() if self.scopepanel.mouseOver: if event.GetWheelRotation() > 0: self.audiohandle.setshift(1) else: self.audiohandle.setshift(-1) self.scope = self.audiohandle.getscopesample() self.Refresh() def O...
if (self.shift < 10000000): self.shift += 2000
conditional_block
main.py
#coding: utf-8 #!/usr/bin/env python3 #Initial test code for MiSynth Wave Generator #Opens Wave Files And Cuts And Plays Them As The FPGA will #Synth plays back 2048 samples at frequency of note #Effective sample rate is 901,120Hz @ 440Hz #CURRENTLY A DRAWING LOOP TO BE SOLVED, THANKS WX/PYTHON FOR YOUR #COMPLETE LACK...
(self, sector): print("obtaining sample") if self.quadrant == -1: self.setsector(1) sample = self.wavehandle.getaudiodata(self.shift, 0, sector) return sample def onPaint(self, event): self.drawcnt += 1 #print("Drawing" + str(self.drawcnt)) dc = w...
getSample
identifier_name
exames.server.controller.js
'use strict'; /** * Module dependencies. */ var mongoose = require('mongoose'), errorHandler = require('./errors.server.controller'), Exame = mongoose.model('Exame'), _ = require('lodash'); /** * Create a Exame */ exports.create = function(req, res) { var exame = new Exame(req.body); exame.user = req.user; ...
exame = _.extend(exame , req.body); exame.save(function(err) { if (err) { return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } else { res.jsonp(exame); } }); }; /** * Delete an Exame */ exports.delete = function(req, res) { var exame = req.exame ; exame.remove(func...
random_line_split
exames.server.controller.js
'use strict'; /** * Module dependencies. */ var mongoose = require('mongoose'), errorHandler = require('./errors.server.controller'), Exame = mongoose.model('Exame'), _ = require('lodash'); /** * Create a Exame */ exports.create = function(req, res) { var exame = new Exame(req.body); exame.user = req.user; ...
}); }; /** * Exame authorization middleware */ exports.hasAuthorization = function(req, res, next) { if (req.exame.user.id !== req.user.id) { return res.status(403).send('User is not authorized'); } next(); };
{ res.jsonp(exames); }
conditional_block
global.ts
import { css, Theme } from "@emotion/react"; import "@fontsource/roboto/400.css"; import "@fontsource/roboto/500.css"; import "@fontsource/roboto/700.css"; import "@fontsource/roboto/900.css"; export const global = (theme: Theme) => css`
box-sizing: border-box; } /** Remove this when bootstrap is removed **/ html { scroll-behavior: revert !important; } body, html { margin: 0; padding: 0; font-family: "Roboto", sans-serif; color: ${theme.fontColor.normal}; font-size: 16px; } body { background: ${theme...
* {
random_line_split
test.js
'use strict'; module.exports = { db: 'mongodb://localhost/angle-test', port: 3001, app: { title: 'Angle - Test Environment'
clientSecret: process.env.FACEBOOK_SECRET || 'APP_SECRET', callbackURL: '/auth/facebook/callback' }, twitter: { clientID: process.env.TWITTER_KEY || 'CONSUMER_KEY', clientSecret: process.env.TWITTER_SECRET || 'CONSUMER_SECRET', callbackURL: '/auth/twitter/callback' }, google: { clientID: process.env.GOO...
}, facebook: { clientID: process.env.FACEBOOK_ID || 'APP_ID',
random_line_split
chorus.js
import {createCustomOsc} from './oscillator' export function createChorus(ctx: Object) { const merger = ctx.createChannelMerger(2) const input = ctx.createGain() const output = ctx.createGain() const feedbackL = ctx.createGain() const feedbackR = ctx.createGain() const delayL = ctx.createDelay() const de...
} } }
set(key, val) { setters[key](val)
random_line_split
chorus.js
import {createCustomOsc} from './oscillator' export function createChorus(ctx: Object) { const merger = ctx.createChannelMerger(2) const input = ctx.createGain() const output = ctx.createGain() const feedbackL = ctx.createGain() const feedbackR = ctx.createGain() const delayL = ctx.createDelay() const de...
(node) { output.connect(node) }, init(patch) { lfoL.init({ frequency: patch.frequency, type: patch.type, phase: 180 }) lfoR.init({ frequency: patch.frequency, type: patch.type, phase: 0 }) // TODO: Add public access to chorus depth here...
connect
identifier_name
chorus.js
import {createCustomOsc} from './oscillator' export function createChorus(ctx: Object)
{ const merger = ctx.createChannelMerger(2) const input = ctx.createGain() const output = ctx.createGain() const feedbackL = ctx.createGain() const feedbackR = ctx.createGain() const delayL = ctx.createDelay() const delayR = ctx.createDelay() const lfoLGain = ctx.createGain() const lfoRGain = ctx.crea...
identifier_body
csvportal.py
import arcpy, os, json, csv from portal import additem, shareItem, generateToken, getUserContent, updateItem, getGroupID, deleteItem, getGroupContent from metadata import metadata from ESRImapservice import ESRImapservice class csvportal(object): def __init__(self, user, password, portal, worksspace, group...
if name in self.existingIDs.keys(): result = deleteItem(self.existingIDs[name] , self.token, self.portal, self.user) if "success" in result.keys() and result["success"]: arcpy.AddMessage("Deleted layer: " + name ) elif "success" in result.keys() and not result["succes...
identifier_body
csvportal.py
import arcpy, os, json, csv from portal import additem, shareItem, generateToken, getUserContent, updateItem, getGroupID, deleteItem, getGroupContent from metadata import metadata from ESRImapservice import ESRImapservice class csvportal(object): def __init__(self, user, password, portal, worksspace, group...
def delLyr(self, name): if name in self.existingIDs.keys(): result = deleteItem(self.existingIDs[name] , self.token, self.portal, self.user) if "success" in result.keys() and result["success"]: arcpy.AddMessage("Deleted layer: " + name ) elif "...
arcpy.AddMessage("unsure of success for layer "+ name +" "+ json.dumps(result))
conditional_block
csvportal.py
from ESRImapservice import ESRImapservice class csvportal(object): def __init__(self, user, password, portal, worksspace, groups=[]): """Connect to portal with username and pasword, also set the local workspace""" self.user = user self.password = password self.portal = port...
import arcpy, os, json, csv from portal import additem, shareItem, generateToken, getUserContent, updateItem, getGroupID, deleteItem, getGroupContent from metadata import metadata
random_line_split
csvportal.py
import arcpy, os, json, csv from portal import additem, shareItem, generateToken, getUserContent, updateItem, getGroupID, deleteItem, getGroupContent from metadata import metadata from ESRImapservice import ESRImapservice class csvportal(object): def __init__(self, user, password, portal, worksspace, group...
(self, name): if name in self.existingIDs.keys(): result = deleteItem(self.existingIDs[name] , self.token, self.portal, self.user) if "success" in result.keys() and result["success"]: arcpy.AddMessage("Deleted layer: " + name ) elif "success" in result.keys()...
delLyr
identifier_name
collection.js
/* * collection * A collection of posts * * If fetch items are specified, then only gets those posts. * Otherwise, gets the posts specified from a configuration endpoint. */ define([ "lodash", "backbone", "helpers/urls", "helpers/types", "helpers/params", "components/content/entities/parser", "modul...
}, // merge in additional fetch items after initialize mergeItems: function(items) { // remove any new fetch items that are already fetched items = _.reject(items, function(item) { return this.get(item.object_id); }, this); // create a union of previous fetch items and the ...
{ this.off("add", this.maintainItems, this); }
conditional_block
collection.js
/* * collection * A collection of posts * * If fetch items are specified, then only gets those posts. * Otherwise, gets the posts specified from a configuration endpoint. */ define([ "lodash", "backbone", "helpers/urls", "helpers/types", "helpers/params", "components/content/entities/parser", "modul...
});
return parser(data); } }); return PostCollection;
random_line_split
cipher.rs
use random::{thread_rng, sample}; use serialize::hex::{FromHex, ToHex}; const BLOCK_SIZE_EXP: u32 = 3; // pow(2, 3) == 8 byte blocks pub enum Mode { Encrypt, Decrypt, } // Invokes the helper functions and does its shifting thing pub fn zombify(mode: Mode, data: &[u8], key: &str) -> Vec<u8> { let hex...
, } }
{ let mut i = data.len() - 1; while i >= size { data[i] = data[i] ^ data[i - size]; i -= 1; } let mut stuff = data[size..].to_owned(); for _ in 0..BLOCK_SIZE_EXP { stuff = charred(stuff); } ...
conditional_block
cipher.rs
use random::{thread_rng, sample}; use serialize::hex::{FromHex, ToHex}; const BLOCK_SIZE_EXP: u32 = 3; // pow(2, 3) == 8 byte blocks pub enum Mode { Encrypt, Decrypt, } // Invokes the helper functions and does its shifting thing pub fn zombify(mode: Mode, data: &[u8], key: &str) -> Vec<u8> { let hex...
(text: &[u8], key: &str) -> Vec<u8> { let key_array = key.as_bytes(); let (text_size, key_size) = (text.len(), key.len()); (0..text_size).map(|i| text[i] ^ key_array[i % key_size]).collect() } // CBC mode as a seed to scramble the final ciphertext fn cbc(mode: Mode, mut data: Vec<u8>) -> Vec<u8> { let ...
xor
identifier_name
cipher.rs
use random::{thread_rng, sample}; use serialize::hex::{FromHex, ToHex}; const BLOCK_SIZE_EXP: u32 = 3; // pow(2, 3) == 8 byte blocks pub enum Mode { Encrypt, Decrypt, } // Invokes the helper functions and does its shifting thing pub fn zombify(mode: Mode, data: &[u8], key: &str) -> Vec<u8> { let hex...
match mode { Mode::Encrypt => { let mut cbc_vec: Vec<u8> = sample(&mut thread_rng(), 1..255, size); // hex the bytes until the vector has the required length (an integral multiple of block size) for _ in 0..BLOCK_SIZE_EXP { data = data.to_hex().into_bytes(...
// Well, there's no encryption going on here - just some fireworks to introduce randomness
random_line_split
ground_station_base.py
import os from optparse import OptionParser import io import time import random import thread import sys from smtp_stuff import sendMail from imap_stuff import checkMessages import datetime import string import array from time import gmtime, strftime from socket import * user = '' recipient = '' incoming_server = ...
print "Exiting application." if __name__ == '__main__': main()
process_cmd(cmd_str)
conditional_block
ground_station_base.py
import os from optparse import OptionParser import io import time import random import thread import sys from smtp_stuff import sendMail from imap_stuff import checkMessages import datetime import string import array from time import gmtime, strftime from socket import * user = '' recipient = '' incoming_server = ...
MSG_TEXT_REPORT = 'U' MSG_TEXT_REPORT_NO_FIX = 'F' def parse_incoming(msg): #TODO: My gawd, this is ugly.. lets do something else? if msg[0] == MSG_TEXT_REPORT_NO_FIX: parse_text_report_no_fix(msg) elif msg[0] == MSG_TEXT_REPORT: parse_text_report(msg) def email_check_task(name): ...
report = report.split(":") report = report[1] report = report.split(",") time_str = report[0] lat = float(report[1]) lon = float(report[2]) alt = float(report[3]) kts = float(report[4]) crs = float(report[5]) position = [time_str,lat,lon,alt,kts,crs] int_temp = float(report[6]) ...
identifier_body
ground_station_base.py
import os from optparse import OptionParser import io import time import random import thread import sys from smtp_stuff import sendMail from imap_stuff import checkMessages import datetime import string import array from time import gmtime, strftime from socket import * user = '' recipient = '' incoming_server = '...
# create socket & connect to server sSock = socket(AF_INET, SOCK_STREAM) sSock.connect((aprs_server, aprs_port)) # logon sSock.send('user ' + aprs_callsign + ' pass ' + aprs_password + ' vers "' + aprs_callsign + ' Python" \n') #get position information and encode s...
global aprs_callsign #print position
random_line_split
ground_station_base.py
import os from optparse import OptionParser import io import time import random import thread import sys from smtp_stuff import sendMail from imap_stuff import checkMessages import datetime import string import array from time import gmtime, strftime from socket import * user = '' recipient = '' incoming_server = ...
(): global user global recipient global incoming_server global outgoing_server global password global email_enabled global ip_enabled global http_post_enabled global aprs_server global aprs_port global aprs_password global aprs_callsign global aprs_is_en...
main
identifier_name
isInstanceOf.js
/** * @name isInstanceOf * @description Checks if given flair class/struct instance is an instance of given class/struct type or * if given class instance implements given interface or has given mixin mixed somewhere in class * hierarchy * @example * isInstanceOf(obj, type) * @params ...
switch(_typeType) { case 'class': isMatched = objMeta.isInstanceOf(Type); if (!isMatched) { isMatched = objMeta.Type[meta].isDerivedFrom(Type); } break; case 'struct': isMatched = objMeta.isInstanceOf(Type); break; ...
if (flairTypes.indexOf(_typeType) === -1 && _typeType !== 'string') { throw _Exception.InvalidArgument('Type', _isInstanceOf); } let objMeta = obj[meta];
random_line_split
isInstanceOf.js
/** * @name isInstanceOf * @description Checks if given flair class/struct instance is an instance of given class/struct type or * if given class instance implements given interface or has given mixin mixed somewhere in class * hierarchy * @example * isInstanceOf(obj, type) * @params ...
if (!isMatched && typeof objMeta.isMixed === 'function') { isMatched = objMeta.isMixed(Type); } break; } // return return isMatched; }; // attach to flair a2f('isInstanceOf', _isInstanceOf);
{ isMatched = objMeta.isImplements(Type); }
conditional_block
main.ts
import {bootstrap} from '@angular/platform-browser-dynamic'; import {HAMMER_GESTURE_CONFIG} from '@angular/platform-browser'; import {DemoApp} from './app/demo-app'; import {HTTP_PROVIDERS} from '@angular/http'; import {ROUTER_PROVIDERS} from '@angular/router'; import {MdIconRegistry} from './components/icon/icon-regis...
]);
Renderer, provide(HAMMER_GESTURE_CONFIG, {useClass: MdGestureConfig})
random_line_split
test_innit.py
from recipe_scrapers.innit import Innit from tests import ScraperTest class TestInnitScraper(ScraperTest): scraper_class = Innit def test_host(self): self.assertEqual("innit.com", self.harvester_class.host()) def test_title(self): self.assertEqual( "Tofu Mixed Greens Salad w...
"1 1/3 tsp Kosher Salt", "2/3 cup Olive Oil", "2 pinches Black Pepper", "1/4 cup Rice Wine Vinegar", "1 cup Sunflower Seeds", ], self.harvester_class.ingredients(), ) def test_nutrients(self): se...
"2 packages Extra Firm Tofu", "1 Tbsp Miso Paste", "1/2 tsp Sesame Seed Oil", "1/2 Tbsp Honey",
random_line_split
test_innit.py
from recipe_scrapers.innit import Innit from tests import ScraperTest class TestInnitScraper(ScraperTest): scraper_class = Innit def test_host(self): self.assertEqual("innit.com", self.harvester_class.host()) def test_title(self): self.assertEqual( "Tofu Mixed Greens Salad w...
(self): self.assertEqual( "https://www.innit.com/meal-service/en-US/images/Meal-Salads%3A%20Blended-Carrot_Ginger_Dressing%2BAssembled-Broccoli_Beet_Mix%2BSeared-Tofu-Diced%2BOlive_Oil%2BPrepared-Mixed_Greens_480x480.png", self.harvester_class.image(), )
test_image
identifier_name
test_innit.py
from recipe_scrapers.innit import Innit from tests import ScraperTest class TestInnitScraper(ScraperTest): scraper_class = Innit def test_host(self): self.assertEqual("innit.com", self.harvester_class.host()) def test_title(self): self.assertEqual( "Tofu Mixed Greens Salad w...
def test_instructions(self): self.assertEqual( """Preheat Preheat the oven to 425F. Line sheet pan with foil. Sear Tofu Drain, pat dry & prepare tofu. Heat pan on high heat for 2 minutes. Cook for 7 min or until golden brown on all sides, seasoning half way. Remove from pan. Bake Broccoli Toss...
self.assertEqual( { "sugarContent": "18 g", "proteinContent": "32 g", "fiberContent": "11 g", "unsaturatedFatContent": "55 g", "fatContent": "64 g", "cholesterolContent": "0 mg", "calories": "830 ...
identifier_body
__init__.py
""" scraping the utility functions for the actual web scraping """ import ssl import datetime import requests import re # this is the endpoint that my new version of this program will # abuse with possible store ids. this is a much more reliable "darts at the wall" # technique than the previous location-based one QUE...
return output
location = response.json() geographic_data = get_addresses(location) address = geographic_data["address"] coordinates = geographic_data["coordinates"] gas_prices = parse_gas_prices(location) amenities = parse_amenities(location) this_location_outp...
conditional_block
__init__.py
""" scraping the utility functions for the actual web scraping """ import ssl import datetime import requests import re # this is the endpoint that my new version of this program will # abuse with possible store ids. this is a much more reliable "darts at the wall" # technique than the previous location-based one QUE...
(limit=None): """ Hits the store number url endpoint to pull down Wawa locations and parse each one's information. We don't know the store numbers as there is not list of store numbers. Through testing I was able to narrow down "series" of store numbers, so we iterate through ranges of possible ...
get_wawa_data
identifier_name
__init__.py
""" scraping the utility functions for the actual web scraping """ import ssl import datetime import requests import re # this is the endpoint that my new version of this program will # abuse with possible store ids. this is a much more reliable "darts at the wall" # technique than the previous location-based one QUE...
if response.status_code != 404: location = response.json() geographic_data = get_addresses(location) address = geographic_data["address"] coordinates = geographic_data["coordinates"] gas_prices = parse_gas_prices(location) amenities = pars...
response = requests.get(QUERY_URL, params={"storeNumber": i})
random_line_split
__init__.py
""" scraping the utility functions for the actual web scraping """ import ssl import datetime import requests import re # this is the endpoint that my new version of this program will # abuse with possible store ids. this is a much more reliable "darts at the wall" # technique than the previous location-based one QUE...
def camel_to_underscore(in_string): """ Basic function that converts a camel-cased word to use underscores :param in_string: The camel-cased string (str) :return: The underscore'd string (str) """ s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', in_string) return re.sub('([a-z0-9])([A-...
""" Breaks open the json for the gas prices :param in_location: The Wawa location we are looking at (dict) :return: The gas price info (dict) """ out_data = {} try: fuel_data = in_location["fuelTypes"] for ft in fuel_data: lowered = ft["des...
identifier_body
activitybar.ts
import { loadstyle } from "../../load"; import * as path from 'path'; import { dom, quickDom, emptyDom } from '../../dom/dom' import { component } from '../component' export class activity { public name: string; public label: dom; public isActive: boolean; public workbench: dom; constructor(name: ...
item.on('mouseover', (e: Event) => { act.label.addClass('active'); }) item.on('mouseout', (e: Event) => { if (act.isActive !== true) { act.label.removeClass('active'); } }) item.on('mousedown', (e: Event) => { act....
{ act.workbench = workbench; act.workbench.addClass('hide'); }
conditional_block
activitybar.ts
import { loadstyle } from "../../load"; import * as path from 'path'; import { dom, quickDom, emptyDom } from '../../dom/dom' import { component } from '../component' export class activity { public name: string; public label: dom; public isActive: boolean; public workbench: dom; constructor(name: ...
updateStyle() { // style update for statusbar super.updateStyle(); } addActivity(name: string, workbench: dom | undefined, context: any, fn: (act: activity, context: any) => void) { let act = new activity(name); var item = emptyDom().element('li', 'activity-item'); ...
{ let activityparent = emptyDom().element('div', 'activity-container'); activityparent.apendTo(this.container); this.activityList = emptyDom().element('ul', 'activity-list'); this.activityList.apendTo(activityparent); }
identifier_body
activitybar.ts
import { loadstyle } from "../../load"; import * as path from 'path'; import { dom, quickDom, emptyDom } from '../../dom/dom' import { component } from '../component' export class activity { public name: string; public label: dom; public isActive: boolean; public workbench: dom; constructor(name: ...
console.log(path.join(__dirname, './media/activitybar.css')); loadstyle(path.join(__dirname, './media/activitybar.css')); export class activitybar extends component { private activityList: dom; private activities: activity[]; constructor( parent: dom ) { super(); if (!parent) ...
random_line_split
activitybar.ts
import { loadstyle } from "../../load"; import * as path from 'path'; import { dom, quickDom, emptyDom } from '../../dom/dom' import { component } from '../component' export class
{ public name: string; public label: dom; public isActive: boolean; public workbench: dom; constructor(name: string) { this.name = name; this.isActive = false; } } console.log(path.join(__dirname, './media/activitybar.css')); loadstyle(path.join(__dirname, './media/activitybar...
activity
identifier_name
wijmo.angular2.grid.filter.min.js
/* * * Wijmo Library 5.20162.188 * http://wijmo.com/ * * Copyright(c) GrapeCity, Inc. All rights reserved. * * Licensed under the Wijmo Commercial License. * sales@wijmo.com * http://wijmo.com/products/wijmo-5/license/ * */ System.register("wijmo/wijmo.angular2....
return __extends(WjFlexGridFilter, _super), WjFlexGridFilter = __decorate([wijmo_angular2_directiveBase_1.WjComponent({ selector: 'wj-flex-grid-filter', template: "", wjParentDirectives: [wijmo_angular2_grid_1.WjFlexGrid] }), __param(0, core_1.Inject(core_1.ElementRef)), __param(1, core_1.Inject(core_1.Injector))], W...
var parentCmp=wijmo_angular2_directiveBase_1.WjDirectiveBehavior.findTypeParentBehavior(injector, WjFlexGridFilter).directive; _super.call(this, parentCmp); wijmo_angular2_directiveBase_1.WjDirectiveBehavior.attach(this, elRef, injector) }
identifier_body
wijmo.angular2.grid.filter.min.js
/* * * Wijmo Library 5.20162.188 * http://wijmo.com/ * * Copyright(c) GrapeCity, Inc. All rights reserved. * * Licensed under the Wijmo Commercial License. * sales@wijmo.com * http://wijmo.com/products/wijmo-5/license/ * */ System.register("wijmo/wijmo.angular2....
}, function(wijmo_angular2_directiveBase_1_1) { wijmo_angular2_directiveBase_1 = wijmo_angular2_directiveBase_1_1 }, function(wijmo_angular2_grid_1_1) { wijmo_angular2_grid_1 = wijmo_angular2_grid_1_1 }], execute: function() { WjFlexGridFilter = function(_super) { function WjFlexGridFilter(elRef, injector) {...
WjFlexGridFilter; return { setters: [function(core_1_1) { core_1 = core_1_1
random_line_split
wijmo.angular2.grid.filter.min.js
/* * * Wijmo Library 5.20162.188 * http://wijmo.com/ * * Copyright(c) GrapeCity, Inc. All rights reserved. * * Licensed under the Wijmo Commercial License. * sales@wijmo.com * http://wijmo.com/products/wijmo-5/license/ * */ System.register("wijmo/wijmo.angular2....
lRef, injector) { var parentCmp=wijmo_angular2_directiveBase_1.WjDirectiveBehavior.findTypeParentBehavior(injector, WjFlexGridFilter).directive; _super.call(this, parentCmp); wijmo_angular2_directiveBase_1.WjDirectiveBehavior.attach(this, elRef, injector) } return __extends(WjFlexGridFilter, _super), WjFlexGridFi...
FlexGridFilter(e
identifier_name
isyeventmonitor.py
import base64 import errno import random import ssl import threading import time import copy import websocket import xmltodict import config import debug from utils import exitutils import hubs.isy.isycodes as isycodes import logsupport from controlevents import CEvent, PostEvent, ConsoleEvent, PostIfInterested from ...
if self.THstate == 'running': self.isy._HubOnline = True self.isy.Vars.CheckValsUpToDate(reload=True) logsupport.Logs.Log(self.hubname + ": Initial status streamed ", self.seq, " items and vars updated") elif self.THstate == 'failed': logsupport.Logs.Log(self.hubname + " Failed Thread Restart", severit...
logsupport.Logs.Log(self.hubname + ": Waiting initial status dump") time.sleep(2) hungcount -= 1 if hungcount < 0: raise ThreadStartException
conditional_block
isyeventmonitor.py
import base64 import errno import random import ssl import threading import time import copy import websocket import xmltodict import config import debug from utils import exitutils import hubs.isy.isycodes as isycodes import logsupport from controlevents import CEvent, PostEvent, ConsoleEvent, PostIfInterested from ...
severity=ConsoleWarning) self.delayedstart = 121 elif self.lasterror == 'ISYClose': logsupport.Logs.Log(self.hubname + ' Recovering closed WS stream') self.delayedstart = 2 elif self.lasterror == 'DirectCommError': logsupport.Logs.Log(self.hubname + ' WS restart because of failed direct c...
elif self.lasterror == 'ISYNetDown': # likely home network down so wait a bit logsupport.Logs.Log(self.hubname + ' WS restart for NETUNREACH - delay likely router reboot or down',
random_line_split
isyeventmonitor.py
import base64 import errno import random import ssl import threading import time import copy import websocket import xmltodict import config import debug from utils import exitutils import hubs.isy.isycodes as isycodes import logsupport from controlevents import CEvent, PostEvent, ConsoleEvent, PostIfInterested from ...
def PreRestartQHThread(self): self.isy._HubOnline = False self.THstate = 'restarting' try: if self.lasterror == 'ISYSocketTimeOut': logsupport.Logs.Log(self.hubname + '(TimeoutError) Wait for likely router reboot or down', severity=ConsoleWarning, tb=False) self.delayedstart = 150 self....
if self.isy.version == -1: # test mode return hungcount = 40 while self.THstate == 'restarting': logsupport.Logs.Log(self.hubname + " Waiting thread start") time.sleep(2) hungcount -= 1 if hungcount < 0: raise ThreadStartException while self.THstate == 'delaying': time.sleep(1) hungcount = ...
identifier_body
isyeventmonitor.py
import base64 import errno import random import ssl import threading import time import copy import websocket import xmltodict import config import debug from utils import exitutils import hubs.isy.isycodes as isycodes import logsupport from controlevents import CEvent, PostEvent, ConsoleEvent, PostIfInterested from ...
(self): # noinspection PyArgumentList PostEvent(ConsoleEvent(CEvent.HubNodeChange, hub=self.isy.name, node=None, value=-1)) def reinit(self): self.watchstarttime = time.time() self.watchlist = [] self.seq = 0 self.hbcount = 0 self.QHnum += 1 def PostStartQHThread(self): if self.isy.version == -1: ...
FakeNodeChange
identifier_name
errors.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 std::local_data; use cssparser::ast::{SyntaxError, SourceLocation}; pub struct ErrorLoggerIterator<I>(I); i...
{ local_data::set(silence_errors, true); let result = f(); local_data::pop(silence_errors); result }
identifier_body
errors.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 std::local_data; use cssparser::ast::{SyntaxError, SourceLocation}; pub struct ErrorLoggerIterator<I>(I); i...
<T>(f: || -> T) -> T { local_data::set(silence_errors, true); let result = f(); local_data::pop(silence_errors); result }
with_errors_silenced
identifier_name
errors.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 std::local_data; use cssparser::ast::{SyntaxError, SourceLocation}; pub struct ErrorLoggerIterator<I>(I); i...
} } } } // FIXME: go back to `()` instead of `bool` after upgrading Rust // past 898669c4e203ae91e2048fb6c0f8591c867bccc6 // Using bool is a work-around for https://github.com/mozilla/rust/issues/13322 local_data_key!(silence_errors: bool) pub fn log_css_error(location: SourceLocation, message...
Some(Ok(v)) => return Some(v), Some(Err(error)) => log_css_error(error.location, format!("{:?}", error.reason)), None => return None,
random_line_split
users.js
"use strict"; var user = require('../../user'), meta = require('../../meta'); var usersController = {}; usersController.search = function(req, res, next) { res.render('admin/manage/users', { search_display: '', loadmore_display: 'hide', users: [] }); }; usersController.sortByPosts = function(req, res, nex...
usersController.getCSV = function(req, res, next) { user.getUsersCSV(function(err, data) { if (err) { return next(err); } res.attachment('users.csv'); res.setHeader('Content-Type', 'text/csv'); res.end(data); }); }; module.exports = usersController;
{ user.getUsersFromSet(set, req.uid, 0, 49, function(err, users) { if (err) { return next(err); } users = users.filter(function(user) { return user && parseInt(user.uid, 10); }); res.render('admin/manage/users', { search_display: 'hidden', loadmore_display: 'block', users: users, yourid: ...
identifier_body
users.js
"use strict"; var user = require('../../user'), meta = require('../../meta'); var usersController = {}; usersController.search = function(req, res, next) { res.render('admin/manage/users', { search_display: '', loadmore_display: 'hide', users: [] }); };
}; usersController.sortByReputation = function(req, res, next) { getUsers('users:reputation', req, res, next); }; usersController.sortByJoinDate = function(req, res, next) { getUsers('users:joindate', req, res, next); }; usersController.banned = function(req, res, next) { getUsers('users:banned', req, res, next);...
usersController.sortByPosts = function(req, res, next) { getUsers('users:postcount', req, res, next);
random_line_split
users.js
"use strict"; var user = require('../../user'), meta = require('../../meta'); var usersController = {}; usersController.search = function(req, res, next) { res.render('admin/manage/users', { search_display: '', loadmore_display: 'hide', users: [] }); }; usersController.sortByPosts = function(req, res, nex...
(set, req, res, next) { user.getUsersFromSet(set, req.uid, 0, 49, function(err, users) { if (err) { return next(err); } users = users.filter(function(user) { return user && parseInt(user.uid, 10); }); res.render('admin/manage/users', { search_display: 'hidden', loadmore_display: 'block', use...
getUsers
identifier_name
users.js
"use strict"; var user = require('../../user'), meta = require('../../meta'); var usersController = {}; usersController.search = function(req, res, next) { res.render('admin/manage/users', { search_display: '', loadmore_display: 'hide', users: [] }); }; usersController.sortByPosts = function(req, res, nex...
users = users.filter(function(user) { return user && parseInt(user.uid, 10); }); res.render('admin/manage/users', { search_display: 'hidden', loadmore_display: 'block', users: users, yourid: req.uid, requireEmailConfirmation: parseInt(meta.config.requireEmailConfirmation, 10) === 1 }); });...
{ return next(err); }
conditional_block
data-gift-service.js
(function () { 'use strict'; angular .module("myApp.presents") .factory("dataGiftService", dataGiftService); function dataGiftService($mdToast, $mdDialog) { var dataGiftService = { notification: notification, pleaseWaitDialog: pleaseWaitDialog }; ...
' <md-dialog-content layout="column" layour-align="center center">' + '<h1 class="text-center">Proszę czekać</h1>' + '<md-content class="text-center">' + msg + '</md-content>'+ ' </md-dialog-content>' + '</md-dialog>' }); ...
$mdDialog.show({ parent: parentEl, template: '<md-dialog class="wait-dialog" aria-label="Please wait">' +
random_line_split
data-gift-service.js
(function () { 'use strict'; angular .module("myApp.presents") .factory("dataGiftService", dataGiftService); function dataGiftService($mdToast, $mdDialog) { var dataGiftService = { notification: notification, pleaseWaitDialog: pleaseWaitDialog }; ...
function pleaseWaitDialog(msg, parentEl) { if (angular.isUndefined(parentEl)) { parentEl = angular.element(document.body); } $mdDialog.show({ parent: parentEl, template: '<md-dialog class="wait-dialog" aria-label="Please wait...
{ if (angular.isUndefined(time)) time = 3000; $mdToast.show( $mdToast.simple() .textContent(msg) .position("top right") .hideDelay(time) .theme(status) ); }
identifier_body
data-gift-service.js
(function () { 'use strict'; angular .module("myApp.presents") .factory("dataGiftService", dataGiftService); function dataGiftService($mdToast, $mdDialog) { var dataGiftService = { notification: notification, pleaseWaitDialog: pleaseWaitDialog }; ...
(msg, parentEl) { if (angular.isUndefined(parentEl)) { parentEl = angular.element(document.body); } $mdDialog.show({ parent: parentEl, template: '<md-dialog class="wait-dialog" aria-label="Please wait">' + ' <md-dialog...
pleaseWaitDialog
identifier_name
robot.rs
use wpilib::wpilib_hal::*; /// The base class from which all robots should be derived. /// /// # Usage /// /// ``` /// struct TestRobot {}; /// /// impl Robot for TestRobot { /// fn new() -> TestRobot { /// TestRobot{} /// } /// /// fn run(self) { /// // Do something... /// } /// } /// ...
fn main() { // Initialize HAL unsafe { let status = HAL_Initialize(0); if status != 1 { panic!("WPILib HAL failed to initialize!"); } } let robot = Self::new(); robot.run(); } }
/// Create an instance of the robot class. fn new() -> Self; /// Run the robot statically.
random_line_split
robot.rs
use wpilib::wpilib_hal::*; /// The base class from which all robots should be derived. /// /// # Usage /// /// ``` /// struct TestRobot {}; /// /// impl Robot for TestRobot { /// fn new() -> TestRobot { /// TestRobot{} /// } /// /// fn run(self) { /// // Do something... /// } /// } /// ...
() { // Initialize HAL unsafe { let status = HAL_Initialize(0); if status != 1 { panic!("WPILib HAL failed to initialize!"); } } let robot = Self::new(); robot.run(); } }
main
identifier_name
robot.rs
use wpilib::wpilib_hal::*; /// The base class from which all robots should be derived. /// /// # Usage /// /// ``` /// struct TestRobot {}; /// /// impl Robot for TestRobot { /// fn new() -> TestRobot { /// TestRobot{} /// } /// /// fn run(self) { /// // Do something... /// } /// } /// ...
} let robot = Self::new(); robot.run(); } }
{ panic!("WPILib HAL failed to initialize!"); }
conditional_block
robot.rs
use wpilib::wpilib_hal::*; /// The base class from which all robots should be derived. /// /// # Usage /// /// ``` /// struct TestRobot {}; /// /// impl Robot for TestRobot { /// fn new() -> TestRobot { /// TestRobot{} /// } /// /// fn run(self) { /// // Do something... /// } /// } /// ...
}
{ // Initialize HAL unsafe { let status = HAL_Initialize(0); if status != 1 { panic!("WPILib HAL failed to initialize!"); } } let robot = Self::new(); robot.run(); }
identifier_body
130-typed-array.js
const { assert, skip, test, module: describe } = require('qunit'); const { GPU } = require('../../src'); describe('issue #130'); function typedArrays(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(changes) { return changes[this.thread.y][this.thread.x]; }) .setOutput([2, ...
(GPU.isWebGLSupported ? test : skip)("Issue #130 - typed array webgl", () => { typedArrays('webgl'); }); (GPU.isWebGL2Supported ? test : skip)("Issue #130 - typed array webgl2", () => { typedArrays('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)("Issue #130 - typed array headlessgl", () => { typedArra...
random_line_split
130-typed-array.js
const { assert, skip, test, module: describe } = require('qunit'); const { GPU } = require('../../src'); describe('issue #130'); function
(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(changes) { return changes[this.thread.y][this.thread.x]; }) .setOutput([2, 1]); const values = [new Float32Array(2)]; values[0][0] = 0; values[0][1] = 0; const result = kernel(values); assert.equal(result[0][0], 0)...
typedArrays
identifier_name
130-typed-array.js
const { assert, skip, test, module: describe } = require('qunit'); const { GPU } = require('../../src'); describe('issue #130'); function typedArrays(mode)
test("Issue #130 - typed array auto", () => { typedArrays(null); }); test("Issue #130 - typed array gpu", () => { typedArrays('gpu'); }); (GPU.isWebGLSupported ? test : skip)("Issue #130 - typed array webgl", () => { typedArrays('webgl'); }); (GPU.isWebGL2Supported ? test : skip)("Issue #130 - typed array we...
{ const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(changes) { return changes[this.thread.y][this.thread.x]; }) .setOutput([2, 1]); const values = [new Float32Array(2)]; values[0][0] = 0; values[0][1] = 0; const result = kernel(values); assert.equal(result[0][0], 0); ass...
identifier_body
__init__.py
""" Support for MQTT vacuums. For more details about this platform, please refer to the documentation at https://www.home-assistant.io/components/vacuum.mqtt/ """ import logging import voluptuous as vol from homeassistant.components.vacuum import DOMAIN from homeassistant.components.mqtt import ATTR_DISCOVERY_HASH f...
raise async_dispatcher_connect( hass, MQTT_DISCOVERY_NEW.format(DOMAIN, "mqtt"), async_discover ) async def _async_setup_entity( config, async_add_entities, config_entry, discovery_hash=None ): """Set up the MQTT vacuum.""" setup_entity = {LEGACY: async_setup_entity_legacy, S...
clear_discovery_hash(hass, discovery_hash)
conditional_block
__init__.py
""" Support for MQTT vacuums. For more details about this platform, please refer to the documentation at https://www.home-assistant.io/components/vacuum.mqtt/ """ import logging import voluptuous as vol from homeassistant.components.vacuum import DOMAIN from homeassistant.components.mqtt import ATTR_DISCOVERY_HASH f...
async_dispatcher_connect( hass, MQTT_DISCOVERY_NEW.format(DOMAIN, "mqtt"), async_discover ) async def _async_setup_entity( config, async_add_entities, config_entry, discovery_hash=None ): """Set up the MQTT vacuum.""" setup_entity = {LEGACY: async_setup_entity_legacy, STATE: async_setup_...
"""Discover and add a MQTT vacuum.""" try: discovery_hash = discovery_payload.pop(ATTR_DISCOVERY_HASH) config = PLATFORM_SCHEMA(discovery_payload) await _async_setup_entity( config, async_add_entities, config_entry, discovery_hash ) except ...
identifier_body
__init__.py
""" Support for MQTT vacuums. For more details about this platform, please refer to the documentation at https://www.home-assistant.io/components/vacuum.mqtt/ """ import logging import voluptuous as vol from homeassistant.components.vacuum import DOMAIN from homeassistant.components.mqtt import ATTR_DISCOVERY_HASH f...
( config, async_add_entities, config_entry, discovery_hash=None ): """Set up the MQTT vacuum.""" setup_entity = {LEGACY: async_setup_entity_legacy, STATE: async_setup_entity_state} await setup_entity[config[CONF_SCHEMA]]( config, async_add_entities, config_entry, discovery_hash )
_async_setup_entity
identifier_name
__init__.py
""" Support for MQTT vacuums. For more details about this platform, please refer to the documentation at https://www.home-assistant.io/components/vacuum.mqtt/ """ import logging import voluptuous as vol from homeassistant.components.vacuum import DOMAIN from homeassistant.components.mqtt import ATTR_DISCOVERY_HASH f...
raise async_dispatcher_connect( hass, MQTT_DISCOVERY_NEW.format(DOMAIN, "mqtt"), async_discover ) async def _async_setup_entity( config, async_add_entities, config_entry, discovery_hash=None ): """Set up the MQTT vacuum.""" setup_entity = {LEGACY: async_setup_entity_legacy, ST...
clear_discovery_hash(hass, discovery_hash)
random_line_split
flat.rs
// Copyright 2015, 2016 Ethcore (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 later version....
(&self) -> LogBloom { self.action.bloom() | self.result.bloom() } } impl HeapSizeOf for FlatTrace { fn heap_size_of_children(&self) -> usize { self.trace_address.heap_size_of_children() } } impl Encodable for FlatTrace { fn rlp_append(&self, s: &mut RlpStream) { s.begin_list(4); s.append(&self.action); ...
bloom
identifier_name
flat.rs
// Copyright 2015, 2016 Ethcore (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 later version....
to: "412fda7643b37d436cb40628f6dbbb80a07267ed".parse().unwrap(), value: 0.into(), gas: 0x010c78.into(), input: vec![0x41, 0xc0, 0xe1, 0xb5], call_type: CallType::Call, }), result: Res::Call(CallResult { gas_used: 0x0127.into(), output: vec![], }), trace_address: Default::default(...
let flat_trace1 = FlatTrace { action: Action::Call(Call { from: "3d0768da09ce77d25e2d998e6a7b6ed4b9116c2d".parse().unwrap(),
random_line_split
flat.rs
// Copyright 2015, 2016 Ethcore (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 later version....
} impl HeapSizeOf for FlatTransactionTraces { fn heap_size_of_children(&self) -> usize { self.0.heap_size_of_children() } } impl FlatTransactionTraces { /// Returns bloom of all traces in the collection. pub fn bloom(&self) -> LogBloom { self.0.iter().fold(Default::default(), | bloom, trace | bloom | trace.b...
{ FlatTransactionTraces(v) }
identifier_body
ModularFocalNetwork.py
""" Examples ======== ModularFocalNetwork(8, [1600, 800], 4).plot() => 8 modules, 4 connections to each neuron """ import numpy as np from Plotters import plot_connectivity_matrix def range_from_base(base, size): return xrange(base, base + size) class ModularFocalNetwork(object): def __init__(self, C, di...
CIJ[i,j] represents the connection from node j in input layer to node i in this layer. """ self.C = C self.dim = dim self.module_dim = [layer_size / C for layer_size in dim] self.focal_width = focal_width self.CIJ = np.zeros(dim) for i in range(C): ...
random_line_split
ModularFocalNetwork.py
""" Examples ======== ModularFocalNetwork(8, [1600, 800], 4).plot() => 8 modules, 4 connections to each neuron """ import numpy as np from Plotters import plot_connectivity_matrix def
(base, size): return xrange(base, base + size) class ModularFocalNetwork(object): def __init__(self, C, dim, focal_width): """ Generates connectivity matrix for a modular network with... C -- # communities/modules dim -- dimensions of matrix, [nodes_in_target_layer, nodes_in_...
range_from_base
identifier_name
ModularFocalNetwork.py
""" Examples ======== ModularFocalNetwork(8, [1600, 800], 4).plot() => 8 modules, 4 connections to each neuron """ import numpy as np from Plotters import plot_connectivity_matrix def range_from_base(base, size): return xrange(base, base + size) class ModularFocalNetwork(object): def __init__(self, C, di...
def plot(self): """ Uses pyplot to draw a plot of the connectivity matrix """ plot_connectivity_matrix(self.CIJ, self.dim).show()
nodes_to_connect = np.random.choice(input_nodes, self.focal_width, replace=False) self.CIJ[i, nodes_to_connect] = 1
conditional_block
ModularFocalNetwork.py
""" Examples ======== ModularFocalNetwork(8, [1600, 800], 4).plot() => 8 modules, 4 connections to each neuron """ import numpy as np from Plotters import plot_connectivity_matrix def range_from_base(base, size):
class ModularFocalNetwork(object): def __init__(self, C, dim, focal_width): """ Generates connectivity matrix for a modular network with... C -- # communities/modules dim -- dimensions of matrix, [nodes_in_target_layer, nodes_in_input_layer] focal_width -- how connection...
return xrange(base, base + size)
identifier_body
api.py
from avatar.templatetags.avatar_tags import avatar_url from django.conf import settings from django.contrib.auth.models import User from django.core.urlresolvers import reverse from tastypie import fields from tastypie.resources import ModelResource from accounts.models import UserProfile from main.api.authentication i...
def dehydrate(self, bundle): bundle.data['absolute_url'] = reverse('account_user_profile_with_username', kwargs={'username': bundle.obj.username}) bundle.data['best_name'] = bundle.obj.profile.get_best_name() bundle.data['tiny_thumbnail'] = avatar_url(bundle.obj, size=settings.AVATAR_SIZE_...
queryset = User.objects.all() authentication = UberAuthentication() #authorization = CourseAuthorization() resource_name = 'users' fields = ['username', 'first_name', 'last_name', 'last_login', 'profile'] allowed_methods = ['get'] include_absolute_url = True seria...
identifier_body
api.py
from avatar.templatetags.avatar_tags import avatar_url from django.conf import settings from django.contrib.auth.models import User
from django.core.urlresolvers import reverse from tastypie import fields from tastypie.resources import ModelResource from accounts.models import UserProfile from main.api.authentication import UberAuthentication from main.api.serializers import UberSerializer class UserResource(ModelResource): #profile = fields.F...
random_line_split
api.py
from avatar.templatetags.avatar_tags import avatar_url from django.conf import settings from django.contrib.auth.models import User from django.core.urlresolvers import reverse from tastypie import fields from tastypie.resources import ModelResource from accounts.models import UserProfile from main.api.authentication i...
(self, bundle): bundle.data['absolute_url'] = reverse('account_user_profile_with_username', kwargs={'username': bundle.obj.username}) bundle.data['best_name'] = bundle.obj.profile.get_best_name() bundle.data['tiny_thumbnail'] = avatar_url(bundle.obj, size=settings.AVATAR_SIZE_IN_ENROLLMENTS_GRID...
dehydrate
identifier_name
text-editor-registry.d.ts
import { Disposable, TextEditor } from '../index'; /** Experimental: This global registry tracks registered TextEditors. */ export interface TextEditorRegistry { // Managing Text Editors /** Remove all editors from the registry. */ clear(): void; /** Register a TextEditor. */ add(editor: TextEdito...
*/ setGrammarOverride(editor: TextEditor, scopeName: string): void; /** * Retrieve the grammar scope name that has been set as a grammar override * for the given TextEditor. */ getGrammarOverride(editor: TextEditor): string | null; /** Remove any grammar override that has been se...
random_line_split