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 |
|---|---|---|---|---|
entry_with_else.rs | // run-rustfix
#![allow(unused, clippy::needless_pass_by_value, clippy::collapsible_if)]
#![warn(clippy::map_entry)]
use std::collections::{BTreeMap, HashMap};
use std::hash::Hash;
macro_rules! m {
($e:expr) => {{ $e }};
}
fn foo() {}
fn insert_if_absent0<K: Eq + Hash + Copy, V: Copy>(m: &mut HashMap<K, V>, k:... | else { m.insert(k, v2) }
} else {
m.insert(k, v)
};
if m.contains_key(&k) {
foo();
m.insert(k, v)
} else {
None
};
}
fn main() {}
| { m.insert(k, v) } | conditional_block |
week.js | import "day";
import "interval";
import "time"; | d3_time_daySymbols.forEach(function(day, i) {
day = day.toLowerCase();
i = 7 - i;
var interval = d3.time[day] = d3_time_interval(function(date) {
(date = d3.time.day(date)).setDate(date.getDate() - (date.getDay() + i) % 7);
return date;
}, function(date, offset) {
date.setDate(date.getDate() + Math... | import "year";
| random_line_split |
Hotel.view.js | import React from 'react'
import {observer} from 'mobx-react'
import {Route, Link} from 'react-router-dom' | import './hotel.less'
export default observer(
(props) => (
<div className="hotel-container">
<div className="banner-container">
<div className="colllect">
{Cookies.get(TOKEN)? props.store.isFavorite == 1? <i className="iconfont btn-colllect icon-hotle_icon_like1" /> : <i className="iconf... | import {IMAGE_DIR, TOKEN, GET_HOTEL_INFO, RESPONSE_CODE_SUCCESS} from 'macros'
import {setParamsToURL, dateToZh} from 'utils'
import Cookies from 'js-cookie'
import WeiXinShareTips from 'WeiXinShareTips' | random_line_split |
pydfu.py | :
raise ValueError("Multiple DFU devices found")
__dev = devices[0]
__dev.set_configuration()
# Claim DFU interface
usb.util.claim_interface(__dev, __DFU_INTERFACE)
# Find the DFU configuration descriptor, either in the device or interfaces
__cfg_descr = None
for cfg in __dev.confi... |
def cstring(string):
"""Extracts a null-terminated string from a byte array."""
return string.decode("utf-8").split("\0", 1)[0]
def compute_crc(data):
"""Computes the CRC32 value for the data passed in."""
return 0xFFFFFFFF & -zlib.crc32(data) - 1
def read_dfu_file(filename):
"""Reads a DFU f... | """Parses the struct defined by `fmt` from `data`, stores the parsed fields
into a named tuple using `names`. Returns the named tuple, and the data
with the struct stripped off."""
size = struct.calcsize(fmt)
return named(struct.unpack(fmt, data[:size]), names), data[size:] | identifier_body |
pydfu.py | raise ValueError("Multiple DFU devices found")
__dev = devices[0]
__dev.set_configuration()
# Claim DFU interface
usb.util.claim_interface(__dev, __DFU_INTERFACE)
# Find the DFU configuration descriptor, either in the device or interfaces
__cfg_descr = None
for cfg in __dev.configu... | (buf, xfer_offset):
"""Writes a single page. This routine assumes that memory has already
been erased.
"""
xfer_base = 0x08000000
# Set mem write address
set_address(xfer_base + xfer_offset)
# Send DNLOAD with fw data
__dev.ctrl_transfer(0x21, __DFU_DNLOAD, 2, __DFU_INTERFACE, buf, __... | write_page | identifier_name |
pydfu.py | devices = get_dfu_devices(**kwargs)
if not devices:
raise ValueError("No DFU device found")
if len(devices) > 1:
raise ValueError("Multiple DFU devices found")
__dev = devices[0]
__dev.set_configuration()
# Claim DFU interface
usb.util.claim_interface(__dev, __DFU_INTERFACE)... |
def init(**kwargs):
"""Initializes the found DFU device so that we can program it."""
global __dev, __cfg_descr | random_line_split | |
pydfu.py | raise ValueError("Multiple DFU devices found")
__dev = devices[0]
__dev.set_configuration()
# Claim DFU interface
usb.util.claim_interface(__dev, __DFU_INTERFACE)
# Find the DFU configuration descriptor, either in the device or interfaces
__cfg_descr = None
for cfg in __dev.configu... |
def exit_dfu():
"""Exit DFU mode, and start running the program."""
# Set jump address
set_address(0x08000000)
# Send DNLOAD with 0 length to exit DFU
__dev.ctrl_transfer(0x21, __DFU_DNLOAD, 0, __DFU_INTERFACE, None, __TIMEOUT)
try:
# Execute last command
if get_status() != ... | print("Write: 0x%x " % (xfer_base + xfer_offset)) | conditional_block |
regions-bound-missing-bound-in-impl.rs | // Copyright 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-MIT or ... | () { }
| main | identifier_name |
regions-bound-missing-bound-in-impl.rs | // Copyright 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-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Check that expli... | random_line_split | |
regions-bound-missing-bound-in-impl.rs | // Copyright 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-MIT or ... |
fn wrong_bound2<'b,'c,'e:'b+'c>(self, b: Inv<'b>, c: Inv<'c>, e: Inv<'e>) {
//~^ ERROR distinct set of bounds from its counterpart
}
}
fn main() { }
| {
//~^ ERROR method `wrong_bound1` has an incompatible type for trait
//
// Note: This is a terrible error message. It is caused
// because, in the trait, 'b is early bound, and in the impl,
// 'c is early bound, so -- after substitution -- the
// lifetimes themselves loo... | identifier_body |
future_ext.rs | // Copyright 2021 TiKV Project Authors. Licensed under Apache-2.0.
use crate::ResourceMeteringTag;
use std::pin::Pin;
use std::task::{Context, Poll};
#[pin_project::pin_project]
pub struct InTags<T> {
#[pin]
inner: T,
tag: ResourceMeteringTag,
}
impl<T: std::future::Future> FutureExt for T {}
pub trait... |
}
impl<T: std::future::Future> std::future::Future for InTags<T> {
type Output = T::Output;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let this = self.project();
let _guard = this.tag.attach();
this.inner.poll(cx)
}
}
impl<T: futures::Stream> Stre... | {
InTags { inner: self, tag }
} | identifier_body |
future_ext.rs | // Copyright 2021 TiKV Project Authors. Licensed under Apache-2.0.
use crate::ResourceMeteringTag;
use std::pin::Pin;
use std::task::{Context, Poll};
#[pin_project::pin_project]
pub struct InTags<T> {
#[pin]
inner: T,
tag: ResourceMeteringTag,
}
impl<T: std::future::Future> FutureExt for T {}
pub trait... | }
} | let this = self.project();
let _guard = this.tag.attach();
this.inner.poll_next(cx) | random_line_split |
future_ext.rs | // Copyright 2021 TiKV Project Authors. Licensed under Apache-2.0.
use crate::ResourceMeteringTag;
use std::pin::Pin;
use std::task::{Context, Poll};
#[pin_project::pin_project]
pub struct InTags<T> {
#[pin]
inner: T,
tag: ResourceMeteringTag,
}
impl<T: std::future::Future> FutureExt for T {}
pub trait... | (self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
let this = self.project();
let _guard = this.tag.attach();
this.inner.poll_next(cx)
}
}
| poll_next | identifier_name |
panel.py | # Copyright 2012 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Copyright 2012 Nebula, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the... | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from django.utils.translation import ugettext_lazy as _
import horizon
from openstack_dashboard.dashboards.admin import dashboard
class ... | #
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT | random_line_split |
panel.py | # Copyright 2012 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Copyright 2012 Nebula, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the... | (horizon.Panel):
name = _("Users")
slug = 'users'
dashboard.Admin.register(Users)
| Users | identifier_name |
panel.py | # Copyright 2012 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Copyright 2012 Nebula, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the... |
dashboard.Admin.register(Users)
| name = _("Users")
slug = 'users' | identifier_body |
mod.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... | pub use self::transaction::Transaction;
pub use self::txtest::TransactionTest;
pub use self::test::Test; |
mod transaction;
mod txtest;
mod test;
| random_line_split |
ListAddField.tsx | import classnames from 'classnames';
import cloneDeep from 'lodash/cloneDeep';
import React from 'react';
import {
HTMLFieldProps,
connectField,
filterDOMProps,
joinName,
useField,
} from 'uniforms';
export type ListAddFieldProps = HTMLFieldProps<
unknown, | HTMLSpanElement,
{ initialCount?: number }
>;
function ListAdd({
disabled,
initialCount,
name,
readOnly,
value,
...props
}: ListAddFieldProps) {
const nameParts = joinName(null, name);
const parentName = joinName(nameParts.slice(0, -1));
const parent = useField<
{ initialCount?: number; maxCo... | random_line_split | |
ListAddField.tsx | import classnames from 'classnames';
import cloneDeep from 'lodash/cloneDeep';
import React from 'react';
import {
HTMLFieldProps,
connectField,
filterDOMProps,
joinName,
useField,
} from 'uniforms';
export type ListAddFieldProps = HTMLFieldProps<
unknown,
HTMLSpanElement,
{ initialCount?: number }
>;
... |
}
return (
<i
{...filterDOMProps(props)}
className={classnames(
'ui',
props.className,
limitNotReached ? 'link' : 'disabled',
'fitted add icon',
)}
onClick={onAction}
onKeyDown={onAction}
role="button"
tabIndex={0}
/>
);
}
export... | {
parent.onChange(parent.value!.concat([cloneDeep(value)]));
} | conditional_block |
ListAddField.tsx | import classnames from 'classnames';
import cloneDeep from 'lodash/cloneDeep';
import React from 'react';
import {
HTMLFieldProps,
connectField,
filterDOMProps,
joinName,
useField,
} from 'uniforms';
export type ListAddFieldProps = HTMLFieldProps<
unknown,
HTMLSpanElement,
{ initialCount?: number }
>;
... | (event: React.KeyboardEvent | React.MouseEvent) {
if (
limitNotReached &&
!readOnly &&
(!('key' in event) || event.key === 'Enter')
) {
parent.onChange(parent.value!.concat([cloneDeep(value)]));
}
}
return (
<i
{...filterDOMProps(props)}
className={classnames(
... | onAction | identifier_name |
ListAddField.tsx | import classnames from 'classnames';
import cloneDeep from 'lodash/cloneDeep';
import React from 'react';
import {
HTMLFieldProps,
connectField,
filterDOMProps,
joinName,
useField,
} from 'uniforms';
export type ListAddFieldProps = HTMLFieldProps<
unknown,
HTMLSpanElement,
{ initialCount?: number }
>;
... |
return (
<i
{...filterDOMProps(props)}
className={classnames(
'ui',
props.className,
limitNotReached ? 'link' : 'disabled',
'fitted add icon',
)}
onClick={onAction}
onKeyDown={onAction}
role="button"
tabIndex={0}
/>
);
}
export def... | {
if (
limitNotReached &&
!readOnly &&
(!('key' in event) || event.key === 'Enter')
) {
parent.onChange(parent.value!.concat([cloneDeep(value)]));
}
} | identifier_body |
lib.rs | // This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
//! This module is the main module for the Ligature-SQLite project.
//! It implements the traits supplied by Ligature... |
fn new_memory_store() -> LigatureSQLite {
todo!()
}
}
impl Ligature for LigatureSQLite {
fn all_datasets(&self) -> Box<dyn Iterator<Item=Result<Dataset, LigatureError>>> {
todo!()
}
fn dataset_exists(&self, dataset: &Dataset) -> Result<bool, LigatureError> {
todo!()
}... | {
todo!()
} | identifier_body |
lib.rs | // This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
//! This module is the main module for the Ligature-SQLite project.
//! It implements the traits supplied by Ligature... | (&self, dataset: &Dataset) -> Result<(), LigatureError> {
todo!()
}
fn delete_dataset(&self, dataset: &Dataset) -> Result<(), LigatureError> {
todo!()
}
fn query<T>(&self, dataset: &Dataset, f: QueryFn<T>) -> Result<T, LigatureError> {
todo!()
}
fn write<T>(&self, data... | create_dataset | identifier_name |
lib.rs | // This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
//! This module is the main module for the Ligature-SQLite project.
//! It implements the traits supplied by Ligature... | }
fn dataset_exists(&self, dataset: &Dataset) -> Result<bool, LigatureError> {
todo!()
}
fn match_datasets_prefix(&self, prefix: &str) -> Box<dyn Iterator<Item=Result<Dataset, LigatureError>>> {
todo!()
}
fn match_datasets_range(&self, start: &str, end: &str) -> Box<dyn Iterat... |
impl Ligature for LigatureSQLite {
fn all_datasets(&self) -> Box<dyn Iterator<Item=Result<Dataset, LigatureError>>> {
todo!() | random_line_split |
bans.py | #!/usr/bin/python
# This file is part of Morse.
#
# Morse is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Morse ... |
return self.time_left.days
@property
def hours_left (self):
""" an integer that signifies the number of hours
left to serve (only possible on limited bans)
!!! this attribute DOES NOT signify the absolute
number of hours left, but rather the numbers of
hours l... | raise TypeError("this method is not available on permanent bans") | conditional_block |
bans.py | #!/usr/bin/python
# This file is part of Morse.
#
# Morse is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Morse ... | self.expiration_date = datetime.now() + self.duration
def applies_to (self, board):
""" signifies whether a ban applies to a certain board """
affected = self.affected_board_ids
return board.id in affected
@property
def affected_boards (self):
""" a... | self.duration = timedelta(days = duration_in_days) | random_line_split |
bans.py | #!/usr/bin/python
# This file is part of Morse.
#
# Morse is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Morse ... | (Ban):
""" model for IP bans """
__tablename__ = "ip_bans"
ip_range = db.Column(db.String)
def __init__ (self, ip_range, reason, duration_in_days = None):
Ban.__init__(self, reason, duration_in_days)
self.ip_range = ip_range
@property
def affected_ips (self):
""" us... | IPBan | identifier_name |
bans.py | #!/usr/bin/python
# This file is part of Morse.
#
# Morse is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Morse ... | self.board_id = board_id
self.ban_id = ban_id | identifier_body | |
main.rs | #[macro_use]
extern crate clap;
extern crate rouille;
extern crate filetime;
extern crate time;
use std::path::Path;
use clap::{App, Arg, AppSettings};
use rouille::*;
fn | () {
let m = App::new("servent")
.author(crate_authors!())
.version(crate_version!())
.about(env!("CARGO_PKG_DESCRIPTION"))
.setting(AppSettings::ColoredHelp)
.arg(
Arg::with_name("addr")
.help("Address the server will bind to (e.g. 127.0.0.1:3000)... | main | identifier_name |
main.rs | #[macro_use]
extern crate clap;
extern crate rouille;
extern crate filetime;
extern crate time;
use std::path::Path;
use clap::{App, Arg, AppSettings};
use rouille::*;
fn main() {
let m = App::new("servent")
.author(crate_authors!())
.version(crate_version!())
.about(env!("CARGO_PKG_DESCRI... | if !potential_file.starts_with(path) {
return Response::empty_404();
}
match fs::metadata(&potential_file) {
Ok(ref m) if m.is_file() => (),
Ok(ref m) if m.is_dir() => potential_file = potential_file.join("index.html"),
_ => return Response::empty_404(),
};
let exte... | {
let path = path.as_ref();
let path = match path.canonicalize() {
Ok(p) => p,
Err(_) => return Response::empty_404(),
};
let potential_file = {
let mut path = path.to_path_buf();
for component in req.url().split('/') {
path.push(component);
}
... | identifier_body |
main.rs | #[macro_use]
extern crate clap;
extern crate rouille;
extern crate filetime;
extern crate time;
use std::path::Path;
use clap::{App, Arg, AppSettings};
use rouille::*;
fn main() {
let m = App::new("servent")
.author(crate_authors!())
.version(crate_version!())
.about(env!("CARGO_PKG_DESCRI... | // Code below is a modified version of `rouille::match_assets`
fn handle<P: AsRef<Path>>(req: &Request, path: &P) -> Response{
let path = path.as_ref();
let path = match path.canonicalize() {
Ok(p) => p,
Err(_) => return Response::empty_404(),
};
let potential_file = {
let mut p... |
use std::fs;
| random_line_split |
guidebox_getid.js | (function(env){
"use strict";
env.ddg_spice_guidebox_getid = function(api_result) {
if (!api_result || !api_result.results) {
return Spice.failed('guidebox');
}
var SKIP_ARRAY = ["online","tv","episode","episodes","free","guidebox","watch","full"],
results = a... |
// Prevent jQuery from appending "_={timestamp}" in our url.
$.ajaxSetup({
cache: true
});
var metadata = {
res_title : relevant.title,
network : relevant.network,
more : relevant.url
};
var url = '/js/spice/guidebox/las... | {
return;
} | conditional_block |
guidebox_getid.js | (function(env){
"use strict";
env.ddg_spice_guidebox_getid = function(api_result) {
if (!api_result || !api_result.results) {
return Spice.failed('guidebox');
}
var SKIP_ARRAY = ["online","tv","episode","episodes","free","guidebox","watch","full"],
results = a... |
Handlebars.registerHelper("guideBox_getDate", function(first_aired) {
var aired = DDG.getDateFromString(first_aired),
days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'],
months = [ 'January','February','March','April','May','June','July','August','September','... | {
var result = [];
if($.isArray(obj)) {
return obj;
} else {
$.each(obj, function(key, value) {
result[key] = value;
});
return result;
}
} | identifier_body |
guidebox_getid.js | (function(env){
"use strict";
env.ddg_spice_guidebox_getid = function(api_result) {
if (!api_result || !api_result.results) {
return Spice.failed('guidebox');
}
var SKIP_ARRAY = ["online","tv","episode","episodes","free","guidebox","watch","full"],
results = a... | (obj) {
var result = [];
if($.isArray(obj)) {
return obj;
} else {
$.each(obj, function(key, value) {
result[key] = value;
});
return result;
}
}
Handlebars.registerHelper("guideBox_getDate", function(first_aired) {... | toArray | identifier_name |
guidebox_getid.js | (function(env){ | }
var SKIP_ARRAY = ["online","tv","episode","episodes","free","guidebox","watch","full"],
results = api_result.results.result,
relevant;
// Check which show is relevant to our query.
$.each(results, function(key, result) {
if (DDG.isRelevant(result.... | "use strict";
env.ddg_spice_guidebox_getid = function(api_result) {
if (!api_result || !api_result.results) {
return Spice.failed('guidebox'); | random_line_split |
announcements.server.controller.js | 'use strict';
var mongoose = require('mongoose'),
Announcements = mongoose.model('Announcements'),
Users = mongoose.model('User'),
_ = require('lodash');
exports.create = function (req, res) {
//create a new announcement
var announcement = new Announcements(req.body);
announcement.save(function(err) ... | } else if(!announcement){
return res.status(404).send({
message:'No announcement with that id was found'
});
}
req.announcement = announcement;
next();
});
};
exports.update = function(req,res){
var annoucement = req.announcement;
annoucement.title = req.body.title;
annouce... | });
}
Announcements.findById(id).populate('user','displayName').exec(function(err,announcement){
if(err){
return next(err); | random_line_split |
announcements.server.controller.js | 'use strict';
var mongoose = require('mongoose'),
Announcements = mongoose.model('Announcements'),
Users = mongoose.model('User'),
_ = require('lodash');
exports.create = function (req, res) {
//create a new announcement
var announcement = new Announcements(req.body);
announcement.save(function(err) ... |
else {
res.end();
}
});
};
| {
res.status(400).send(err);
} | conditional_block |
etw_results.py | """
Parses the results found for the ETW started on a machine,
downloads the results and stops the ETW.
All credit to pauldotcom-
http://pauldotcom.com/2012/07/post-exploitation-recon-with-e.html
Module built by @harmj0y
"""
import settings
from lib import command_methods
from lib import helpers
from lib im... |
else:
# save the file off to the appropriate location
saveFile = helpers.saveModuleFile(self, target, moduleFile, parseResult)
self.output += "[*] ETW results for "+flag+" using creds '"+username+":"+password+"' on " + target + " stored at "+saveFile+"\n"
| self.output += "[!] No ETW results for "+flag+" using creds '"+username+":"+password+"' on : " + target + "\n" | conditional_block |
etw_results.py | """
Parses the results found for the ETW started on a machine,
downloads the results and stops the ETW.
All credit to pauldotcom-
http://pauldotcom.com/2012/07/post-exploitation-recon-with-e.html
Module built by @harmj0y
"""
import settings
from lib import command_methods
from lib import helpers
from lib im... | (self):
# assume single set of credentials
username, password = self.creds[0]
triggerMethod = self.required_options["trigger_method"][0]
flag = self.required_options["flag"][0]
for target in self.targets:
# stop the ETW
stopCMD = "logman stop Status32 ... | run | identifier_name |
etw_results.py | """
Parses the results found for the ETW started on a machine,
downloads the results and stops the ETW.
All credit to pauldotcom-
http://pauldotcom.com/2012/07/post-exploitation-recon-with-e.html
Module built by @harmj0y
"""
import settings
from lib import command_methods
from lib import helpers
from lib im... |
def run(self):
# assume single set of credentials
username, password = self.creds[0]
triggerMethod = self.required_options["trigger_method"][0]
flag = self.required_options["flag"][0]
for target in self.targets:
# stop the ETW
stopCMD = "logman st... | def __init__(self, targets=None, creds=None, args=None):
self.name = "ETW Data Download"
self.description = "Download data results from ETW and clean everything up."
# internal list() that holds one or more targets
self.targets = targets
# internal list() that holds o... | identifier_body |
etw_results.py | """
Parses the results found for the ETW started on a machine,
downloads the results and stops the ETW.
All credit to pauldotcom-
http://pauldotcom.com/2012/07/post-exploitation-recon-with-e.html
Module built by @harmj0y
"""
import settings
from lib import command_methods
from lib import helpers
from lib im... | self.targets = targets
# internal list() that holds one or more cred tuples
# [ (username, pw), (username2, pw2), ...]
self.creds = creds
# a state output file that will be written out by pillage.py
# ex- if you're querying domain users
self.output = ""
... | # internal list() that holds one or more targets | random_line_split |
mod.rs | //! Parser guides
//!
//! A parser uses a guide to decide which transition to us given a particular
//! parser state. This module defines traits for parser guides, `Guide` and
//! `BatchGuide`, and provides an implementation using Tensorflow in the | //! `Tensorflow` submodule.
use crate::system::{ParserState, Transition};
/// Guide for parsers without batch processing
pub trait Guide {
type Transition: Transition;
/// Returns the best (permissible) transition given the current parser
/// state.
fn best_transition(&mut self, state: &ParserState<'... | random_line_split | |
suspend_and_re_activate.py | from paypalrestsdk import BillingAgreement
import logging
BILLING_AGREEMENT_ID = "I-HT38K76XPMGJ"
try:
billing_agreement = BillingAgreement.find(BILLING_AGREEMENT_ID)
print("Billing Agreement [%s] has state %s" % (billing_agreement.id, billing_agreement.state))
suspend_note = {
"note": "Suspendin... |
else:
print(billing_agreement.error)
else:
print(billing_agreement.error)
except ResourceNotFound as error:
print("Billing Agreement Not Found")
| billing_agreement = BillingAgreement.find(BILLING_AGREEMENT_ID)
print("Billing Agreement [%s] has state %s" % (billing_agreement.id, billing_agreement.state)) | conditional_block |
suspend_and_re_activate.py | from paypalrestsdk import BillingAgreement
import logging
BILLING_AGREEMENT_ID = "I-HT38K76XPMGJ"
try:
billing_agreement = BillingAgreement.find(BILLING_AGREEMENT_ID)
print("Billing Agreement [%s] has state %s" % (billing_agreement.id, billing_agreement.state))
suspend_note = { | # Would expect state has changed to Suspended
billing_agreement = BillingAgreement.find(BILLING_AGREEMENT_ID)
print("Billing Agreement [%s] has state %s" % (billing_agreement.id, billing_agreement.state))
reactivate_note = {
"note": "Reactivating the agreement"
}
... | "note": "Suspending the agreement"
}
if billing_agreement.suspend(suspend_note): | random_line_split |
render.tsx | import * as React from 'react';
import { Field, FieldArray, BaseFieldProps, FormSection } from 'redux-form';
import { TypeNode } from 'graphql';
import { FieldProps, ArrayFieldProps, FormSectionProps } from './apolloForm';
import { fromCamelToHuman } from './utils';
export type FormRenderFunction = React.Component... | ) {
const { render, ...rest } = renderer;
return (
<FieldArray
key={name}
name={name}
component={render}
required={required}
{...rest as any}
/>
);
}
}
| {
const { render, ...rest } = renderer;
const renderFn = render || defaultRenderSelectField;
return (
<Field
key={name}
name={name}
label={fromCamelToHuman(name)}
required={required}
component={renderFn}
options={options}
{...rest as any}
/... | identifier_body |
render.tsx | import * as React from 'react';
import { Field, FieldArray, BaseFieldProps, FormSection } from 'redux-form';
import { TypeNode } from 'graphql';
import { FieldProps, ArrayFieldProps, FormSectionProps } from './apolloForm';
import { fromCamelToHuman } from './utils';
export type FormRenderFunction = React.Component... | (
renderer: FormRenderer,
name: string,
type: string,
options: SelectOption[],
required?: boolean
) {
const { render, ...rest } = renderer;
const renderFn = render || defaultRenderSelectField;
return (
<Field
key={name}
name={name}
label={fromCamelToHuman(... | createSelectField | identifier_name |
render.tsx | import * as React from 'react';
import { Field, FieldArray, BaseFieldProps, FormSection } from 'redux-form';
import { TypeNode } from 'graphql';
import { FieldProps, ArrayFieldProps, FormSectionProps } from './apolloForm';
import { fromCamelToHuman } from './utils';
export type FormRenderFunction = React.Component... | (warning && <span>{warning}</span>))}
</div>
</div>
);
};
const defaultHiddenField = (props: FieldProps) => {
const { input, meta, ...rest } = props;
return <input type="hidden" {...input} {...rest} />;
};
const defaultRenderSelectField = (props: FieldProps) => {
const {
input,
l... | <Component type={type} {...input} placeholder={label} {...rest} />
{touched &&
((error && <span>{error}</span>) || | random_line_split |
FinalizeOAuth.py | # -*- coding: utf-8 -*-
###############################################################################
#
# FinalizeOAuth
# Completes the OAuth process by retrieving a Foursquare access token for a user, after they have visited the authorization URL returned by the InitializeOAuth choreo and clicked "allow."
#
# Pytho... | (self, temboo_session):
"""
Create a new instance of the FinalizeOAuth Choreo. A TembooSession object, containing a valid
set of Temboo credentials, must be supplied.
"""
super(FinalizeOAuth, self).__init__(temboo_session, '/Library/Foursquare/OAuth/FinalizeOAuth')
def new_... | __init__ | identifier_name |
FinalizeOAuth.py | # -*- coding: utf-8 -*-
###############################################################################
#
# FinalizeOAuth
# Completes the OAuth process by retrieving a Foursquare access token for a user, after they have visited the authorization URL returned by the InitializeOAuth choreo and clicked "allow."
#
# Pytho... | """
super(FinalizeOAuthInputSet, self)._set_input('AccountName', value)
def set_AppKeyName(self, value):
"""
Set the value of the AppKeyName input for this Choreo. ((optional, string) Deprecated (retained for backward compatibility only).)
"""
super(FinalizeOAuthInput... | Set the value of the AccountName input for this Choreo. ((optional, string) Deprecated (retained for backward compatibility only).) | random_line_split |
FinalizeOAuth.py | # -*- coding: utf-8 -*-
###############################################################################
#
# FinalizeOAuth
# Completes the OAuth process by retrieving a Foursquare access token for a user, after they have visited the authorization URL returned by the InitializeOAuth choreo and clicked "allow."
#
# Pytho... |
def get_AccessToken(self):
"""
Retrieve the value for the "AccessToken" output from this Choreo execution. ((string) The access token for the user that has granted access to your application.)
"""
return self._output.get('AccessToken', None)
class FinalizeOAuthChoreographyExecutio... | return json.loads(str) | identifier_body |
markdown.js | ////////////////////////////////////////////////
//
// Markdown to HTML converter demo (markdown widget)
//
//
// IoT Manager https://play.google.com/store/apps/details?id=ru.esp8266.iotmanager
//
// version : 1.0
// IoT Manager : 1.5.4 and above
//
////////////////////////////////////////////////
////////////////... |
pubStatus();
})
////////////////////////////////////////////////
function pubConfig() {
config.forEach(function(item, i, arr) {
client.publish(prefix + "/" + deviceID + "/config", JSON.stringify(item),{ qos : 1 });
});
}
////////////////////////////////////////////////
function pubStatus() {
va... | {
console.log('HELLO detected');
pubConfig();
} | conditional_block |
markdown.js | ////////////////////////////////////////////////
//
// Markdown to HTML converter demo (markdown widget)
//
//
// IoT Manager https://play.google.com/store/apps/details?id=ru.esp8266.iotmanager
//
// version : 1.0
// IoT Manager : 1.5.4 and above
//
////////////////////////////////////////////////
////////////////... | () {
var x = 10 + Math.round(Math.random() * 10);
var y = 100 + Math.round(Math.random() * 100);
var z = 1000 + Math.round(Math.random() * 1000);
var z1= 1000 + Math.round(Math.random() * 5000);
var text = '\n';
text += '\n__Sensor1 ' + x + '__';
text += '\n~~Sensor2 ' + y + '~~';
text += ... | pubStatus | identifier_name |
markdown.js | ////////////////////////////////////////////////
//
// Markdown to HTML converter demo (markdown widget)
//
//
// IoT Manager https://play.google.com/store/apps/details?id=ru.esp8266.iotmanager
//
// version : 1.0
// IoT Manager : 1.5.4 and above
//
////////////////////////////////////////////////
////////////////... | text += '\n## Sensor 2: '+y;
text += '\n### Sensor 3: '+z;
text += '\n#### Sensor 4: '+z1;
text += '\n';
client.publish( config[0].topic+"/status", JSON.stringify({ status: text }) );
console.log('Publish');
}
////////////////////////////////////////////////
// run main
console.log('Start'... | {
var x = 10 + Math.round(Math.random() * 10);
var y = 100 + Math.round(Math.random() * 100);
var z = 1000 + Math.round(Math.random() * 1000);
var z1= 1000 + Math.round(Math.random() * 5000);
var text = '\n';
text += '\n__Sensor1 ' + x + '__';
text += '\n~~Sensor2 ' + y + '~~';
text += '\n... | identifier_body |
markdown.js | ////////////////////////////////////////////////
//
// Markdown to HTML converter demo (markdown widget)
//
//
// IoT Manager https://play.google.com/store/apps/details?id=ru.esp8266.iotmanager
//
// version : 1.0
// IoT Manager : 1.5.4 and above
//
////////////////////////////////////////////////
////////////////... | client.on('offline', function () {
console.log('Broker offline');
});
client.on('message', function (topic, message) {
console.log("Message arrived: " + topic.toString() + " => " + message.toString());
if (topic.toString() === prefix && message.toString() == "HELLO" ){
console.log('HELLO detected');
... | });
| random_line_split |
ignore.rs | use crate::{api_client::Client,
common::ui::{Status,
UIWriter,
UI},
error::{Error,
Result},
PRODUCT,
VERSION};
pub async fn start(ui: &mut UI,
bldr_url: &str,
orig... | {
let api_client = Client::new(bldr_url, PRODUCT, VERSION, None).map_err(Error::APIClient)?;
ui.status(Status::Ignoring,
format!("invitation id {} in origin {}", invitation_id, origin))?;
match api_client.ignore_origin_invitation(origin, token, invitation_id)
.await
{... | identifier_body | |
ignore.rs | use crate::{api_client::Client,
common::ui::{Status,
UIWriter,
UI},
error::{Error,
Result},
PRODUCT,
VERSION};
pub async fn | (ui: &mut UI,
bldr_url: &str,
origin: &str,
token: &str,
invitation_id: u64)
-> Result<()> {
let api_client = Client::new(bldr_url, PRODUCT, VERSION, None).map_err(Error::APIClient)?;
ui.status(Status::Ignoring,
... | start | identifier_name |
ignore.rs | use crate::{api_client::Client,
common::ui::{Status,
UIWriter,
UI},
error::{Error,
Result},
PRODUCT,
VERSION};
pub async fn start(ui: &mut UI,
bldr_url: &str,
orig... |
}
}
| {
ui.fatal(format!("Failed to ignore invitation {} in origin {}, {:?}",
invitation_id, origin, e))?;
Err(Error::from(e))
} | conditional_block |
ignore.rs | use crate::{api_client::Client,
common::ui::{Status,
UIWriter,
UI},
error::{Error,
Result},
PRODUCT,
VERSION};
pub async fn start(ui: &mut UI,
bldr_url: &str,
orig... | ui.status(Status::Ignored, "the invitation successfully!".to_string())
.or(Ok(()))
}
Err(e) => {
ui.fatal(format!("Failed to ignore invitation {} in origin {}, {:?}",
invitation_id, origin, e))?;
Err(Error::from(e))
}... | random_line_split | |
settings.py | BACKUPPC_DIR = "/usr/share/backuppc"
TARGET_HOST = "192.168.1.65"
BACKUPPC_USER_UID = 110
BACKUPPC_USER_GID = 116
DEBUG = False
TRANSLATIONS = {
'Status_idle': 'inattivo',
'Status_backup_starting': 'avvio backup',
'Status_backup_in_progress': 'backup in esecuzione',
'Status_restore_starting': 'avvio ri... | 'Reason_nothing_to_do': 'nulla da fare',
'Reason_backup_failed': 'backup fallito',
'Reason_restore_failed': 'restore fallito',
'Reason_archive_failed': 'archivio fallito',
'Reason_no_ping': 'no ping',
'Reason_backup_canceled_by_user': 'backup annullato dall\'utente',
'Reason_restore_canceled... | 'Reason_backup_done': 'backup eseguito',
'Reason_restore_done': 'restore eseguito',
'Reason_archive_done': 'archivio eseguito', | random_line_split |
index.d.ts | /*
* @license Apache-2.0
*
* Copyright (c) 2020 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by ap... | *
* @example
* var x = [ 4.0, 2.0, -3.0, 5.0, -1.0 ];
* var y = [ 2.0, 6.0, -1.0, -4.0, 8.0 ];
*
* gswap( x, y );
* // x => [ 2.0, 6.0, -1.0, -4.0, 8.0 ]
* // y => [ 4.0, 2.0, -3.0, 5.0, -1.0 ]
*/
declare function gswap( x: ndarray | ArrayLike<any>, y: ndarray | ArrayLike<any> ): ndarray | ArrayLike<any>; // tslint:dis... | * @param y - second input array
* @throws first argument must be either an array-like object or a 1-dimensional `ndarray`
* @throws second argument must be either an array-like object or a 1-dimensional `ndarray`
* @throws input arrays must be the same length
* @returns `y` | random_line_split |
name-list.service.ts | import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
// import 'rxjs/add/operator/do'; // for debugging
import { Config } from '../../shared/config/env.config';
import { Contact } from './contact';
import 'rxjs/add/operator/toPromis... | (private http: Http) {}
/**
* Returns an Observable for the HTTP GET request for the JSON resource.
* @return {string[]} The Observable for the HTTP request.
*/
get(): Observable<string[]> {
return this.http.get('assets/data.json')
.map((res: Response) => res.json())
// ... | constructor | identifier_name |
name-list.service.ts | import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
// import 'rxjs/add/operator/do'; // for debugging
import { Config } from '../../shared/config/env.config';
import { Contact } from './contact';
import 'rxjs/add/operator/toPromis... | } | error.status ? `${error.status} - ${error.statusText}` : 'Server error';
console.error(errMsg); // log to console instead
return Observable.throw(errMsg);
} | random_line_split |
stringcache.py | # Copyright 2008-2015 Nokia Solutions and Networks
#
# 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 l... |
class StringCache(object):
_compress_threshold = 80
_use_compressed_threshold = 1.1
_zero_index = StringIndex(0)
def __init__(self):
self._cache = OrderedDict({'*': self._zero_index})
def add(self, text):
if not text:
return self._zero_index
text = self._enco... | pass | identifier_body |
stringcache.py | # Copyright 2008-2015 Nokia Solutions and Networks
#
# 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 l... |
return raw
def _raw(self, text):
return '*'+text
def dump(self):
return tuple(self._cache)
| return compressed | conditional_block |
stringcache.py | # Copyright 2008-2015 Nokia Solutions and Networks
#
# 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 l... | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from robot.utils import OrderedDict, compress_text
class StringIndex(int):
pass
class StringCache(object):
_compress_threshold... | random_line_split | |
stringcache.py | # Copyright 2008-2015 Nokia Solutions and Networks
#
# 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 l... | (self, text):
raw = self._raw(text)
if raw in self._cache or len(raw) < self._compress_threshold:
return raw
compressed = compress_text(text)
if len(compressed) * self._use_compressed_threshold < len(raw):
return compressed
return raw
def _raw(self, t... | _encode | identifier_name |
wsgi.py | """
WSGI config for p1 project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION`` setti... | # mod_wsgi daemon mode with each site in its own daemon process, or use
# os.environ["DJANGO_SETTINGS_MODULE"] = "p1.settings"
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "conference.settings")
# This application object is used by any WSGI server configured to use this
# file. This includes Django's development se... | # We defer to a DJANGO_SETTINGS_MODULE already in the environment. This breaks
# if running multiple sites in the same mod_wsgi process. To fix this, use | random_line_split |
viewerCesium3DTilesInspectorMixin.js | import Check from "../../Core/Check.js";
import Cesium3DTilesInspector from "../Cesium3DTilesInspector/Cesium3DTilesInspector.js";
/**
* A mixin which adds the {@link Cesium3DTilesInspector} widget to the {@link Viewer} widget.
* Rather than being called directly, this function is normally passed as
* a parameter t... | }
export default viewerCesium3DTilesInspectorMixin;
| {
//>>includeStart('debug', pragmas.debug);
Check.typeOf.object("viewer", viewer);
//>>includeEnd('debug');
var container = document.createElement("div");
container.className = "cesium-viewer-cesium3DTilesInspectorContainer";
viewer.container.appendChild(container);
var cesium3DTilesInspector = new Cesiu... | identifier_body |
viewerCesium3DTilesInspectorMixin.js | import Check from "../../Core/Check.js";
import Cesium3DTilesInspector from "../Cesium3DTilesInspector/Cesium3DTilesInspector.js";
/**
* A mixin which adds the {@link Cesium3DTilesInspector} widget to the {@link Viewer} widget.
* Rather than being called directly, this function is normally passed as
* a parameter t... |
Object.defineProperties(viewer, {
cesium3DTilesInspector: {
get: function () {
return cesium3DTilesInspector;
},
},
});
}
export default viewerCesium3DTilesInspectorMixin; | ); | random_line_split |
viewerCesium3DTilesInspectorMixin.js | import Check from "../../Core/Check.js";
import Cesium3DTilesInspector from "../Cesium3DTilesInspector/Cesium3DTilesInspector.js";
/**
* A mixin which adds the {@link Cesium3DTilesInspector} widget to the {@link Viewer} widget.
* Rather than being called directly, this function is normally passed as
* a parameter t... | (viewer) {
//>>includeStart('debug', pragmas.debug);
Check.typeOf.object("viewer", viewer);
//>>includeEnd('debug');
var container = document.createElement("div");
container.className = "cesium-viewer-cesium3DTilesInspectorContainer";
viewer.container.appendChild(container);
var cesium3DTilesInspector = ... | viewerCesium3DTilesInspectorMixin | identifier_name |
enums.py | GALAXY = ("Samsung Galaxy S", "Mozilla/5.0 (Linux; U; Android 2.2; en-US; SGH-T959D Build/FROYO) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1")
HP = ("HP iPAQ 6365", "Mozilla/4.0 (compatible; MSIE 4.01; Windows CE; PPC; 240x320; HP iPAQ h6300)")
HTC = ("HTC Sensation", "Mozilla/5.0 ... | AUTOCOMPLETE_TYPE | identifier_name | |
enums.py | LOWER = -50
LOW = -10
NORMAL = 0
HIGH = 10
HIGHER = 50
HIGHEST = 100
class SORT_ORDER:
FIRST = 0
SECOND = 1
THIRD = 2
FOURTH = 3
FIFTH = 4
LAST = 100
class DBMS:
ACCESS = "Microsoft Access"
DB2 = "IBM DB2"
FIREBIRD = "Firebird"
MAXDB = "SAP MaxDB"
MS... | LOWEST = -100 | random_line_split | |
enums.py | Linux; U; Android 4.0.3; de-ch; HTC Sensation Build/IML74K) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30")
IPHONE = ("Apple iPhone 4s", "Mozilla/5.0 (iPhone; CPU iPhone OS 5_1 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9B179 Safari/7534.48.3")
NEXUS = ("G... | NORMAL = 0
EXCEPTION = 1
TIMEOUT = 2 | identifier_body | |
replaceComerceDateTime.test.ts | import { GraphQLSchema, GraphQLObjectType, GraphQLScalarType } from "graphql"
import { runQueryOrThrow } from "test/utils"
import gql from "lib/gql"
import { transformSchema } from "graphql-tools" | query: new GraphQLObjectType({
name: "Query",
fields: {
someRootField: {
type: new GraphQLObjectType({
name: "SomeType",
fields: {
someDateField: {
type: new GraphQLScalarType({
name: "CommerceDateTime",
serialize: x =... | import { ReplaceCommerceDateTimeType } from "../transformers/replaceCommerceDateTimeType"
const originalSchema = new GraphQLSchema({ | random_line_split |
ct_result.rs | use std::io::Error as IoError;
use std::fmt::Display;
use serde_json::Error as SerdeError;
use clap::Error as ClapError;
use tempfile;
use atomicwrites;
/// the result type used for the whole application
pub type CtResult<T> = Result<T, CtError>;
// the error type used for the whole application
error_type! {
#[de... | (err: atomicwrites::Error<E>) -> CtError {
CtError::Msg(format!("{}", err))
}
}
pub trait OkOr {
type R;
fn ok_or<E>(self, err: E) -> Result<Self::R, E>;
}
impl OkOr for bool {
type R = ();
fn ok_or<E>(self, err: E) -> Result<Self::R, E> {
if self {
Ok(())
} e... | from | identifier_name |
ct_result.rs | use std::io::Error as IoError;
use std::fmt::Display;
use serde_json::Error as SerdeError;
use clap::Error as ClapError;
use tempfile;
use atomicwrites;
/// the result type used for the whole application
pub type CtResult<T> = Result<T, CtError>;
// the error type used for the whole application
error_type! {
#[de... | else {
Err(err)
}
}
}
| {
Ok(())
} | conditional_block |
ct_result.rs | use std::io::Error as IoError;
use std::fmt::Display;
use serde_json::Error as SerdeError;
use clap::Error as ClapError;
use tempfile;
use atomicwrites;
/// the result type used for the whole application
pub type CtResult<T> = Result<T, CtError>;
// the error type used for the whole application
error_type! {
#[de... |
}
| {
if self {
Ok(())
} else {
Err(err)
}
} | identifier_body |
ct_result.rs | use std::io::Error as IoError;
use std::fmt::Display;
use serde_json::Error as SerdeError;
use clap::Error as ClapError;
use tempfile;
use atomicwrites;
/// the result type used for the whole application
pub type CtResult<T> = Result<T, CtError>;
// the error type used for the whole application
error_type! {
#[de... | } else {
Err(err)
}
}
} | random_line_split | |
test_createkilldye.py | # ------------------------------------------------------------
# Developping with MicroPython in an async way
#
# ------------------------------------------------------------
# === asyncio tests ===
# ------------------------------------------------------------
print("==== /test/asyncio/tes... |
log.info("Task led3 dies!")
def master_of_universe():
yield
log.info("Creating task led0. Red led goes flashing fast!")
tid = yield asyncio.CreateTask( led0(), period = 100, prio = 11 )
log.info("Kill task led0 with tid %d. Red led stops flashing!",tid)
yield asyncio.KillTask(tid)
... | neo.toggleR( 3,80 )
neo.writeBuffer()
yield | conditional_block |
test_createkilldye.py | # ------------------------------------------------------------
# Developping with MicroPython in an async way
#
# ------------------------------------------------------------
# === asyncio tests ===
# ------------------------------------------------------------
print("==== /test/asyncio/tes... |
now = time.ticks_ms()
print (now)
# Run them
sched = asyncio.sched
sched.task(led1(), period = 300, time2run = 200)
sched.task(led2(), period = 700, time2run = 300)
sched.task(led3(), period = 4000, time2run = 4000)
sched.task(master_of_universe(), period = 4000, time2run = 4000 )
log.info("test creating k... | yield
log.info("Creating task led0. Red led goes flashing fast!")
tid = yield asyncio.CreateTask( led0(), period = 100, prio = 11 )
log.info("Kill task led0 with tid %d. Red led stops flashing!",tid)
yield asyncio.KillTask(tid)
log.info("Kill the os itself!")
yield asyncio.KillOs()
lo... | identifier_body |
test_createkilldye.py | # ------------------------------------------------------------
# Developping with MicroPython in an async way
#
# ------------------------------------------------------------
# === asyncio tests ===
# ------------------------------------------------------------
print("==== /test/asyncio/tes... | ():
yield
while True:
neo.toggleG( 1,80 )
neo.writeBuffer()
yield
log.info("Task led1 dies!")
def led2():
yield
while True:
neo.toggleB( 2,80 )
neo.writeBuffer()
yield
log.info("Task led2 dies!")
def led3():
yield
while True:
ne... | led1 | identifier_name |
test_createkilldye.py | # ------------------------------------------------------------
# Developping with MicroPython in an async way
#
# ------------------------------------------------------------
# === asyncio tests ===
# ------------------------------------------------------------
print("==== /test/asyncio/tes... | neo.toggleB( 2,80 )
neo.writeBuffer()
yield
log.info("Task led2 dies!")
def led3():
yield
while True:
neo.toggleR( 3,80 )
neo.writeBuffer()
yield
log.info("Task led3 dies!")
def master_of_universe():
yield
log.info("Creating task led0. Red led... | yield
while True: | random_line_split |
main-component.test.ts | import 'angular';
import 'angular-mocks';
import {MainComponent} from './main/main-component';
describe('ComponentTest', () => {
let _mockHttpService;
let _mockSentData;
let _mockResponseData;
let _mockPath;
let _mockId;
angular.module('ComponentTest', [])
.directive('mainComponent', MainCompone... | let serverService = new ServerService(_mockHttpService);
expect(serverService.get(_mockPath)).not.toBeUndefined();
});
it('should receive successful response to GET request', () => {
expect(_mockHttpService).not.toBeUndefined();
let serverService = new ServerService(_mockHttpService);
return ser... | });
it('should load', () => {
expect(_mockHttpService).not.toBeUndefined();
| random_line_split |
angular-linkto.js | (function() {
angular.module('angular-linkto', []);
angular.module('angular-linkto').service('keymaster', function() {
return {
replaceKey: function(str, key, params) {
return str.replace(":" + key, params != null ? params[key] : void 0);
}, | var key, keys;
if (params != null ? typeof params.hasAttributes === "function" ? params.hasAttributes() : void 0 : void 0) {
params = params.toJSON();
}
keys = this.findKeys(str);
for (key in params) {
str = this.replaceKey(str, key, params);
}
... | findKeys: function(str) {
return str.match(/:[\w\d_\-]+/g);
},
replaceKeys: function(str, params) { | random_line_split |
angular-linkto.js | (function() {
angular.module('angular-linkto', []);
angular.module('angular-linkto').service('keymaster', function() {
return {
replaceKey: function(str, key, params) {
return str.replace(":" + key, params != null ? params[key] : void 0);
},
findKeys: function(str) {
return st... |
}
} else if (containsColon(route)) {
if (containsColonBeforeSlash(route)) {
throwUnfilledParamError(route);
} else {
route = dropLastParam(route);
}
}
return route;
};
});
}).call(this);
/*
//@ sourceMappingURL=angular-linkto.js.map
*/ | {
route = dropLastParam(route);
} | conditional_block |
mod.rs | // Copyright 2015 The Athena Developers.
//
// 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 ag... | fn raise_event(
&mut self, event: &Event,
prev_area: &render::RenderArea, offset: &mut render::RenderOffset);
/// Writes rendering data for this widget to `data`.
fn render(
&self, renderer: &mut render::Renderer<R>,
prev_area: &render::RenderArea, offset: &mut render::Rende... | pub use widget::text::*;
/// An interface for referencing to any kind of widget.
pub trait Widget<R: gfx::Resources> {
/// Handles an event that may or may not apply to this widget. | random_line_split |
SubHeader.tsx | import * as React from 'react';
import { Link } from 'react-router';
import { style, media } from 'typestyle';
import { hideAtRange } from 'utils/style';
import { VlLogoRed, VlLogoGrey } from 'app/colors';
import { HEADER_HEIGHT_SM, HEADER_HEIGHT_LG } from './Header';
export const SUB_HEADER_HEIGHT = 3;
const navList... | <nav className={navListStyle}>
<Link activeClassName={activeLinkStyle} to='/veislur'>Veislur</Link>
<Link activeClassName={activeLinkStyle} to='/smurbraud' className={style(hideAtRange(0, 395))}>Smurbraud</Link>
<Link activeClassName={activeLinkStyle} to='/tertur'>Tertur</Link>
<Link activeClassName={... | textDecoration: 'underline',
color: VlLogoRed.toString(),
fontSize: '1.8rem',
}, media({ minWidth: 900 }, { fontSize: '2.3rem' }));
export const SubHeader = () => ( | random_line_split |
Welcome.js | /** @jsx m */
import m from 'mithril';
import { linkTo, hrefTo } from '@storybook/addon-links';
const Main = {
view: vnode => (
<article
style={{
padding: 15,
lineHeight: 1.4,
fontFamily: '"Helvetica Neue", Helvetica, "Segoe UI", Arial, freesans, sans-serif',
backgroundColo... | <a
style={{
color: '#1474f3',
textDecoration: 'none',
borderBottom: '1px solid #1474f3',
paddingBottom: 2,
}}
{...vnode.attrs}
>
{vnode.children}
</a>
),
};
const NavButton = {
view: vnode => (
<button
type="button"
style={{
... | random_line_split | |
_scripted_fields.js | import _ from 'lodash';
import 'ui/paginated_table';
import popularityHtml from 'plugins/kibana/management/sections/indices/_field_popularity.html';
import controlsHtml from 'plugins/kibana/management/sections/indices/_field_controls.html';
import dateScripts from 'plugins/kibana/management/sections/indices/_date_scrip... | rowScopes.length = 0;
const fields = filter($scope.indexPattern.getScriptedFields(), { name: $scope.fieldFilter });
_.find($scope.editSections, { index: 'scriptedFields' }).count = fields.length; // Update the tab count
$scope.rows = fields.map(function (field) {
const rowSco... | _.invoke(rowScopes, '$destroy'); | random_line_split |
_scripted_fields.js | import _ from 'lodash';
import 'ui/paginated_table';
import popularityHtml from 'plugins/kibana/management/sections/indices/_field_popularity.html';
import controlsHtml from 'plugins/kibana/management/sections/indices/_field_controls.html';
import dateScripts from 'plugins/kibana/management/sections/indices/_date_scrip... |
};
$scope.create = function () {
const params = {
indexPattern: $scope.indexPattern.id
};
kbnUrl.change(fieldCreatorPath, params);
};
$scope.edit = function (field) {
const params = {
indexPattern: $scope.indexPattern.id,
fieldNam... | {
notify.info('Not adding ' + conflictFields.length + ' duplicate fields: ' + conflictFields.join(', '));
} | conditional_block |
_scripted_fields.js | import _ from 'lodash';
import 'ui/paginated_table';
import popularityHtml from 'plugins/kibana/management/sections/indices/_field_popularity.html';
import controlsHtml from 'plugins/kibana/management/sections/indices/_field_controls.html';
import dateScripts from 'plugins/kibana/management/sections/indices/_date_scrip... | () {
_.invoke(rowScopes, '$destroy');
rowScopes.length = 0;
const fields = filter($scope.indexPattern.getScriptedFields(), { name: $scope.fieldFilter });
_.find($scope.editSections, { index: 'scriptedFields' }).count = fields.length; // Update the tab count
$scope.rows = fields... | refreshRows | identifier_name |
_scripted_fields.js | import _ from 'lodash';
import 'ui/paginated_table';
import popularityHtml from 'plugins/kibana/management/sections/indices/_field_popularity.html';
import controlsHtml from 'plugins/kibana/management/sections/indices/_field_controls.html';
import dateScripts from 'plugins/kibana/management/sections/indices/_date_scrip... | }
];
});
}
$scope.addDateScripts = function () {
const conflictFields = [];
let fieldsAdded = 0;
_.each(dateScripts($scope.indexPattern), function (script, field) {
try {
$scope.indexPattern.addScriptedField(field, script, 'number... | {
_.invoke(rowScopes, '$destroy');
rowScopes.length = 0;
const fields = filter($scope.indexPattern.getScriptedFields(), { name: $scope.fieldFilter });
_.find($scope.editSections, { index: 'scriptedFields' }).count = fields.length; // Update the tab count
$scope.rows = fields.ma... | identifier_body |
lib.rs | // Copyright 2016 LambdaStack All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law... |
// NOTE: This attribute only needs to be set once.
#![doc(html_logo_url = "https://lambdastackio.github.io/static/images/lambdastack-200x200.png",
html_favicon_url = "https://lambdastackio.github.io/static/images/favicon.ico",
html_root_url = "https://lambdastackio.github.io/aws-sdk-rust/ceph-rust/ceph_r... | // distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License. | random_line_split |
geo.py | # -*- coding: utf-8 -*-
import math
EARTH_RADIUS = 6367009
METERS_PER_DEGREE = 111319.0
FEET_PER_METER = 3.2808399
def | (loc1, loc2):
"""
Calculate the great circle distance between two points
on the earth (specified in decimal degrees)
"""
# convert decimal degrees to radians
lat1, lon1, lat2, lon2 = map(math.radians,
[loc1.latitude, loc1.longitude,
... | geographic_distance | identifier_name |
geo.py | # -*- coding: utf-8 -*-
import math
EARTH_RADIUS = 6367009 | """
Calculate the great circle distance between two points
on the earth (specified in decimal degrees)
"""
# convert decimal degrees to radians
lat1, lon1, lat2, lon2 = map(math.radians,
[loc1.latitude, loc1.longitude,
loc2.latit... | METERS_PER_DEGREE = 111319.0
FEET_PER_METER = 3.2808399
def geographic_distance(loc1, loc2): | random_line_split |
geo.py | # -*- coding: utf-8 -*-
import math
EARTH_RADIUS = 6367009
METERS_PER_DEGREE = 111319.0
FEET_PER_METER = 3.2808399
def geographic_distance(loc1, loc2):
| """
Calculate the great circle distance between two points
on the earth (specified in decimal degrees)
"""
# convert decimal degrees to radians
lat1, lon1, lat2, lon2 = map(math.radians,
[loc1.latitude, loc1.longitude,
loc2.latitude,... | identifier_body | |
metrics.rs | /*
* Copyright 2020 Google LLC
*
* 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 i... | <T: Collector + Sized + 'static>(
registry: &Registry,
collector: T,
) -> Result<()> {
registry.register(Box::new(collector))
}
pub trait CollectorExt: Collector + Clone + Sized + 'static {
/// Registers the current metric collector with the provided registry
/// if not already registered.
fn r... | register_metric | identifier_name |
metrics.rs | /*
* Copyright 2020 Google LLC
*
* 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 i... | impl<C: Collector + Clone + 'static> CollectorExt for C {} | }
| random_line_split |
metrics.rs | /*
* Copyright 2020 Google LLC
*
* 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 i... |
}
impl<C: Collector + Clone + 'static> CollectorExt for C {}
| {
match register_metric(crate::metrics::registry(), self.clone()) {
Ok(_) | Err(prometheus::Error::AlreadyReg) => Ok(self),
Err(err) => Err(err),
}
} | identifier_body |
compute_rmsd_pdb_files.py | """
Routines to compute RMSD of all PROT_IND_ files
These routines were developed by:
Rodrigo Antonio Faccioli - rodrigo.faccioli@usp.br / rodrigo.faccioli@gmail.com
Leandro Oliveira Bortot - leandro.bortot@usp.br / leandro.obt@gmail.com
"""
import os
import sys
from collections import OrderedDict... | (mypath):
only_pdb_file = []
for root, dirs, files in os.walk(mypath):
for file in files:
#if file.endswith(".pdb"):
if file.find("PROT_IND_") >=0:
f_path = os.path.join(root,file)
only_pdb_file.append(f_path)
return only_pdb_file
def main():
pdb_path = sys.argv[1]
dict_rmsd = {}
all_pdbs = g... | get_PROT_IND_files_pdb | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.