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 |
|---|---|---|---|---|
cursor.rs | //! Cursor movement.
use std::fmt;
use std::ops;
use std::io::{self, Write, Error, ErrorKind, Read};
use async::async_stdin_until;
use std::time::{SystemTime, Duration};
use raw::CONTROL_SEQUENCE_TIMEOUT;
use numtoa::NumToA;
derive_csi_sequence!("Hide the cursor.", Hide, "?25l");
derive_csi_sequence!("Show the cursor... | (&mut self) -> io::Result<()> {
self.output.flush()
}
}
| flush | identifier_name |
cursor.rs | //! Cursor movement.
use std::fmt;
use std::ops;
use std::io::{self, Write, Error, ErrorKind, Read};
use async::async_stdin_until;
use std::time::{SystemTime, Duration};
use raw::CONTROL_SEQUENCE_TIMEOUT;
use numtoa::NumToA;
derive_csi_sequence!("Hide the cursor.", Hide, "?25l");
derive_csi_sequence!("Show the cursor... |
}
if read_chars.is_empty() {
return Err(Error::new(ErrorKind::Other, "Cursor position detection timed out."));
}
// The answer will look like `ESC [ Cy ; Cx R`.
read_chars.pop(); // remove trailing R.
let read_str = String::from_utf8(read_chars).unwrap();
... | {
read_chars.push(buf[0]);
} | conditional_block |
UserCards.js | import React, {Component} from 'react';
import { Router, IndexRoute, Route, browserHistory } from 'react-router';
import UserCard from './UserCard';
import firebase from './firebase';
import NewContact from './NewContact';
class | extends Component {
constructor() {
super();
this.state = {
contacts: []
};
this.contactsArray = [];
}
get baseContactReference() {
return firebase.database().ref(`baseContact/${firebase.auth().currentUser.uid}/`);
}
componentDidMount() {
this.baseContactReference.on('child_ad... | UserCards | identifier_name |
UserCards.js | import React, {Component} from 'react';
import { Router, IndexRoute, Route, browserHistory } from 'react-router';
import UserCard from './UserCard';
import firebase from './firebase';
import NewContact from './NewContact';
class UserCards extends Component {
constructor() {
super();
this.state = {
cont... |
export default UserCards | random_line_split | |
UserCards.js | import React, {Component} from 'react';
import { Router, IndexRoute, Route, browserHistory } from 'react-router';
import UserCard from './UserCard';
import firebase from './firebase';
import NewContact from './NewContact';
class UserCards extends Component {
constructor() {
super();
this.state = {
cont... |
}
export default UserCards
| {
return(
<div className="user-cards">
{this.loadCards()}
</div>
)
} | identifier_body |
ShopStyle.ts | import {style} from "typestyle";
export namespace ShopStyle {
export const Shop = style({
display: "flex",
flexFlow: "column",
height: "100vh",
overflow: "hidden",
backgroundColor: "black"
});
export const overview = (active:boolean = false) =>{
if (active){... | } else {
return style({
backgroundColor: "white",
transition: "opacity 0.2s linear, transform 0.2s",
willChange: "opacity, transform",
transform: "translate3d(0px,0px,0px)",
opacity: 1
});
}
};
... | random_line_split | |
ShopStyle.ts | import {style} from "typestyle";
export namespace ShopStyle {
export const Shop = style({
display: "flex",
flexFlow: "column",
height: "100vh",
overflow: "hidden",
backgroundColor: "black"
});
export const overview = (active:boolean = false) =>{
if (active) | else {
return style({
backgroundColor: "white",
transition: "opacity 0.2s linear, transform 0.2s",
willChange: "opacity, transform",
transform: "translate3d(0px,0px,0px)",
opacity: 1
});
}
};
expor... | {
return style({
backgroundColor: "white",
transition: "opacity 0.2s linear, transform 0.2s",
willChange: "opacity, transform",
//transform: "translate3d(0px,0px,0px)",
transform:"perspective(500px) translate3d(0px, 0px, -50px);... | conditional_block |
UmfApp.ts | import { FormMetadata, FormResponse, FormResponseMetadata, ClientFunctionMetadata } from "uimf-core";
import { UmfServer } from "./UmfServer";
import { FormInstance } from "./FormInstance";
import { IFormResponseHandler } from "./IFormResponseHandler";
import { InputFieldValue } from "./InputFieldValue";
import { Cont... | {
return this.server.getAllMetadata()
.then(response => {
this.forms = response;
for (let form of this.forms) {
this.formsById[form.id] = form;
}
});
}
getForm(id: string) {
return this.formsById[id];
}
getFormInstance(formId: string, throwError: boolean = false) {
let metadata = th... | ad() | identifier_name |
UmfApp.ts | import { FormMetadata, FormResponse, FormResponseMetadata, ClientFunctionMetadata } from "uimf-core";
import { UmfServer } from "./UmfServer";
import { FormInstance } from "./FormInstance";
import { IFormResponseHandler } from "./IFormResponseHandler";
import { InputFieldValue } from "./InputFieldValue";
import { Cont... | var responseMetadata = response.metadata || new FormResponseMetadata();
var handler = this.formResponseHandlers[responseMetadata.handler];
if (handler == null) {
var error = new Error(`Cannot find FormResponseHandler "${responseMetadata.handler}".`);
console.error(error);
throw error;
}
return hand... |
handleResponse(response: FormResponse, form: FormInstance) { | random_line_split |
UmfApp.ts | import { FormMetadata, FormResponse, FormResponseMetadata, ClientFunctionMetadata } from "uimf-core";
import { UmfServer } from "./UmfServer";
import { FormInstance } from "./FormInstance";
import { IFormResponseHandler } from "./IFormResponseHandler";
import { InputFieldValue } from "./InputFieldValue";
import { Cont... | let promises = [];
for (let f of functionMetadata) {
let handler = this.controlRegister.functions[f.id];
if (handler == null) {
throw new Error(`Could not find function '${f.id}'.`);
}
let promise = handler.run(f);
promises.push(promise);
}
return Promise.all(promises);
}
} | return Promise.resolve();
}
| conditional_block |
UmfApp.ts | import { FormMetadata, FormResponse, FormResponseMetadata, ClientFunctionMetadata } from "uimf-core";
import { UmfServer } from "./UmfServer";
import { FormInstance } from "./FormInstance";
import { IFormResponseHandler } from "./IFormResponseHandler";
import { InputFieldValue } from "./InputFieldValue";
import { Cont... | if (functionMetadata == null) {
return Promise.resolve();
}
let promises = [];
for (let f of functionMetadata) {
let handler = this.controlRegister.functions[f.id];
if (handler == null) {
throw new Error(`Could not find function '${f.id}'.`);
}
let promise = handler.run(f);
promises.pus... | identifier_body | |
test_packages.py | import pytest
@pytest.mark.parametrize("name", [
("apt-file"),
("apt-transport-https"),
("arandr"),
("atom"),
("blktrace"),
("ca-certificates"),
("chromium-browser"),
("cowsay"),
("cron"),
("curl"),
("deluge"),
("diod"),
("docker-ce"),
("dropbox"),
("fonts-font-awesome"),
("git"),
("g... | (host, name):
pkg = host.package(name)
assert pkg.is_installed
| test_packages | identifier_name |
test_packages.py | import pytest
@pytest.mark.parametrize("name", [
("apt-file"),
("apt-transport-https"),
("arandr"),
("atom"),
("blktrace"),
("ca-certificates"),
("chromium-browser"),
("cowsay"),
("cron"),
("curl"),
("deluge"),
("diod"),
("docker-ce"),
("dropbox"),
("fonts-font-awesome"),
("git"),
("g... | pkg = host.package(name)
assert pkg.is_installed | identifier_body | |
test_packages.py | import pytest
@pytest.mark.parametrize("name", [
("apt-file"),
("apt-transport-https"),
("arandr"),
("atom"),
("blktrace"),
("ca-certificates"),
("chromium-browser"),
("cowsay"),
("cron"),
("curl"),
("deluge"),
("diod"),
("docker-ce"),
("dropbox"),
("fonts-font-awesome"),
("git"),
("g... | ("ntp"),
("openssh-client"),
("openssh-server"),
("openssh-sftp-server"),
("openssl"),
("pavucontrol"),
("pinta"),
("pulseaudio"),
("pulseaudio-module-x11"),
("pulseaudio-utils"),
("python"),
("python-pip"),
("scrot"),
("sl"),
("slack-desktop"),
("software-properties-common"),
("suckle... | ("ntop"), | random_line_split |
logger.py | """
Component that will help set the level of logging for components.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/logger/
"""
import logging
from collections import OrderedDict
import voluptuous as vol
import homeassistant.helpers.config_validation... |
hass.services.async_register(
DOMAIN, SERVICE_SET_DEFAULT_LEVEL, async_service_handler,
schema=SERVICE_SET_DEFAULT_LEVEL_SCHEMA)
hass.services.async_register(
DOMAIN, SERVICE_SET_LEVEL, async_service_handler,
schema=SERVICE_SET_LEVEL_SCHEMA)
return True
| """Handle logger services."""
if service.service == SERVICE_SET_DEFAULT_LEVEL:
set_default_log_level(service.data.get(ATTR_LEVEL))
else:
set_log_levels(service.data) | identifier_body |
logger.py | """
Component that will help set the level of logging for components.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/logger/
"""
import logging
from collections import OrderedDict
import voluptuous as vol
import homeassistant.helpers.config_validation... |
else:
set_default_log_level('DEBUG')
logger = logging.getLogger('')
logger.setLevel(logging.NOTSET)
# Set log filter for all log handler
for handler in logging.root.handlers:
handler.setLevel(logging.NOTSET)
handler.addFilter(HomeAssistantLogFilter(logfilter))
if LOGG... | set_default_log_level(config.get(DOMAIN)[LOGGER_DEFAULT]) | conditional_block |
logger.py | """
Component that will help set the level of logging for components.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/logger/
"""
import logging
from collections import OrderedDict
import voluptuous as vol
import homeassistant.helpers.config_validation... |
_VALID_LOG_LEVEL = vol.All(vol.Upper, vol.In(LOGSEVERITY))
SERVICE_SET_DEFAULT_LEVEL_SCHEMA = vol.Schema({ATTR_LEVEL: _VALID_LOG_LEVEL})
SERVICE_SET_LEVEL_SCHEMA = vol.Schema({cv.string: _VALID_LOG_LEVEL})
CONFIG_SCHEMA = vol.Schema({
DOMAIN: vol.Schema({
vol.Optional(LOGGER_DEFAULT): _VALID_LOG_LEVEL,
... | ATTR_LEVEL = 'level' | random_line_split |
logger.py | """
Component that will help set the level of logging for components.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/logger/
"""
import logging
from collections import OrderedDict
import voluptuous as vol
import homeassistant.helpers.config_validation... | (level):
"""Set the default log level for components."""
logfilter[LOGGER_DEFAULT] = LOGSEVERITY[level]
def set_log_levels(logpoints):
"""Set the specified log levels."""
logs = {}
# Preserve existing logs
if LOGGER_LOGS in logfilter:
logs.update(logfilt... | set_default_log_level | identifier_name |
cabi_mips.rs | // Copyright 2012-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-MI... | let mut fields = padding.map_move_default(~[], |p| ~[p]);
if coerce {
fields = vec::append(fields, coerce_to_int(size));
} else {
fields.push(ty);
}
return Type::struct_(fields, false);
}
pub fn compute_abi_info(_ccx: &mut CrateContext,
atys: &[Type],
... | random_line_split | |
cabi_mips.rs | // Copyright 2012-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-MI... |
fn padding_ty(align: uint, offset: uint) -> Option<Type> {
if ((align - 1 ) & offset) > 0 {
return Some(Type::i32());
}
return None;
}
fn coerce_to_int(size: uint) -> ~[Type] {
let int_ty = Type::i32();
let mut args = ~[];
let mut n = size / 32;
while n > 0 {
args.push(i... | {
return match ty.kind() {
Integer
| Pointer
| Float
| Double => true,
_ => false
};
} | identifier_body |
cabi_mips.rs | // Copyright 2012-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-MI... | (off: uint, ty: Type) -> uint {
let a = ty_align(ty);
return align_up_to(off, a);
}
fn ty_align(ty: Type) -> uint {
match ty.kind() {
Integer => {
unsafe {
((llvm::LLVMGetIntTypeWidth(ty.to_ref()) as uint) + 7) / 8
}
}
Pointer => 4,
Fl... | align | identifier_name |
cabi_mips.rs | // Copyright 2012-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-MI... | else { 0 };
for aty in atys.iter() {
let (ty, attr) = classify_arg_ty(*aty, &mut offset);
arg_tys.push(ty);
attrs.push(attr);
};
if sret {
arg_tys = vec::append(~[ret_ty], arg_tys);
attrs = vec::append(~[ret_attr], attrs);
ret_ty = LLVMType { cast: false, t... | { 4 } | conditional_block |
borrowck-freeze-frozen-mut.rs | // run-pass
// Test that a `&mut` inside of an `&` is freezable.
struct MutSlice<'a, T:'a> {
data: &'a mut [T]
}
fn get<'a, T>(ms: &'a MutSlice<'a, T>, index: usize) -> &'a T |
pub fn main() {
let mut data = [1, 2, 3];
{
let slice = MutSlice { data: &mut data };
slice.data[0] += 4;
let index0 = get(&slice, 0);
let index1 = get(&slice, 1);
let index2 = get(&slice, 2);
assert_eq!(*index0, 5);
assert_eq!(*index1, 2);
asser... | {
&ms.data[index]
} | identifier_body |
borrowck-freeze-frozen-mut.rs | // run-pass
// Test that a `&mut` inside of an `&` is freezable.
struct MutSlice<'a, T:'a> {
data: &'a mut [T]
}
| }
pub fn main() {
let mut data = [1, 2, 3];
{
let slice = MutSlice { data: &mut data };
slice.data[0] += 4;
let index0 = get(&slice, 0);
let index1 = get(&slice, 1);
let index2 = get(&slice, 2);
assert_eq!(*index0, 5);
assert_eq!(*index1, 2);
asse... | fn get<'a, T>(ms: &'a MutSlice<'a, T>, index: usize) -> &'a T {
&ms.data[index] | random_line_split |
borrowck-freeze-frozen-mut.rs | // run-pass
// Test that a `&mut` inside of an `&` is freezable.
struct | <'a, T:'a> {
data: &'a mut [T]
}
fn get<'a, T>(ms: &'a MutSlice<'a, T>, index: usize) -> &'a T {
&ms.data[index]
}
pub fn main() {
let mut data = [1, 2, 3];
{
let slice = MutSlice { data: &mut data };
slice.data[0] += 4;
let index0 = get(&slice, 0);
let index1 = get(&sl... | MutSlice | identifier_name |
login.js | 'use strict';
const model = require('../model');
const crypto = require('crypto');
const fs = require('fs');
const utils = require('../utils');
const api = require('./../api');
let User = model.User;
var fn_login = async(ctx, next)=> {
var
phone = ctx.request.body.phone || '',
password = ctx.requ... | ctx.response.type = 'application/json';
ctx.response.body = {
code: 1,
data: {},
msg: "登入失败",
haveMore: false
}
}
};
var fn_avatar = async(ctx, next) => {
await User.update({
avatar: ctx.req.file.filename,
updatedAt: Date... | data = {};
data.uid = user.id;
data.phone = user.phone;
data.token = user.token;
data.avatar = api.baseFileUrl + user.avatar;
data.nick = user.nick;
data.signature = user.signature;
ctx.rest(data);
} else {
| conditional_block |
login.js | 'use strict';
const model = require('../model');
const crypto = require('crypto');
const fs = require('fs');
const utils = require('../utils');
const api = require('./../api');
let User = model.User;
var fn_login = async(ctx, next)=> {
var
phone = ctx.request.body.phone || '',
password = ctx.requ... | 'POST /api/login': fn_login,
'PUT /api/avatar': fn_avatar
}; | });
};
module.exports = { | random_line_split |
common.ts | ,
"error": number,
"fatal error": number,
};
function reduceStats(previous, current) {
previous["note"] += current["note"];
previous["remark"] += current["remark"];
previous["warning"] += current["warning"];
previous["error"] += current["error"];
previous["fatal error"] += current["f... | if (report.diagnostics.length === 1)
ret += ` with ${report.diagnostics.length} issue`;
else if (report.diagnostics.length > 1)
ret += ` with ${report.diagnostics.length} issues`;
else if (!report.failed)
ret += ` without issues`;
if (report.diagnostics.length > 0)
ret += ` (${th... | }
}
formatReportConclusion(report: Report) {
let ret = '';
ret += `${report.name} ${report.failed ? chalk.red('failed') : chalk.green('succeeded')}`; | random_line_split |
common.ts | undefined;
this.failed = reporter ? reporter.failed : false;
this.duration = duration;
this.stats = {
"note": 0,
"remark": 0,
"warning": 0,
"error": 0,
"fatal error": 0,
};
this.diagnostics.reduce((prev, current) => {
prev[current.is] += 1;
return prev;
... | output.write(`${indentation}task failed for unknown reasons`);
}
| conditional_block | |
common.ts | "error": number,
"fatal error": number,
};
function reduceStats(previous, current) {
previous["note"] += current["note"];
previous["remark"] += current["remark"];
previous["warning"] += current["warning"];
previous["error"] += current["error"];
previous["fatal error"] += current["fat... | eport: Report) {
let ret = '';
ret += `${report.name} ${report.failed ? chalk.red('failed') : chalk.green('succeeded')}`;
if (report.diagnostics.length === 1)
ret += ` with ${report.diagnostics.length} issue`;
else if (report.diagnostics.length > 1)
ret += ` with ${report.diagnostics.length}... | rmatReportConclusion(r | identifier_name |
look_command.rs | use super::{inventory_command::inventory, CommandHelpers, CommandLineProcessor};
use crate::{
actions::{self, ActionOutput},
entity::{EntityRef, Realm},
player_output::PlayerOutput,
relative_direction::RelativeDirection,
utils::{direction_by_abbreviation, is_direction, vector_for_direction},
};
///... | (realm: &mut Realm, player_ref: EntityRef, helpers: CommandHelpers) -> ActionOutput {
let (player, room) = realm.character_and_room_res(player_ref)?;
let processor = helpers.command_line_processor;
let alias = processor.take_word().unwrap();
if alias.starts_with('l') {
if !processor.has_words_... | look | identifier_name |
look_command.rs | use super::{inventory_command::inventory, CommandHelpers, CommandLineProcessor};
use crate::{
actions::{self, ActionOutput},
entity::{EntityRef, Realm},
player_output::PlayerOutput,
relative_direction::RelativeDirection,
utils::{direction_by_abbreviation, is_direction, vector_for_direction},
};
///... | ..helpers
},
);
}
let description = processor.take_entity_description().ok_or_else(|| {
if alias == "examine" {
"Examine what?".to_owned()
} else {
"Look at what?".to_owned()
}
})?;
if processor.peek_rest() == "in inve... | {
let (player, room) = realm.character_and_room_res(player_ref)?;
let processor = helpers.command_line_processor;
let alias = processor.take_word().unwrap();
if alias.starts_with('l') {
if !processor.has_words_left() {
return actions::look_at_entity(realm, player_ref, player.curren... | identifier_body |
look_command.rs | use super::{inventory_command::inventory, CommandHelpers, CommandLineProcessor};
use crate::{
actions::{self, ActionOutput},
entity::{EntityRef, Realm},
player_output::PlayerOutput,
relative_direction::RelativeDirection,
utils::{direction_by_abbreviation, is_direction, vector_for_direction},
};
///... | command_line_processor: &mut CommandLineProcessor::new(player_ref, "inventory"),
..helpers
},
);
}
let description = processor.take_entity_description().ok_or_else(|| {
if alias == "examine" {
"Examine what?".to_owned()
} else {
... | CommandHelpers { | random_line_split |
look_command.rs | use super::{inventory_command::inventory, CommandHelpers, CommandLineProcessor};
use crate::{
actions::{self, ActionOutput},
entity::{EntityRef, Realm},
player_output::PlayerOutput,
relative_direction::RelativeDirection,
utils::{direction_by_abbreviation, is_direction, vector_for_direction},
};
///... | else {
"Look where?".to_owned()
});
};
let mut output = vec![PlayerOutput::new_from_string(player_ref.id(), output)];
output.append(&mut actions::look_in_direction(
realm, player_ref, &direction,
)?);
outpu... | {
"Examine what?".to_owned()
} | conditional_block |
actions.ts | /*
* This file is part of CoCalc: Copyright © 2020 Sagemath, Inc.
* License: AGPLv3 s.t. "Commons Clause" – see LICENSE.md for details
*/
/*
Media wiki Editor Actions
*/
import { reuseInFlight } from "async-await-utils/hof";
import { Actions as MarkdownActions } from "../markdown-editor/actions";
import { conver... | void {
if (!this.is_public) {
// one extra thing after base class init...
this._init_wiki2html();
}
}
_init_wiki2html(): void {
this.run_wiki2html = reuseInFlight(this._run_wiki2html.bind(this));
this._syncstring.on(
"save-to-disk",
reuseInFlight(async () => {
if (t... | it2(): | identifier_name |
actions.ts | /*
* This file is part of CoCalc: Copyright © 2020 Sagemath, Inc.
* License: AGPLv3 s.t. "Commons Clause" – see LICENSE.md for details
*/ | */
import { reuseInFlight } from "async-await-utils/hof";
import { Actions as MarkdownActions } from "../markdown-editor/actions";
import { convert } from "./wiki2html";
import { FrameTree } from "../frame-tree/types";
import { print_html } from "../frame-tree/print";
import { aux_file } from "@cocalc/util/misc";
impo... |
/*
Media wiki Editor Actions | random_line_split |
modpython.py | import os
from pprint import pformat
from django import http
from django.core import signals
from django.core.handlers.base import BaseHandler
from django.dispatch import dispatcher
from django.utils import datastructures
from django.utils.encoding import force_unicode, smart_str
# NOTE: do *not* import settings (or ... |
finally:
response.close()
return 0 # mod_python.apache.OK
def handler(req):
# mod_python hooks into this function.
return ModPythonHandler()(req)
| req.write(chunk) | conditional_block |
modpython.py | import os
from pprint import pformat
from django import http
from django.core import signals
from django.core.handlers.base import BaseHandler
from django.dispatch import dispatcher
from django.utils import datastructures
from django.utils.encoding import force_unicode, smart_str
# NOTE: do *not* import settings (or ... |
def _get_method(self):
return self.META['REQUEST_METHOD'].upper()
GET = property(_get_get, _set_get)
POST = property(_get_post, _set_post)
COOKIES = property(_get_cookies, _set_cookies)
FILES = property(_get_files)
META = property(_get_meta)
REQUEST = property(_get_request)
ra... | try:
return self._raw_post_data
except AttributeError:
self._raw_post_data = self._req.read()
return self._raw_post_data | identifier_body |
modpython.py | import os
from pprint import pformat
from django import http
from django.core import signals
from django.core.handlers.base import BaseHandler
from django.dispatch import dispatcher
from django.utils import datastructures
from django.utils.encoding import force_unicode, smart_str
# NOTE: do *not* import settings (or ... | (http.HttpRequest):
def __init__(self, req):
self._req = req
self.path = force_unicode(req.uri)
def __repr__(self):
# Since this is called as part of error handling, we need to be very
# robust against potentially malformed input.
try:
get = pformat(self.GET)... | ModPythonRequest | identifier_name |
modpython.py | import os
from pprint import pformat
from django import http
from django.core import signals
from django.core.handlers.base import BaseHandler
from django.dispatch import dispatcher
from django.utils import datastructures
from django.utils.encoding import force_unicode, smart_str
# NOTE: do *not* import settings (or ... |
# now that the environ works we can see the correct settings, so imports
# that use settings now can work
from django.conf import settings
# if we need to set up middleware, now that settings works we can do it now.
if self._request_middleware is None:
self.load_mid... | os.environ.update(req.subprocess_env) | random_line_split |
transaction.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import unicode_literals
from .exceptions import TransactionValidationError
AVAIABLE_PAYMENT_METHOD = ['credit_card', 'boleto']
def validate_transaction(attrs):
if len(attrs) <= 0:
raise TransactionValidationError('Need a vali... |
def get_transactions(self, page=1):
return self.requester.commit('/transactions', {'page': page}, 'GET')
def build_transaction(self, transaction_attributes):
if not isinstance(transaction_attributes, dict):
raise TransactionValidationError(
'Transaction attributes ... | self.requester = requester
self.attributes = {} | identifier_body |
transaction.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import unicode_literals
from .exceptions import TransactionValidationError
AVAIABLE_PAYMENT_METHOD = ['credit_card', 'boleto']
def validate_transaction(attrs):
if len(attrs) <= 0:
raise TransactionValidationError('Need a vali... |
if 'payment_method' in attrs:
if not attrs['payment_method'] in AVAIABLE_PAYMENT_METHOD:
errors.append(
"invalid payment_method need be boleto or credit_card")
if len(errors) > 0:
raise TransactionValidationError(', '.join(errors))
class Transaction():
def __... | errors.append('Need to define an valid payment_method') | conditional_block |
transaction.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import unicode_literals
from .exceptions import TransactionValidationError
AVAIABLE_PAYMENT_METHOD = ['credit_card', 'boleto']
def validate_transaction(attrs):
if len(attrs) <= 0:
raise TransactionValidationError('Need a vali... | ():
def __init__(self, requester):
self.requester = requester
self.attributes = {}
def get_transactions(self, page=1):
return self.requester.commit('/transactions', {'page': page}, 'GET')
def build_transaction(self, transaction_attributes):
if not isinstance(transaction_att... | Transaction | identifier_name |
transaction.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import unicode_literals
from .exceptions import TransactionValidationError
AVAIABLE_PAYMENT_METHOD = ['credit_card', 'boleto']
def validate_transaction(attrs):
if len(attrs) <= 0:
raise TransactionValidationError('Need a vali... | 'Transaction attributes need be an dict')
self.attributes.update(transaction_attributes)
def charge(self):
self.validate_attrs
def validate_attrs(self):
validate_transaction(self.attributes) | random_line_split | |
sys-utils.js | var Q = require('q'),
os = require('os');
module.exports = {
architecture: getArchitecture,
platform: getPlatform,
ip: getIpAddress,
id: getUniqueId
};
function getPlatform() {
return os.platform();
}
function getArchitecture() |
function getIpAddress(nic) {
var nics = os.networkInterfaces();
if (! nics[nic]) {
throw new Error('Unable to find details about the ' + nic + ' network interface. Does it have an ip?');
}
for (var idx in nics[nic]) {
if (! nics[nic].hasOwnProperty(idx)) continue;
if (nics[ni... | {
var architecture = os.arch();
if (architecture == 'x64') return 'x86_64';
else if (architecture == 'ia32') return 'x86';
else if (architecture == 'arm') return 'armv7l';
else return 'unknown';
} | identifier_body |
sys-utils.js | var Q = require('q'),
os = require('os');
module.exports = {
architecture: getArchitecture,
platform: getPlatform,
ip: getIpAddress,
id: getUniqueId
};
function getPlatform() {
return os.platform();
}
function getArchitecture() {
var architecture = os.arch();
if (architecture == 'x64... | for (var idx in nics[nic]) {
if (! nics[nic].hasOwnProperty(idx)) continue;
if (nics[nic][idx]['family'] == 'IPv4')
return nics[nic][idx].address;
}
return null;
}
function getUniqueId(nic) {
var nics = os.networkInterfaces();
if (! nics[nic]) {
throw new Error... | throw new Error('Unable to find details about the ' + nic + ' network interface. Does it have an ip?');
}
| random_line_split |
sys-utils.js | var Q = require('q'),
os = require('os');
module.exports = {
architecture: getArchitecture,
platform: getPlatform,
ip: getIpAddress,
id: getUniqueId
};
function getPlatform() {
return os.platform();
}
function | () {
var architecture = os.arch();
if (architecture == 'x64') return 'x86_64';
else if (architecture == 'ia32') return 'x86';
else if (architecture == 'arm') return 'armv7l';
else return 'unknown';
}
function getIpAddress(nic) {
var nics = os.networkInterfaces();
if (! nics[nic]) {
... | getArchitecture | identifier_name |
ffz.rs | use std;
use serde_json;
use serde;
use std::io::Read;
use emote;
use emote::{EmoteError,JsonError};
use http;
const CHANNEL_URL:&str = "https://api.frankerfacez.com/v1/room/";
const GLOBAL_URL:&str = "https://api.frankerfacez.com/v1/set/global";
pub struct Emote<'a>{
http: &'a http::Http,
}
#[derive(Serialize,... | }
impl <'a>Emote<'a>{
pub fn new(client:&http::Http)->Result<Emote,String>{
Ok(Emote{
http:client
})
}
pub fn get_channel(&self,channel:&str)->Result<Vec<Emoticon>,EmoteError>{
let s = try!(self.http.get_body_string(&format!("{}{}",CHANNEL_URL,channel)).map_err(... | pub struct Emoticon{
id:i64,
name:String, | random_line_split |
ffz.rs | use std;
use serde_json;
use serde;
use std::io::Read;
use emote;
use emote::{EmoteError,JsonError};
use http;
const CHANNEL_URL:&str = "https://api.frankerfacez.com/v1/room/";
const GLOBAL_URL:&str = "https://api.frankerfacez.com/v1/set/global";
pub struct Emote<'a>{
http: &'a http::Http,
}
#[derive(Serialize,... | {
display_name:String,
id:String,
set:i64,
twitch_id:i64,
}
#[derive(Serialize, Deserialize)]
pub struct Emoticon{
id:i64,
name:String,
}
impl <'a>Emote<'a>{
pub fn new(client:&http::Http)->Result<Emote,String>{
Ok(Emote{
http:client
})
}
pub fn... | Room | identifier_name |
ffz.rs | use std;
use serde_json;
use serde;
use std::io::Read;
use emote;
use emote::{EmoteError,JsonError};
use http;
const CHANNEL_URL:&str = "https://api.frankerfacez.com/v1/room/";
const GLOBAL_URL:&str = "https://api.frankerfacez.com/v1/set/global";
pub struct Emote<'a>{
http: &'a http::Http,
}
#[derive(Serialize,... |
let ref sets = v["sets"];
let ref set_id = sets[default_sets[0].to_string()];
let set: Set_id= try_map!(serde_json::from_value(set_id.clone()),EmoteError::Json(JsonError::ParseError));
Ok(set.emoticons)
}
}
impl emote::Emote for Emoticon{
fn name(&self)->&str{
&self.n... | {
return Err(EmoteError::Json(JsonError::ParseError))
} | conditional_block |
referenceSearch.ts | /message/common/message';
import {ITelemetryService} from 'vs/platform/telemetry/common/telemetry';
import {IWorkspaceContextService} from 'vs/platform/workspace/common/workspace';
import {IKeybindingService, IKeybindingContextKey, ICommandHandler} from 'vs/platform/keybinding/common/keybindingService';
import {Keybind... |
// create result model
this.model = new model.Model(references, this.editorService);
this.model.currentReference = this.model.findReference(editorModel.getAssociatedResource(), range.getStartPosition());
var unbind = this.model.addListener(model.EventType.CurrentReferenceChanged, () => {
this.modelR... | {
this.widget.showMessage(nls.localize('noResults', "No results"));
timer.stop();
return;
} | conditional_block |
referenceSearch.ts | /message/common/message';
import {ITelemetryService} from 'vs/platform/telemetry/common/telemetry';
import {IWorkspaceContextService} from 'vs/platform/workspace/common/workspace';
import {IKeybindingService, IKeybindingContextKey, ICommandHandler} from 'vs/platform/keybinding/common/keybindingService';
import {Keybind... |
public processRequest(range: EditorCommon.IEditorRange, referencesPromise: TPromise<Modes.IReference[]>) : widget.ReferenceWidget {
var widgetPosition = !this.widget ? null : this.widget.position;
// clean up from previous invocation
var widgetClosed = this.clear();
// Close if the position is still the sa... | {
this.clear();
} | identifier_body |
referenceSearch.ts | /message/common/message';
import {ITelemetryService} from 'vs/platform/telemetry/common/telemetry';
import {IWorkspaceContextService} from 'vs/platform/workspace/common/workspace';
import {IKeybindingService, IKeybindingContextKey, ICommandHandler} from 'vs/platform/keybinding/common/keybindingService';
import {Keybind... | ():boolean {
return ReferenceRegistry.has(this.editor.getModel()) && super.isSupported();
}
public getEnablementState():boolean {
if(this.peekViewService && this.peekViewService.isActive) {
return false;
}
let model = this.editor.getModel();
let position = this.editor.getSelection().getStartPosition();... | isSupported | identifier_name |
referenceSearch.ts | /platform/message/common/message';
import {ITelemetryService} from 'vs/platform/telemetry/common/telemetry';
import {IWorkspaceContextService} from 'vs/platform/workspace/common/workspace';
import {IKeybindingService, IKeybindingContextKey, ICommandHandler} from 'vs/platform/keybinding/common/keybindingService';
import... | if(requestId !== this.requestIdPool) {
timer.stop();
return;
}
// has a result
if (isFalsyOrEmpty(references)) {
this.widget.showMessage(nls.localize('noResults', "No results"));
timer.stop();
return;
}
// create result model
this.model = new model.Model(references, this.edito... | referencesPromise.then((references:Modes.IReference[]) => {
// still current request? | random_line_split |
test_dfs.py | """Tests for the DFS module"""
import unittest
from dfs import dfsTraverse
class test_dfsTraverse(unittest.TestCase):
"""Test the correct order in traversing a graph"""
def setUp(self):
|
def test_traverse(self):
"""Test the traverse function"""
result = dfsTraverse(self.graphDict, 'a')
self.assertEqual(result, self.correctResTup)
if __name__ == '__main__':
unittest.main()
| """Create a graph and a tuple with the correct traverse"""
self.correctResTup = ('a', 'b', 'e', 'g', 'f', 'c', 'h', 'd')
self.graphDict = {'a': ('b', 'g', 'd'),
'b': ('e', 'a', 'f'),
'd': ('a', 'f'),
'e': ('b', 'g'),
... | identifier_body |
test_dfs.py | """Tests for the DFS module"""
import unittest
from dfs import dfsTraverse
class test_dfsTraverse(unittest.TestCase):
"""Test the correct order in traversing a graph"""
def setUp(self):
"""Create a graph and a tuple with the correct traverse""" | self.correctResTup = ('a', 'b', 'e', 'g', 'f', 'c', 'h', 'd')
self.graphDict = {'a': ('b', 'g', 'd'),
'b': ('e', 'a', 'f'),
'd': ('a', 'f'),
'e': ('b', 'g'),
'g': ('e', 'a'),
... | random_line_split | |
test_dfs.py | """Tests for the DFS module"""
import unittest
from dfs import dfsTraverse
class test_dfsTraverse(unittest.TestCase):
"""Test the correct order in traversing a graph"""
def setUp(self):
"""Create a graph and a tuple with the correct traverse"""
self.correctResTup = ('a', 'b', 'e', 'g', 'f', '... | (self):
"""Test the traverse function"""
result = dfsTraverse(self.graphDict, 'a')
self.assertEqual(result, self.correctResTup)
if __name__ == '__main__':
unittest.main()
| test_traverse | identifier_name |
test_dfs.py | """Tests for the DFS module"""
import unittest
from dfs import dfsTraverse
class test_dfsTraverse(unittest.TestCase):
"""Test the correct order in traversing a graph"""
def setUp(self):
"""Create a graph and a tuple with the correct traverse"""
self.correctResTup = ('a', 'b', 'e', 'g', 'f', '... | unittest.main() | conditional_block | |
eip150_state.rs | // Copyright 2015, 2016 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any la... | (json_data: &[u8]) -> Vec<String> {
json_chain_test(json_data, ChainEra::Eip150)
}
declare_test!{StateTests_EIP150_stEIPSpecificTest, "StateTests/EIP150/stEIPSpecificTest"}
declare_test!{StateTests_EIP150_stEIPsingleCodeGasPrices, "StateTests/EIP150/stEIPsingleCodeGasPrices"}
declare_test!{StateTests_EIP150_stMemExpa... | do_json_test | identifier_name |
eip150_state.rs | // Copyright 2015, 2016 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any la... |
declare_test!{StateTests_EIP150_stEIPSpecificTest, "StateTests/EIP150/stEIPSpecificTest"}
declare_test!{StateTests_EIP150_stEIPsingleCodeGasPrices, "StateTests/EIP150/stEIPsingleCodeGasPrices"}
declare_test!{StateTests_EIP150_stMemExpandingEIPCalls, "StateTests/EIP150/stMemExpandingEIPCalls"}
declare_test!{StateTests... | use super::state::json_chain_test;
fn do_json_test(json_data: &[u8]) -> Vec<String> {
json_chain_test(json_data, ChainEra::Eip150)
} | random_line_split |
eip150_state.rs | // Copyright 2015, 2016 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any la... |
declare_test!{StateTests_EIP150_stEIPSpecificTest, "StateTests/EIP150/stEIPSpecificTest"}
declare_test!{StateTests_EIP150_stEIPsingleCodeGasPrices, "StateTests/EIP150/stEIPsingleCodeGasPrices"}
declare_test!{StateTests_EIP150_stMemExpandingEIPCalls, "StateTests/EIP150/stMemExpandingEIPCalls"}
declare_test!{StateTest... | {
json_chain_test(json_data, ChainEra::Eip150)
} | identifier_body |
mixins.py | from __future__ import unicode_literals
from __future__ import absolute_import
from django.views.generic.base import TemplateResponseMixin
from wiki.core.plugins import registry
from wiki.conf import settings
class ArticleMixin(TemplateResponseMixin):
"""A mixin that receives an article object as a parameter (u... |
except AttributeError as e:
raise Exception(
"Attribute error most likely caused by wrong MPTT version. Use 0.5.3+.\n\n" +
str(e))
return super(ArticleMixin, self).dispatch(request, *args, **kwargs)
def get_context_data(self, **kwargs):
... | self.children_slice.append(child) | conditional_block |
mixins.py | from __future__ import unicode_literals
from __future__ import absolute_import
from django.views.generic.base import TemplateResponseMixin
from wiki.core.plugins import registry
from wiki.conf import settings
class ArticleMixin(TemplateResponseMixin):
"""A mixin that receives an article object as a parameter (u... | kwargs['urlpath'] = self.urlpath
kwargs['article'] = self.article
kwargs['article_tabs'] = registry.get_article_tabs()
kwargs['children_slice'] = self.children_slice[:20]
kwargs['children_slice_more'] = len(self.children_slice) > 20
kwargs['plugins'] = registry.get_plugins()
... | identifier_body | |
mixins.py | from __future__ import unicode_literals
from __future__ import absolute_import
from django.views.generic.base import TemplateResponseMixin
from wiki.core.plugins import registry
from wiki.conf import settings
class ArticleMixin(TemplateResponseMixin):
"""A mixin that receives an article object as a parameter (u... | 1,
articles__article__current_revision__deleted=False,
user_can_read=request.user):
self.children_slice.append(child)
except AttributeError as e:
raise Exception(
"Attribute error ... | try:
for child in self.article.get_children(
max_num=settings.SHOW_MAX_CHILDREN + | random_line_split |
mixins.py | from __future__ import unicode_literals
from __future__ import absolute_import
from django.views.generic.base import TemplateResponseMixin
from wiki.core.plugins import registry
from wiki.conf import settings
class ArticleMixin(TemplateResponseMixin):
"""A mixin that receives an article object as a parameter (u... | (self, **kwargs):
kwargs['urlpath'] = self.urlpath
kwargs['article'] = self.article
kwargs['article_tabs'] = registry.get_article_tabs()
kwargs['children_slice'] = self.children_slice[:20]
kwargs['children_slice_more'] = len(self.children_slice) > 20
kwargs['plugins'] = r... | get_context_data | identifier_name |
aaaa.rs | /*
* Copyright (C) 2015 Benjamin Fry <benjaminfry@me.com>
*
* 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 ap... | () -> Vec<(Ipv6Addr, Vec<u8>)> {
vec![
(
Ipv6Addr::from_str("::").unwrap(),
vec![0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
), // base case
(
Ipv6Addr::from_str("1::").unwrap(),
vec![0, 1, 0, 0, 0, 0, 0, 0,... | get_data | identifier_name |
aaaa.rs | /*
* Copyright (C) 2015 Benjamin Fry <benjaminfry@me.com>
*
* 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 ap... | encoder.emit_u16(segments[6])?;
encoder.emit_u16(segments[7])?;
Ok(())
}
#[cfg(test)]
mod tests {
use std::net::Ipv6Addr;
use std::str::FromStr;
use super::*;
use crate::serialize::binary::bin_tests::{test_emit_data_set, test_read_data_set};
fn get_data() -> Vec<(Ipv6Addr, Vec<u8>)> {... | random_line_split | |
aaaa.rs | /*
* Copyright (C) 2015 Benjamin Fry <benjaminfry@me.com>
*
* 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 ap... |
#[test]
fn test_emit() {
test_emit_data_set(get_data(), |e, d| emit(e, &d));
}
}
| {
test_read_data_set(get_data(), |ref mut d| read(d));
} | identifier_body |
lib.rs | #![cfg_attr(feature = "clippy", feature(plugin))]
#![cfg_attr(feature = "clippy", plugin(clippy))]
extern crate clang;
extern crate directories;
#[macro_use]
extern crate failure;
extern crate glob;
#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate log;
extern crate python_parser;
extern crate regex;
ex... | (&self) -> Fallible<()> {
if let Some(project_path_s) = self.project_dir.to_str() {
info!("Starting project analysis at '{}'", project_path_s);
}
if self.project_dir.is_dir() {
// Project path is a directory, thus it is neccessay to traverse to the project
//... | analyze_project | identifier_name |
lib.rs | #![cfg_attr(feature = "clippy", feature(plugin))]
#![cfg_attr(feature = "clippy", plugin(clippy))]
extern crate clang;
extern crate directories;
#[macro_use]
extern crate failure;
extern crate glob;
#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate log;
extern crate python_parser;
extern crate regex;
ex... | pub mod stubs;
pub mod synthesis;
pub mod value_parser;
use analysis::{Analysis, ProjectFile};
use directories::BaseDirs;
use failure::{err_msg, Fallible};
use language_type::LanguageType;
use project_parameters::ProjectParameters;
use std::path::PathBuf;
use synthesis::*;
////////////////////////////////////////////... | pub mod analysis;
pub mod entity;
pub mod language_type;
pub mod project_parameters; | random_line_split |
lib.rs | #![cfg_attr(feature = "clippy", feature(plugin))]
#![cfg_attr(feature = "clippy", plugin(clippy))]
extern crate clang;
extern crate directories;
#[macro_use]
extern crate failure;
extern crate glob;
#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate log;
extern crate python_parser;
extern crate regex;
ex... |
Ok(())
}
/// Traverses upwared through the `seed_dir`s parent directories until
/// `thinline.yml` configuration exists in dir or home directory is reached.
fn find_thinline_config_dir<'a>(seed_dir: &'a PathBuf, config_name: &str) -> Option<PathBuf> {
if let Some(base_dirs) = BaseDirs... | {
self.project_parameters.build_script.run(&self.project_dir)?;
} | conditional_block |
lib.rs | #![cfg_attr(feature = "clippy", feature(plugin))]
#![cfg_attr(feature = "clippy", plugin(clippy))]
extern crate clang;
extern crate directories;
#[macro_use]
extern crate failure;
extern crate glob;
#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate log;
extern crate python_parser;
extern crate regex;
ex... | self.analysis
.project_files_mut()
.push(ProjectFile::new(&self.project_dir));
}
}
}
self.analysis.extract_entities()?;
Ok(())
}
/// Starts the synthesis of the target projects test files.... | {
if let Some(project_path_s) = self.project_dir.to_str() {
info!("Starting project analysis at '{}'", project_path_s);
}
if self.project_dir.is_dir() {
// Project path is a directory, thus it is neccessay to traverse to the project
// and collect all the sou... | identifier_body |
day1.rs | use get_input::get_input;
#[derive(Copy, Clone)]
enum Rotation {
Left,
Right,
}
impl Rotation {
fn from_char(c: char) -> Option<Rotation> {
match c {
'L' => Some(Rotation::Left),
'R' => Some(Rotation::Right),
_ => None,
}
}
}
#[derive(Copy, Clone)]
... | {
x: i32,
y: i32,
}
impl Position {
fn move_by(self, dir: Direction, dist: i32) -> Position {
match dir {
Direction::North => Position { x: self.x, y: self.y + dist },
Direction::East => Position { x: self.x + dist, y: self.y },
Direction::South => Position { x:... | Position | identifier_name |
day1.rs | use get_input::get_input;
#[derive(Copy, Clone)]
enum Rotation {
Left,
Right,
}
impl Rotation {
fn from_char(c: char) -> Option<Rotation> {
match c {
'L' => Some(Rotation::Left),
'R' => Some(Rotation::Right),
_ => None,
}
}
}
#[derive(Copy, Clone)]
... |
pub fn solve() {
let input = get_input("assets/day/1/input");
//let input = "R8, R4, R4, R8";
let mut position = Position { x: 0, y: 0 };
let mut direction = Direction::North;
for movement in input.split(',') {
let (rotation, distance) = parse_movement(&movement);
direction = dire... | {
let mut m = m.trim().chars();
let rotation = m.next().expect("Could not read input");
let rotation = Rotation::from_char(rotation).unwrap();
let distance = m.as_str().parse::<i32>().expect("Could not read integer in input");
(rotation, distance)
} | identifier_body |
day1.rs | use get_input::get_input;
#[derive(Copy, Clone)]
enum Rotation {
Left,
Right,
}
impl Rotation {
fn from_char(c: char) -> Option<Rotation> {
match c {
'L' => Some(Rotation::Left),
'R' => Some(Rotation::Right),
_ => None,
}
}
}
#[derive(Copy, Clone)]
... |
for movement in input.split(',') {
let (rotation, distance) = parse_movement(&movement);
direction = direction.rotate(rotation);
position = position.move_by(direction, distance);
// Print Logo commands to draw the path,
// turned out the first repeated position was easy to ... | pub fn solve() {
let input = get_input("assets/day/1/input");
//let input = "R8, R4, R4, R8";
let mut position = Position { x: 0, y: 0 };
let mut direction = Direction::North; | random_line_split |
_request.js | var http = require('http')
// make requests to the server
var request = module.exports = function request (o, cb ) {
if (!request.address) throw new Error('missing host/port');
return new Request;
}
function Request () {
this.host = request.address.address;
this.port = request.address.port;
this.path;
thi... |
req.on('response', function (res) {
var buf = '';
res.setEncoding('utf8');
res.on('data', function (data) {
buf += data;
});
res.on('end', function () {
res.body = buf;
cb(res);
});
});
req.end();
} | this.data.forEach(function (data) {
req.write(data);
}); | random_line_split |
_request.js |
var http = require('http')
// make requests to the server
var request = module.exports = function request (o, cb ) {
if (!request.address) throw new Error('missing host/port');
return new Request;
}
function Request () |
Request.prototype.post = function (path) {
this.path = path;
this.method = 'post';
return this;
}
Request.prototype.get= function (path) {
this.path = path;
this.method = 'get';
return this;
}
Request.prototype.header = function (key, val) {
this.headers[key] = val;
return this;
}
Request.prototype.wr... | {
this.host = request.address.address;
this.port = request.address.port;
this.path;
this.method;
this.headers = {};
this.data= [];
} | identifier_body |
_request.js |
var http = require('http')
// make requests to the server
var request = module.exports = function request (o, cb ) {
if (!request.address) throw new Error('missing host/port');
return new Request;
}
function | () {
this.host = request.address.address;
this.port = request.address.port;
this.path;
this.method;
this.headers = {};
this.data= [];
}
Request.prototype.post = function (path) {
this.path = path;
this.method = 'post';
return this;
}
Request.prototype.get= function (path) {
this.path = path;
thi... | Request | identifier_name |
model.py | import tensorflow as tf
from tensorflow.python.ops import rnn_cell
from tensorflow.python.ops import seq2seq
import numpy as np
class Model():
def __init__(self, args, infer=False):
self.args = args
if infer:
args.batch_size = 1
args.seq_length = 1
if args.model ==... |
ret = prime
char = prime[-1]
for n in range(num):
x = np.zeros((1, 1))
x[0, 0] = vocab[char]
feed = {self.input_data: x, self.initial_state:state}
[probs, state] = sess.run([self.probs, self.final_state], feed)
p = probs[0]
... | t = np.cumsum(weights)
s = np.sum(weights)
return(int(np.searchsorted(t, np.random.rand(1)*s))) | identifier_body |
model.py | import tensorflow as tf
from tensorflow.python.ops import rnn_cell
from tensorflow.python.ops import seq2seq
import numpy as np
class | ():
def __init__(self, args, infer=False):
self.args = args
if infer:
args.batch_size = 1
args.seq_length = 1
if args.model == 'rnn':
cell_fn = rnn_cell.BasicRNNCell
elif args.model == 'gru':
cell_fn = rnn_cell.GRUCell
elif arg... | Model | identifier_name |
model.py | import tensorflow as tf
from tensorflow.python.ops import rnn_cell
from tensorflow.python.ops import seq2seq
import numpy as np
class Model():
def __init__(self, args, infer=False):
self.args = args
if infer:
|
if args.model == 'rnn':
cell_fn = rnn_cell.BasicRNNCell
elif args.model == 'gru':
cell_fn = rnn_cell.GRUCell
elif args.model == 'lstm':
cell_fn = rnn_cell.BasicLSTMCell
else:
raise Exception("model type not supported: {}".format(args.mode... | args.batch_size = 1
args.seq_length = 1 | conditional_block |
model.py | import tensorflow as tf
from tensorflow.python.ops import rnn_cell
from tensorflow.python.ops import seq2seq
import numpy as np
class Model():
def __init__(self, args, infer=False):
self.args = args
if infer:
args.batch_size = 1
args.seq_length = 1
if args.model ==... | else:
raise Exception("model type not supported: {}".format(args.model))
cell = cell_fn(args.rnn_size)
self.cell = cell = rnn_cell.MultiRNNCell([cell] * args.num_layers)
self.input_data = tf.placeholder(tf.float32, [args.batch_size, args.seq_length], name="input")
... | elif args.model == 'lstm':
cell_fn = rnn_cell.BasicLSTMCell | random_line_split |
day_5.rs | use std::iter::Peekable;
use std::str::Chars;
pub fn evaluate(line: &str) -> f32 {
evaluate_iter(&mut line.chars().peekable())
}
fn evaluate_iter(iter: &mut Peekable<Chars>) -> f32 {
let mut accumulator = parse_term(iter.by_ref());
while iter.peek().is_some() {
let sign = iter.peek().cloned();
... | else {
accumulator = accumulator*10.0 + v;
}
},
_ => break,
}
}
accumulator
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_evaluate_simple_number() {
assert_eq!(evaluate("1"), 1.0);
}
#[te... | accumulator += v * exponent;
exponent *= 0.1;
}
| conditional_block |
day_5.rs | use std::iter::Peekable;
use std::str::Chars;
pub fn evaluate(line: &str) -> f32 {
evaluate_iter(&mut line.chars().peekable())
}
fn evaluate_iter(iter: &mut Peekable<Chars>) -> f32 {
let mut accumulator = parse_term(iter.by_ref());
while iter.peek().is_some() {
let sign = iter.peek().cloned();
... | assert_eq!(evaluate("2×2"), 4.0);
}
#[test]
fn test_evaluate_div() {
assert_eq!(evaluate("22÷2"), 11.0);
}
#[test]
fn test_two_adds() {
assert_eq!(evaluate("2+3+6"), 11.0);
}
#[test]
fn test_two_subs() {
assert_eq!(evaluate("6-4-1"), 1.0);
}
... | assert_eq!(evaluate("2-1"), 1.0);
}
#[test]
fn test_evaluate_mul() { | random_line_split |
day_5.rs | use std::iter::Peekable;
use std::str::Chars;
pub fn evaluate(line: &str) -> f32 {
evaluate_iter(&mut line.chars().peekable())
}
fn evaluate_iter(iter: &mut Peekable<Chars>) -> f32 {
let mut accumulator = parse_term(iter.by_ref());
while iter.peek().is_some() {
let sign = iter.peek().cloned();
... |
assert_eq!(evaluate("6-4-1"), 1.0);
}
#[test]
fn test_operation_with_different_priority() {
assert_eq!(evaluate("2+3×2"), 8.0);
}
}
| _two_subs() { | identifier_name |
day_5.rs | use std::iter::Peekable;
use std::str::Chars;
pub fn evaluate(line: &str) -> f32 {
evaluate_iter(&mut line.chars().peekable())
}
fn evaluate_iter(iter: &mut Peekable<Chars>) -> f32 {
let mut accumulator = parse_term(iter.by_ref());
while iter.peek().is_some() {
let sign = iter.peek().cloned();
... | #[test]
fn test_evaluate_big_number() {
assert_eq!(evaluate("100"), 100.0);
}
#[test]
fn test_evaluate_real_number() {
assert_eq!(evaluate("1.09"), 1.09)
}
#[test]
fn test_evaluate_add() {
assert_eq!(evaluate("1.09+1.01"), 2.1);
}
#[test]
fn test_ev... | assert_eq!(evaluate("1"), 1.0);
}
| identifier_body |
config_vlan.py | # Copyright 2015 Internap.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, so... |
def do_exit(self):
self.is_done = True | return self.switch_configuration.name + "(config-vlan)#"
def do_name(self, *args):
self.vlan.name = (args[0][:32]) | random_line_split |
config_vlan.py | # Copyright 2015 Internap.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, so... | (BaseCommandProcessor):
def init(self, switch_configuration, terminal_controller, logger, piping_processor, *args):
super(ConfigVlanCommandProcessor, self).init(switch_configuration, terminal_controller, logger, piping_processor)
self.vlan = args[0]
def get_prompt(self):
return self.swi... | ConfigVlanCommandProcessor | identifier_name |
config_vlan.py | # Copyright 2015 Internap.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, so... |
def do_exit(self):
self.is_done = True
| self.vlan.name = (args[0][:32]) | identifier_body |
test_output.py | import pytest
from httpie import ExitStatus
from httpie.output.formatters.colors import get_lexer
from utils import TestEnvironment, http, HTTP_OK, COLOR, CRLF
class TestVerboseFlag:
def test_verbose(self, httpbin):
r = http('--verbose',
'GET', httpbin.url + '/get', 'test-header:__test__... | if header == CRLF:
break
assert header.endswith(CRLF), repr(header)
else:
assert 0, 'CRLF between headers and body not found in %r' % msg
body = ''.join(lines)
assert CRLF not in body
return body
def test_CRLF_headers_only(self, ht... | def _validate_crlf(self, msg):
lines = iter(msg.splitlines(True))
for header in lines: | random_line_split |
test_output.py | import pytest
from httpie import ExitStatus
from httpie.output.formatters.colors import get_lexer
from utils import TestEnvironment, http, HTTP_OK, COLOR, CRLF
class TestVerboseFlag:
def test_verbose(self, httpbin):
r = http('--verbose',
'GET', httpbin.url + '/get', 'test-header:__test__... |
else:
assert 0, 'CRLF between headers and body not found in %r' % msg
body = ''.join(lines)
assert CRLF not in body
return body
def test_CRLF_headers_only(self, httpbin):
r = http('--headers', 'GET', httpbin.url + '/get')
body = self._validate_crlf(r)
... | if header == CRLF:
break
assert header.endswith(CRLF), repr(header) | conditional_block |
test_output.py | import pytest
from httpie import ExitStatus
from httpie.output.formatters.colors import get_lexer
from utils import TestEnvironment, http, HTTP_OK, COLOR, CRLF
class TestVerboseFlag:
def test_verbose(self, httpbin):
r = http('--verbose',
'GET', httpbin.url + '/get', 'test-header:__test__... |
class TestColors:
@pytest.mark.parametrize('mime', [
'application/json',
'application/json+foo',
'application/foo+json',
'foo/json',
'foo/json+bar',
'foo/bar+json',
])
def test_get_lexer(self, mime):
lexer = get_lexer(mime)
assert lexer is ... | r = http('--verbose',
'POST', httpbin.url + '/post', 'foo=bar', 'baz=bar')
assert HTTP_OK in r
assert '"baz": "bar"' in r | identifier_body |
test_output.py | import pytest
from httpie import ExitStatus
from httpie.output.formatters.colors import get_lexer
from utils import TestEnvironment, http, HTTP_OK, COLOR, CRLF
class TestVerboseFlag:
def test_verbose(self, httpbin):
r = http('--verbose',
'GET', httpbin.url + '/get', 'test-header:__test__... | (self, httpbin):
r = http('--pretty=format', 'GET', httpbin.url + '/get')
assert r.exit_status == ExitStatus.OK
self._validate_crlf(r)
def test_CRLF_ugly_request(self, httpbin):
r = http('--pretty=none', '--print=HB', 'GET', httpbin.url + '/get')
self._validate_crlf(r)
... | test_CRLF_formatted_response | identifier_name |
medea.light.js | /* medea.js - Open Source, High-Performance 3D Engine based on WebGL.
*
* (c) 2011-2013, Alexander C. Gessler
* https://github.com/acgessler/medea.js
*
* Made available under the terms and conditions of a 3-clause BSD license.
*
*/
medealib.define('light', ['entity', 'renderer'],function(medealib, undefined) {... |
this.dir = vec3.create(dir);
vec3.normalize(this.dir);
},
});
medea.CreateDirectionalLight = function(color, dir) {
return new medea.DirectionalLight(color, dir);
};
}); | {
return this.dir;
} | conditional_block |
medea.light.js | /* medea.js - Open Source, High-Performance 3D Engine based on WebGL.
*
* (c) 2011-2013, Alexander C. Gessler
* https://github.com/acgessler/medea.js
*
* Made available under the terms and conditions of a 3-clause BSD license.
*
*/
medealib.define('light', ['entity', 'renderer'],function(medealib, undefined) {... |
// class Light
this.Light = medea.Entity.extend(
{
cast_shadows : false,
shadowmap_res_bias : 0,
rq_idx : -1,
init : function(color, rq) {
this.color = color || [1,1,1];
this.rq_idx = rq === undefined ? medea.RENDERQUEUE_LIGHT : rq;
},
Render : function(camera, node, rqmanager) {
// Constr... | Draw : function(renderer, statepool) {
renderer.DrawLight(this, statepool);
},
}); | random_line_split |
wpullargs_test.py | from os import environ as env
import unittest
from .wpull import WpullArgs
from seesaw.item import Item
# taken form pipeline/pipeline.py
if 'WARC_MAX_SIZE' in env:
WARC_MAX_SIZE = env['WARC_MAX_SIZE']
else:
WARC_MAX_SIZE = '5368709120'
def joined(args):
return str.join(' ', args)
class TestWpullArgs(un... | (self):
self.item['recursive'] = True
self.item['depth'] = 'inf'
self.item['no_offsite_links'] = True
cmdline = joined(self.args.realize(self.item))
self.assertIn('--span-hosts-allow page-requisites', cmdline)
self.assertNotIn('linked-pages', cmdline)
def t... | test_recursive_fetch_with_no_offsite_links_enables_requisites | identifier_name |
wpullargs_test.py | from os import environ as env
import unittest
from .wpull import WpullArgs | # taken form pipeline/pipeline.py
if 'WARC_MAX_SIZE' in env:
WARC_MAX_SIZE = env['WARC_MAX_SIZE']
else:
WARC_MAX_SIZE = '5368709120'
def joined(args):
return str.join(' ', args)
class TestWpullArgs(unittest.TestCase):
def setUp(self):
self.item = {
'cookie_jar': '/foobar/cookie... | from seesaw.item import Item
| random_line_split |
wpullargs_test.py | from os import environ as env
import unittest
from .wpull import WpullArgs
from seesaw.item import Item
# taken form pipeline/pipeline.py
if 'WARC_MAX_SIZE' in env:
|
else:
WARC_MAX_SIZE = '5368709120'
def joined(args):
return str.join(' ', args)
class TestWpullArgs(unittest.TestCase):
def setUp(self):
self.item = {
'cookie_jar': '/foobar/cookies.txt',
'ident': 'abc123',
'item_dir': '/foobar',
'ur... | WARC_MAX_SIZE = env['WARC_MAX_SIZE'] | conditional_block |
wpullargs_test.py | from os import environ as env
import unittest
from .wpull import WpullArgs
from seesaw.item import Item
# taken form pipeline/pipeline.py
if 'WARC_MAX_SIZE' in env:
WARC_MAX_SIZE = env['WARC_MAX_SIZE']
else:
WARC_MAX_SIZE = '5368709120'
def joined(args):
return str.join(' ', args)
class TestWpullArgs(un... |
def test_youtube_dl_activation(self):
self.item['youtube_dl'] = True
self.assertIn('--youtube-dl', joined(self.args.realize(self.item)))
def test_uses_default_user_agent(self):
self.assertIn('-U Default/1', joined(self.args.realize(self.item)))
def test_recursive_fetch_settings(... | self.item['user_agent'] = 'Frobinator/20.1'
self.assertIn('-U Frobinator/20.1', joined(self.args.realize(self.item))) | identifier_body |
bufferTime.ts | import { IScheduler } from '../Scheduler';
import { Action } from '../scheduler/Action';
import { Operator } from '../Operator';
import { async } from '../scheduler/async';
import { Observable } from '../Observable';
import { Subscriber } from '../Subscriber';
import { Subscription } from '../Subscription';
import { is... |
call(subscriber: Subscriber<T[]>, source: any): any {
return source.subscribe(new BufferTimeSubscriber(
subscriber, this.bufferTimeSpan, this.bufferCreationInterval, this.maxBufferSize, this.scheduler
));
}
}
class Context<T> {
buffer: T[] = [];
closeAction: Subscription;
}
type CreationState<... | {
} | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.