file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
base_handler.py | #!/usr/bin/env python3
# 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/.
#
# Copyright 2017-2019 - Edoardo Morassutto <edoardo.morassutto@gmail.com>
# Copyright 2017 - Luc... | "=".join((kv[0], str(kv[1]))) for kv in kwargs.items()
if not kv[0].startswith("_") and not kv[0] == "file"
) if len(kwargs) > 0 else ""
)
)
return method(**kwargs)
@staticmethod
def _get_file_name(request):
... | method.__name__,
", with parameters " + ", ".join( | random_line_split |
base_handler.py | #!/usr/bin/env python3
# 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/.
#
# Copyright 2017-2019 - Edoardo Morassutto <edoardo.morassutto@gmail.com>
# Copyright 2017 - Luc... |
@staticmethod
def format_dates(dct, fields=["date"]):
"""
Given a dict, format all the *fields* fields from int to iso format. The original dict is modified
:param dct: dict to format
:param fields: list of the names of the fields to format
:return: The modified dict
... | """
Compute the end time for a window started after `start_delay` and with `extra_time` delay for the user.
Note that this time may exceed the contest end time, additional checks are required.
:param user_extra_time: Extra time specific for the user in seconds
:param start_delay: The tim... | identifier_body |
base_handler.py | #!/usr/bin/env python3
# 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/.
#
# Copyright 2017-2019 - Edoardo Morassutto <edoardo.morassutto@gmail.com>
# Copyright 2017 - Luc... | (request):
"""
Extract the name of the file from the multipart body
:param request: The Request object
:return: The filename in the request
"""
if "file" not in request.files:
return None
return request.files["file"].filename
@staticmethod
def... | _get_file_name | identifier_name |
i2c.rs | // Copyright lowRISC contributors.
// Licensed under the Apache License, Version 2.0, see LICENSE for details.
// SPDX-License-Identifier: Apache-2.0
use anyhow::Result;
use erased_serde::Serialize;
use std::any::Any;
use structopt::StructOpt;
use opentitanlib::app::command::CommandDispatch;
use opentitanlib::app::Tr... | {
#[structopt(flatten)]
params: I2cParams,
#[structopt(short, long, help = "7-bit address of I2C device (0..0x7F).")]
addr: u8,
#[structopt(subcommand)]
command: InternalI2cCommand,
}
impl CommandDispatch for I2cCommand {
fn run(
&self,
_context: &dyn Any,
transpo... | I2cCommand | identifier_name |
i2c.rs | // Copyright lowRISC contributors.
// Licensed under the Apache License, Version 2.0, see LICENSE for details.
// SPDX-License-Identifier: Apache-2.0
use anyhow::Result;
use erased_serde::Serialize;
use std::any::Any;
use structopt::StructOpt;
use opentitanlib::app::command::CommandDispatch;
use opentitanlib::app::Tr... | transport: &TransportWrapper,
) -> Result<Option<Box<dyn Serialize>>> {
transport.capabilities()?.request(Capability::I2C).ok()?;
let context = context.downcast_ref::<I2cCommand>().unwrap();
let i2c_bus = context.params.create(transport)?;
i2c_bus.run_transaction(
... | context: &dyn Any, | random_line_split |
i2c.rs | // Copyright lowRISC contributors.
// Licensed under the Apache License, Version 2.0, see LICENSE for details.
// SPDX-License-Identifier: Apache-2.0
use anyhow::Result;
use erased_serde::Serialize;
use std::any::Any;
use structopt::StructOpt;
use opentitanlib::app::command::CommandDispatch;
use opentitanlib::app::Tr... |
}
/// Write plain data bytes to a I2C device.
#[derive(Debug, StructOpt)]
pub struct I2cRawWrite {
#[structopt(short, long, help = "Hex data bytes to write.")]
hexdata: String,
}
impl CommandDispatch for I2cRawWrite {
fn run(
&self,
context: &dyn Any,
transport: &TransportWrapper,... | {
transport.capabilities()?.request(Capability::I2C).ok()?;
let context = context.downcast_ref::<I2cCommand>().unwrap();
let i2c_bus = context.params.create(transport)?;
let mut v = vec![0u8; self.length];
i2c_bus.run_transaction(context.addr, &mut [Transfer::Read(&mut v)])?;
... | identifier_body |
test_round.py | import numpy as np
import pytest
import pandas as pd |
class TestSeriesRound:
def test_round(self, datetime_series):
datetime_series.index.name = "index_name"
result = datetime_series.round(2)
expected = Series(
np.round(datetime_series.values, 2), index=datetime_series.index, name="ts"
)
tm.assert_series_equal(resu... | from pandas import Series
import pandas._testing as tm | random_line_split |
test_round.py | import numpy as np
import pytest
import pandas as pd
from pandas import Series
import pandas._testing as tm
class TestSeriesRound:
def | (self, datetime_series):
datetime_series.index.name = "index_name"
result = datetime_series.round(2)
expected = Series(
np.round(datetime_series.values, 2), index=datetime_series.index, name="ts"
)
tm.assert_series_equal(result, expected)
assert result.name ==... | test_round | identifier_name |
test_round.py | import numpy as np
import pytest
import pandas as pd
from pandas import Series
import pandas._testing as tm
class TestSeriesRound:
def test_round(self, datetime_series):
datetime_series.index.name = "index_name"
result = datetime_series.round(2)
expected = Series(
np.round(dat... |
@pytest.mark.parametrize("method", ["round", "floor", "ceil"])
@pytest.mark.parametrize("freq", ["s", "5s", "min", "5min", "h", "5h"])
def test_round_nat(self, method, freq):
# GH14940
ser = Series([pd.NaT])
expected = Series(pd.NaT)
round_method = getattr(ser.dt, method)
... | ser = Series(
[1.123, 2.123, 3.123],
index=range(3),
dtype=any_float_dtype,
)
result = round(ser)
expected_rounded0 = Series(
[1.0, 2.0, 3.0], index=range(3), dtype=any_float_dtype
)
tm.assert_series_equal(result, expected_rounded0)... | identifier_body |
list_salesummary.js | var gId = '#dataGrid';
var lastIndex;
$(document).ready(function(){
//列表
$(gId).datagrid({
url:getUrlOpt(),
idField:'id',
fitColumns:true,
frozenColumns:[[
{field:'ck',checkbox:true}
]],
columns:[
getTableHeadOpt(),
getColumnsOpt(),
getTotal()
],
rownumbers:true,
pag... | oodTypeName,goodName,begin,end,brandName,positionName){
var queryParams = $(gId).datagrid('options').queryParams;
queryParams={"saleWare.goodTypeName":goodTypeName,"saleWare.goodName":goodName,"saleWare.begin":begin,"saleWare.end":end,"saleWare.brandName":brandName,"saleWare.warehousePositionName":positionName};
$(g... | nd,brandName,positionName);
}
function cancelSearch(){
$('#goodTypeName').val('');
$('#goodName').val('');
$('#begin').val('');
$('#end').val('');
$('#brandName').val('');
$('#warehouseName').val('');
$('#warehousePositionName').val('');
searchData();
}
//确定搜索时重新加载datagrid
function realoadGrid(g | identifier_body |
list_salesummary.js | var gId = '#dataGrid';
var lastIndex;
$(document).ready(function(){
//列表
$(gId).datagrid({
url:getUrlOpt(),
idField:'id',
fitColumns:true,
frozenColumns:[[
{field:'ck',checkbox:true}
]],
columns:[
getTableHeadOpt(),
getColumnsOpt(),
getTotal()
],
rownumbers:true,
pag... | = rowIndex;
}
});
});
//计算总计
function getTotal()
{
var opt=[
{field:'totalSalesmoney',title:'出货金额总计',hidden:true,align:'left',formatter:totalFormat},
{field:'totalCostmoney',title:'成本金额总计',hidden:true,align:'left'},
{field:'totalOrderNum',title:'出货数量总计',hidden:true,align:'left'}
];
return opt;
}
//格式化总计
fun... | atagrid('endEdit', lastIndex);
$(gId).datagrid('beginEdit', rowIndex);
}
lastIndex | conditional_block |
list_salesummary.js | var gId = '#dataGrid';
var lastIndex;
$(document).ready(function(){
//列表
$(gId).datagrid({
url:getUrlOpt(),
idField:'id',
fitColumns:true,
frozenColumns:[[
{field:'ck',checkbox:true}
]],
columns:[
getTableHeadOpt(),
getColumnsOpt(),
getTotal()
],
rownumbers:true,
pag... | 获取列头参数
function getColumnsOpt(){
var opt = [
{field:'goodCode',title:'资料编号',width:15,align:'left'},
{field:'goodTypeName',title:'资料类别',width:10,align:'left'},
{field:'goodName',title:'资料名',width:30,align:'left'},
{field:'unit',title:'单位',width:10,align:'left'},
{field:'purchasePrice',title:'进货价',width:15,ali... | urn opt;
}
// | identifier_name |
list_salesummary.js | var gId = '#dataGrid';
var lastIndex;
$(document).ready(function(){
//列表
$(gId).datagrid({
url:getUrlOpt(),
idField:'id',
fitColumns:true,
frozenColumns:[[
{field:'ck',checkbox:true}
]],
columns:[
getTableHeadOpt(),
getColumnsOpt(),
getTotal()
],
rownumbers:true,
pag... | //格式化总计
function totalFormat(value,rowData,rowIndex){
var totalSalesmoney = rowData.totalSalesmoney;
var totalCostmoney=rowData.totalCostmoney;
var totalOrderNum=rowData.totalOrderNum;
$("#num").html(totalOrderNum);
$("#sale").html(totalSalesmoney);
$("#cost").html(totalCostmoney);
return totalSalesmoney;
}
//获取... | {field:'totalOrderNum',title:'出货数量总计',hidden:true,align:'left'}
];
return opt;
} | random_line_split |
fetch-zero-knowledge.js | /**
* Fetch configuration data using an API Key and the Application Secret Key.
* By doing so, the sconfig servers will just apply firewall rules (if any) and return
* the encrypted configuration data. The client will then decrypt the configuration
* data using the App Secret Key
* Note: Ff no API Key or App Secre... | var sconfig = require('sconfig');
sconfig({
key: '{YOUR_API_KEY}', // the 32-char version of an API Key
secret: '{YOUR_APP_SECRET}', // the 32 char secret key found under the App Details tab
//version: '{YOUR_VERSION}', // version name to fetch, defaults to latest version created
// json: true ... | random_line_split | |
fetch-zero-knowledge.js | /**
* Fetch configuration data using an API Key and the Application Secret Key.
* By doing so, the sconfig servers will just apply firewall rules (if any) and return
* the encrypted configuration data. The client will then decrypt the configuration
* data using the App Secret Key
* Note: Ff no API Key or App Secre... |
console.log("OK", config);
}); | {
console.log(err);
return;
} | conditional_block |
from_other_type_slice.rs | use malachite_base::named::Named;
use malachite_base::num::basic::unsigneds::PrimitiveUnsigned;
use malachite_base::num::conversion::traits::FromOtherTypeSlice;
use malachite_base_test_util::bench::bucketers::vec_len_bucketer;
use malachite_base_test_util::bench::{run_benchmark, BenchmarkType};
use malachite_base_test_... | <T: Display + FromOtherTypeSlice<U> + Named, U: PrimitiveUnsigned>(
gm: GenMode,
config: GenConfig,
limit: usize,
) {
for xs in unsigned_vec_gen::<U>().get(gm, &config).take(limit) {
println!(
"{}::from_other_type_slice({:?}) = {}",
T::NAME,
xs,
T:... | demo_from_other_type_slice | identifier_name |
from_other_type_slice.rs | use malachite_base::named::Named;
use malachite_base::num::basic::unsigneds::PrimitiveUnsigned;
use malachite_base::num::conversion::traits::FromOtherTypeSlice;
use malachite_base_test_util::bench::bucketers::vec_len_bucketer;
use malachite_base_test_util::bench::{run_benchmark, BenchmarkType};
use malachite_base_test_... | );
} | random_line_split | |
from_other_type_slice.rs | use malachite_base::named::Named;
use malachite_base::num::basic::unsigneds::PrimitiveUnsigned;
use malachite_base::num::conversion::traits::FromOtherTypeSlice;
use malachite_base_test_util::bench::bucketers::vec_len_bucketer;
use malachite_base_test_util::bench::{run_benchmark, BenchmarkType};
use malachite_base_test_... | {
run_benchmark(
&format!("{}.from_other_type_slice(&[{}])", T::NAME, U::NAME),
BenchmarkType::Single,
unsigned_vec_gen::<U>().get(gm, &config),
gm.name(),
limit,
file_name,
&vec_len_bucketer(),
&mut [("Malachite", &mut |xs| {
no_out!(T::fr... | identifier_body | |
trigger.tsx | import React, { ComponentType } from "react";
import queryString from "query-string";
import { RouteComponentProps } from "react-router-dom";
import isEqual from "lodash/isEqual";
import MoiraApi from "../../Api/MoiraApi";
import { Trigger, TriggerState } from "../../Domain/Trigger";
import { Event } from "../../Domain... | or,
page,
pageCount,
trigger,
triggerState,
triggerEvents,
} = this.state;
const { view: TriggerView } = this.props;
return (
<TriggerView
trigger={trigger}
state={triggerState}
... | err | identifier_name |
trigger.tsx | import React, { ComponentType } from "react";
import queryString from "query-string";
import { RouteComponentProps } from "react-router-dom";
import isEqual from "lodash/isEqual";
import MoiraApi from "../../Api/MoiraApi";
import { Trigger, TriggerState } from "../../Domain/Trigger";
import { Event } from "../../Domain... | static getEventMetricName(event: Event, triggerName: string): string {
if (event.trigger_event) {
return triggerName;
}
return event.metric.length !== 0 ? event.metric : "No metric evaluated";
}
static composeEvents(
events: Array<Event>,
triggerName: str... | onlyProblems: false,
};
}
| random_line_split |
trigger.tsx | import React, { ComponentType } from "react";
import queryString from "query-string";
import { RouteComponentProps } from "react-router-dom";
import isEqual from "lodash/isEqual";
import MoiraApi from "../../Api/MoiraApi";
import { Trigger, TriggerState } from "../../Domain/Trigger";
import { Event } from "../../Domain... | error,
page,
pageCount,
trigger,
triggerState,
triggerEvents,
} = this.state;
const { view: TriggerView } = this.props;
return (
<TriggerView
trigger={trigger}
state={triggerState}
... | ray<Event> }, event: Event) => {
const metric = this.getEventMetricName(event, triggerName);
if (data[metric]) {
data[metric].push(event);
} else {
data[metric] = [event];
}
return data;
}, {});
}
render() {
... | identifier_body |
trigger.tsx | import React, { ComponentType } from "react";
import queryString from "query-string";
import { RouteComponentProps } from "react-router-dom";
import isEqual from "lodash/isEqual";
import MoiraApi from "../../Api/MoiraApi";
import { Trigger, TriggerState } from "../../Domain/Trigger";
import { Event } from "../../Domain... | er() {
const {
loading,
error,
page,
pageCount,
trigger,
triggerState,
triggerEvents,
} = this.state;
const { view: TriggerView } = this.props;
return (
<TriggerView
trigger={... | return data;
}, {});
}
rend | conditional_block |
whoami.py | # -*- coding: utf-8 -*-
"""
Display logged-in username.
Configuration parameters:
format: display format for whoami (default '{username}')
Format placeholders:
{username} display current username
Inspired by i3 FAQ:
https://faq.i3wm.org/question/1618/add-user-name-to-status-bar.1.html
@author ultrabug
... | :
"""
"""
# available configuration parameters
format = '{username}'
class Meta:
deprecated = {
'remove': [
{
'param': 'cache_timeout',
'msg': 'obsolete parameter',
},
],
}
def whoam... | Py3status | identifier_name |
whoami.py | # -*- coding: utf-8 -*-
"""
Display logged-in username.
Configuration parameters:
format: display format for whoami (default '{username}')
Format placeholders:
{username} display current username
Inspired by i3 FAQ:
https://faq.i3wm.org/question/1618/add-user-name-to-status-bar.1.html
@author ultrabug
... |
class Py3status:
"""
"""
# available configuration parameters
format = '{username}'
class Meta:
deprecated = {
'remove': [
{
'param': 'cache_timeout',
'msg': 'obsolete parameter',
},
],
... | """
from getpass import getuser | random_line_split |
whoami.py | # -*- coding: utf-8 -*-
"""
Display logged-in username.
Configuration parameters:
format: display format for whoami (default '{username}')
Format placeholders:
{username} display current username
Inspired by i3 FAQ:
https://faq.i3wm.org/question/1618/add-user-name-to-status-bar.1.html
@author ultrabug
... | """
Run module in test mode.
"""
from py3status.module_test import module_test
module_test(Py3status) | conditional_block | |
whoami.py | # -*- coding: utf-8 -*-
"""
Display logged-in username.
Configuration parameters:
format: display format for whoami (default '{username}')
Format placeholders:
{username} display current username
Inspired by i3 FAQ:
https://faq.i3wm.org/question/1618/add-user-name-to-status-bar.1.html
@author ultrabug
... |
if __name__ == "__main__":
"""
Run module in test mode.
"""
from py3status.module_test import module_test
module_test(Py3status)
| """
"""
# available configuration parameters
format = '{username}'
class Meta:
deprecated = {
'remove': [
{
'param': 'cache_timeout',
'msg': 'obsolete parameter',
},
],
}
def whoami(self... | identifier_body |
fs.rs | /*
Rust - Std Misc Filesystem Operation
Licence : GNU GPL v3 or later
Author : Aurélien DESBRIÈRES
Mail : aurelien(at)hackers(dot)camp
Created on : June 2017
Write with Emacs-nox ───────────────┐
Rust ───────────────────────────────┘
*/
// fs.rs | use std::io::prelude::*;
use std::os::unix;
use std::path::Path;
// A simple implementation of `% cat path`
fn cat(path: &Path) -> io::Result<String> {
let mut f = try!(File::open(path));
let mut s = String::new();
match f.read_to_string(&mut s) {
Ok(_) => Ok(s),
Err(e) => Err(e),
}
}
... |
use std::fs;
use std::fs::{File, OpenOptions};
use std::io; | random_line_split |
fs.rs | /*
Rust - Std Misc Filesystem Operation
Licence : GNU GPL v3 or later
Author : Aurélien DESBRIÈRES
Mail : aurelien(at)hackers(dot)camp
Created on : June 2017
Write with Emacs-nox ───────────────┐
Rust ───────────────────────────────┘
*/
// fs.rs
use std::fs;
use std::fs::{File, OpenOptions};
use std::io... | atch fs::create_dir("a") {
Err(why) => println!("! {:?}", why.kind()),
Ok(_) => {},
}
println!("`echo hello > a/b.txt`");
// The previous match can be simplified using the `unwrap_or_else` method
echo("hello", &Path::new("a/b.txt")).unwrap_or_else(|why| {
println!("! {:?}", why.... | Err(e) => Err(e),
}
}
fn main() {
println!("`mkdir a`");
// Create a directory, returns `io::Result<()>`
m | identifier_body |
fs.rs | /*
Rust - Std Misc Filesystem Operation
Licence : GNU GPL v3 or later
Author : Aurélien DESBRIÈRES
Mail : aurelien(at)hackers(dot)camp
Created on : June 2017
Write with Emacs-nox ───────────────┐
Rust ───────────────────────────────┘
*/
// fs.rs
use std::fs;
use std::fs::{File, OpenOptions};
use std::io... | {
Ok(_) => Ok(()),
Err(e) => Err(e),
}
}
fn main() {
println!("`mkdir a`");
// Create a directory, returns `io::Result<()>`
match fs::create_dir("a") {
Err(why) => println!("! {:?}", why.kind()),
Ok(_) => {},
}
println!("`echo hello > a/b.txt`");
// The pre... | path) | identifier_name |
summary.py | #!/usr/bin/python -u
#----------------------------------------------------------------------------
# Summarizes a twogtp tournament.
#
# TODO: - Simplify stuff. The table idea seems bad, in retrospect.
# - Do we really care about which openings are won/lost?
import os, sys, getopt, re, string
from statistics imp... |
# for k in sorted(table.keys()):
# print k, table[k]
def showIterativeResults(numvalid, table, opencount, openings,
progs, showTable, p1Timeouts, p2Timeouts):
if showTable:
print "+-------------+--------+-------+-------+"
print "+ OPENING | COUNT | p1 | ... | print "Analyzing: \'" + fname + "\'..."
if plotScore:
pf = open("plot.dat", "w")
f = open(fname, "r")
line = f.readline()
linenum = 1
numvalid = 0
table = {}
opencount = {}
openings = []
progs = []
p1Timeouts = 0.0
p2Timeouts = 0.0
while line != "... | identifier_body |
summary.py | #!/usr/bin/python -u
#----------------------------------------------------------------------------
# Summarizes a twogtp tournament.
#
# TODO: - Simplify stuff. The table idea seems bad, in retrospect.
# - Do we really care about which openings are won/lost?
import os, sys, getopt, re, string
from statistics imp... | ():
count = 50000
timeLimit = 123456.789
longOpening = False
showTable = False
plotScore = False
resfile = ""
openingsFile = ""
openings = []
try:
options = "clr:sf:"
longOptions = ["count=","long","showTable","plot","file=",
"time=","openings... | main | identifier_name |
summary.py | #!/usr/bin/python -u
#----------------------------------------------------------------------------
# Summarizes a twogtp tournament.
#
# TODO: - Simplify stuff. The table idea seems bad, in retrospect.
# - Do we really care about which openings are won/lost?
import os, sys, getopt, re, string
from statistics imp... | table = {}
opencount = {}
openings = []
progs = []
p1Timeouts = 0.0
p2Timeouts = 0.0
while line != "":
if line[0] != "#":
array = string.split(line, "\t")
fullopening = array[2]
black = array[3]
white = array[4]
b... | f = open(fname, "r")
line = f.readline()
linenum = 1
numvalid = 0 | random_line_split |
summary.py | #!/usr/bin/python -u
#----------------------------------------------------------------------------
# Summarizes a twogtp tournament.
#
# TODO: - Simplify stuff. The table idea seems bad, in retrospect.
# - Do we really care about which openings are won/lost?
import os, sys, getopt, re, string
from statistics imp... |
else:
p2Timeouts = p2Timeouts + 1.0
p2Overtime.add(overtime)
gamelen.add(float(length))
p1Wins.add(valueForP1)
if (plotScore):
print >> pf, str(p1Wins.count()) + "\t" + str(p1Wins.me... | p1Timeouts = p1Timeouts + 1.0
p1Overtime.add(overtime) | conditional_block |
main.js | import React from 'react';
import {render} from 'react-dom';
class StaffList extends React.Component {
render() {
console.log(this.props);
var stafflist = Object.values(this.props.staffs).map(staffObject =>
<Staff staffObject = {JSON.parse(staffObject)}/>
);
return(... | render() {
return(
<StaffList staffs = {this.getStaffList()} />
);
}
}
render(<View />, document.getElementById('target')); | return list;
}
| random_line_split |
main.js | import React from 'react';
import {render} from 'react-dom';
class StaffList extends React.Component {
| () {
console.log(this.props);
var stafflist = Object.values(this.props.staffs).map(staffObject =>
<Staff staffObject = {JSON.parse(staffObject)}/>
);
return(
<table>
<thead>
<tr>
<th><center>IDNumber... | render | identifier_name |
boaview.py | #!/usr/bin/env python3
import sys
import click
from boadata import __version__
from boadata.cli import try_load, try_apply_sql, qt_app
| @click.argument("uri")
@click.option("-s", "--sql", required=False, help="SQL to run on the object.")
@click.option("-t", "--type", default=None, help="What type is the object.")
@click.option("-p", "--parameter", help="Additional parameters for loader, specified as key=value", multiple=True)
def run_app(uri, type, par... |
@click.command()
@click.version_option(__version__) | random_line_split |
boaview.py | #!/usr/bin/env python3
import sys
import click
from boadata import __version__
from boadata.cli import try_load, try_apply_sql, qt_app
@click.command()
@click.version_option(__version__)
@click.argument("uri")
@click.option("-s", "--sql", required=False, help="SQL to run on the object.")
@click.option("-t", "--type... |
if __name__ == "__main__":
run_app()
| kwargs = {key: value for key, value in kwargs.items() if value is not None}
do = try_load(uri, type, parameters=parameter)
do = try_apply_sql(do, kwargs)
with qt_app():
from boadata.gui.qt import DataObjectWindow
window = DataObjectWindow(do)
window.show()
window.setWindow... | identifier_body |
boaview.py | #!/usr/bin/env python3
import sys
import click
from boadata import __version__
from boadata.cli import try_load, try_apply_sql, qt_app
@click.command()
@click.version_option(__version__)
@click.argument("uri")
@click.option("-s", "--sql", required=False, help="SQL to run on the object.")
@click.option("-t", "--type... | run_app() | conditional_block | |
boaview.py | #!/usr/bin/env python3
import sys
import click
from boadata import __version__
from boadata.cli import try_load, try_apply_sql, qt_app
@click.command()
@click.version_option(__version__)
@click.argument("uri")
@click.option("-s", "--sql", required=False, help="SQL to run on the object.")
@click.option("-t", "--type... | (uri, type, parameter, **kwargs):
kwargs = {key: value for key, value in kwargs.items() if value is not None}
do = try_load(uri, type, parameters=parameter)
do = try_apply_sql(do, kwargs)
with qt_app():
from boadata.gui.qt import DataObjectWindow
window = DataObjectWindow(do)
... | run_app | identifier_name |
gradients.js | #!/usr/bin/env node-canvas
/*jslint indent: 2, node: true */
"use strict";
var Canvas = require('../lib/canvas');
var canvas = new Canvas(320, 320);
var ctx = canvas.getContext('2d');
var fs = require('fs');
var eu = require('./util');
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.scale(3, 3);
// Create gra... | ctx.fillRect(0, 150, 150, 150);
lingrad = ctx.createRadialGradient(30, 180, 50, 30, 180, 100);
lingrad.addColorStop(0, '#00ABEB');
lingrad.addColorStop(0.5, '#fff');
lingrad.addColorStop(0.5, '#26C000');
lingrad.addColorStop(1, '#fff');
ctx.fillStyle = lingrad;
ctx.fillRect(10, 160, 130, 130);
canvas.vgSwapBuffers()... | ctx.fillStyle = lingrad;
ctx.fillRect(160, 10, 130, 130);
// Radial gradients
ctx.fillStyle = '#a00000'; | random_line_split |
__init__.py | # -*- encoding: utf-8 -*-
###########################################################################
# Module Writen to OpenERP, Open Source Management Solution
# Copyright (C) OpenERP Venezuela (<http://openerp.com.ve>).
# All Rights Reserved
###############Credits############################################... | # 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 with this program. If not, see <http://www.gnu.org... | #
# This program is distributed in the hope that it will be useful, | random_line_split |
right-to-tradeskill.ts |
import { isUndefined } from 'lodash';
import { Command } from '../../../../base/Command';
import { Player } from '../../../../../shared/models/player';
export class RightToTradeskill extends Command {
public name = '~RtT';
public format = 'TradeskillSlot TradeskillDestSlot AlchUUID';
| (player: Player, { room, args }) {
if(this.isBusy(player)) return;
const [tsSlot, tsDestSlot, alchUUID] = args.split(' ');
if(!tsSlot || isUndefined(tsDestSlot) || !alchUUID) return false;
const container = room.state.findNPC(alchUUID);
if(!container) return player.sendClientMessage('That person is... | execute | identifier_name |
right-to-tradeskill.ts | import { isUndefined } from 'lodash';
import { Command } from '../../../../base/Command';
import { Player } from '../../../../../shared/models/player';
| execute(player: Player, { room, args }) {
if(this.isBusy(player)) return;
const [tsSlot, tsDestSlot, alchUUID] = args.split(' ');
if(!tsSlot || isUndefined(tsDestSlot) || !alchUUID) return false;
const container = room.state.findNPC(alchUUID);
if(!container) return player.sendClientMessage('That ... | export class RightToTradeskill extends Command {
public name = '~RtT';
public format = 'TradeskillSlot TradeskillDestSlot AlchUUID';
| random_line_split |
loops.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... | <'this>(&'this mut self) -> NestedVisitorMap<'this, 'hir> {
NestedVisitorMap::OnlyBodies(&self.hir_map)
}
fn visit_item(&mut self, i: &'hir hir::Item) {
self.with_context(Normal, |v| intravisit::walk_item(v, i));
}
fn visit_impl_item(&mut self, i: &'hir hir::ImplItem) {
self.wi... | nested_visit_map | identifier_name |
loops.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... | Normal | AnonConst => {
struct_span_err!(self.sess, span, E0268, "`{}` outside of loop", name)
.span_label(span, "cannot break outside of a loop")
.emit();
}
}
}
fn require_label_in_labeled_block(&mut self, span: Span, label: &Dest... | Closure => {
struct_span_err!(self.sess, span, E0267, "`{}` inside of a closure", name)
.span_label(span, "cannot break inside of a closure")
.emit();
} | random_line_split |
loops.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... |
impl<'a, 'hir> Visitor<'hir> for CheckLoopVisitor<'a, 'hir> {
fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'hir> {
NestedVisitorMap::OnlyBodies(&self.hir_map)
}
fn visit_item(&mut self, i: &'hir hir::Item) {
self.with_context(Normal, |v| intravisit::walk_item(v, ... | {
let krate = map.krate();
krate.visit_all_item_likes(&mut CheckLoopVisitor {
sess,
hir_map: map,
cx: Normal,
}.as_deep_visitor());
} | identifier_body |
path.py | import unicodedata
import re
class PathExtension:
"""
Enables readable url path names instead of ids for object traversal.
Names are stored as meta.pool_filename and generated from
title by default. Automatic generation can be disabled by setting
*meta.customfilename* to False for each object.
... | """
def Init(self):
self.ListenEvent("commit", "UpdateRouting")
self.ListenEvent("dataloaded", "UpdateRouting")
self.UpdateRouting()
def UpdateRouting(self, **kw):
# check url name of root
if self.meta.get("pool_filename"):
name = self.meta.get("pool_fil... | class PersistentRootPath(object):
"""
Extension for nive root objects to handle alternative url names | random_line_split |
path.py |
import unicodedata
import re
class PathExtension:
"""
Enables readable url path names instead of ids for object traversal.
Names are stored as meta.pool_filename and generated from
title by default. Automatic generation can be disabled by setting
*meta.customfilename* to False for each object.... |
def EscapeFilename(self, path):
"""
Converts name to valid path/url
Path length between *self.maxlength-20* and *self.maxlength* chars. Tries to cut longer names at spaces.
(based on django's slugify)
"""
path = unicodedata.normalize("NFKD", path).en... | """
Converts name to valid path/url
"""
if name == "file":
name = "file_"
if self.containerNamespace:
unitref = self.parent.id
else:
unitref = None
cnt = 1
root = self.root
while root.search.FilenameToID(self.AddExtensio... | identifier_body |
path.py |
import unicodedata
import re
class PathExtension:
"""
Enables readable url path names instead of ids for object traversal.
Names are stored as meta.pool_filename and generated from
title by default. Automatic generation can be disabled by setting
*meta.customfilename* to False for each object.... | (self, **kw):
# check url name of root
if self.meta.get("pool_filename"):
name = self.meta.get("pool_filename")
if name != self.__name__:
# close cached root
self.app._CloseRootObj(name=self.__name__)
# update __name__ and hash
... | UpdateRouting | identifier_name |
path.py |
import unicodedata
import re
class PathExtension:
"""
Enables readable url path names instead of ids for object traversal.
Names are stored as meta.pool_filename and generated from
title by default. Automatic generation can be disabled by setting
*meta.customfilename* to False for each object.... |
else:
unitref = None
cnt = 1
root = self.root
while root.search.FilenameToID(self.AddExtension(name), unitref, parameter=dict(id=self.id), operators=dict(id="!=")) != 0:
if cnt>1:
name = name.rstrip("1234567890-")
name = name+"-"+str(... | unitref = self.parent.id | conditional_block |
base.py | import curses
import random
class Screen(object):
def __init__(self, maxy, maxx):
self.setmaxyx(maxy, maxx)
self.pos = (0, 0)
def clear(self, *args):
if not args:
y, x = self.getmaxyx()
self.lines = []
for i in range(y):
self.lines.ap... | y, x = self.getmaxyx()
get_screen().clear(y, x, y0, x0)
class CursesError(Exception):
pass
screen = None
def get_screen():
return screen
def initscr():
global screen
screen = Screen(100, 100)
return screen
def newwin(*args):
return Window(*args)
class CommandsManager(object)... | get_screen().addstr(y + y0, x + x0, s, a)
def clear(self):
y0, x0 = self.getbegyx() | random_line_split |
base.py | import curses
import random
class Screen(object):
def __init__(self, maxy, maxx):
self.setmaxyx(maxy, maxx)
self.pos = (0, 0)
def clear(self, *args):
if not args:
y, x = self.getmaxyx()
self.lines = []
for i in range(y):
self.lines.ap... | (self):
self.commands = []
def add(self, command):
if isinstance(command, list):
self.commands += command
else:
self.commands.append(command)
def get(self):
try:
return self.commands.pop(0)
except IndexError:
raise CursesE... | reset | identifier_name |
base.py | import curses
import random
class Screen(object):
def __init__(self, maxy, maxx):
self.setmaxyx(maxy, maxx)
self.pos = (0, 0)
def clear(self, *args):
if not args:
y, x = self.getmaxyx()
self.lines = []
for i in range(y):
self.lines.ap... |
if not width:
width = x - 1
def get_line():
line = ''.join([random.choice(letters)
for j in range(random.randint(1, width))]).strip()
return line or get_line()
return [get_line() for i in range(num)]
| num = y + 50 | conditional_block |
base.py | import curses
import random
class Screen(object):
def __init__(self, maxy, maxx):
self.setmaxyx(maxy, maxx)
self.pos = (0, 0)
def clear(self, *args):
if not args:
y, x = self.getmaxyx()
self.lines = []
for i in range(y):
self.lines.ap... |
def setmaxyx(self, maxy, maxx):
self.maxyx = (maxy, maxx)
self.clear()
class Window(Screen):
def __init__(self, *args):
if len(args) == 2:
y0, x0 = args
sy, sx = get_screen().getmaxyx()
y, x = sy - y0, sx - x0
elif len(args) == 4:
... | return self.pos | identifier_body |
test_householder_reflection.py | """
Python unit-test
"""
import unittest
import numpy as np
import numpy.testing as npt
from .. import qr_decomposition
class TestHouseholderReflection(unittest.TestCase):
"""Test case for QR decomposition using Householder reflection."""
def test_wikipedia_example1(self):
"""Test of Wikipedia exa... | R_desired = np.array([[14, 21, -14],
[0, 175, -70],
[0, 0, -35]], dtype=np.float64)
npt.assert_almost_equal(Q, Q_desired, 4)
npt.assert_almost_equal(R, R_desired, 4)
if __name__ == "__main__":
unittest.main() | (Q, R) = qr_decomposition.householder_reflection(A)
Q_desired = np.array([[0.8571, -0.3943, 0.3314],
[0.4286, 0.9029, -0.0343],
[-0.2857, 0.1714, 0.9429]], dtype=np.float64) | random_line_split |
test_householder_reflection.py | """
Python unit-test
"""
import unittest
import numpy as np
import numpy.testing as npt
from .. import qr_decomposition
class TestHouseholderReflection(unittest.TestCase):
"""Test case for QR decomposition using Householder reflection."""
def test_wikipedia_example1(self):
"""Test of Wikipedia exa... | unittest.main() | conditional_block | |
test_householder_reflection.py | """
Python unit-test
"""
import unittest
import numpy as np
import numpy.testing as npt
from .. import qr_decomposition
class TestHouseholderReflection(unittest.TestCase):
"""Test case for QR decomposition using Householder reflection."""
def test_wikipedia_example1(self):
|
if __name__ == "__main__":
unittest.main()
| """Test of Wikipedia example
The example for the following QR decomposition is taken from
https://en.wikipedia.org/wiki/Qr_decomposition#Example_2.
"""
A = np.array([[12, -51, 4],
[6, 167, -68],
[-4, 24, -41]], dtype=np.float64)
(Q, ... | identifier_body |
test_householder_reflection.py | """
Python unit-test
"""
import unittest
import numpy as np
import numpy.testing as npt
from .. import qr_decomposition
class TestHouseholderReflection(unittest.TestCase):
"""Test case for QR decomposition using Householder reflection."""
def | (self):
"""Test of Wikipedia example
The example for the following QR decomposition is taken from
https://en.wikipedia.org/wiki/Qr_decomposition#Example_2.
"""
A = np.array([[12, -51, 4],
[6, 167, -68],
[-4, 24, -41]], dtype=np.float6... | test_wikipedia_example1 | identifier_name |
cmd_away.py | from twisted.plugin import IPlugin
from twisted.words.protocols import irc
from txircd.config import ConfigValidationError
from txircd.module_interface import Command, ICommand, IModuleData, ModuleData
from txircd.utils import trimStringToByteLength
from zope.interface import implementer
from typing import Any, Callabl... |
def parseParams(self, user: "IRCUser", params: List[str], prefix: str, tags: Dict[str, Optional[str]]) -> Optional[Dict[Any, Any]]:
if not params:
return {}
message = " ".join(params)
message = trimStringToByteLength(message, self.ircd.config.get("away_length", 200))
return {
"message": message
}
... | user.sendMessage(irc.RPL_UNAWAY, "You are no longer marked as being away") | conditional_block |
cmd_away.py | from twisted.plugin import IPlugin
from twisted.words.protocols import irc | from zope.interface import implementer
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
@implementer(IPlugin, IModuleData, ICommand)
class AwayCommand(ModuleData, Command):
name = "AwayCommand"
core = True
def userCommands(self) -> List[Tuple[str, int, Command]]:
return [ ("AWAY", 1, self) ]... | from txircd.config import ConfigValidationError
from txircd.module_interface import Command, ICommand, IModuleData, ModuleData
from txircd.utils import trimStringToByteLength | random_line_split |
cmd_away.py | from twisted.plugin import IPlugin
from twisted.words.protocols import irc
from txircd.config import ConfigValidationError
from txircd.module_interface import Command, ICommand, IModuleData, ModuleData
from txircd.utils import trimStringToByteLength
from zope.interface import implementer
from typing import Any, Callabl... |
def addWhois(self, user: "IRCUser", targetUser: "IRCUser") -> None:
if targetUser.metadataKeyExists("away"):
user.sendMessage(irc.RPL_AWAY, targetUser.nick, targetUser.metadataValue("away"))
def buildISupport(self, data: Dict[str, Union[str, int]]) -> None:
data["AWAYLEN"] = self.ircd.config.get("away_len... | if "targetusers" not in data:
return
for u in data["targetusers"].keys():
if u.metadataKeyExists("away"):
user.sendMessage(irc.RPL_AWAY, u.nick, u.metadataValue("away")) | identifier_body |
cmd_away.py | from twisted.plugin import IPlugin
from twisted.words.protocols import irc
from txircd.config import ConfigValidationError
from txircd.module_interface import Command, ICommand, IModuleData, ModuleData
from txircd.utils import trimStringToByteLength
from zope.interface import implementer
from typing import Any, Callabl... | (ModuleData, Command):
name = "AwayCommand"
core = True
def userCommands(self) -> List[Tuple[str, int, Command]]:
return [ ("AWAY", 1, self) ]
def actions(self) -> List[Tuple[str, int, Callable]]:
return [ ("commandextra-PRIVMSG", 10, self.notifyAway),
("commandextra-NOTICE", 10, self.notifyAway)... | AwayCommand | identifier_name |
GoogleMap.js | import React from 'react';
import { GoogleMapLoader, GoogleMap, Marker } from 'react-google-maps';
const noop = () => {};
// Wrap all `react-google-maps` components with `withGoogleMap` HOC
// and name it GettingStartedGoogleMap
const Map = ({ lat, lng, onMapLoad, marker, onMapClick = noop, containerElementProps }) ... |
Map.propTypes = {};
export default Map; | random_line_split | |
pypi.py | """PyPi blueprint."""
import os
from flask import Blueprint, current_app, g, request
blueprint = Blueprint('pypi', __name__, url_prefix='/pypi')
def register_package(localproxy):
"""Register a new package.
Creates a folder on the filesystem so a new package can be uploaded.
Arguments:
localprox... |
return 'ok'
def upload_package(localproxy):
"""Save a new package and it's md5 sum in a previously registered path.
Arguments:
localproxy (``werkzeug.local.LocalProxy``):The localproxy object is
needed to read the ``form`` properties from the request
Returns:
``'ok'``
... | os.mkdir(package_dir) | conditional_block |
pypi.py | """PyPi blueprint."""
import os
from flask import Blueprint, current_app, g, request
blueprint = Blueprint('pypi', __name__, url_prefix='/pypi')
def register_package(localproxy):
"""Register a new package.
Creates a folder on the filesystem so a new package can be uploaded.
Arguments:
localprox... | digest = localproxy.form['md5_digest']
file_path = os.path.join(current_app.config['BASEDIR'],
localproxy.form['name'].lower(),
contents.filename.lower())
contents.save(file_path)
with open('{}.md5'.format(file_path), 'w') as md5_digest:
... | Returns:
``'ok'``
"""
contents = localproxy.files['content'] | random_line_split |
pypi.py | """PyPi blueprint."""
import os
from flask import Blueprint, current_app, g, request
blueprint = Blueprint('pypi', __name__, url_prefix='/pypi')
def register_package(localproxy):
"""Register a new package.
Creates a folder on the filesystem so a new package can be uploaded.
Arguments:
localprox... | """Find a package and return the contents of it.
Upon calling this endpoint the ``PRIVATE_EGGS`` set will be updated,
and proper action will be taken based on the request.
"""
actions = {
'submit': register_package,
'file_upload': upload_package,
}
if g.database.new_egg(request.... | identifier_body | |
pypi.py | """PyPi blueprint."""
import os
from flask import Blueprint, current_app, g, request
blueprint = Blueprint('pypi', __name__, url_prefix='/pypi')
def | (localproxy):
"""Register a new package.
Creates a folder on the filesystem so a new package can be uploaded.
Arguments:
localproxy (``werkzeug.local.LocalProxy``): The localproxy object is
needed to read the ``form`` properties from the request
Returns:
``'ok'``
"""
... | register_package | identifier_name |
partnersRoutes.ts | import loadable from "@loadable/component"
import { graphql } from "react-relay"
import { AppRouteConfig } from "v2/System/Router/Route"
const GalleriesRoute = loadable(
() =>
import(/* webpackChunkName: "partnersBundle" */ "./Routes/GalleriesRoute"),
{ resolveComponent: component => component.GalleriesRouteFr... | ),
{
resolveComponent: component => component.InstitutionsRouteFragmentContainer,
}
)
export const partnersRoutes: AppRouteConfig[] = [
{
path: "/galleries",
getComponent: () => GalleriesRoute,
onClientSideRender: () => {
return GalleriesRoute.preload()
},
query: graphql`
... | () =>
import(
/* webpackChunkName: "partnersBundle" */ "./Routes/InstitutionsRoute" | random_line_split |
lib.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
#![deny(warnings)]
use anyhow::{anyhow, Error, Result};
use cloned::cloned;
use context::CoreContext;
use derived_data_manager::Derivation... |
}
}
Ok(sources)
}
});
future::try_join_all(sources_futs)
.map_ok(|unodes| unodes.into_iter().flatten().collect())
.await
}
/// Given bonsai changeset find unodes for all renames that happened in this changesest.
///
/// Returns mapping from path... | {
for to_path in to_paths {
sources.push((
to_path.clone(),
UnodeRenameSource {
parent_index,
from_path: from_path.clone(),
... | conditional_block |
lib.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
#![deny(warnings)]
use anyhow::{anyhow, Error, Result};
use cloned::cloned;
use context::CoreContext;
use derived_data_manager::Derivation... | .collect::<HashMap<_, _>>()
})
.await
});
future::try_join_all(unodes)
.map_ok(|unodes| unodes.into_iter().flatten().collect())
.await
}
#[cfg(test)]
mod tests {
use anyhow::Result;
use blobrepo::BlobRepo;
use blobstore::Loadable;
use... | .filter_map(|(from_path, unode_id)| Some((paths.remove(&from_path)?, unode_id))) | random_line_split |
lib.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
#![deny(warnings)]
use anyhow::{anyhow, Error, Result};
use cloned::cloned;
use context::CoreContext;
use derived_data_manager::Derivation... | {
/// Index of the parent changeset in the list of parents in the bonsai
/// changeset.
pub parent_index: usize,
/// Path of the file in the parent changeset (i.e., the path it was
/// renamed from).
pub from_path: MPath,
/// Unode ID of the file in the parent changeset.
pub unode_id:... | UnodeRenameSource | identifier_name |
lib.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
#![deny(warnings)]
use anyhow::{anyhow, Error, Result};
use cloned::cloned;
use context::CoreContext;
use derived_data_manager::Derivation... |
/// Given bonsai changeset find unodes for all renames that happened in this changesest.
///
/// Returns mapping from paths in current changeset to file unodes in parents changesets
/// that were coppied to a given path.
///
/// This version of the function is incorrect: it fails to take into account
/// files that a... | {
// Collect together a map of (source_path -> [dest_paths]) for each parent
// changeset.
let mut references: HashMap<ChangesetId, HashMap<&MPath, Vec<&MPath>>> = HashMap::new();
for (to_path, file_change) in bonsai.file_changes() {
if let Some((from_path, csid)) = file_change.copy_from() {
... | identifier_body |
seventeen.rs | use std::string::ToString;
fn singler<'a>(digit: u32) -> &'a str {
match digit {
0 => "zero",
1 => "one",
2 => "two",
3 => "three",
4 => "four",
5 => "five",
6 => "six",
7 => "seven",
8 => "eight",
9 => "nine",
_ => "",
}
}
fn twentor<'a>(num: u32) -> &'a str {
matc... | }
fn thouse(num: u32) -> String {
match num {
0...99 => hunnert(num).to_string(),
100 => "one hundred".to_string(),
101...199 => format!("one hundred and {}", hunnert(num % 100)),
200 => "two hundred".to_string(),
201...299 => format!("two hundred and {}", hunnert(num % 100)),
... | 81...89 => format!("eighty-{}", singler(num % 80)),
90 => "ninety".to_string(),
91...99 => format!("ninety-{}", singler(num % 90)),
_ => "".to_string(),
} | random_line_split |
seventeen.rs | use std::string::ToString;
fn singler<'a>(digit: u32) -> &'a str {
match digit {
0 => "zero",
1 => "one",
2 => "two",
3 => "three",
4 => "four",
5 => "five",
6 => "six",
7 => "seven",
8 => "eight",
9 => "nine",
_ => "",
}
}
fn twentor<'a>(num: u32) -> &'a str |
fn hunnert<'a>(num: u32) -> String {
match num {
0...19 => twentor(num).to_string(),
20 => "twenty".to_string(),
21...29 => format!("twenty-{}", singler(num % 20)),
30 => "thirty".to_string(),
31...39 => format!("thirty-{}", singler(num % 30)),
40 => "forty".to_string(),
... | {
match num {
0...9 => singler(num),
10 => "ten",
11 => "eleven",
12 => "twelve",
13 => "thirteen",
14 => "fourteen",
15 => "fifteen",
16 => "sixteen",
17 => "seventeen",
18 => "eighteen",
19 => "nineteen",
_ => "",
}
} | identifier_body |
seventeen.rs | use std::string::ToString;
fn singler<'a>(digit: u32) -> &'a str {
match digit {
0 => "zero",
1 => "one",
2 => "two",
3 => "three",
4 => "four",
5 => "five",
6 => "six",
7 => "seven",
8 => "eight",
9 => "nine",
_ => "",
}
}
fn twentor<'a>(num: u32) -> &'a str {
matc... | (s: String) -> u32 {
s.chars().fold(0, |memo, ch| {
memo + match ch {
'a'...'z' => 1,
_ => 0,
}
})
}
pub fn run() {
let sum: u32 = (1..1001).map(|i| count(thouse(i))).sum();
println!("Sum of number words: {}", sum);
} | count | identifier_name |
test_views.py | """
Tests for django-registration's built-in views.
"""
from django.core.urlresolvers import reverse
from django.test import override_settings, TestCase
from ..models import RegistrationProfile
@override_settings(ROOT_URLCONF='registration.tests.urls')
class ActivationViewTests(TestCase):
"""
Tests for asp... | """
Activation of an account functions properly when using a
simple string URL as the success redirect.
"""
data = {
'username': 'bob',
'email': 'bob@example.com',
'password1': 'secret',
'password2': 'secret'
}
resp = self.... | identifier_body | |
test_views.py | """
Tests for django-registration's built-in views.
"""
from django.core.urlresolvers import reverse
from django.test import override_settings, TestCase
from ..models import RegistrationProfile
@override_settings(ROOT_URLCONF='registration.tests.urls')
class ActivationViewTests(TestCase):
"""
Tests for asp... | 'registration_activate',
args=(),
kwargs={'activation_key': profile.activation_key}
)
)
self.assertRedirects(resp, '/') | resp = self.client.get(
reverse( | random_line_split |
test_views.py | """
Tests for django-registration's built-in views.
"""
from django.core.urlresolvers import reverse
from django.test import override_settings, TestCase
from ..models import RegistrationProfile
@override_settings(ROOT_URLCONF='registration.tests.urls')
class | (TestCase):
"""
Tests for aspects of the activation view not currently exercised
by any built-in workflow.
"""
@override_settings(ACCOUNT_ACTIVATION_DAYS=7)
def test_activation(self):
"""
Activation of an account functions properly when using a
simple string URL as t... | ActivationViewTests | identifier_name |
error.tsx | import React, { FunctionComponent } from "react"
import path from "path"
import { Box, Text } from "ink"
import { IStructuredError } from "../../../../structured-errors/types"
interface IFileProps {
filePath: string
location: IStructuredError["location"]
}
const File: FunctionComponent<IFileProps> = ({ filePath, ... | locString += `:${columnNumber}`
}
}
return (
<Text color="blue">
{path.relative(process.cwd(), filePath)}
{locString}
</Text>
)
}
interface IDocsLinkProps {
docsUrl: string | undefined
}
const DocsLink: FunctionComponent<IDocsLinkProps> = ({ docsUrl }) => {
// TODO: when there... | if (typeof columnNumber !== `undefined`) { | random_line_split |
error.tsx | import React, { FunctionComponent } from "react"
import path from "path"
import { Box, Text } from "ink"
import { IStructuredError } from "../../../../structured-errors/types"
interface IFileProps {
filePath: string
location: IStructuredError["location"]
}
const File: FunctionComponent<IFileProps> = ({ filePath, ... |
return (
<Text color="blue">
{path.relative(process.cwd(), filePath)}
{locString}
</Text>
)
}
interface IDocsLinkProps {
docsUrl: string | undefined
}
const DocsLink: FunctionComponent<IDocsLinkProps> = ({ docsUrl }) => {
// TODO: when there's no specific docsUrl, add helpful message des... | {
locString += `:${lineNumber}`
const columnNumber = location?.start.column
if (typeof columnNumber !== `undefined`) {
locString += `:${columnNumber}`
}
} | conditional_block |
post_anju.py | #!/usr/bin/env python
#-*- coding:utf-8 -*-
from poster.encode import multipart_encode
from poster.streaminghttp import register_openers
import urllib2,urllib,sys,time
import cookielib,mechanize
import re
DEBUG =0
reload(sys)
sys.setdefaultencoding('utf8') #@UndefinedVariable
register_openers()
headers = {
... |
return res
#aQQ_ajklastuser junyue_liuhua
#print self.opener.open('http://my.anjuke.com/v2/user/broker/checked/').read()
#open('login.txt','w').write(r.read().encode('utf-8'))
def post(self):
pass
#postData = {}
#postData['loginUrl... | if item.name == 'aQQ_ajklastuser':
res = item.value | conditional_block |
post_anju.py | #!/usr/bin/env python
#-*- coding:utf-8 -*-
from poster.encode import multipart_encode
from poster.streaminghttp import register_openers
import urllib2,urllib,sys,time
import cookielib,mechanize
import re
DEBUG =0
reload(sys)
sys.setdefaultencoding('utf8') #@UndefinedVariable
register_openers()
headers = {
... | (self,dataDic):
self.cookie = cookielib.CookieJar()
httpsHandler = urllib2.HTTPHandler()
httpsHandler.set_http_debuglevel(DEBUG)
self.opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(self.cookie),httpsHandler)
self.data = dataDic... | __init__ | identifier_name |
post_anju.py | #!/usr/bin/env python
#-*- coding:utf-8 -*-
from poster.encode import multipart_encode
from poster.streaminghttp import register_openers
import urllib2,urllib,sys,time
import cookielib,mechanize
import re
DEBUG =0
reload(sys)
sys.setdefaultencoding('utf8') #@UndefinedVariable
register_openers()
headers = {
... | response = mechanize.urlopen(loginUrl)
print response.read().decode('gb2312')
def login(self):
self.cookie = cookielib.CookieJar()
httpsHandler = urllib2.HTTPHandler()
httpsHandler.set_http_debuglevel(DEBUG)
self.opener = urllib2.buil... | login['name'] = self.data['name']
login['pwd'] = self.data['pwd']
loginUrl = self.data['loginUrl']+'?'+urllib.urlencode(login)
print loginUrl
response = mechanize.urlopen("http://esf.soufun.com/") | random_line_split |
post_anju.py | #!/usr/bin/env python
#-*- coding:utf-8 -*-
from poster.encode import multipart_encode
from poster.streaminghttp import register_openers
import urllib2,urllib,sys,time
import cookielib,mechanize
import re
DEBUG =0
reload(sys)
sys.setdefaultencoding('utf8') #@UndefinedVariable
register_openers()
headers = {
... |
def login(self):
self.cookie = cookielib.CookieJar()
httpsHandler = urllib2.HTTPHandler()
httpsHandler.set_http_debuglevel(DEBUG)
self.opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(self.cookie),httpsHandler)
login={}
logi... | self.brow = mechanize.Browser()
httpHandler = mechanize.HTTPHandler()
httpsHandler = mechanize.HTTPSHandler()
httpHandler.set_http_debuglevel(DEBUG)
self.cookiejar = mechanize.LWPCookieJar()
#self.cookiejar = "Cookie lzstat_uv=34741959842666604402|1786789; Hm... | identifier_body |
flash.py | """
"Flash" messaging support.
A "flash" message is a message displayed on a web page that is removed next
request.
"""
__all__ = ['add_message', 'get_messages', 'get_flash',
'flash_middleware_factory']
import itertools
import webob
from wsgiapptools import cookies
ENVIRON_KEY = 'wsgiapptools.flash'
C... | (environ, message, type=None):
"""
Add the flash message to the Flash manager in the WSGI environ."
"""
return get_flash(environ).add_message(message, type)
def get_messages(environ):
"""
Get the flasg messages from the Flash manager in the WSGI environ.
"""
return get_flash(environ).g... | add_message | identifier_name |
flash.py | """
"Flash" messaging support.
A "flash" message is a message displayed on a web page that is removed next
request.
"""
__all__ = ['add_message', 'get_messages', 'get_flash',
'flash_middleware_factory']
import itertools
import webob
from wsgiapptools import cookies
ENVIRON_KEY = 'wsgiapptools.flash'
C... |
# Remove the cookie, presumably it will be displayed shortly.
cookies_mgr.delete_cookie(cookie_name)
# Parse and yield the message.
try:
type, message = message.split(':', 1)
except ValueError:
# Skip an unparseable cookie val... | break | conditional_block |
flash.py | """
"Flash" messaging support.
A "flash" message is a message displayed on a web page that is removed next
request.
"""
__all__ = ['add_message', 'get_messages', 'get_flash',
'flash_middleware_factory']
import itertools
import webob
from wsgiapptools import cookies
ENVIRON_KEY = 'wsgiapptools.flash'
C... |
class Flash(object):
"""
Flash message manager, associated with a WSGI environ.
"""
def __init__(self, environ):
self.request = webob.Request(environ)
self.flashes = []
def add_message(self, message, type=None):
"""
Add a new flash message.
Note: this can... | """
return environ[ENVIRON_KEY] | random_line_split |
flash.py | """
"Flash" messaging support.
A "flash" message is a message displayed on a web page that is removed next
request.
"""
__all__ = ['add_message', 'get_messages', 'get_flash',
'flash_middleware_factory']
import itertools
import webob
from wsgiapptools import cookies
ENVIRON_KEY = 'wsgiapptools.flash'
C... |
def flash_middleware_factory(app):
"""
Create a flash middleware WSGI application around the given WSGI
application.
"""
def middleware(environ, start_response):
def _start_response(status, response_headers, exc_info=None):
# Iterate the new flash messages in the WSGI, setting... | """
Flash message manager, associated with a WSGI environ.
"""
def __init__(self, environ):
self.request = webob.Request(environ)
self.flashes = []
def add_message(self, message, type=None):
"""
Add a new flash message.
Note: this can be called multiple times t... | identifier_body |
build.rs | // Copyright 2016 Joe Wilm, The Alacritty Project Contributors
//
// 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 b... | use std::fs::File;
use std::path::Path;
fn main() {
let dest = env::var("OUT_DIR").unwrap();
let mut file = File::create(&Path::new(&dest).join("gl_bindings.rs")).unwrap();
Registry::new(Api::Gl, (4, 5), Profile::Core, Fallbacks::All, [
"GL_ARB_blend_func_extended"
])
.write_bi... | use std::env; | random_line_split |
build.rs | // Copyright 2016 Joe Wilm, The Alacritty Project Contributors
//
// 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 b... | {
let dest = env::var("OUT_DIR").unwrap();
let mut file = File::create(&Path::new(&dest).join("gl_bindings.rs")).unwrap();
Registry::new(Api::Gl, (4, 5), Profile::Core, Fallbacks::All, [
"GL_ARB_blend_func_extended"
])
.write_bindings(GlobalGenerator, &mut file)
.unwrap(... | identifier_body | |
build.rs | // Copyright 2016 Joe Wilm, The Alacritty Project Contributors
//
// 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 b... | () {
let dest = env::var("OUT_DIR").unwrap();
let mut file = File::create(&Path::new(&dest).join("gl_bindings.rs")).unwrap();
Registry::new(Api::Gl, (4, 5), Profile::Core, Fallbacks::All, [
"GL_ARB_blend_func_extended"
])
.write_bindings(GlobalGenerator, &mut file)
.unwr... | main | identifier_name |
reducer.ts | import { defaultBucketAgg } from '../../../../query_def';
import { ElasticsearchQuery } from '../../../../types';
import { metricAggregationConfig } from '../../MetricAggregationsEditor/utils';
import { BucketAggregation, Terms } from '../aggregations';
import { initQuery } from '../../state';
import { bucketAggregatio... | return state!.filter((bucketAgg) => bucketAgg.id !== action.payload);
}
if (changeBucketAggregationType.match(action)) {
return state!.map((bucketAgg) => {
if (bucketAgg.id !== action.payload.id) {
return bucketAgg;
}
/*
TODO: The previous version of the q... |
if (removeBucketAggregation.match(action)) { | random_line_split |
reducer.ts | import { defaultBucketAgg } from '../../../../query_def';
import { ElasticsearchQuery } from '../../../../types';
import { metricAggregationConfig } from '../../MetricAggregationsEditor/utils';
import { BucketAggregation, Terms } from '../aggregations';
import { initQuery } from '../../state';
import { bucketAggregatio... |
const newSettings = removeEmpty({
...bucketAgg.settings,
[action.payload.settingName]: action.payload.newValue,
});
return {
...bucketAgg,
settings: {
...newSettings,
},
};
});
}
if (initQuery.match(action)) ... | {
return bucketAgg;
} | conditional_block |
make_new_database.py | __author__ = 'austin'
import dataset
import os
import time
import sys
def | (new_database_name, media_folder):
file_ext = (".mp4", ".avi", ".flv", ".wmv", ".mpg", ".mov", ".mkv", ".mpeg")
start_time = time.time() # FOR TESTING ... start time
db = dataset.connect('sqlite:///{}.vdb'.format(new_database_name))
table = db[new_database_name]
for root, dirs, files in os.walk(m... | make_new_database | identifier_name |
make_new_database.py | __author__ = 'austin'
import dataset
import os
import time
import sys
def make_new_database(new_database_name, media_folder):
file_ext = (".mp4", ".avi", ".flv", ".wmv", ".mpg", ".mov", ".mkv", ".mpeg")
start_time = time.time() # FOR TESTING ... start time
db = dataset.connect('sqlite:///{}.vdb'.forma... |
else:
pass
end_time = time.time()
print("{} files in {} seconds".format(len(db[new_database_name]), end_time - start_time))
exit(0) # TODO need to specify different exit codes on different errors, so we can handle these errors
def main():
new_database_name = sys.argv[1]
... | if table.find_one(title=file[:-4]) is None:
table.insert(dict(title=file[:-4],
location=(root + '/' + file),
genre='none',
length='none',
ispresent=... | conditional_block |
make_new_database.py | __author__ = 'austin'
import dataset
import os
import time
import sys
def make_new_database(new_database_name, media_folder):
|
def main():
new_database_name = sys.argv[1]
media_folder = sys.argv[2]
make_new_database(new_database_name, media_folder)
if __name__ == "__main__":
main() | file_ext = (".mp4", ".avi", ".flv", ".wmv", ".mpg", ".mov", ".mkv", ".mpeg")
start_time = time.time() # FOR TESTING ... start time
db = dataset.connect('sqlite:///{}.vdb'.format(new_database_name))
table = db[new_database_name]
for root, dirs, files in os.walk(media_folder):
for file in files... | identifier_body |
make_new_database.py | __author__ = 'austin'
import dataset
import os
import time
import sys
def make_new_database(new_database_name, media_folder):
file_ext = (".mp4", ".avi", ".flv", ".wmv", ".mpg", ".mov", ".mkv", ".mpeg")
start_time = time.time() # FOR TESTING ... start time
db = dataset.connect('sqlite:///{}.vdb'.forma... | location=(root + '/' + file),
genre='none',
length='none',
ispresent=True))
print(root + '/' + file)
else:
pass
... | for root, dirs, files in os.walk(media_folder):
for file in files:
if file.endswith(file_ext):
if table.find_one(title=file[:-4]) is None:
table.insert(dict(title=file[:-4], | random_line_split |
cryptotestutils.d.ts | /**
* @license
* Copyright 2019 Google LLC.
* This code may only be used under the BSD style license found at
* http://polymer.github.io/LICENSE.txt
* Code distributed by Google as part of this project is also
* subject to an additional IP rights grant found at | import { KeyStorage } from '../manager.js';
export interface TestableKey {
encrypt(buffer: ArrayBuffer, iv: Uint8Array): PromiseLike<ArrayBuffer>;
decrypt(buffer: ArrayBuffer, iv: Uint8Array): PromiseLike<ArrayBuffer>;
}
/**
* Implementation of KeyStorage using a Map, used for testing only.
*/
export declare ... | * http://polymer.github.io/PATENTS.txt
*/
import { DeviceKey, Key, WrappedKey } from '../keys.js'; | random_line_split |
cryptotestutils.d.ts | /**
* @license
* Copyright 2019 Google LLC.
* This code may only be used under the BSD style license found at
* http://polymer.github.io/LICENSE.txt
* Code distributed by Google as part of this project is also
* subject to an additional IP rights grant found at
* http://polymer.github.io/PATENTS.txt
*/
import {... | implements KeyStorage {
storageMap: Map<string, Key>;
constructor();
find(keyFingerPrint: string): PromiseLike<Key | null>;
write(keyFingerprint: string, key: DeviceKey | WrappedKey): Promise<string>;
static getInstance(): WebCryptoMemoryKeyStorage;
}
| WebCryptoMemoryKeyStorage | identifier_name |
blob_storage.rs | use services::blob_storage::BlobStorageService;
use std::rc::Rc;
use errors::prelude::*;
pub enum BlobStorageCommand {
OpenReader(
String, // type
String, // config
Box<Fn(IndyResult<i32 /* handle */>) + Send>), | Box<Fn(IndyResult<i32 /* handle */>) + Send>),
}
pub struct BlobStorageCommandExecutor {
blob_storage_service: Rc<BlobStorageService>
}
impl BlobStorageCommandExecutor {
pub fn new(blob_storage_service: Rc<BlobStorageService>) -> BlobStorageCommandExecutor {
BlobStorageCommandExecutor {
... | OpenWriter(
String, // writer type
String, // writer config JSON | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.