file_name large_stringlengths 4 140 | prefix large_stringlengths 0 12.1k | suffix large_stringlengths 0 12k | middle large_stringlengths 0 7.51k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
result.py | import numpy as np
from . import finiteelements as fe
from . import matrices
from math import cos
class Result:
def __init__(self):
pass
def __init__(self, freq, u1, u2, u3, mesh, geometry):
self.freq = freq
self.u1 = u1
self.u2 = u2
self.u3 = u3
self.mesh ... |
def get_displacement_and_deriv(self, x1, x2, x3, time):
element = self.mesh.get_element(x1, x3)
if (element is None):
print ("x1 = {}, x2 = {}".format(x1, x3))
u_nodes = np.zeros((8))
u_nodes[0] = self.u1[element.top_left_index]
u_nodes[1] = self.u1[element.... | return rps/(2*np.pi) | identifier_body |
result.py | import numpy as np
from . import finiteelements as fe
from . import matrices
from math import cos
class | :
def __init__(self):
pass
def __init__(self, freq, u1, u2, u3, mesh, geometry):
self.freq = freq
self.u1 = u1
self.u2 = u2
self.u3 = u3
self.mesh = mesh
self.geometry = geometry
def rad_per_sec_to_Hz(self, rps):
return rps/(2*np.... | Result | identifier_name |
result.py | import numpy as np
from . import finiteelements as fe
from . import matrices
from math import cos
class Result:
def __init__(self):
pass
def __init__(self, freq, u1, u2, u3, mesh, geometry):
self.freq = freq
self.u1 = u1 | self.u2 = u2
self.u3 = u3
self.mesh = mesh
self.geometry = geometry
def rad_per_sec_to_Hz(self, rps):
return rps/(2*np.pi)
def get_displacement_and_deriv(self, x1, x2, x3, time):
element = self.mesh.get_element(x1, x3)
if (element is None):
... | random_line_split | |
am-regional-general-chart.js | // JavaScript Document
var chart16;
var rChartData16;
var chartData16 = [
[
{
"label" : "General",
"litres": 93760
},
{
"label": "Public",
"litres": 95100
},
{
"label": "Other",
"litres": 22303
},
{
"label": "Subsidy",
"litres": 74425
... | (){
// PIE CHART
chart16 = new AmCharts.AmPieChart();
chart16.dataProvider = rChartData16;
chart16.titleField = "label";
chart16.valueField = "litres";
chart16.outlineColor = "#FFFFFF";
chart16.outlineAlpha = 0.8;
chart16.outlineThickness = 2;
chart16.balloonText = "[[title]]<br... | drawChart16 | identifier_name |
am-regional-general-chart.js | // JavaScript Document
var chart16;
var rChartData16;
var chartData16 = [
[
{
"label" : "General",
"litres": 93760
},
{
"label": "Public",
"litres": 95100
},
{
"label": "Other",
"litres": 22303
},
{
"label": "Subsidy",
"litres": 74425
... | chart16.titleField = "label";
chart16.valueField = "litres";
chart16.outlineColor = "#FFFFFF";
chart16.outlineAlpha = 0.8;
chart16.outlineThickness = 2;
chart16.balloonText = "[[title]]<br><span style='font-size:14px'><b>[[value]]</b> ([[percents]]%)</span>";
chart16.colors = [ "#c7c8a7", "#ddd... | // PIE CHART
chart16 = new AmCharts.AmPieChart();
chart16.dataProvider = rChartData16;
| random_line_split |
am-regional-general-chart.js | // JavaScript Document
var chart16;
var rChartData16;
var chartData16 = [
[
{
"label" : "General",
"litres": 93760
},
{
"label": "Public",
"litres": 95100
},
{
"label": "Other",
"litres": 22303
},
{
"label": "Subsidy",
"litres": 74425
... | chart16.write("regional-general-chart");
}
AmCharts.ready(function () {
rChartData16 = chartData16[0];
drawChart16();
}); | {
// PIE CHART
chart16 = new AmCharts.AmPieChart();
chart16.dataProvider = rChartData16;
chart16.titleField = "label";
chart16.valueField = "litres";
chart16.outlineColor = "#FFFFFF";
chart16.outlineAlpha = 0.8;
chart16.outlineThickness = 2;
chart16.balloonText = "[[title]]<br><... | identifier_body |
text.rs | -allocated object for scanning an inline flow into `TextRun`-containing `TextBox`es.
pub struct TextRunScanner {
clump: Range,
}
impl TextRunScanner {
pub fn new() -> TextRunScanner {
TextRunScanner {
clump: Range::empty(),
}
}
pub fn scan_for_runs(&mut self, font_context: ... | // handle remaining clumps
if self.clump.length() > 0 {
self.flush_clump_to_list(font_context, flow, last_whitespace, &mut out_boxes);
}
debug!("TextRunScanner: swapping out boxes.");
// Swap out the old and new box list of the flow.
flow.as_inline().boxes =... | {
{
let inline = flow.as_immutable_inline();
debug!("TextRunScanner: scanning {:u} boxes for text runs...", inline.boxes.len());
}
let mut last_whitespace = true;
let mut out_boxes = ~[];
for box_i in range(0, flow.as_immutable_inline().boxes.len()) {
... | identifier_body |
text.rs | -allocated object for scanning an inline flow into `TextRun`-containing `TextBox`es.
pub struct TextRunScanner {
clump: Range,
}
impl TextRunScanner {
pub fn new() -> TextRunScanner {
TextRunScanner {
clump: Range::empty(),
}
}
pub fn scan_for_runs(&mut self, font_context: ... | (boxes: &[Box], left_i: uint, right_i: uint) -> bool {
assert!(left_i < boxes.len());
assert!(right_i > 0 && right_i < boxes.len());
assert!(left_i != right_i);
boxes[left_i].can_merge_with_box(&boxes[right_i])
}
}
/// A "clump" is a range of inline flow ... | can_coalesce_text_nodes | identifier_name |
text.rs | -allocated object for scanning an inline flow into `TextRun`-containing `TextBox`es.
pub struct TextRunScanner {
clump: Range,
}
impl TextRunScanner {
pub fn new() -> TextRunScanner {
TextRunScanner {
clump: Range::empty(),
}
}
pub fn scan_for_runs(&mut self, font_context: ... | struct NewLinePositions {
new_line_pos: ~[uint],
}
let mut new_line_positions: ~[NewLinePositions] = ~[];
// First, transform/compress text of all the nodes.
let mut last_whitespace_in_clump = new_whitespace;
... | random_line_split | |
setup.py | import setuptools
with open("space_tracer.md") as f:
long_description = f.read()
about = {}
with open("plugin/PySrc/space_tracer/about.py") as f:
exec(f.read(), about)
# noinspection PyUnresolvedReferences
setuptools.setup(
name=about['__title__'],
version=about['__version__'],
author=about['__aut... | ],
project_urls={
'Bug Reports': 'https://github.com/donkirkby/live-py-plugin/issues',
'Source': 'https://github.com/donkirkby/live-py-plugin'}
) | "License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Development Status :: 5 - Production/Stable",
"Environment :: Console" | random_line_split |
ping.rs | extern crate mqttc;
extern crate netopt;
#[macro_use] extern crate log;
extern crate env_logger;
use std::env;
use std::process::exit;
use std::time::Duration;
use netopt::NetworkOptions;
use mqttc::{Client, ClientOptions, ReconnectMethod};
fn main() | Some(message) => println!("{:?}", message),
None => {
println!(".");
}
}
}
}
| {
env_logger::init();
let mut args: Vec<_> = env::args().collect();
if args.len() < 2 {
println!("Usage: cargo run --example ping -- 127.0.0.1:1883");
exit(0);
}
let ref address = args[1];
info!("Display logs");
println!("Establish connection to {}", address);
// Connect... | identifier_body |
ping.rs | extern crate mqttc;
extern crate netopt; | extern crate env_logger;
use std::env;
use std::process::exit;
use std::time::Duration;
use netopt::NetworkOptions;
use mqttc::{Client, ClientOptions, ReconnectMethod};
fn main() {
env_logger::init();
let mut args: Vec<_> = env::args().collect();
if args.len() < 2 {
println!("Usage: cargo run --ex... | #[macro_use] extern crate log; | random_line_split |
ping.rs | extern crate mqttc;
extern crate netopt;
#[macro_use] extern crate log;
extern crate env_logger;
use std::env;
use std::process::exit;
use std::time::Duration;
use netopt::NetworkOptions;
use mqttc::{Client, ClientOptions, ReconnectMethod};
fn | () {
env_logger::init();
let mut args: Vec<_> = env::args().collect();
if args.len() < 2 {
println!("Usage: cargo run --example ping -- 127.0.0.1:1883");
exit(0);
}
let ref address = args[1];
info!("Display logs");
println!("Establish connection to {}", address);
// Conn... | main | identifier_name |
welcome.js | const Request = require('request');
const env2 = require('env2');
const HapiCookie = require('hapi-auth-cookie');
env2('./config.env');
module.exports = {
path: '/welcome',
method: 'GET',
handler: (req, rep) => {
const accessUrl = `https://github.com/login/oauth/access_token`;
Request.post({
heade... | let parsed = JSON.parse(body);
const userToken = {
access_token: parsed.access_token
};
Request.get({
headers: {
'User-Agent': 'GitPom',
// as recommended by the API documentation
Accept: `application/json`,
Authorization: `token ${userToke... | }, (err, res, body) => {
if (err) throw err; | random_line_split |
http_utils.rs | use url::Url;
use hyper::Client;
use hyper::header::{ContentType};
use hyper::status::StatusCode;
use hyper::error::Error;
use std::io::Read;
pub struct HttpResponse {
pub status: StatusCode,
pub body: String
}
pub fn | (url: &Url) -> Result<HttpResponse, Error> {
let mut client = Client::new();
let result_response = client.get(&url.to_string()).send();
//TODO: use try! macro here
match result_response {
Ok(mut res) => {
let mut body = String::new();
let result = res.read_to_string(&mut ... | get | identifier_name |
http_utils.rs | use url::Url;
use hyper::Client;
use hyper::header::{ContentType};
use hyper::status::StatusCode;
use hyper::error::Error;
use std::io::Read;
pub struct HttpResponse {
pub status: StatusCode,
pub body: String
}
pub fn get(url: &Url) -> Result<HttpResponse, Error> | }
pub fn post_json(url: &Url, body: &str) -> Result<HttpResponse, Error> {
let mut client = Client::new();
let result_response = client.post(&url.to_string())
.header(ContentType::json())
.body(body)
.send();
match result_response {
Ok(mut res) => {
let mut bod... | {
let mut client = Client::new();
let result_response = client.get(&url.to_string()).send();
//TODO: use try! macro here
match result_response {
Ok(mut res) => {
let mut body = String::new();
let result = res.read_to_string(&mut body);
match result {
... | identifier_body |
http_utils.rs | use url::Url;
use hyper::Client;
use hyper::header::{ContentType};
use hyper::status::StatusCode;
use hyper::error::Error;
use std::io::Read;
pub struct HttpResponse {
pub status: StatusCode,
pub body: String
} |
pub fn get(url: &Url) -> Result<HttpResponse, Error> {
let mut client = Client::new();
let result_response = client.get(&url.to_string()).send();
//TODO: use try! macro here
match result_response {
Ok(mut res) => {
let mut body = String::new();
let result = res.read_to_s... | random_line_split | |
app.js | 'use strict';
angular.module('main', ['ngRoute', 'ngResource', 'ui.route', 'main.system', 'main.index', 'main.events']);
angular.module('main.system', []);
angular.module('main.index', []);
angular.module('main.events', []);
'use strict';
//Setting HTML5 Location Mode
angular.module('main').config(['$locationProvide... | 'use strict';
angular.module('main.system')
.factory('Global', [
function () {
var obj = this;
obj._data = {
app: window.app || false
};
return obj._data;
}
]);
'use strict';
angular.element(document).ready(function() {
//... | $locationProvider.hashPrefix('!');
}
]); | random_line_split |
newsSearchAPIClient.d.ts | /*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
* Changes may cause incorrect behavior and will be lost if the code is
* regenerated.
*/
i... | extends ServiceClient {
/**
* @class
* Initializes a new instance of the NewsSearchAPIClient class.
* @constructor
*
* @param {credentials} credentials - Subscription credentials which uniquely identify client subscription.
*
* @param {string} [baseUri] - The base URI of the service.
*
* @... | NewsSearchAPIClient | identifier_name |
newsSearchAPIClient.d.ts | /*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
* Changes may cause incorrect behavior and will be lost if the code is
* regenerated.
*/
i... | *
* @param {string} [baseUri] - The base URI of the service.
*
* @param {object} [options] - The parameter options
*
* @param {Array} [options.filters] - Filters to be added to the request pipeline
*
* @param {object} [options.requestOptions] - Options for the underlying request object
* {@li... | * @param {credentials} credentials - Subscription credentials which uniquely identify client subscription. | random_line_split |
urls.py | #
# Copyright (C) 2013 Uninett AS
#
# This file is part of Network Administration Visualized (NAV).
#
# NAV is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public License version 3 as published by
# the Free Software Foundation.
#
# This program is distributed in the hope... | #
"""Django URL configuration for messages tool"""
from django.conf.urls import url
from nav.web.messages import views
from nav.web.messages.feeds import ActiveMessagesFeed
urlpatterns = [
url(r'^$', views.redirect_to_active),
url(r'^active/$', views.active, name='messages-home'),
url(r'^create/$', views... | random_line_split | |
mock_api_parser.py | # Copyright 2013 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... |
raise ValueError('Invalid integer format {value}'.format(
value=value_format))
def _ParseNumberType(self, discovery_type):
value_format = discovery_type.get('format')
if value_format in (None, 'double', 'float'):
return mock_api_types.NumberType(value_format or 'double')
raise ValueErr... | return mock_api_types.IntegerType(value_format or 'int32') | conditional_block |
mock_api_parser.py | # Copyright 2013 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | if method_id in self._parsed_methods:
raise ValueError('Duplicate method {method}'.format(method=method_id))
all_parameters = dict((p.name, p) for p in self._common_parameters)
all_parameters.update(dict((p.name, p) for p in parameters))
path = self._base_url + path
method = mock_api_types.Metho... | identifier_body | |
mock_api_parser.py | # Copyright 2013 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | import mock_api_types
from gcutil_lib import mock_api_types
class Parser(object):
"""Discovery document parser.
Parses discovery document types, resources and methods. Result of parsing is a
dictionary method_id -> method.
"""
__slots__ = ('_discovery_document', '_parsed_schemas', '_parsed_methods',
... |
"""Parsing API Discovery document."""
| random_line_split |
mock_api_parser.py | # Copyright 2013 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | (self, discovery_type):
ref = discovery_type.get('$ref')
if ref:
return self._GetSchema(ref)
type_name = discovery_type['type']
if type_name == 'any':
return mock_api_types.AnyType()
elif type_name == 'array':
return mock_api_types.ArrayType(self._ParseType(discovery_type['items']... | _ParseType | identifier_name |
warn_corner_cases.rs | // run-pass
// This test is checking our logic for structural match checking by enumerating
// the different kinds of const expressions. This test is collecting cases where
// we have accepted the const expression as a pattern in the past but we want
// to begin warning the user that a future version of Rust may start... | () {
const INDEX: Option<NoDerive> = [None, Some(NoDerive(10))][0];
match None { Some(_) => panic!("whoops"), INDEX => dbg!(INDEX), };
//~^ WARN must be annotated with `#[derive(PartialEq, Eq)]`
//~| WARN this was previously accepted
const fn build() -> Option<NoDerive> { None }
const CALL: Opt... | main | identifier_name |
warn_corner_cases.rs | // run-pass
// This test is checking our logic for structural match checking by enumerating
// the different kinds of const expressions. This test is collecting cases where
// we have accepted the const expression as a pattern in the past but we want
// to begin warning the user that a future version of Rust may start... | } | match None { Some(_) => panic!("whoops"), METHOD_CALL => dbg!(METHOD_CALL), };
//~^ WARN must be annotated with `#[derive(PartialEq, Eq)]`
//~| WARN this was previously accepted | random_line_split |
buffer.ts | .buffer);
const copiedBuffer = new Buffer(utf8Buffer);
console.log(Buffer.isBuffer(octetBuffer));
console.log(Buffer.isEncoding('utf8'));
console.log(Buffer.byteLength('xyz123'));
console.log(Buffer.byteLength('xyz123', 'ascii'));
const result1 = Buffer.concat([utf8Buffer, base64Buffer] as ReadonlyArray<Uint8Array>);
c... | ;
buf = Buffer.from(pseudoString);
buf = Buffer.from(pseudoString, "utf-8");
// $ExpectError
Buffer.from(pseudoString, 1, 2);
const pseudoArrayBuf = { valueOf() { return new Uint16Array(2); } };
buf = Buffer.from(pseudoArrayBuf, 1, 1);
}
// Class Method: Buffer.alloc(size[, fill[, encoding]])
{... | return "Hello"; }} | identifier_body |
buffer.ts | .buffer);
const copiedBuffer = new Buffer(utf8Buffer);
console.log(Buffer.isBuffer(octetBuffer));
console.log(Buffer.isEncoding('utf8'));
console.log(Buffer.byteLength('xyz123'));
console.log(Buffer.byteLength('xyz123', 'ascii'));
const result1 = Buffer.concat([utf8Buffer, base64Buffer] as ReadonlyArray<Uint8Array>);
c... | ) { return "Hello"; }};
buf = Buffer.from(pseudoString);
buf = Buffer.from(pseudoString, "utf-8");
// $ExpectError
Buffer.from(pseudoString, 1, 2);
const pseudoArrayBuf = { valueOf() { return new Uint16Array(2); } };
buf = Buffer.from(pseudoArrayBuf, 1, 1);
}
// Class Method: Buffer.alloc(size[... | alueOf( | identifier_name |
buffer.ts | console.log(Buffer.byteLength('xyz123'));
console.log(Buffer.byteLength('xyz123', 'ascii'));
const result1 = Buffer.concat([utf8Buffer, base64Buffer] as ReadonlyArray<Uint8Array>);
const result2 = Buffer.concat([utf8Buffer, base64Buffer] as ReadonlyArray<Uint8Array>, 9999999);
// Module constants
{
const value1: n... | const sharedBuffer = new Buffer(octets.buffer);
const copiedBuffer = new Buffer(utf8Buffer);
console.log(Buffer.isBuffer(octetBuffer));
console.log(Buffer.isEncoding('utf8')); | random_line_split | |
buffer.ts | .buffer);
const copiedBuffer = new Buffer(utf8Buffer);
console.log(Buffer.isBuffer(octetBuffer));
console.log(Buffer.isEncoding('utf8'));
console.log(Buffer.byteLength('xyz123'));
console.log(Buffer.byteLength('xyz123', 'ascii'));
const result1 = Buffer.concat([utf8Buffer, base64Buffer] as ReadonlyArray<Uint8Array>);
c... |
// write* methods return offsets.
const b = new Buffer(16);
let result: number = b.writeUInt32LE(0, 0);
result = b.writeUInt16LE(0, 4);
result = b.writeUInt8(0, 6);
result = b.writeInt8(0, 7);
result = b.writeDoubleLE(0, 8);
result = b.write('asd');
result = b.write('asd', 'hex');
result = b.write('asd', 123, 'hex');
... |
a.writeUInt8(3, 4);
}
| conditional_block |
issue-6128.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 g : Box<HashMap<int,int>> = box HashMap::new();
let _g2 : Box<Graph<int,int>> = g as Box<Graph<int,int>>;
} | identifier_body | |
issue-6128.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 ... | // except according to those terms.
#![allow(unknown_features)]
#![feature(box_syntax)]
extern crate collections;
use std::collections::HashMap;
trait Graph<Node, Edge> {
fn f(&self, Edge);
}
impl<E> Graph<int, E> for HashMap<int, int> {
fn f(&self, _e: E) {
panic!();
}
}
pub fn main() {
... | random_line_split | |
issue-6128.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 g : Box<HashMap<int,int>> = box HashMap::new();
let _g2 : Box<Graph<int,int>> = g as Box<Graph<int,int>>;
}
| main | identifier_name |
simple.rs | use std::convert::Infallible;
use hyper::service::{make_service_fn, service_fn};
use hyper::{Body, Request, Response, Server};
use lazy_static::lazy_static;
use reroute::{Captures, RouterBuilder};
lazy_static! {
static ref ROUTER: reroute::Router = {
let mut builder = RouterBuilder::new();
// Use... | (req: Request<Body>, _: Captures) -> Response<Body> {
Response::new(req.into_body())
}
// A custom 404 handler.
fn not_found(req: Request<Body>, _: Captures) -> Response<Body> {
let message = format!("why you calling {}?", req.uri());
Response::new(Body::from(message))
}
async fn handler(req: Request<Body... | body_handler | identifier_name |
simple.rs | use std::convert::Infallible;
use hyper::service::{make_service_fn, service_fn};
use hyper::{Body, Request, Response, Server};
use lazy_static::lazy_static;
use reroute::{Captures, RouterBuilder};
lazy_static! { | static ref ROUTER: reroute::Router = {
let mut builder = RouterBuilder::new();
// Use raw strings so you don't need to escape patterns.
builder.get(r"/(\d+)", digit_handler);
builder.post(r"/body", body_handler);
// Using a closure also works!
builder.delete(r"/clos... | random_line_split | |
simple.rs | use std::convert::Infallible;
use hyper::service::{make_service_fn, service_fn};
use hyper::{Body, Request, Response, Server};
use lazy_static::lazy_static;
use reroute::{Captures, RouterBuilder};
lazy_static! {
static ref ROUTER: reroute::Router = {
let mut builder = RouterBuilder::new();
// Use... |
async fn handler(req: Request<Body>) -> Result<Response<Body>, Infallible> {
Ok(ROUTER.handle(req))
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
let addr = ([127, 0, 0, 1], 3000).into();
let svc = make_service_fn(|_conn| async { Ok::<_, Infallible>(service_fn... | {
let message = format!("why you calling {}?", req.uri());
Response::new(Body::from(message))
} | identifier_body |
simple.rs | use std::convert::Infallible;
use hyper::service::{make_service_fn, service_fn};
use hyper::{Body, Request, Response, Server};
use lazy_static::lazy_static;
use reroute::{Captures, RouterBuilder};
lazy_static! {
static ref ROUTER: reroute::Router = {
let mut builder = RouterBuilder::new();
// Use... | else {
Response::new(Body::from("not a big number"))
}
}
// You can ignore captures if you don't want to use them.
fn body_handler(req: Request<Body>, _: Captures) -> Response<Body> {
Response::new(req.into_body())
}
// A custom 404 handler.
fn not_found(req: Request<Body>, _: Captures) -> Response<B... | {
Response::new(Body::from("that's a big number!"))
} | conditional_block |
renderer.js | FRAMETIMES_TO_KEEP = 10;
function init() {
(async () => {
initDom();
initDrawData();
if (INIT_OPENGL) {
initOpenGL();
}
initData();
await initOpenCL();
initGame();
initEvents();
startGameLoop();
render();
})();
}
function initDom() {
canvas = document.getElementById('glscreen');
fps... | } catch(err) {
console.error(cl.getProgramBuildInfo(clProgram, clBuildDevice, cl.PROGRAM_BUILD_LOG));
process.exit(-1);
}
// create buffers
const clBufferNeighbors = cl.createBuffer(clCtx, cl.MEM_READ_ONLY, cellNeighbors.byteLength);
clBufferAlive = [
cl.createBuffer(clCtx, cl.MEM_READ_WRITE, cellAlive[inp... | try {
// clKernelMove = cl.createKernel(clProgram, 'kmove');
clKernelGol = cl.createKernel(clProgram, 'kgol'); | random_line_split |
renderer.js | y++) {
const
prevRow = (y - 1) * gridWidth,
thisRow = prevRow + gridWidth,
nextRow = thisRow + gridWidth;
for (let x = 0; x < gridWidth; x++) {
cellNeighbors[indexNeighbors++] = (prevRow + x - 1 + cellsTotal) % cellsTotal;
cellNeighbors[indexNeighbors++] = (prevRow + x + cellsTotal) % cellsTotal;... | {
fps = 1000 * frameTimes.length / frameTimes.reduce((pv, cv) => pv + cv);
// do not update every frame
if ((frameTimesIndex % 5) === 0) {
fpsDisplay.innerHTML = fps.toFixed(2);
}
} | conditional_block | |
renderer.js | ('vertexShaderLog', gl.getShaderInfoLog(vertexShader));
const fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);
gl.shaderSource(fragmentShader, fs.readFileSync(__dirname + '/shader-fragment.glsl', 'utf-8'));
gl.compileShader(fragmentShader);
console.log('fragmentShaderLog', gl.getShaderInfoLog(fragmentShader))... | renderOpenGL | identifier_name | |
renderer.js | FRAMETIMES_TO_KEEP = 10;
function init() {
(async () => {
initDom();
initDrawData();
if (INIT_OPENGL) {
initOpenGL();
}
initData();
await initOpenCL();
initGame();
initEvents();
startGameLoop();
render();
})();
}
function initDom() {
canvas = document.getElementById('glscreen');
fps... |
function initOpenGL() {
gl = canvas.getContext('experimental-webgl');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
// init vertex buffer
vertexCoordBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, vertexCoordB... | {
imageData = new Uint8Array(bytesTotal);
} | identifier_body |
session.rs | // Copyright (C) 2015 Wire Swiss GmbH <support@wire.com>
// Based on libsignal-protocol-java by Open Whisper Systems
// https://github.com/WhisperSystems/libsignal-protocol-java.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as publish... | // GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pub use internal::session::Error;
pub use internal::session::PreKeyStore;
pub use internal::session::Session; | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | random_line_split |
lib.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#![cfg(test)]
extern crate cookie as cookie_rs;
extern crate devtools_traits;
extern crate flate2;
extern crate h... | (request: &mut Request, cache: &mut CorsCache) -> Response {
let (sender, receiver) = channel();
let mut target = FetchResponseCollector {
sender: sender,
};
methods::fetch_with_cors_cache(request, cache, &mut target, &new_fetch_context(None));
receiver.recv().unwrap()
}
fn make_server<H:... | fetch_with_cors_cache | identifier_name |
lib.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#![cfg(test)]
extern crate cookie as cookie_rs;
extern crate devtools_traits;
extern crate flate2;
extern crate h... | extern crate servo_config;
extern crate servo_url;
extern crate time;
extern crate unicase;
extern crate url;
mod chrome_loader;
mod cookie;
mod cookie_http_state;
mod data_loader;
mod fetch;
mod file_loader;
mod filemanager_thread;
mod hsts;
mod http_loader;
mod mime_classifier;
mod resource_thread;
mod subresource_i... | extern crate profile_traits; | random_line_split |
lib.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#![cfg(test)]
extern crate cookie as cookie_rs;
extern crate devtools_traits;
extern crate flate2;
extern crate h... |
fn process_response(&mut self, _: &Response) {}
fn process_response_chunk(&mut self, _: Vec<u8>) {}
/// Fired when the response is fully fetched
fn process_response_eof(&mut self, response: &Response) {
let _ = self.sender.send(response.clone());
}
}
fn fetch(request: &mut Request, dc: Opt... | {} | identifier_body |
utf8_idents.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | 10;
let غداء = 10;
let լանչ = 10;
let обед = 10;
let абед = 10;
let μεσημεριανό = 10;
let hádegismatur = 10;
let ручек = 10;
let ăn_trưa = 10;
let อาหารกลางวัน = 10;
// Lunchy arithmetic, mm.
assert_eq!(hádegismatur * ручек * обед, 1000);
assert_eq!(10, ארוחת_צהריי);
... | nguages.
let ランチ = 10;
let 午餐 = 10;
let ארוחת_צהריי = | identifier_name |
utf8_idents.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | t غداء = 10;
let լանչ = 10;
let обед = 10;
let абед = 10;
let μεσημεριανό = 10;
let hádegismatur = 10;
let ручек = 10;
let ăn_trưa = 10;
let อาหารกลางวัน = 10;
// Lunchy arithmetic, mm.
assert_eq!(hádegismatur * ручек * обед, 1000);
assert_eq!(10, ארוחת_צהריי);
assert_... | identifier_body | |
utf8_idents.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | fn საჭმელად_გემრიელი_სადილი() -> int {
// Lunch in several languages.
let ランチ = 10;
let 午餐 = 10;
let ארוחת_צהריי = 10;
let غداء = 10;
let լանչ = 10;
let обед = 10;
let абед = 10;
let μεσημεριανό = 10;
let hádegismatur = 10;
let ручек = 10;
let ăn_trưa = 10;
let อา... | random_line_split | |
XFileSharingPro.py | XFileSharingPro"
__type__ = "hoster"
__pattern__ = r'^unmatchable$'
__version__ = "0.31"
__description__ = """XFileSharingPro base hoster plugin"""
__author_name__ = ("zoidberg", "stickell")
__author_mail__ = ("zoidberg@mujmail.cz", "l.stickell@yahoo.it")
FILE_INFO_PATTERN = r'<tr><td align... |
return self.errmsg
def getPostParameters(self):
for _ in xrange(3):
| self.errmsg = None | conditional_block |
XFileSharingPro.py | FileSharingPro"
__type__ = "hoster"
__pattern__ = r'^unmatchable$'
__version__ = "0.31"
__description__ = """XFileSharingPro base hoster plugin"""
__author_name__ = ("zoidberg", "stickell")
__author_mail__ = ("zoidberg@mujmail.cz", "l.stickell@yahoo.it")
FILE_INFO_PATTERN = r'<tr><td align=... | if not hasattr(self, "HOSTER_NAME"):
self.HOSTER_NAME = re.match(self.__pattern__, self.pyfile.url).group(1)
if not hasattr(self, "LINK_PATTERN"):
self.LINK_PATTERN = r'(http://([^/]*?%s|\d+\.\d+\.\d+\.\d+)(:\d+)?(/d/|(?:/files)?/\d+/\w+/)[^"\'<]+)' % self.HOSTER_NAME
se... |
def prepare(self):
""" Initialize important variables """ | random_line_split |
XFileSharingPro.py | FileSharingPro"
__type__ = "hoster"
__pattern__ = r'^unmatchable$'
__version__ = "0.31"
__description__ = """XFileSharingPro base hoster plugin"""
__author_name__ = ("zoidberg", "stickell")
__author_mail__ = ("zoidberg@mujmail.cz", "l.stickell@yahoo.it")
FILE_INFO_PATTERN = r'<tr><td align=... | (self):
if self.__name__ == "XFileSharingPro":
self.__pattern__ = self.core.pluginManager.hosterPlugins[self.__name__]['pattern']
self.multiDL = True
else:
self.resumeDownload = self.multiDL = self.premium
self.chunkLimit = 1
def process(self, pyfile):
... | setup | identifier_name |
XFileSharingPro.py | FileSharingPro"
__type__ = "hoster"
__pattern__ = r'^unmatchable$'
__version__ = "0.31"
__description__ = """XFileSharingPro base hoster plugin"""
__author_name__ = ("zoidberg", "stickell")
__author_mail__ = ("zoidberg@mujmail.cz", "l.stickell@yahoo.it")
FILE_INFO_PATTERN = r'<tr><td align=... |
def getDirectDownloadLink(self):
""" Get download link for premium users with direct download enabled """
self.req.http.lastURL = self.pyfile.url
self.req.http.c.setopt(FOLLOWLOCATION, 0)
self.html = self.load(self.pyfile.url, cookies=True, decode=True)
self.header = self.... | """ Initialize important variables """
if not hasattr(self, "HOSTER_NAME"):
self.HOSTER_NAME = re.match(self.__pattern__, self.pyfile.url).group(1)
if not hasattr(self, "LINK_PATTERN"):
self.LINK_PATTERN = r'(http://([^/]*?%s|\d+\.\d+\.\d+\.\d+)(:\d+)?(/d/|(?:/files)?/\d+/\w+/)[^... | identifier_body |
htmlfieldsetelement.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 dom::attr::Attr;
use dom::bindings::codegen::Bindings::HTMLFieldSetElementBinding;
use dom::bindings::codegen:... | (&self) -> Root<ValidityState> {
let window = window_from_node(self);
ValidityState::new(&window, self.upcast())
}
// https://html.spec.whatwg.org/multipage/#dom-fieldset-disabled
make_bool_getter!(Disabled, "disabled");
// https://html.spec.whatwg.org/multipage/#dom-fieldset-disabled
... | Validity | identifier_name |
htmlfieldsetelement.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 dom::attr::Attr;
use dom::bindings::codegen::Bindings::HTMLFieldSetElementBinding;
use dom::bindings::codegen:... | } else if node.is::<HTMLLegendElement>() {
found_legend = true;
false
} else {
true
}
});
let fields = children.flat_map(|child| {
child... | {
self.super_type().unwrap().attribute_mutated(attr, mutation);
match attr.local_name() {
&local_name!("disabled") => {
let disabled_state = match mutation {
AttributeMutation::Set(None) => true,
AttributeMutation::Set(Some(_)) => {
... | identifier_body |
htmlfieldsetelement.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 dom::attr::Attr;
use dom::bindings::codegen::Bindings::HTMLFieldSetElementBinding;
use dom::bindings::codegen:... | Some(self.upcast::<HTMLElement>() as &VirtualMethods)
}
fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) {
self.super_type().unwrap().attribute_mutated(attr, mutation);
match attr.local_name() {
&local_name!("disabled") => {
let disabled_... | fn super_type(&self) -> Option<&VirtualMethods> { | random_line_split |
ArtworkImageBrowserSmall_artwork.graphql.ts | /* tslint:disable */
/* eslint-disable */
import { ReaderFragment } from "relay-runtime";
import { FragmentRefs } from "relay-runtime"; | readonly images: ReadonlyArray<{
readonly internalID: string | null;
readonly isZoomable: boolean | null;
readonly " $fragmentRefs": FragmentRefs<"DeepZoom_image">;
} | null> | null;
readonly " $fragmentRefs": FragmentRefs<"ArtworkLightbox_artwork">;
readonly " $refType": "Artwor... | export type ArtworkImageBrowserSmall_artwork = { | random_line_split |
editor.rs | use rand;
use rand::Rng;
use std::process::Command;
use std::io::prelude::*;
use std::fs::File;
const TEMP_FILE_LENGTH: usize = 16;
pub fn text_from_editor() -> String | Err(_) => String::new()
}
}
/// TODO Return proper editor from env / config
fn editor() -> String {
return "vim".to_string();
}
/// TODO Ensure real unique names
fn temp_file() -> String {
let result = String::from("/tmp/");
let file = rand::thread_rng()
.gen_ascii_chars()... | {
let temp_file = temp_file();
let status = Command::new(editor())
.arg(temp_file.clone())
.status();
match status {
Ok(status) => {
if !status.success() {
return String::new();
}
let mut file = ... | identifier_body |
editor.rs | use rand;
use rand::Rng;
use std::process::Command;
use std::io::prelude::*;
use std::fs::File;
const TEMP_FILE_LENGTH: usize = 16;
pub fn text_from_editor() -> String {
let temp_file = temp_file();
let status = Command::new(editor())
.arg(temp_file.clone())
... | () -> String {
return "vim".to_string();
}
/// TODO Ensure real unique names
fn temp_file() -> String {
let result = String::from("/tmp/");
let file = rand::thread_rng()
.gen_ascii_chars()
.take(TEMP_FILE_LENGTH)
.collect::<String>();
result ... | editor | identifier_name |
editor.rs | use rand;
use rand::Rng;
use std::process::Command;
use std::io::prelude::*;
use std::fs::File;
const TEMP_FILE_LENGTH: usize = 16;
pub fn text_from_editor() -> String {
let temp_file = temp_file();
let status = Command::new(editor())
.arg(temp_file.clone())
... | fn editor() -> String {
return "vim".to_string();
}
/// TODO Ensure real unique names
fn temp_file() -> String {
let result = String::from("/tmp/");
let file = rand::thread_rng()
.gen_ascii_chars()
.take(TEMP_FILE_LENGTH)
.collect::<String>();
... | /// TODO Return proper editor from env / config | random_line_split |
admin.ria_dashboard.js | /**
* Created with JetBrains PhpStorm.
* User: amalyuhin
* Date: 28.06.13
* Time: 19:19
* To change this template use File | Settings | File Templates.
*/
$(function(){
$('.pop').popover();
//FROM Marketing form
var isSearchable = $('input:radio[name="wealthbot_riabundle_riacompanyinform... |
}
});
event.preventDefault();
});
$('div#tab2 table thead th a').live('click', function(event) {
$.ajax({
url: $(this).attr('href'),
dataType: 'json',
success: function (response) {
if (response.status == 'suc... | {
if (response.pagination_type == 'clients') {
$('#tab2').html(response.content);
} else if (response.pagination_type == 'history') {
$('#tab4').html(response.content);
}
} | conditional_block |
admin.ria_dashboard.js | /**
* Created with JetBrains PhpStorm.
* User: amalyuhin
* Date: 28.06.13
* Time: 19:19
* To change this template use File | Settings | File Templates.
*/
$(function(){
$('.pop').popover();
//FROM Marketing form
var isSearchable = $('input:radio[name="wealthbot_riabundle_riacompanyinform... | }
},
complete: function() {
parent.find('.ajax-loader').remove();
}
});
});
$('input[name="ria_relationship_form[relationship_type]"]').live('click', function(event) {
var form = $(this).closest('#ria_update_relation... | random_line_split | |
mod.rs | pub struct BlockPtr {
pub start: RecordPtr,
pub length: u64,
// A guard is used for wrongly ordered block-insertion. See [hash_index.rs] for details
pub is_guard: bool
} |
impl BlockPtr {
pub fn to_guard(self) -> BlockPtr {
BlockPtr {
start: self.start,
length: self.length,
is_guard: true
}
}
pub fn to_non_guard(self) -> BlockPtr {
BlockPtr {
start: self.start,
length: self.length,... |
impl HashIndexGuard for BlockPtr {
fn is_guard(self) -> bool { self.is_guard }
} | random_line_split |
mod.rs | pub struct BlockPtr {
pub start: RecordPtr,
pub length: u64,
// A guard is used for wrongly ordered block-insertion. See [hash_index.rs] for details
pub is_guard: bool
}
impl HashIndexGuard for BlockPtr {
fn is_guard(self) -> bool { self.is_guard }
}
impl BlockPtr {
pub fn to_guard(sel... | {
pub blocks: i64,
pub inputs: i64,
pub seeks: i64,
pub total_move: i64,
pub total_diff: i64,
pub jumps: i64,
}
// Make stats additive
impl ::std::ops::Add for SpendTreeStats {
type Output = SpendTreeStats;
fn add(self, other: SpendTreeStats) -> SpendTreeStats {
... | SpendTreeStats | identifier_name |
mod.rs | &mut HashIndex<TxPtr>,
block: BlockPtr) {
let mut input_idx = 0;
let mut last_tx_ptr: Option<TxPtr> = None;
for record in self.get_block_mut(block) {
if record.is_unmatched_input() {
let bytes = transactions.read(last_tx_ptr.... | {
// care must be taken that when a block is added to the spend-tree before one of its
// predecessors, it may not be complete.
// This because in the spend tree, the inputs are stored as the outputs they reference,
// but these inputs may not have been available.
// The resolve... | identifier_body | |
RoomUpgradeDialog.tsx | /*
Copyright 2018 - 2021 The Matrix.org Foundation C.I.C.
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... |
private onCancelClick = (): void => {
this.props.onFinished(false);
};
private onUpgradeClick = (): void => {
this.setState({ busy: true });
upgradeRoom(this.props.room, this.targetVersion, false, false).then(() => {
this.props.onFinished(true);
}).catch((err) ... | {
const recommended = await this.props.room.getRecommendedVersion();
this.targetVersion = recommended.version;
this.setState({ busy: false });
} | identifier_body |
RoomUpgradeDialog.tsx | /*
Copyright 2018 - 2021 The Matrix.org Foundation C.I.C.
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... |
import Modal from '../../../Modal';
import { _t } from '../../../languageHandler';
import { replaceableComponent } from "../../../utils/replaceableComponent";
import { upgradeRoom } from "../../../utils/RoomUpgrade";
import { IDialogProps } from "./IDialogProps";
import BaseDialog from "./BaseDialog";
import ErrorDial... | import React from 'react';
import { Room } from "matrix-js-sdk/src/models/room"; | random_line_split |
RoomUpgradeDialog.tsx | /*
Copyright 2018 - 2021 The Matrix.org Foundation C.I.C.
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... | () {
const recommended = await this.props.room.getRecommendedVersion();
this.targetVersion = recommended.version;
this.setState({ busy: false });
}
private onCancelClick = (): void => {
this.props.onFinished(false);
};
private onUpgradeClick = (): void => {
this... | componentDidMount | identifier_name |
options.rs | //! This module contains the configuration of the application.
//!
//! All options are passed individually to each function and are not bundled
//! together.
//!
//! # Examples
//!
//! ```no_run
//! # use doh::Options;
//! let options = Options::parse();
//! println!("Showing {}", options.remote_dir);
//! ```
use cla... | () -> Options {
let matches = app_from_crate!("\n")
.setting(AppSettings::ColoredHelp)
.arg(Arg::from_usage("<URL> 'Remote directory to browse'").validator(Options::url_validator))
.get_matches();
let u = matches.value_of("URL").unwrap();
Options {
... | parse | identifier_name |
options.rs | //! This module contains the configuration of the application.
//!
//! All options are passed individually to each function and are not bundled
//! together.
//!
//! # Examples
//!
//! ```no_run
//! # use doh::Options;
//! let options = Options::parse();
//! println!("Showing {}", options.remote_dir);
//! ```
use cla... | #[derive(Debug, Clone, Hash, PartialEq, Eq)]
pub struct Options {
/// Remote directory to start on.
pub remote_dir: Url,
}
impl Options {
/// Parse `env`-wide command-line arguments into an `Options` instance
pub fn parse() -> Options {
let matches = app_from_crate!("\n")
.setting(A... | use reqwest::Url;
/// Representation of the application's all configurable values. | random_line_split |
options.rs | //! This module contains the configuration of the application.
//!
//! All options are passed individually to each function and are not bundled
//! together.
//!
//! # Examples
//!
//! ```no_run
//! # use doh::Options;
//! let options = Options::parse();
//! println!("Showing {}", options.remote_dir);
//! ```
use cla... |
}
| {
Url::parse(&s)
.or_else(|_| Url::parse(&format!("http://{}", s)))
.map(|_| ())
.map_err(|e| e.to_string())
} | identifier_body |
roost_worker.js | "use strict";
//var _roostSW = {version: 1, logging: true, appKey:"6paox8ctqtmfggp1b94355tknhdoc47q", host: "http://localhost:8081", baseURL: "http://localhost:8081"};
var _roostSW = {
version: 1,
logging: true,
appKey: "6paox8ctqtmfggp1b94355tknhdoc47q",
host: "https://go.goroost.com"
};
self.addEven... | if (_roostSW.logging) console.log("Opening URL: " + query.url[0]);
return clients.openWindow(query.url[0]);
}
}
console.log("Failed to redirect to notification for iconURL: " + iconURL);
}
//Utility function to actually show the notification.
function showNotification(title, bod... | if (iconURL.indexOf("?") > -1) {
var queryString = iconURL.split("?")[1];
var query = parseQueryString(queryString);
if (query.url && query.url.length == 1) { | random_line_split |
roost_worker.js | "use strict";
//var _roostSW = {version: 1, logging: true, appKey:"6paox8ctqtmfggp1b94355tknhdoc47q", host: "http://localhost:8081", baseURL: "http://localhost:8081"};
var _roostSW = {
version: 1,
logging: true,
appKey: "6paox8ctqtmfggp1b94355tknhdoc47q",
host: "https://go.goroost.com"
};
self.addEven... | (queryString) {
var qd = {};
queryString.split("&").forEach(function (item) {
var parts = item.split("=");
var k = parts[0];
var v = decodeURIComponent(parts[1]);
(k in qd) ? qd[k].push(v) : qd[k] = [v, ]
});
return qd;
}
//Utility function to handle the click
function h... | parseQueryString | identifier_name |
roost_worker.js | "use strict";
//var _roostSW = {version: 1, logging: true, appKey:"6paox8ctqtmfggp1b94355tknhdoc47q", host: "http://localhost:8081", baseURL: "http://localhost:8081"};
var _roostSW = {
version: 1,
logging: true,
appKey: "6paox8ctqtmfggp1b94355tknhdoc47q",
host: "https://go.goroost.com"
};
self.addEven... |
//Utility function to actually show the notification.
function showNotification(title, body, url, appKey) {
var options = {
body: body,
tag: "roost",
icon: _roostSW.host + '/api/browser/logo?size=100&direct=true&appKey=' + _roostSW.appKey + '&url=' + encodeURIComponent(url)
};
retu... | {
if (_roostSW.logging) console.log("Notification clicked: ", evt.notification);
evt.notification.close();
var iconURL = evt.notification.icon;
if (iconURL.indexOf("?") > -1) {
var queryString = iconURL.split("?")[1];
var query = parseQueryString(queryString);
if (query.url && qu... | identifier_body |
roost_worker.js | "use strict";
//var _roostSW = {version: 1, logging: true, appKey:"6paox8ctqtmfggp1b94355tknhdoc47q", host: "http://localhost:8081", baseURL: "http://localhost:8081"};
var _roostSW = {
version: 1,
logging: true,
appKey: "6paox8ctqtmfggp1b94355tknhdoc47q",
host: "https://go.goroost.com"
};
self.addEven... |
console.log("Failed to redirect to notification for iconURL: " + iconURL);
}
//Utility function to actually show the notification.
function showNotification(title, body, url, appKey) {
var options = {
body: body,
tag: "roost",
icon: _roostSW.host + '/api/browser/logo?size=100&direct=tr... | {
var queryString = iconURL.split("?")[1];
var query = parseQueryString(queryString);
if (query.url && query.url.length == 1) {
if (_roostSW.logging) console.log("Opening URL: " + query.url[0]);
return clients.openWindow(query.url[0]);
}
} | conditional_block |
error.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/. */
//! Utilities to throw exceptions from Rust bindings.
use dom::bindings::codegen::PrototypeList::proto_id_to_name... | (cx: *mut JSContext, error: &str) {
throw_js_error(cx, error, JSExnType::JSEXN_TYPEERR as u32);
}
/// Throw a `RangeError` with the given message.
pub fn throw_range_error(cx: *mut JSContext, error: &str) {
throw_js_error(cx, error, JSExnType::JSEXN_RANGEERR as u32);
}
| throw_type_error | identifier_name |
error.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/. */
//! Utilities to throw exceptions from Rust bindings.
use dom::bindings::codegen::PrototypeList::proto_id_to_name... | }
/// Throw an exception to signal that a `JSObject` can not be converted to a
/// given DOM type.
pub fn throw_invalid_this(cx: *mut JSContext, proto_id: u16) {
debug_assert!(unsafe { JS_IsExceptionPending(cx) } == 0);
let error = format!("\"this\" object does not implement interface {}.",
... | let error = format!("argument could not be converted to any of: {}", names);
throw_type_error(cx, &error); | random_line_split |
error.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/. */
//! Utilities to throw exceptions from Rust bindings.
use dom::bindings::codegen::PrototypeList::proto_id_to_name... |
/// Format string used to throw javascript errors.
static ERROR_FORMAT_STRING_STRING: [libc::c_char; 4] = [
'{' as libc::c_char,
'0' as libc::c_char,
'}' as libc::c_char,
0 as libc::c_char,
];
/// Format string struct used to throw `TypeError`s.
static mut TYPE_ERROR_FORMAT_STRING: JSErrorFormatStrin... | {
debug_assert!(unsafe { JS_IsExceptionPending(cx) } == 0);
let error = format!("\"this\" object does not implement interface {}.",
proto_id_to_name(proto_id));
throw_type_error(cx, &error);
} | identifier_body |
da.js | videojs.addLanguage("da",{
"Play": "Afspil",
"Pause": "Pause",
"Current Time": "Aktuel tid",
"Duration Time": "Varighed",
"Remaining Time": "Resterende tid",
"Stream Type": "Stream-type",
"LIVE": "LIVE",
"Loaded": "Indlæst",
"Progress": "Status",
"Fullscreen": "Fuldskærm",
"Non-Fullscreen": "Luk fuldskærm",
... | "Chapters": "Kapitler",
"You aborted the video playback": "Du afbrød videoafspilningen.",
"A network error caused the video download to fail part-way.": "En netværksfejl fik download af videoen til at fejle.",
"The video could not be loaded, either because the server or network failed or because the format is not s... | "captions off": "Uden undertekster for hørehæmmede", | random_line_split |
multi_redirect.py | import urllib.parse
from wptserve.utils import isomorphic_encode
def main(request, response):
"""Handler that causes multiple redirections. Redirect chain is as follows:
1. Initial URL containing multi-redirect.py
2. Redirect to cross-origin URL
3. Redirect to same-origin URL
4. Fin... |
response.status = 302
response.headers.set(b"Location", redirect_url)
| redirect_url = page_origin + final_resource | conditional_block |
multi_redirect.py | import urllib.parse
from wptserve.utils import isomorphic_encode
def main(request, response):
"""Handler that causes multiple redirections. Redirect chain is as follows:
1. Initial URL containing multi-redirect.py
2. Redirect to cross-origin URL
3. Redirect to same-origin URL
4. Fin... | Optional parameters:
tao_steps - Number of redirects for which the TAO header will be present (a number 0 - 3 makes the most sense). Default value is 0.
tao_value - The value of the TAO header, when present. Default value is "*".
Note that |step| is a parameter used internally for the multi-redirect. It... | Mandatory parameters:
page_origin - The page origin, used for redirection and to set TAO. This is a mandatory parameter.
cross_origin - The cross origin used to make this a cross-origin redirect. This is a mandatory parameter.
final_resource - Path of the final resource, without origin. This is a mandat... | random_line_split |
multi_redirect.py | import urllib.parse
from wptserve.utils import isomorphic_encode
def main(request, response):
|
page_origin = request.GET.first(b"page_origin")
cross_origin = request.GET.first(b"cross_origin")
final_resource = request.GET.first(b"final_resource")
tao_value = b"*"
if b"tao_value" in request.GET:
tao_value = request.GET.first(b"tao_value")
tao_steps = 0
if b"tao_steps" in requ... | """Handler that causes multiple redirections. Redirect chain is as follows:
1. Initial URL containing multi-redirect.py
2. Redirect to cross-origin URL
3. Redirect to same-origin URL
4. Final URL containing the final same-origin resource.
Mandatory parameters:
page_origin - The p... | identifier_body |
multi_redirect.py | import urllib.parse
from wptserve.utils import isomorphic_encode
def | (request, response):
"""Handler that causes multiple redirections. Redirect chain is as follows:
1. Initial URL containing multi-redirect.py
2. Redirect to cross-origin URL
3. Redirect to same-origin URL
4. Final URL containing the final same-origin resource.
Mandatory parameters... | main | identifier_name |
deletewebsitelogs.py | """
Clean up the website log table.
"""
# pylint: disable=C0301,C0103,W1201
from apiary.tasks import BaseApiaryTask
import logging
import datetime
LOGGER = logging.getLogger()
class DeleteWebsiteLogsTask(BaseApiaryTask):
"""Delete old entries from the bot_log."""
def run(self):
"""Execute the task.... | return rows_deleted |
LOGGER.info("Deleted %d rows." % rows_deleted)
| random_line_split |
deletewebsitelogs.py | """
Clean up the website log table.
"""
# pylint: disable=C0301,C0103,W1201
from apiary.tasks import BaseApiaryTask
import logging
import datetime
LOGGER = logging.getLogger()
class DeleteWebsiteLogsTask(BaseApiaryTask):
"""Delete old entries from the bot_log."""
def | (self):
"""Execute the task."""
sql_query = """
DELETE FROM
apiary_website_logs
WHERE
log_date < '%s'
"""
delete_before = datetime.datetime.utcnow() - datetime.timedelta(weeks=8)
delete_before_str = delete_before.strftime('%Y-%m-%d %H:%M:%S')
LOGGER.info("Deleting apiary_we... | run | identifier_name |
deletewebsitelogs.py | """
Clean up the website log table.
"""
# pylint: disable=C0301,C0103,W1201
from apiary.tasks import BaseApiaryTask
import logging
import datetime
LOGGER = logging.getLogger()
class DeleteWebsiteLogsTask(BaseApiaryTask):
"""Delete old entries from the bot_log."""
def run(self):
| """Execute the task."""
sql_query = """
DELETE FROM
apiary_website_logs
WHERE
log_date < '%s'
"""
delete_before = datetime.datetime.utcnow() - datetime.timedelta(weeks=8)
delete_before_str = delete_before.strftime('%Y-%m-%d %H:%M:%S')
LOGGER.info("Deleting apiary_website_logs befor... | identifier_body | |
downsample.py | #!/usr/bin/python3
#
# Copyright (c) 2014-2022 The Voxie Authors
#
# 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,... |
version = update.Finish()
result = {}
result[outputPath] = {
'Data': voxie.Variant('o', data._objectPath),
'DataVersion': voxie.Variant('o', version._objectPath),
}
op.Finish(result)
| buffer[:, :, z] = np.mean(
arrayOld3[:, :, :, :, z, :], axis=(1, 3, 4))
op.SetProgress((z + 1) / zCount) | conditional_block |
downsample.py | #!/usr/bin/python3
#
# Copyright (c) 2014-2022 The Voxie Authors
#
# 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,... | 'DataVersion': voxie.Variant('o', version._objectPath),
}
op.Finish(result) | random_line_split | |
distributions.py | # coding=utf-8
# Copyright 2022 The ML Fairness Gym Authors.
#
# 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 applicab... | weights = attr.ib(
factory=list, validator=[_check_sum_to_one,
_check_nonnegative]) # type: Sequence[float]
def sample(self, rng):
logging.debug("Sampling from a mixture with %d components. Weights: %s",
len(self.components), self.weights)
component =... | """A mixture distribution."""
components = attr.ib(factory=list) # type: Sequence[Distribution] | random_line_split |
distributions.py | # coding=utf-8
# Copyright 2022 The ML Fairness Gym Authors.
#
# 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 applicab... |
self.dim = self.components[0].dim
@attr.s
class Gaussian(Distribution):
"""A Gaussian Distribution."""
mean = attr.ib()
std = attr.ib()
def __attrs_post_init__(self):
self.dim = len(self.mean)
def sample(self, rng):
return rng.normal(self.mean, self.std)
@attr.s
class Bernoulli(Distribution... | if component.dim != self.components[0].dim:
raise ValueError("Components do not have the same dimensionality.") | conditional_block |
distributions.py | # coding=utf-8
# Copyright 2022 The ML Fairness Gym Authors.
#
# 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 applicab... | (instance, attribute, value):
"""Raises ValueError if the value does not sum to one."""
del instance, attribute # Unused.
value = np.array(value)
if not np.isclose(np.sum(value), 1):
raise ValueError("Array must sum to one. Got %s." % np.sum(value))
def _check_nonnegative(instance, attribute, value):
"... | _check_sum_to_one | identifier_name |
distributions.py | # coding=utf-8
# Copyright 2022 The ML Fairness Gym Authors.
#
# 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 applicab... |
def _check_sum_to_one(instance, attribute, value):
"""Raises ValueError if the value does not sum to one."""
del instance, attribute # Unused.
value = np.array(value)
if not np.isclose(np.sum(value), 1):
raise ValueError("Array must sum to one. Got %s." % np.sum(value))
def _check_nonnegative(instance... | raise NotImplementedError | identifier_body |
bigint.rs | // Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
|
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along ... | // 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. | random_line_split |
bigint.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.... | (b: &mut Bencher) {
b.iter(|| {
let n = black_box(10000);
(0..n).fold(U128([12345u64, 0u64]), |old, new| { old.overflowing_mul(U128::from(new)).0 })
});
}
| u128_mul | identifier_name |
bigint.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.... |
#[bench]
fn u256_mul(b: &mut Bencher) {
b.iter(|| {
let n = black_box(10000);
(0..n).fold(U256([rand::random::<u64>(), rand::random::<u64>(), rand::random::<u64>(), rand::random::<u64>()]), |old, new| { old.overflowing_mul(U256::from(new)).0 })
});
}
#[bench]
fn u256_full_mul(b: &mut Bencher) {
b.iter(|| {
... | {
b.iter(|| {
let n = black_box(10000);
(0..n).fold(U512([0, 0, 0, 0, 0, 0, 0, 0]),
|old, new| { old.overflowing_add(U512([new, new, new, new, new, new, new, new])).0 })
});
} | identifier_body |
MenuListComposition.tsx | import * as React from 'react';
import Button from '@material-ui/core/Button';
import ClickAwayListener from '@material-ui/core/ClickAwayListener';
import Grow from '@material-ui/core/Grow';
import Paper from '@material-ui/core/Paper';
import Popper from '@material-ui/core/Popper';
import MenuItem from '@material-ui/co... | else if (event.key === 'Escape') {
setOpen(false);
}
}
// return focus to the button when we transitioned from !open -> open
const prevOpen = React.useRef(open);
React.useEffect(() => {
if (prevOpen.current === true && open === false) {
anchorRef.current!.focus();
}
prevOpen.curre... | {
event.preventDefault();
setOpen(false);
} | conditional_block |
MenuListComposition.tsx | import * as React from 'react';
import Button from '@material-ui/core/Button';
import ClickAwayListener from '@material-ui/core/ClickAwayListener';
import Grow from '@material-ui/core/Grow';
import Paper from '@material-ui/core/Paper';
import Popper from '@material-ui/core/Popper';
import MenuItem from '@material-ui/co... |
// return focus to the button when we transitioned from !open -> open
const prevOpen = React.useRef(open);
React.useEffect(() => {
if (prevOpen.current === true && open === false) {
anchorRef.current!.focus();
}
prevOpen.current = open;
}, [open]);
return (
<Stack direction="row" spa... | {
if (event.key === 'Tab') {
event.preventDefault();
setOpen(false);
} else if (event.key === 'Escape') {
setOpen(false);
}
} | identifier_body |
MenuListComposition.tsx | import * as React from 'react';
import Button from '@material-ui/core/Button';
import ClickAwayListener from '@material-ui/core/ClickAwayListener';
import Grow from '@material-ui/core/Grow';
import Paper from '@material-ui/core/Paper';
import Popper from '@material-ui/core/Popper';
import MenuItem from '@material-ui/co... | (event: React.KeyboardEvent) {
if (event.key === 'Tab') {
event.preventDefault();
setOpen(false);
} else if (event.key === 'Escape') {
setOpen(false);
}
}
// return focus to the button when we transitioned from !open -> open
const prevOpen = React.useRef(open);
React.useEffect(() ... | handleListKeyDown | identifier_name |
MenuListComposition.tsx | import * as React from 'react';
import Button from '@material-ui/core/Button';
import ClickAwayListener from '@material-ui/core/ClickAwayListener';
import Grow from '@material-ui/core/Grow';
import Paper from '@material-ui/core/Paper';
import Popper from '@material-ui/core/Popper';
import MenuItem from '@material-ui/co... | <Paper>
<ClickAwayListener onClickAway={handleClose}>
<MenuList
autoFocusItem={open}
id="composition-menu"
aria-labelledby="composition-button"
onKeyDown={handleListKeyDown}
... | transformOrigin:
placement === 'bottom-start' ? 'left top' : 'left bottom',
}}
> | random_line_split |
parseL4Info.py | #!/usr/bin/env python
# take a large pcap and dump the data into a CSV so it can be analysed by something like R.
#
# This version we want to know what the source IP is, what the protocol is and based on those
# peices of info run a function to grab that data and write a line to a CSV file
#
# Ignore all traffic sourc... |
else:
return
def parseTCP(tpkt):
#print "running parseTCP"
if len(tpkt.layers) > 3:
# pass to http module
decoded = tcpdecode(tpkt.layers[3],thisproto)
rowlist[8]= str(decoded)
#rowlist[8]= str(tpkt.layers[3]).replace('\n','')
# Complete this section regardless
... | tmplist=[]
tmpdict=lyrlst._all_fields
for key in tmpdict:
tmplist.append(tmpdict[key])
return "#".join(map(str,tmplist)) | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.