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
mqtt_chat_client.py
# -*- coding: utf-8 -*- ''' Created on 17/2/16. @author: love ''' import paho.mqtt.client as mqtt import json import ssl def on_connect(client, userdata, flags, rc): print("Connected with result code %d"%rc) client.publish("Login/HD_Login/1", json.dumps({"userName": user, "passWord": "Hello,anyone!"}),qos=0,re...
n=False)
/HD_Say/2", json.dumps({"roomName": "mqant","from":user,"target":"*","content": s}),qos=0,retai
conditional_block
mqtt_chat_client.py
# -*- coding: utf-8 -*- ''' Created on 17/2/16. @author: love ''' import paho.mqtt.client as mqtt import json import ssl def on_connect(client, userdata, flags, rc): print("Connected with result code %d"%rc) client.publish("Login/HD_Login/1", json.dumps({"userName": user, "passWord": "Hello,anyone!"}),qos=0,re...
client.publish("Chat/HD_Say/2", json.dumps({"roomName": "mqant","from":user,"target":"*","content": s}),qos=0,retain=False)
client.publish("Master/HD_Start_Process/2", json.dumps({"ProcessID": "001"}),qos=0,retain=False) elif s=="stop": client.publish("Master/HD_Stop_Process/2", json.dumps({"ProcessID": "001"}),qos=0,retain=False) else:
random_line_split
test_3080_cmd_rm.py
import unittest import os from pprint import pprint import pym_elfinder.exceptions as exc from .. import lib from .. import lib_localfilesystem as lfs class TestCmdRm(unittest.TestCase): @classmethod def setUpClass(cls): cls.finder = lib.create_finder() cls.fixt = lib.CMD_FIXT['cmd_rm.txt']...
""" Test removal of dir_1 """ os.mkdir(self.dir_1) lfs.mkfile(self.file_1_1) req = self.fixt[1]['request'] cmd, args = lib.prepare_request(req) assert cmd == 'rm' with self.assertRaisesRegexp(exc.FinderError, exc.ERROR_RM): ...
identifier_body
test_3080_cmd_rm.py
import unittest import os from pprint import pprint import pym_elfinder.exceptions as exc from .. import lib from .. import lib_localfilesystem as lfs class TestCmdRm(unittest.TestCase): @classmethod def setUpClass(cls): cls.finder = lib.create_finder() cls.fixt = lib.CMD_FIXT['cmd_rm.txt']...
cmd, args = lib.prepare_request(req) assert cmd == 'rm' with self.assertRaisesRegexp(exc.FinderError, exc.ERROR_RM): self.finder.run(cmd, args, debug=True) r = self.finder.response self.assertTrue('error' in r) self.assertEqual(r['error'][0],...
os.mkdir(self.dir_1) lfs.mkfile(self.file_1_1) req = self.fixt[1]['request']
random_line_split
test_3080_cmd_rm.py
import unittest import os from pprint import pprint import pym_elfinder.exceptions as exc from .. import lib from .. import lib_localfilesystem as lfs class
(unittest.TestCase): @classmethod def setUpClass(cls): cls.finder = lib.create_finder() cls.fixt = lib.CMD_FIXT['cmd_rm.txt'] cls.file_1 = os.path.join(lfs.DIR, 'file_1.txt') cls.file_2 = os.path.join(lfs.DIR, 'file_2.txt') cls.dir_1 = os.path.join(lfs.DIR, 'dir_1') ...
TestCmdRm
identifier_name
permissions.py
# 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, sublicense, and/or sell copies of # the Software, and to permit persons to whom the Software is furnished to...
# Copyright (c) 2019, CRS4 # # Permission is hereby granted, free of charge, to any person obtaining a copy of
random_line_split
permissions.py
# Copyright (c) 2019, CRS4 # # 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, distribu...
return False
conditional_block
permissions.py
# Copyright (c) 2019, CRS4 # # 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, distribu...
""" Only specific users that belong to ODIN_MEMBERS group will be allowed to perform queries using Odin toolkit """ RESTRICTED_METHODS = ['GET'] def has_permission(self, request, view): if not (request.user and request.user.is_authenticated()): return False else: ...
identifier_body
permissions.py
# Copyright (c) 2019, CRS4 # # 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, distribu...
(self, request, view): if not (request.user and request.user.is_authenticated()): return False else: if request.method in self.RESTRICTED_METHODS: if request.user.groups.filter( name__in=[DEFAULT_GROUPS['odin_members']['name']] ...
has_permission
identifier_name
Notification.js
/** * Notification.js * * Released under LGPL License. * Copyright (c) 1999-2015 Ephox Corp. All rights reserved * * License: http://www.tinymce.com/license * Contributing: http://www.tinymce.com/contributing */ /** * Creates a notification instance. * * @-x-less Notification.less * @class tinymce.ui.Notif...
return ( '<div id="' + self._id + '" class="' + self.classes + '"' + notificationStyle + ' role="presentation">' + icon + '<div class="' + prefix + 'notification-inner">' + self.state.get('text') + '</div>' + progressBar + closeButton + '</div>' ); }, postRender: function() { ...
{ progressBar = self.progressBar.renderHtml(); }
conditional_block
Notification.js
/** * Notification.js * * Released under LGPL License. * Copyright (c) 1999-2015 Ephox Corp. All rights reserved * * License: http://www.tinymce.com/license * Contributing: http://www.tinymce.com/contributing */ /** * Creates a notification instance. * * @-x-less Notification.less * @class tinymce.ui.Notif...
// Hardcoded arbitrary z-value because we want the // notifications under the other windows style.zIndex = 0xFFFF - 1; } }); });
style.left = rect.x + 'px'; style.top = rect.y + 'px';
random_line_split
InputAdornment.js
import _extends from "@babel/runtime/helpers/esm/extends"; import _objectWithoutProperties from "@babel/runtime/helpers/esm/objectWithoutProperties"; import * as React from 'react'; import PropTypes from 'prop-types'; import clsx from 'clsx'; import Typography from '../Typography'; import withStyles from '../styles/wit...
root: { display: 'flex', height: '0.01em', // Fix IE 11 flexbox alignment. To remove at some point. maxHeight: '2em', alignItems: 'center', whiteSpace: 'nowrap' }, /* Styles applied to the root element if `variant="filled"`. */ filled: { '&$positionStart:not($hiddenLabel)': { ...
import FormControlContext, { useFormControl } from '../FormControl/FormControlContext'; export var styles = { /* Styles applied to the root element. */
random_line_split
InputAdornment.js
import _extends from "@babel/runtime/helpers/esm/extends"; import _objectWithoutProperties from "@babel/runtime/helpers/esm/objectWithoutProperties"; import * as React from 'react'; import PropTypes from 'prop-types'; import clsx from 'clsx'; import Typography from '../Typography'; import withStyles from '../styles/wit...
} if (muiFormControl && !variant) { variant = muiFormControl.variant; } return /*#__PURE__*/React.createElement(FormControlContext.Provider, { value: null }, /*#__PURE__*/React.createElement(Component, _extends({ className: clsx(classes.root, className, disablePointerEvents && classes.disablePo...
{ if (variantProp === muiFormControl.variant) { console.error('Material-UI: The `InputAdornment` variant infers the variant prop ' + 'you do not have to provide one.'); } }
conditional_block
prescript.py
import os import sys import argparse from pandaharvester.harvesterconfig import harvester_config from pandaharvester.harvestermisc.selfcheck import harvesterPackageInfo def main(): oparser = argparse.ArgumentParser(prog='prescript', add_help=True) oparser.add_argument('-f', '--local_info_file', action='store...
if __name__ == '__main__': main()
random_line_split
prescript.py
import os import sys import argparse from pandaharvester.harvesterconfig import harvester_config from pandaharvester.harvestermisc.selfcheck import harvesterPackageInfo def main():
if __name__ == '__main__': main()
oparser = argparse.ArgumentParser(prog='prescript', add_help=True) oparser.add_argument('-f', '--local_info_file', action='store', dest='local_info_file', help='path of harvester local info file') if len(sys.argv) == 1: print('No argument or flag specified. Did nothing') sys.exit(0) args = ...
identifier_body
prescript.py
import os import sys import argparse from pandaharvester.harvesterconfig import harvester_config from pandaharvester.harvestermisc.selfcheck import harvesterPackageInfo def main(): oparser = argparse.ArgumentParser(prog='prescript', add_help=True) oparser.add_argument('-f', '--local_info_file', action='store...
if __name__ == '__main__': main()
print('Harvester package unchanged. Skipped')
conditional_block
prescript.py
import os import sys import argparse from pandaharvester.harvesterconfig import harvester_config from pandaharvester.harvestermisc.selfcheck import harvesterPackageInfo def
(): oparser = argparse.ArgumentParser(prog='prescript', add_help=True) oparser.add_argument('-f', '--local_info_file', action='store', dest='local_info_file', help='path of harvester local info file') if len(sys.argv) == 1: print('No argument or flag specified. Did nothing') sys.exit(0) ...
main
identifier_name
index.d.ts
// Type definitions for html2canvas.js 1.0-alpha // Project: https://github.com/niklasvh/html2canvas // Definitions by: Richard Hepburn <https://github.com/rwhepburn>, Pei-Tang Huang <https://github.com/tan9>, Sebastian Schocke <https://github.com/sschocke>, Rickard Staaf <https://github.com/Ristaaf> // Definitions: ht...
/** Whether to render each letter seperately. Necessary if letter-spacing is used. */ letterRendering?: boolean; /** Whether to log events in the console. */ logging?: boolean; /** Callback function which is called when the Document has been cloned for rendering, can be used to...
/** Timeout for loading images, in milliseconds. Setting it to 0 will result in no timeout. */ imageTimeout?: number;
random_line_split
iso_8859_5.rs
pub fn charmap() -> [&'static str, .. 256]
{ return ["\x00", // 0x0 "\x01", // 0x1 "\x02", // 0x2 "\x03", // 0x3 "\x04", // 0x4 "\x05", // 0x5 "\x06", // 0x6 "\x07", // 0x7 "\x08", // 0x8 "\t", // 0x9 "\n", // 0xa "\x0b", // 0xb "\x0c", // 0xc "\r", // 0xd "\x0e", // 0xe "\x0f", // 0xf "\x10", // 0x10 "\x11", // 0x11 "\x12", // 0x12 "\x13", // 0x13 "\x14", // 0...
identifier_body
iso_8859_5.rs
pub fn charmap() -> [&'static str, .. 256]{ return ["\x00", // 0x0 "\x01", // 0x1 "\x02", // 0x2 "\x03", // 0x3 "\x04", // 0x4 "\x05", // 0x5 "\x06", // 0x6 "\x07", // 0x7 "\x08", // 0x8 "\t", // 0x9 "\n", // 0xa "\x0b", // 0xb "\x0c", // 0xc "\r", // 0xd "\x0e", // 0xe "\x0f", // 0xf "\x10", // 0x10 "\x11", // 0x11 "\...
"M", // 0x4d "N", // 0x4e "O", // 0x4f "P", // 0x50 "Q", // 0x51 "R", // 0x52 "S", // 0x53 "T", // 0x54 "U", // 0x55 "V", // 0x56 "W", // 0x57 "X", // 0x58 "Y", // 0x59 "Z", // 0x5a "[", // 0x5b "\\", // 0x5c "]", // 0x5d "^", // 0x5e "_", // 0x5f "`", // 0x60 "a", // 0x61 "b", // 0x62 "c", // 0x63 "d", // 0x64 "e", //...
"J", // 0x4a "K", // 0x4b "L", // 0x4c
random_line_split
iso_8859_5.rs
pub fn
() -> [&'static str, .. 256]{ return ["\x00", // 0x0 "\x01", // 0x1 "\x02", // 0x2 "\x03", // 0x3 "\x04", // 0x4 "\x05", // 0x5 "\x06", // 0x6 "\x07", // 0x7 "\x08", // 0x8 "\t", // 0x9 "\n", // 0xa "\x0b", // 0xb "\x0c", // 0xc "\r", // 0xd "\x0e", // 0xe "\x0f", // 0xf "\x10", // 0x10 "\x11", // 0x11 "\x12", // 0x12 ...
charmap
identifier_name
lib.rs
// Copyright (C) 2016 Cloudlabs, Inc // // 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 3 of the License, or // (at your option) any later version. // // This program is distri...
else { Ok(err as usize) } } #[test] fn test_file_ext() { extern crate tempfile; let file = tempfile::tempfile().unwrap(); file.write_at(50, &[1, 2, 3, 4, 5]).unwrap(); file.write_at(100, &[7, 6, 5, 4, 3, 2, 1]).unwrap(); let mut buf = &mut [0; 5]; file.read_at(50, buf).unwrap(); ...
{ Err(io::Error::last_os_error()) }
conditional_block
lib.rs
// Copyright (C) 2016 Cloudlabs, Inc // // 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 3 of the License, or // (at your option) any later version. // // This program is distri...
data.as_ptr() as *const ::libc::c_void, data.len(), offset as ::libc::off_t) as ::libc::c_int) } } fn close(self) -> io::Result<()> { use libc::close; use std::os::unix::io::IntoRawFd; unsafe { cvt(clos...
unsafe { cvt(pwrite(self.as_raw_fd(),
random_line_split
lib.rs
// Copyright (C) 2016 Cloudlabs, Inc // // 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 3 of the License, or // (at your option) any later version. // // This program is distri...
(&self, offset: u64, size: usize) -> io::Result<()> { use libc::{fallocate, FALLOC_FL_PUNCH_HOLE, FALLOC_FL_KEEP_SIZE}; use std::os::unix::io::AsRawFd; unsafe { cvt(fallocate(self.as_raw_fd(), FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE, ...
punch
identifier_name
lib.rs
// Copyright (C) 2016 Cloudlabs, Inc // // 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 3 of the License, or // (at your option) any later version. // // This program is distri...
} // Shim for converting C-style errors to io::Errors. fn cvt(err: ::libc::c_int) -> io::Result<usize> { if err < 0 { Err(io::Error::last_os_error()) } else { Ok(err as usize) } } #[test] fn test_file_ext() { extern crate tempfile; let file = tempfile::tempfile().unwrap(); fi...
{ self.write_at(offset, &vec![0; size]).map(|_| ()) }
identifier_body
envelope.rs
//! Envelope function used by sounds 1, 2 and 4 use spu::{Sample, SOUND_MAX}; #[derive(Clone,Copy)] pub struct Envelope { direction: EnvelopeDirection, volume: Volume, step_duration: u32, counter: u32, } impl Envelope { pub fn from_reg(val: u8) -> Envelope { let vol = Vo...
} fn down(&mut self) { let Volume(v) = *self; if v > 0 { *self = Volume(v - 1); } } }
{ *self = Volume(v + 1); }
conditional_block
envelope.rs
//! Envelope function used by sounds 1, 2 and 4 use spu::{Sample, SOUND_MAX}; #[derive(Clone,Copy)] pub struct Envelope { direction: EnvelopeDirection, volume: Volume, step_duration: u32, counter: u32, } impl Envelope { pub fn from_reg(val: u8) -> Envelope { let vol = Vo...
let Volume(v) = *self; if v > 0 { *self = Volume(v - 1); } } }
fn down(&mut self) {
random_line_split
envelope.rs
//! Envelope function used by sounds 1, 2 and 4 use spu::{Sample, SOUND_MAX}; #[derive(Clone,Copy)] pub struct Envelope { direction: EnvelopeDirection, volume: Volume, step_duration: u32, counter: u32, } impl Envelope { pub fn from_reg(val: u8) -> Envelope { let vol = Vo...
(&self) -> Sample { self.volume.into_sample() } /// DAC is disabled when envelope direction goes down and volume is 0 pub fn dac_enabled(&self) -> bool { self.direction != EnvelopeDirection::Down || self.volume.into_sample() != 0 } } // Sound envelopes can become louder or ...
into_sample
identifier_name
firebase-app-externs.js
/** * @fileoverview Firebase namespace and Firebase App API. * Version: 3.3.0 * * Copyright 2016 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * *...
firebase.FirebaseError; /** * Error codes are strings using the following format: * * "service/string-code" * * While the message for a given error can change, the code will remain the same * between backward-compatible versions of the Firebase SDK. * * @type {string} */ firebase.FirebaseError.prototype.cod...
* FirebaseError is a subclass of the standard JavaScript Error object. In * addition to a message string, it contains a string-valued code. * * @interface */
random_line_split
lixuzdd.js
/* * LIXUZ content management system * Copyright (C) Utrop A/S Portu media & Communications 2008-2011 * * 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 3 of the * License, ...
() { // We're being run as a method on the dragdrop object, so we can // access it as this. // The actual ordering is alphabetical, so we don't care about simple // reordering the user is doing. Therefore we do our own sorting here // so that results are predictable, and to avoid sending useless ...
lixuz_DD_OrderChangeEvent
identifier_name
lixuzdd.js
/* * LIXUZ content management system * Copyright (C) Utrop A/S Portu media & Communications 2008-2011 * * 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 3 of the * License, ...
var lixuz_DD_LastOrder; var lixuz_DD_URL; var lixuz_DD_FolderType = 'single'; var lixuz_DD_DialogBox; var folderLimit_override; var lixuz_DD_myDragDrop; /* * Called whenever the ordering of the folder tree is changed */ function lixuz_DD_OrderChangeEvent () { // We're being run as a method on the dragdrop object...
* Requires: asyncHelper.js * * Copyright (C) Portu media & communications * All Rights Reserved */
random_line_split
lixuzdd.js
/* * LIXUZ content management system * Copyright (C) Utrop A/S Portu media & Communications 2008-2011 * * 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 3 of the * License, ...
} } if (!foundEntities || !foundTargets || !foundSources) { return; } else { try { var dragdrop = new dragDrop_dragDrop(); for(var i = 0; i < sources.length; i++) { dragdrop.addSource(sources[i],true); ...
{ lastFound = false; }
conditional_block
lixuzdd.js
/* * LIXUZ content management system * Copyright (C) Utrop A/S Portu media & Communications 2008-2011 * * 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 3 of the * License, ...
/* * Handle an item being dropped somewhere using d+d functions */ function lixuz_DD_ItemDropped(sourceId, targetId, mouseX, mouseY) { var sourceObj = document.getElementById(sourceId); lixuz_DD_ItemHide(sourceObj,sourceObj.parentNode); var source = sourceObj.getAttribute('uid'); targetId = targetId...
{ parentItem.style.display = 'none'; item.style.display = 'none'; item.style.visibility = 'hidden'; parentItem.style.visibility = 'hidden'; // Handles hiding mouseOver elements from files/mouseOver.js if they // are present. We catch and ignore errors because if they're not, we don't care. ...
identifier_body
getDataName.ts
import { RowProps } from './types'; export default (p: RowProps) => process.env.NODE_ENV === 'production' ? undefined : [ 'row', p.alignItems ? `align-items-${p.alignItems}` : '', p.smAlignItems ? `align-items-sm-${p.smAlignItems}` : '', p.mdAlignItems ? `align-items-md-${p.md...
p.mdJustifyContent ? `justify-content-md-${p.mdJustifyContent}` : '', p.lgJustifyContent ? `justify-content-lg-${p.lgJustifyContent}` : '', p.xlJustifyContent ? `justify-content-xl-$p.{xlJustifyContent}` : '', ] .filter(Boolean) .join(' ');
p.smJustifyContent ? `justify-content-sm-${p.smJustifyContent}` : '',
random_line_split
cluster.ts
/** * Wrap cluster forking/restarting into a module */ import * as os from 'os'; import * as events from 'events'; import * as cluster from 'cluster'; import { Console, KernelEvents, KernelListener, XEvent } from '@lyrics/core'; export class Cluster { private emitter: events.EventEmitter; private numC...
() { this.numCPUs = 1; // @todo Remove, only for debug // this.numCPUs = os.cpus().length - 2; KernelListener.on(XEvent.CLUSTER_FORK, (args) => { Console.red(args); }); KernelListener.on(XEvent.CLUSTER_EXIT, (args) => { Console.red(args); }); ...
constructor
identifier_name
cluster.ts
/** * Wrap cluster forking/restarting into a module */ import * as os from 'os'; import * as events from 'events'; import * as cluster from 'cluster'; import { Console, KernelEvents, KernelListener, XEvent } from '@lyrics/core'; export class Cluster { private emitter: events.EventEmitter; private numC...
for (var i = 0; i < this.numCPUs; i++) { cluster.fork(); KernelEvents.emit(XEvent.CLUSTER_FORK, 'Cluster process started'); } // restart a cluster for whenever a cluster dies cluster.on('exit', function(worker, code, signal) { ...
*/ public start(onMasterProcessStart: Function) { if (cluster.isMaster) { // fork a new cluster for each CPU
random_line_split
cluster.ts
/** * Wrap cluster forking/restarting into a module */ import * as os from 'os'; import * as events from 'events'; import * as cluster from 'cluster'; import { Console, KernelEvents, KernelListener, XEvent } from '@lyrics/core'; export class Cluster { private emitter: events.EventEmitter; private numC...
} }
{ onMasterProcessStart(); }
conditional_block
cluster.ts
/** * Wrap cluster forking/restarting into a module */ import * as os from 'os'; import * as events from 'events'; import * as cluster from 'cluster'; import { Console, KernelEvents, KernelListener, XEvent } from '@lyrics/core'; export class Cluster { private emitter: events.EventEmitter; private numC...
}
{ if (cluster.isMaster) { // fork a new cluster for each CPU for (var i = 0; i < this.numCPUs; i++) { cluster.fork(); KernelEvents.emit(XEvent.CLUSTER_FORK, 'Cluster process started'); } // restart a cluster for whenever a cluster...
identifier_body
messages_util.rs
// Copyright 2015 MaidSafe.net limited. // // This SAFE Network Software is licensed to you under (1) the MaidSafe.net Commercial License, // version 1.0 or later, or (2) The General Public License (GPL), version 3, depending on which // licence you accepted on initial access to the Software (the "Licences"). // // By ...
impl Random for messages::ConnectRequest { fn generate_random() -> messages::ConnectRequest { messages::ConnectRequest { local_endpoints: random_endpoints(), external_endpoints: random_endpoints(), requester_fob: Random::generate_random(), ...
{ let range = Range::new(1, 10); let mut rng = thread_rng(); let count = range.ind_sample(&mut rng); let mut endpoints = vec![]; for _ in 0..count { endpoints.push(random_endpoint()); } endpoints }
identifier_body
messages_util.rs
// Copyright 2015 MaidSafe.net limited. // // This SAFE Network Software is licensed to you under (1) the MaidSafe.net Commercial License, // version 1.0 or later, or (2) The General Public License (GPL), version 3, depending on which // licence you accepted on initial access to the Software (the "Licences"). // // By ...
// Please review the Licences for the specific language governing permissions and limitations // relating to use of the SAFE Network Software. #[cfg(test)] pub mod test { use messages; use crust::Endpoint; use sodiumoxide::crypto; use rand::distributions::{IndependentSample, Range}; use rand::{ran...
//
random_line_split
messages_util.rs
// Copyright 2015 MaidSafe.net limited. // // This SAFE Network Software is licensed to you under (1) the MaidSafe.net Commercial License, // version 1.0 or later, or (2) The General Public License (GPL), version 3, depending on which // licence you accepted on initial access to the Software (the "Licences"). // // By ...
() -> Endpoint { use std::net::{Ipv4Addr, SocketAddrV4, SocketAddr}; Endpoint::Tcp(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(random::<u8>(), random::<u8>(), rand...
random_endpoint
identifier_name
SVGComponent.ts
import {Component} from "./Component"; import {HtmlTagName} from "./Html"; import {ComponentProperty, Binding} from "./Binding"; import {ModelElement} from "./ModelElement"; export class SVGComponent extends Component { constructor(tagName: HtmlTagName, parent?: Element) { super(tagName, parent, "http://www...
} // this is the line that is modified from base class this.element.setAttribute("class", classNames.join(" ")); } withWidth(width: ComponentProperty<number>): this { return this.withAttribute("width", width) } withHeight(height: ComponentProperty<number>): this { ...
{// cp is Binding<any,string> let binding = cp as Binding<any,string>; classNames.push(binding.onupdate(binding.model.get())); }
conditional_block
SVGComponent.ts
import {Component} from "./Component"; import {HtmlTagName} from "./Html"; import {ComponentProperty, Binding} from "./Binding"; import {ModelElement} from "./ModelElement"; export class SVGComponent extends Component { constructor(tagName: HtmlTagName, parent?: Element) { super(tagName, parent, "http://www...
* So override to set the class attribute instead */ protected updateClass(): void { if (!this.classes) return; let classNames: string[] = []; for (let cp of this.classes.values()) { if (typeof cp == "string") { classNames.push(cp as string);...
/** * Override AbstractComponent here * SVGElement.classname is readonly * Will cause an error in browser
random_line_split
SVGComponent.ts
import {Component} from "./Component"; import {HtmlTagName} from "./Html"; import {ComponentProperty, Binding} from "./Binding"; import {ModelElement} from "./ModelElement"; export class SVGComponent extends Component { constructor(tagName: HtmlTagName, parent?: Element) { super(tagName, parent, "http://www...
(y: ComponentProperty<number>): this { return this.withAttribute("y", y); } }
withY
identifier_name
SVGComponent.ts
import {Component} from "./Component"; import {HtmlTagName} from "./Html"; import {ComponentProperty, Binding} from "./Binding"; import {ModelElement} from "./ModelElement"; export class SVGComponent extends Component { constructor(tagName: HtmlTagName, parent?: Element)
/** * Override AbstractComponent here * SVGElement.classname is readonly * Will cause an error in browser * So override to set the class attribute instead */ protected updateClass(): void { if (!this.classes) return; let classNames: string[] = []; ...
{ super(tagName, parent, "http://www.w3.org/2000/svg"); }
identifier_body
quality_studies_psf.py
import numpy, sys, os, pylab, astropy, astropy.io.fits as pyfits, ldac, math def open_and_get_shearcat(filename, tablename): # # for opening and retrieving shear cat. # return ldac.openObjectFile(filename, tablename) #class ello def avg_shear(g1array, g2array): avg1 = numpy.mean(g1array)...
# # switch to polar coordinates # def cartesianToPolar(x, y): r = numpy.sqrt(x**2+y**2) phi = numpy.arccos(x/r) phi2 = phi = 2. * numpy.pi - phi phi_yp = y>=0. phi2_yp = y<0. phi = phi* phi_yp +phi2* phi2_yp return r, phi # # make the plots # def make_scatter_inputs(yvals, xvals,t...
n = len(inputarray) npars=inputarray[numpy.random.random_integers(0,n-1,(n,nbootstraps))] meanlist = numpy.mean(npars,0) if len(meanlist) != nbootstraps: print 'averaging across wrong axis' return numpy.std(meanlist)
identifier_body
quality_studies_psf.py
import numpy, sys, os, pylab, astropy, astropy.io.fits as pyfits, ldac, math def open_and_get_shearcat(filename, tablename): # # for opening and retrieving shear cat. # return ldac.openObjectFile(filename, tablename) #class ello def avg_shear(g1array, g2array): avg1 = numpy.mean(g1array)...
maxrg=numpy.max(starcat['rg']) galcat = galcat.filter(galcat['rg']>maxrg) galcat = galcat.filter(galcat['Flag']==0) gal_g1arr = numpy.array(galcat['gs1']) gal_g2arr = numpy.array(galcat['gs2']) gal_xarr = numpy.array(galcat['x']) gal_yarr = numpy.array(galcat['y']) gal_e1corr = n...
print ' got Star cat'
conditional_block
quality_studies_psf.py
import numpy, sys, os, pylab, astropy, astropy.io.fits as pyfits, ldac, math def open_and_get_shearcat(filename, tablename): # # for opening and retrieving shear cat. # return ldac.openObjectFile(filename, tablename) #class ello def avg_shear(g1array, g2array): avg1 = numpy.mean(g1array)...
(g1array, g2array, epol1, epol2): # g1 array : numpy array of g1 # g2 array : numpy array of g2 # e1po1 array: array of e1 correction at gal position # e2pol array: array of e2 correction at gal position # Average shear in bins of the ell correction # this may be defunct. # get indices of s...
avg_shear_aniscorr
identifier_name
quality_studies_psf.py
import numpy, sys, os, pylab, astropy, astropy.io.fits as pyfits, ldac, math def open_and_get_shearcat(filename, tablename): # # for opening and retrieving shear cat. # return ldac.openObjectFile(filename, tablename) #class ello def avg_shear(g1array, g2array): avg1 = numpy.mean(g1array)...
star_xarr = numpy.array(starcat['x']) star_yarr = numpy.array(starcat['y']) star_e1corr = numpy.array(starcat['e1corrpol']) star_e2corr = numpy.array(starcat['e2corrpol']) star_e1 = numpy.array(starcat['e1']) star_e2 = numpy.array(starcat['e2']) pylab.rc('text', usetex=True)...
gal_yarr = numpy.array(galcat['y']) gal_e1corr = numpy.array(galcat['e1corrpol']) gal_e2corr = numpy.array(galcat['e2corrpol'])
random_line_split
setup.py
from distutils.core import setup setup(name = "pywapi-dbus", version = "0.1-git", description = "D-Bus Python Weather API Service is a D-Bus service providing weather information", author = "Sasu Karttunen", author_email = "sasu.karttunen@tpnet.fi", url = "https://github.com/skfin/pywapi-dbus", ...
'Intended Audience :: System Administrators', 'License :: OSI Approved :: GNU Library or Lesser General Public License (LGPL)', 'Programming Language :: Python', 'Environment :: No Input/Output (Daemon)', 'Operating System :: UNIX', 'Topic :: Software Development :: Libraries', # Not...
classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers',
random_line_split
test_stacks.py
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # 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...
(self): resp, stacks = self.client.list_stacks() self.assertEqual('200', resp['status']) self.assertIsInstance(stacks, list) @attr(type='smoke') def test_stack_crud_no_resources(self): stack_name = data_utils.rand_name('heat') # create the stack stack_identifier...
test_stack_list_responds
identifier_name
test_stacks.py
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # 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...
stack_name = data_utils.rand_name('heat') # create the stack stack_identifier = self.create_stack( stack_name, self.empty_template) stack_id = stack_identifier.split('/')[1] # wait for create complete (with no resources it should be instant) self.client.wait_for_sta...
identifier_body
test_stacks.py
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # 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...
LOG = logging.getLogger(__name__) class StacksTestJSON(base.BaseOrchestrationTest): _interface = 'json' empty_template = "HeatTemplateFormatVersion: '2012-12-12'\n" @classmethod def setUpClass(cls): super(StacksTestJSON, cls).setUpClass() cls.client = cls.orchestration_client ...
from tempest.common.utils import data_utils from tempest.openstack.common import log as logging from tempest.test import attr
random_line_split
main.rs
use sendgrid::SGClient; use sendgrid::{Destination, Mail}; fn main()
{ let mut env_vars = std::env::vars(); let api_key_check = env_vars.find(|var| var.0 == "SENDGRID_API_KEY"); let api_key: String; match api_key_check { Some(key) => api_key = key.1, None => panic!("Must supply API key in environment variables to use!"), } let sg = SGClient::new(...
identifier_body
main.rs
use sendgrid::SGClient; use sendgrid::{Destination, Mail}; fn
() { let mut env_vars = std::env::vars(); let api_key_check = env_vars.find(|var| var.0 == "SENDGRID_API_KEY"); let api_key: String; match api_key_check { Some(key) => api_key = key.1, None => panic!("Must supply API key in environment variables to use!"), } let sg = SGClient::n...
main
identifier_name
main.rs
use sendgrid::SGClient; use sendgrid::{Destination, Mail}; fn main() {
let mut env_vars = std::env::vars(); let api_key_check = env_vars.find(|var| var.0 == "SENDGRID_API_KEY"); let api_key: String; match api_key_check { Some(key) => api_key = key.1, None => panic!("Must supply API key in environment variables to use!"), } let sg = SGClient::new(ap...
random_line_split
logger.rs
use log::{Level, LevelFilter, Log, Metadata, Record, SetLoggerError}; struct Logger { log_level: Level, } impl Log for Logger { fn
(&self, metadata: &Metadata) -> bool { metadata.level() <= self.log_level } fn log(&self, record: &Record) { if self.enabled(record.metadata()) { println!("[{:>5}@{}] {}", record.level(), record.target(), record.args()); } } fn flush(&self) {} } pub fn init(level: ...
enabled
identifier_name
logger.rs
use log::{Level, LevelFilter, Log, Metadata, Record, SetLoggerError}; struct Logger {
fn enabled(&self, metadata: &Metadata) -> bool { metadata.level() <= self.log_level } fn log(&self, record: &Record) { if self.enabled(record.metadata()) { println!("[{:>5}@{}] {}", record.level(), record.target(), record.args()); } } fn flush(&self) {} } pub f...
log_level: Level, } impl Log for Logger {
random_line_split
logger.rs
use log::{Level, LevelFilter, Log, Metadata, Record, SetLoggerError}; struct Logger { log_level: Level, } impl Log for Logger { fn enabled(&self, metadata: &Metadata) -> bool
fn log(&self, record: &Record) { if self.enabled(record.metadata()) { println!("[{:>5}@{}] {}", record.level(), record.target(), record.args()); } } fn flush(&self) {} } pub fn init(level: &str) -> Result<(), SetLoggerError> { if level != "off" { let log_level = m...
{ metadata.level() <= self.log_level }
identifier_body
text_run.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 app_units::Au; use font::{Font, FontHandleMethods, FontMetrics, ShapingFlags}; use font::{RunMetrics, ShapingO...
let mut byte_range = self.range.intersect(&slice_glyphs.range); let slice_range_begin = slice_glyphs.range.begin(); byte_range.shift_by(-slice_range_begin); if !byte_range.is_empty() { Some(TextRunSlice { glyphs: &*slice_glyphs.glyph_store, o...
random_line_split
text_run.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 app_units::Au; use font::{Font, FontHandleMethods, FontMetrics, ShapingFlags}; use font::{RunMetrics, ShapingO...
(&mut self) -> Option<TextRunSlice<'a>> { let slice_glyphs; if self.reverse { if self.index == 0 { return None; } self.index -= 1; slice_glyphs = &self.glyphs[self.index]; } else { if self.index >= self.glyphs.len() { ...
next
identifier_name
trigger.tsx
import * as React from 'react'; import * as Constants from './constants'; import { IContextMenuTrigger } from './interfaces'; import { ContextMenuHelper } from './helper'; interface Props { id: string; args?: null | undefined | number | string; } interface State { } export class
extends React.PureComponent <Props, State> implements IContextMenuTrigger { public constructor(props: Props) { super(props); this.showContextMenu = this.showContextMenu.bind(this); } public render() { const { id } = this.props; return( <div ...
Trigger
identifier_name
trigger.tsx
import * as React from 'react'; import * as Constants from './constants'; import { IContextMenuTrigger } from './interfaces'; import { ContextMenuHelper } from './helper'; interface Props { id: string; args?: null | undefined | number | string;
interface State { } export class Trigger extends React.PureComponent <Props, State> implements IContextMenuTrigger { public constructor(props: Props) { super(props); this.showContextMenu = this.showContextMenu.bind(this); } public render() { const { id } = this...
}
random_line_split
trigger.tsx
import * as React from 'react'; import * as Constants from './constants'; import { IContextMenuTrigger } from './interfaces'; import { ContextMenuHelper } from './helper'; interface Props { id: string; args?: null | undefined | number | string; } interface State { } export class Trigger extends React.PureCo...
public render() { const { id } = this.props; return( <div id={id} className={Constants.CLASS_MENU_WRAPPER} onContextMenu={this.showContextMenu} > {this.props.children} </div> ...
{ super(props); this.showContextMenu = this.showContextMenu.bind(this); }
identifier_body
footer.ts
import * as b from 'bobril'; import { link, button } from './../../components/gui'; import { ALL_TODOS, ACTIVE_TODOS, COMPLETED_TODOS } from './../constants'; import { TodosStore } from '../store'; export const create = b.createVirtualComponent<IData>({ render(ctx: IContext, me: b.IBobrilNode) { let { stor...
function createFilters(store: TodosStore): b.IBobrilNode { let filter: b.IBobrilNode = { tag: 'ul', children: [ createLink('All', '', store.nowShowing === ALL_TODOS), createLink('Active', 'todoActive', store.nowShowing === ACTIVE_TODOS), createLink('Completed', ...
{ let countLabel: b.IBobrilNode = { tag: 'span', children: [ { tag: 'strong', children: count }, { tag: 'span', children: ' ' }, { tag: 'span', children: count === 1 ? 'item' : 'items' }, { tag: 'span', children: ' left' } ] }; return b...
identifier_body
footer.ts
import * as b from 'bobril'; import { link, button } from './../../components/gui'; import { ALL_TODOS, ACTIVE_TODOS, COMPLETED_TODOS } from './../constants'; import { TodosStore } from '../store'; export const create = b.createVirtualComponent<IData>({ render(ctx: IContext, me: b.IBobrilNode) { let { stor...
(store: TodosStore): b.IBobrilNode { let filter: b.IBobrilNode = { tag: 'ul', children: [ createLink('All', '', store.nowShowing === ALL_TODOS), createLink('Active', 'todoActive', store.nowShowing === ACTIVE_TODOS), createLink('Completed', 'todoCompleted', store.n...
createFilters
identifier_name
footer.ts
import * as b from 'bobril'; import { link, button } from './../../components/gui'; import { ALL_TODOS, ACTIVE_TODOS, COMPLETED_TODOS } from './../constants'; import { TodosStore } from '../store'; export const create = b.createVirtualComponent<IData>({ render(ctx: IContext, me: b.IBobrilNode) { let { stor...
button( { value: 'Clear completed', onClick: () => { store.clearCompleted(); } } ), clearButtonStyle ); } const footerStyle = b.styleDef('footer'); const countStyle = b.styleDef('todo-count'); const ...
} function createClearButton(store: TodosStore): b.IBobrilNode { return b.style(
random_line_split
items.js
$(function() { /* We're going to use these elements a lot, so let's save references to them * here. All of these elements are already created by the HTML code produced * by the items page. */ var $orderPanel = $('#order-panel'); var $orderPanelCloseButton = $('#order-panel-close-button'); var $itemName =...
}); /* When the form is submitted (button is pressed or enter key is pressed), * make the Ajax call to add the item to the current order. */ $('#item-add-form').submit(function(event) { // Prevent default form submission event.preventDefault(); /* No input validation... yet. */ var quantity...
{ $orderPanel.offset({ right: -$orderPanel.outerWidth() }); }
conditional_block
items.js
$(function() { /* We're going to use these elements a lot, so let's save references to them * here. All of these elements are already created by the HTML code produced * by the items page. */ var $orderPanel = $('#order-panel'); var $orderPanelCloseButton = $('#order-panel-close-button'); var $itemName =...
/* This is called if and when the server responds with a 2XX (success) * status code. */ /* Show a success message. */ showAlert('Posted the order with id ' + orderID, 'success'); /* Close the side panel while we're at it. */ togglePanel(false); }).fail(function() { sho...
/* The `Accept` header. This tells the server that we want to receive * JSON. This sets the header as something like * `Accept: application/json`. */ dataType: 'json' }).done(function() {
random_line_split
main.rs
extern crate may; extern crate num_cpus; #[macro_use] extern crate serde_derive; extern crate serde_json; extern crate may_minihttp; use std::io; use may_minihttp::{HttpServer, HttpService, Request, Response}; #[derive(Serialize)] struct Message<'a> { message: &'a str, } struct Techempower; impl HttpService for...
() { may::config().set_io_workers(num_cpus::get()); let server = HttpServer(Techempower).start("0.0.0.0:8080").unwrap(); server.join().unwrap(); }
main
identifier_name
main.rs
extern crate may; extern crate num_cpus; #[macro_use] extern crate serde_derive; extern crate serde_json; extern crate may_minihttp; use std::io; use may_minihttp::{HttpServer, HttpService, Request, Response}; #[derive(Serialize)] struct Message<'a> { message: &'a str, } struct Techempower;
impl HttpService for Techempower { fn call(&self, req: Request) -> io::Result<Response> { let mut resp = Response::new(); // Bare-bones router match req.path() { "/json" => { resp.header("Content-Type", "application/json"); *resp.body_mut() = ...
random_line_split
urls.js
const electron = require("electron"); const http = require("http"); const npm = require("npm"); const path = require("path"); const url = require("url"); let baseUrl = null; exports.loadURL = (win, relativeUrl) => { if (baseUrl === null) { if (process.argv.indexOf("--dev") >= 0) { process.env....
setTimeout(loop, 1000); }); }; setTimeout(loop); win.setSize(1920, 1080); win.toggleDevTools(); } else { baseUrl = `${url.format({ "pathname": path.join(__dirname, "..", "build", "index.html"), ...
console.log("Connected to development server."); win.loadURL(baseUrl + relativeUrl); }).once("error", () => { console.log("Unable to connect to development server.");
random_line_split
urls.js
const electron = require("electron"); const http = require("http"); const npm = require("npm"); const path = require("path"); const url = require("url"); let baseUrl = null; exports.loadURL = (win, relativeUrl) => { if (baseUrl === null) { if (process.argv.indexOf("--dev") >= 0) { process.env....
} else { win.loadURL(baseUrl + relativeUrl); } };
{ baseUrl = `${url.format({ "pathname": path.join(__dirname, "..", "build", "index.html"), "protocol": "file:", "slashes": true })}#`; win.loadURL(baseUrl + relativeUrl); }
conditional_block
testPriority.rs
extern mod extra; use std::rt::io::*; use std::rt::io::net::ip::SocketAddr; use std::io::println; use std::cell::Cell; use std::{os, str, io, run, uint}; use extra::arc; use std::comm::*; use extra::priority_queue::PriorityQueue; use std::rt::io::net::ip::*; use std::hashmap::HashMap; struct sched_msg { ip:...
impl Ord for sched_msg { fn lt(&self, other: &sched_msg) -> bool { let selfIP: IpAddr = self.ip; let otherIP: IpAddr = other.ip; let selfSize : Option<uint> = self.filesize; let mut sSize: uint = 0; match selfSize{ Some(i) => { sSize=i;}, None => {return true;} } let otherSize : Option...
{ let mut opt1 : Option<uint> = Some(10u); let mut opt2 : Option<uint> = Some(3u); let mut opt3 : Option<uint> = Some(20u); let mut local: IpAddr = std::rt::io::net::ip::Ipv4Addr(128, 143, -1, -1); let mut local2: IpAddr = std::rt::io::net::ip::Ipv4Addr(137, 54, -1, -1); let mut other: IpAddr = std::rt::io::net::ip::...
identifier_body
testPriority.rs
extern mod extra; use std::rt::io::*; use std::rt::io::net::ip::SocketAddr; use std::io::println; use std::cell::Cell; use std::{os, str, io, run, uint}; use extra::arc; use std::comm::*; use extra::priority_queue::PriorityQueue; use std::rt::io::net::ip::*; use std::hashmap::HashMap; struct sched_msg { ip: ...
match selfSize{ Some(i) => { sSize=i;}, None => {return true;} } let otherSize : Option<uint> = other.filesize; let mut oSize: uint = 0; match otherSize{ Some(k) => { oSize=k;}, None => {return true;} } let mut sIP : bool = false; let mut oIP : bool = false; match selfIP { ...
let mut sSize: uint = 0;
random_line_split
testPriority.rs
extern mod extra; use std::rt::io::*; use std::rt::io::net::ip::SocketAddr; use std::io::println; use std::cell::Cell; use std::{os, str, io, run, uint}; use extra::arc; use std::comm::*; use extra::priority_queue::PriorityQueue; use std::rt::io::net::ip::*; use std::hashmap::HashMap; struct sched_msg { ip:...
, None => {return true;} } let mut sIP : bool = false; let mut oIP : bool = false; match selfIP { Ipv4Addr(a , b, c, d) => { if ((a == 128 && b == 143) || (a == 137 && b == 54)){ sIP = true; } }, Ipv6Addr(a, b, c, d, e, f, g, h) => { if ((a == 128 && b == 143) || (a == 137 && b =...
{ oSize=k;}
conditional_block
testPriority.rs
extern mod extra; use std::rt::io::*; use std::rt::io::net::ip::SocketAddr; use std::io::println; use std::cell::Cell; use std::{os, str, io, run, uint}; use extra::arc; use std::comm::*; use extra::priority_queue::PriorityQueue; use std::rt::io::net::ip::*; use std::hashmap::HashMap; struct
{ ip: IpAddr, filesize: Option<uint>, //filesize added to store file size } fn main() { let mut opt1 : Option<uint> = Some(10u); let mut opt2 : Option<uint> = Some(3u); let mut opt3 : Option<uint> = Some(20u); let mut local: IpAddr = std::rt::io::net::ip::Ipv4Addr(128, 143, -1, -1); let mut local2: IpA...
sched_msg
identifier_name
diagnostic.rs
// Copyright 2012 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 ...
'\t' => s.push('\t'), _ => s.push(' '), }; } } try!(write!(&mut err.dst, "{}", s)); let mut s = String::from_str("^"); let hi = cm.lookup_char_pos(sp.hi); if hi.col != lo.col { // the ^ already takes...
random_line_split
diagnostic.rs
// Copyright 2012 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 ...
else { for &line_number in lines.iter() { if let Some(line) = fm.get_line(line_number) { try!(write!(&mut w.dst, "{}:{} {}\n", fm.name, line_number + 1, line)); } } } let last_line_start = format!("{}:{} ", fm.name, lines[lines...
{ if let Some(line) = fm.get_line(lines[0]) { try!(write!(&mut w.dst, "{}:{} {}\n", fm.name, lines[0] + 1, line)); } try!(write!(&mut w.dst, "...\n")); let last_line_number = lines[lines.len() - 1]; if let Some(last_line) = fm.get_line(last_lin...
conditional_block
diagnostic.rs
// Copyright 2012 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 ...
pub fn span_err_with_code(&self, sp: Span, msg: &str, code: &str) { self.handler.emit_with_code(Some((&self.cm, sp)), msg, code, Error); self.handler.bump_err_count(); } pub fn span_warn(&self, sp: Span, msg: &str) { self.handler.emit(Some((&self.cm, sp)), msg, Warning); } p...
{ self.handler.emit(Some((&self.cm, sp)), msg, Error); self.handler.bump_err_count(); }
identifier_body
diagnostic.rs
// Copyright 2012 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 ...
(&self, f: &mut fmt::Formatter) -> fmt::Result { use std::fmt::Display; match *self { Bug => "error: internal compiler error".fmt(f), Fatal | Error => "error".fmt(f), Warning => "warning".fmt(f), Note => "note".fmt(f), Help => "help".fmt(f), ...
fmt
identifier_name
server3.py
#!/usr/bin/env python import server import time from Sensoria.stereotypes.TimeControlData import TimeControlData from Sensoria.stereotypes.InstantMessageData import InstantMessageData class TemperatureSensor (server.TemperatureSensor): def __init__ (self): super (TemperatureSensor, self).__init__ ("HD", "Heater T...
time.sleep (1)
conditional_block
server3.py
#!/usr/bin/env python import server import time from Sensoria.stereotypes.TimeControlData import TimeControlData from Sensoria.stereotypes.InstantMessageData import InstantMessageData class TemperatureSensor (server.TemperatureSensor): def __init__ (self): super (TemperatureSensor, self).__init__ ("HD", "Heater T...
(self): super (HeaterTimer, self).__init__ ("HT", "Heater Timer") initData = TimeControlData () initData.unmarshal ("PMO:000000001000000003222110 PTU:000000001000000003222110 PWE:000000001000000003222110 PTH:000000001000000003222110 PFR:000000001000000003222111 PSA:000000000322222222222211 PSU:000000000322222222...
__init__
identifier_name
server3.py
#!/usr/bin/env python import server import time from Sensoria.stereotypes.TimeControlData import TimeControlData from Sensoria.stereotypes.InstantMessageData import InstantMessageData class TemperatureSensor (server.TemperatureSensor): def __init__ (self): super (TemperatureSensor, self).__init__ ("HD", "Heater T...
@values.setter def values (self, v): self.levels = v[0:3] hd = TemperatureSensor () hc = HeaterController () ht = HeaterTimer () hs = HeaterSettings () listener = server.CommandListener ("HeatingSystem") listener.register_sensor (hd) listener.register_sensor (hc) listener.register_sensor (ht) listener.register_s...
return self.levels
identifier_body
server3.py
#!/usr/bin/env python import server import time from Sensoria.stereotypes.TimeControlData import TimeControlData from Sensoria.stereotypes.InstantMessageData import InstantMessageData class TemperatureSensor (server.TemperatureSensor): def __init__ (self): super (TemperatureSensor, self).__init__ ("HD", "Heater T...
@property def values (self): return self.levels @values.setter def values (self, v): self.levels = v[0:3] hd = TemperatureSensor () hc = HeaterController () ht = HeaterTimer () hs = HeaterSettings () listener = server.CommandListener ("HeatingSystem") listener.register_sensor (hd) listener.register_sensor (h...
class HeaterSettings (server.ValueSetActuator): def __init__ (self): super (HeaterSettings, self).__init__ ("HS", "Heater Settings") self.levels = [10, 18, 21]
random_line_split
issue-7013.rs
// Copyright 2013 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 a = A {v: ~B{v: None} as ~Foo:Send}; //~^ ERROR cannot pack type `~B`, which does not fulfill `Send` let v = Rc::new(RefCell::new(a)); let w = v.clone(); let b = &*v; let mut b = b.borrow_mut(); b.v.set(w.clone()); }
main
identifier_name
issue-7013.rs
// Copyright 2013 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 ...
} } struct A { v: ~Foo:Send, } fn main() { let a = A {v: ~B{v: None} as ~Foo:Send}; //~^ ERROR cannot pack type `~B`, which does not fulfill `Send` let v = Rc::new(RefCell::new(a)); let w = v.clone(); let b = &*v; let mut b = b.borrow_mut(); b.v.set(w.clone()); }
impl Foo for B { fn set(&mut self, v: Rc<RefCell<A>>) { self.v = Some(v);
random_line_split
models.py
from django.db import models from .managers import CRUDManager, CRUDException class CRUDFilterModel(models.Model): class Meta: abstract = True @classmethod def verify_user_has_role(cls, user, role, request): """ Call user-defined auth function to determine if this user can use th...
@classmethod def check_for_permissions(cls, user, role, operation, request, filters=['__default']): """ Make sure this role can perform this operation """ cls.verify_user_has_role(user, role, request) for filter_str in filters: if not cls.role_can_perform_op...
""" Return queryset that this user/role has access to (given these filters) """ # UNSAFE to call this function from outside of the "get_queryset_or_false" function. # If this is not an abstract class, start with all objects, and filter down. if hasattr(cls, 'objects'): ...
identifier_body
models.py
from django.db import models from .managers import CRUDManager, CRUDException class CRUDFilterModel(models.Model): class Meta: abstract = True
Call user-defined auth function to determine if this user can use this role. """ if role in ['anonymous', 'authenticated']: return True elif role == "admin": return user.is_superuser if CRUDManager.auth_function is None: raise CRUDException("Y...
@classmethod def verify_user_has_role(cls, user, role, request): """
random_line_split
models.py
from django.db import models from .managers import CRUDManager, CRUDException class CRUDFilterModel(models.Model): class Meta: abstract = True @classmethod def verify_user_has_role(cls, user, role, request): """ Call user-defined auth function to determine if this user can use th...
if CRUDManager.auth_function is None: raise CRUDException("You must define an auth_function for CRUDManagerMixin", 500) try: value = CRUDManager.auth_function(role, user, request) except Exception as exc: raise CRUDException("Your auth_function in CRUDManage...
return user.is_superuser
conditional_block
models.py
from django.db import models from .managers import CRUDManager, CRUDException class CRUDFilterModel(models.Model): class Meta: abstract = True @classmethod def verify_user_has_role(cls, user, role, request): """ Call user-defined auth function to determine if this user can use th...
(cls, role, operation, filter_str): """ For this class, make sure this role can perform this operation (with this filter) """ # print("Check cls ", str(cls), " role ", role, " operation ", operation, " filter_str ", filter_str) if operation.upper() not in ['C', 'R', 'U', 'D']: ...
role_can_perform_operation_with_filter
identifier_name
mind.rs
use std::f32::{INFINITY, NEG_INFINITY}; use std::cmp::Ordering; use std::default::Default; use std::fmt; use std::hash::BuildHasherDefault; use std::mem; use std::sync::Arc; use std::sync::mpsc; use std::thread; use std::time::Duration; use time; use lru_cache::LruCache; use parking_lot; use twox_hash::XxHash; use fnv...
::new(); b.iter(|| kickoff::<Patch>(&ws, 2, None, true, MOCK_DÉJÀ_VU_BOUND)); } #[bench] fn benchmark_kickoff_depth_2_carefully(b: &mut Bencher) { let ws = WorldState::new(); b.iter(|| kickoff::<Patch>(&ws, 2, None, false, MOCK_DÉJÀ_VU_BOUND)); } #[bench] fn benchmark_k...
) { let ws = WorldState
identifier_name
mind.rs
use std::f32::{INFINITY, NEG_INFINITY}; use std::cmp::Ordering; use std::default::Default; use std::fmt; use std::hash::BuildHasherDefault; use std::mem; use std::sync::Arc; use std::sync::mpsc; use std::thread; use std::time::Duration; use time; use lru_cache::LruCache; use parking_lot; use twox_hash::XxHash; use fnv...
assert_eq!(0.0, score(WorldState::new()) - REWARD_FOR_INITIATIVE); } #[test] fn concerning_servant_ascension_choices() { let ws = WorldState::reconstruct("8/q1P1k/8/8/8/8/6PP/7K w - -"); // looking ahead 3 movements allows the Leafline AI to catch the // split, whereby trans...
// but they do have well-defined behavior.
random_line_split
mind.rs
use std::f32::{INFINITY, NEG_INFINITY}; use std::cmp::Ordering; use std::default::Default; use std::fmt; use std::hash::BuildHasherDefault; use std::mem; use std::sync::Arc; use std::sync::mpsc; use std::thread; use std::time::Duration; use time; use lru_cache::LruCache; use parking_lot; use twox_hash::XxHash; use fnv...
à_vu_table_size_bound<T: Memory>(gib: f32) -> usize { let bound = usize::from(Bytes::gibi(gib)) / (mem::size_of::<SpaceTime>() + mem::size_of::<Lodestar<T>>()); bound } pub fn potentially_timebound_kickoff<T: 'static + Memory>( world: &WorldState, depth: u8, extension_maybe: Option<u8>, n...
let mut premonitions = world.reckless_lookahead(); let mut optimum = NEG_INFINITY; let mut optimand = T::blank(); if depth <= 0 || premonitions.is_empty() { let potential_score = orientation(world.initiative) * score(world); match quiet { None => { return Lodest...
identifier_body
statistics.rs
use std::cmp; use crate::sketch_schemes::KmerCount; pub fn cardinality(sketch: &[KmerCount]) -> Result<u64, &'static str> { // Other (possibly more accurate) possibilities: // "hyper log-log" estimate from lowest value? // multiset distribution applied to total count number? // "AKMV" approach: http:/...
{ let sketch = vec![ KmerCount { hash: 1, kmer: vec![], count: 1, extra_count: 0, label: None, }, KmerCount { hash: 2, kmer: vec![], count: 1, extra_count: 0, label: None, ...
identifier_body
statistics.rs
use std::cmp; use crate::sketch_schemes::KmerCount; pub fn cardinality(sketch: &[KmerCount]) -> Result<u64, &'static str> { // Other (possibly more accurate) possibilities: // "hyper log-log" estimate from lowest value? // multiset distribution applied to total count number? // "AKMV" approach: http:/...
extra_count: 0, label: None, }, KmerCount { hash: 3, kmer: vec![], count: 1, extra_count: 0, label: None, }, ]; let hist_data = hist(&sketch); assert_eq!(hist_data.len(), 1); assert_eq!(hist_data...
random_line_split
statistics.rs
use std::cmp; use crate::sketch_schemes::KmerCount; pub fn cardinality(sketch: &[KmerCount]) -> Result<u64, &'static str> { // Other (possibly more accurate) possibilities: // "hyper log-log" estimate from lowest value? // multiset distribution applied to total count number? // "AKMV" approach: http:/...
(sketch: &[KmerCount]) -> Vec<u64> { let mut counts = vec![0u64; 65536]; let mut max_count: u64 = 0; for kmer in sketch { max_count = cmp::max(max_count, u64::from(kmer.count)); counts[kmer.count as usize - 1] += 1; } counts.truncate(max_count as usize); counts } #[test] fn test...
hist
identifier_name
statistics.rs
use std::cmp; use crate::sketch_schemes::KmerCount; pub fn cardinality(sketch: &[KmerCount]) -> Result<u64, &'static str> { // Other (possibly more accurate) possibilities: // "hyper log-log" estimate from lowest value? // multiset distribution applied to total count number? // "AKMV" approach: http:/...
Ok(((sketch.len() - 1) as f32 / (sketch.last().unwrap().hash as f32 / usize::max_value() as f32)) as u64) } /// Generates a Vec of numbers of kmers for each coverage level /// /// For example, a size 1000 sketch of the same genome repeated 5 times (e.g. 5x coverage) should /// produce a "histogram" like [...
{ return Ok(0u64); }
conditional_block
main.rs
#[macro_use] extern crate clap; #[macro_use] extern crate log; extern crate env_logger; extern crate chrono; extern crate responder; use std::env::{self, VarError}; use std::io::{self, Write}; use std::net::SocketAddr; use std::path::Path; use std::process; use clap::{App, Arg, Format}; use log::{LogRecord, LogLeve...
(arg: String) -> Result<(), String> { arg.parse::<SocketAddr>() .map(|_| ()) .map_err(|_| String::from("invalid adrress")) } fn run_server(address: Option<&str>, config_file: &Path, reload: bool) -> Result<(), String> { let context = try!(Context::from_config_file(config_file, reload)); ...
address_validator
identifier_name
main.rs
#[macro_use] extern crate clap; #[macro_use] extern crate log; extern crate env_logger; extern crate chrono; extern crate responder; use std::env::{self, VarError}; use std::io::{self, Write}; use std::net::SocketAddr; use std::path::Path; use std::process; use clap::{App, Arg, Format}; use log::{LogRecord, LogLeve...
else { None }; let config = matches.value_of("config").map(|c| Path::new(c)).unwrap(); let reload = matches.is_present("reload"); match run_server(address, config, reload) { Ok(_) => {} Err(e) => { write!(io::stderr(), "{} {}\n", Format::Error("error:"), e) ...
{ matches.value_of("bind") }
conditional_block