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 |
|---|---|---|---|---|
expect.rs | use std::fmt;
use std::str;
use unicase::UniCase;
use header::{Header, HeaderFormat};
/// The `Expect` header.
///
/// > The "Expect" header field in a request indicates a certain set of
/// > behaviors (expectations) that need to be supported by the server in
/// > order to properly handle this request. The only s... |
fn parse_header(raw: &[Vec<u8>]) -> Option<Expect> {
if raw.len() == 1 {
let text = unsafe {
// safe because:
// 1. we just checked raw.len == 1
// 2. we don't actually care if it's utf8, we just want to
// compare the bytes wi... | {
"Expect"
} | identifier_body |
expect.rs | use std::fmt;
use std::str;
use unicase::UniCase;
use header::{Header, HeaderFormat};
/// The `Expect` header.
///
/// > The "Expect" header field in a request indicates a certain set of
/// > behaviors (expectations) that need to be supported by the server in
/// > order to properly handle this request. The only s... | (raw: &[Vec<u8>]) -> Option<Expect> {
if raw.len() == 1 {
let text = unsafe {
// safe because:
// 1. we just checked raw.len == 1
// 2. we don't actually care if it's utf8, we just want to
// compare the bytes with the "case" normali... | parse_header | identifier_name |
expect.rs | use std::fmt;
use std::str;
use unicase::UniCase;
use header::{Header, HeaderFormat};
/// The `Expect` header.
///
/// > The "Expect" header field in a request indicates a certain set of
/// > behaviors (expectations) that need to be supported by the server in
/// > order to properly handle this request. The only s... | else {
None
}
}
}
impl HeaderFormat for Expect {
fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str("100-continue")
}
}
| {
let text = unsafe {
// safe because:
// 1. we just checked raw.len == 1
// 2. we don't actually care if it's utf8, we just want to
// compare the bytes with the "case" normalized. If it's not
// utf8, then the byte compa... | conditional_block |
expect.rs | use std::fmt;
use std::str;
use unicase::UniCase;
use header::{Header, HeaderFormat};
/// The `Expect` header.
///
/// > The "Expect" header field in a request indicates a certain set of
/// > behaviors (expectations) that need to be supported by the server in
/// > order to properly handle this request. The only s... | str::from_utf8_unchecked(raw.get_unchecked(0))
};
if UniCase(text) == EXPECT_CONTINUE {
Some(Expect::Continue)
} else {
None
}
} else {
None
}
}
}
impl HeaderFormat for Expect {
fn fmt_he... | // 1. we just checked raw.len == 1
// 2. we don't actually care if it's utf8, we just want to
// compare the bytes with the "case" normalized. If it's not
// utf8, then the byte comparison will fail, and we'll return
// None. No bi... | random_line_split |
group_api_urls.py | from __future__ import absolute_import
import logging
import re
from django.core.urlresolvers import RegexURLResolver, RegexURLPattern
from django.conf.urls import patterns, include, url
from sentry.plugins import plugins
logger = logging.getLogger("sentry.plugins")
def | (u):
if isinstance(u, (tuple, list)):
return url(*u)
elif not isinstance(u, (RegexURLResolver, RegexURLPattern)):
raise TypeError(
"url must be RegexURLResolver or RegexURLPattern, not %r: %r" % (type(u).__name__, u)
)
return u
def load_plugin_urls(plugins):
urlpatt... | ensure_url | identifier_name |
group_api_urls.py | from __future__ import absolute_import
import logging
import re
from django.core.urlresolvers import RegexURLResolver, RegexURLPattern
from django.conf.urls import patterns, include, url
from sentry.plugins import plugins
logger = logging.getLogger("sentry.plugins")
def ensure_url(u):
if isinstance(u, (tuple,... | else:
urlpatterns.append(url(r"^%s/" % re.escape(plugin.slug), include(urls)))
return urlpatterns
urlpatterns = load_plugin_urls(plugins.all()) | urls = [ensure_url(u) for u in urls]
except Exception:
logger.exception("routes.failed", extra={"plugin": type(plugin).__name__}) | random_line_split |
group_api_urls.py | from __future__ import absolute_import
import logging
import re
from django.core.urlresolvers import RegexURLResolver, RegexURLPattern
from django.conf.urls import patterns, include, url
from sentry.plugins import plugins
logger = logging.getLogger("sentry.plugins")
def ensure_url(u):
if isinstance(u, (tuple,... |
urlpatterns = load_plugin_urls(plugins.all())
| urlpatterns = patterns("")
for plugin in plugins:
try:
urls = plugin.get_group_urls()
if not urls:
continue
urls = [ensure_url(u) for u in urls]
except Exception:
logger.exception("routes.failed", extra={"plugin": type(plugin).__name__}... | identifier_body |
group_api_urls.py | from __future__ import absolute_import
import logging
import re
from django.core.urlresolvers import RegexURLResolver, RegexURLPattern
from django.conf.urls import patterns, include, url
from sentry.plugins import plugins
logger = logging.getLogger("sentry.plugins")
def ensure_url(u):
if isinstance(u, (tuple,... |
return urlpatterns
urlpatterns = load_plugin_urls(plugins.all())
| urlpatterns.append(url(r"^%s/" % re.escape(plugin.slug), include(urls))) | conditional_block |
api.ts | const HOST_URI = 'https://www.v2ex.com/api/'
// 获取节点
// 所有的节点
const ALL_NODE = 'nodes/all.json'
// 获取节点信息
// 节点id :id 节点名 :name
const NODE_INFO = 'nodes/show.json'
// 获取主题
// 取最新的主题
const LATEST_TOPIC = 'topics/latest.json'
// 获取热议主题
const HOT_TOPIC = 'topics/hot.json'
// 获取主题信息 :id | (:username | :node_id | :node_n... | mponent(obj[k])
}).join('&')
}
function getAllNode () {
return HOST_URI + ALL_NODE
}
function getNodeInfo (o?) {
return HOST_URI + NODE_INFO + queryString(o)
}
function getHotNodes () {
return HOST_URI + HOT_TOPIC
}
function getLatestTopic (o?) {
return HOST_URI + LATEST_TOPIC + queryString(o)
}
function... | + '=' + encodeURICo | conditional_block |
api.ts | const HOST_URI = 'https://www.v2ex.com/api/'
// 获取节点
// 所有的节点
const ALL_NODE = 'nodes/all.json'
// 获取节点信息
// 节点id :id 节点名 :name
const NODE_INFO = 'nodes/show.json'
// 获取主题
// 取最新的主题
const LATEST_TOPIC = 'topics/latest.json'
// 获取热议主题
const HOT_TOPIC = 'topics/hot.json'
// 获取主题信息 :id | (:username | :node_id | :node_n... | ring,
getTopics
}
| LatestTopic,
getReplies,
getHotNodes,
querySt | identifier_body |
api.ts | const HOST_URI = 'https://www.v2ex.com/api/'
// 获取节点
// 所有的节点
const ALL_NODE = 'nodes/all.json'
// 获取节点信息
// 节点id :id 节点名 :name
const NODE_INFO = 'nodes/show.json'
// 获取主题
// 取最新的主题
const LATEST_TOPIC = 'topics/latest.json'
// 获取热议主题
const HOT_TOPIC = 'topics/hot.json'
// 获取主题信息 :id | (:username | :node_id | :node_n... | tring(o)
}
function getHotNodes () {
return HOST_URI + HOT_TOPIC
}
function getLatestTopic (o?) {
return HOST_URI + LATEST_TOPIC + queryString(o)
}
function getReplies (o?) {
return HOST_URI + GET_REPLIES + queryString(o)
}
function getTopics (o?) {
return HOST_URI + GET_TOPICS + queryString(o)
}
export de... | O + queryS | identifier_name |
api.ts | const HOST_URI = 'https://www.v2ex.com/api/'
// 获取节点 | // 节点id :id 节点名 :name
const NODE_INFO = 'nodes/show.json'
// 获取主题
// 取最新的主题
const LATEST_TOPIC = 'topics/latest.json'
// 获取热议主题
const HOT_TOPIC = 'topics/hot.json'
// 获取主题信息 :id | (:username | :node_id | :node_name)
const GET_TOPICS = 'topics/show.json'
// 获取回复 :topic_id (:page , :page_size)?
const GET_REPLIES = 're... | // 所有的节点
const ALL_NODE = 'nodes/all.json'
// 获取节点信息 | random_line_split |
group.client.controller.js | 'use strict';
angular.module('groups').controller('GroupsController', ['$scope', '$state', '$stateParams', '$http', 'Authentication', 'Groups', function ($scope, $state, $stateParams, $http, Authentication, Groups) {
$scope.authentication = Authentication;
// Create a new group
$scope.create = function (isValid) ... |
group.$update(function() {
$state.go('groups.view', {
groupId: group._id
});
}, function (errorResponse) {
$scope.error = errorResponse.data.message;
});
};
// Find existing group
var isMember = function (user) {
return $scope.group.members.length > 0 && undefined !== $scope.group.members.find... | {
if ($scope.students[i]) {
group.members.push($scope.studentsList[i]);
}
} | conditional_block |
group.client.controller.js | 'use strict';
angular.module('groups').controller('GroupsController', ['$scope', '$state', '$stateParams', '$http', 'Authentication', 'Groups', function ($scope, $state, $stateParams, $http, Authentication, Groups) {
$scope.authentication = Authentication;
// Create a new group
$scope.create = function (isValid) ... | });
// Redirect after save
group.$save(function (response) {
$state.go('groups.view', {
groupId: response._id
});
// Clear form fields
$scope.name = '';
}, function (errorResponse) {
$scope.error = errorResponse.data.message;
});
};
// Update a group
$scope.update = function (isValid)... | // Create a new Groups object
var group = new Groups({
name: this.name | random_line_split |
search_errors.rs | use std::env;
use std::fs::File;
use std::io::{BufWriter, Write};
use std::path::PathBuf;
use calamine::{open_workbook_auto, DataType, Error, Reader};
use glob::{glob, GlobError, GlobResult};
#[derive(Debug)]
enum FileStatus {
VbaError(Error),
RangeError(Error),
Glob(GlobError),
}
fn main() {
// Sear... | (f: GlobResult) -> Result<(PathBuf, Option<usize>, usize), FileStatus> {
let f = f.map_err(FileStatus::Glob)?;
println!("Analysing {:?}", f.display());
let mut xl = open_workbook_auto(&f).unwrap();
let mut missing = None;
let mut cell_errors = 0;
match xl.vba_project() {
Some(Ok(vba)) ... | run | identifier_name |
search_errors.rs | use std::env;
use std::fs::File;
use std::io::{BufWriter, Write};
use std::path::PathBuf;
use calamine::{open_workbook_auto, DataType, Error, Reader};
use glob::{glob, GlobError, GlobResult};
#[derive(Debug)]
enum FileStatus {
VbaError(Error),
RangeError(Error),
Glob(GlobError),
} | // Output statistics: nb broken references, nb broken cells etc...
let folder = env::args().nth(1).unwrap_or_else(|| ".".to_string());
let pattern = format!("{}/**/*.xl*", folder);
let mut filecount = 0;
let mut output = pattern
.chars()
.take_while(|c| *c != '*')
.filter_ma... |
fn main() {
// Search recursively for all excel files matching argument pattern | random_line_split |
webhooks.rs | use std::io::Read;
use crypto::hmac::Hmac;
use crypto::mac::Mac;
use crypto::mac::MacResult;
use crypto::sha1::Sha1;
use hex::FromHex;
use iron;
use serde_json;
use DB_POOL;
use builds;
use config::CONFIG;
use error::DashResult;
use github::models::{CommentFromJson, IssueFromJson, PullRequestFromJson};
use github::{h... |
fn authenticated_handler(event: Event) -> DashResult<()> {
let conn = &*DB_POOL.get()?;
match event.payload {
Payload::Issues(issue_event) => {
handle_issue(conn, issue_event.issue, &issue_event.repository.full_name)?;
}
Payload::PullRequest(pr_event) => {
han... | {
match event_name {
"issue_comment" => Ok(Payload::IssueComment(serde_json::from_str(body)?)),
"issues" => Ok(Payload::Issues(serde_json::from_str(body)?)),
"pull_request" => Ok(Payload::PullRequest(serde_json::from_str(body)?)),
"status" => Ok(Payload::Status(serde_json::from_str(b... | identifier_body |
webhooks.rs | use std::io::Read;
use crypto::hmac::Hmac;
use crypto::mac::Mac;
use crypto::mac::MacResult;
use crypto::sha1::Sha1;
use hex::FromHex;
use iron;
use serde_json;
use DB_POOL;
use builds;
use config::CONFIG;
use error::DashResult;
use github::models::{CommentFromJson, IssueFromJson, PullRequestFromJson};
use github::{h... | {
action: String,
issue: IssueFromJson,
repository: Repository,
comment: CommentFromJson,
}
#[derive(Debug, Deserialize)]
struct PullRequestEvent {
action: String,
repository: Repository,
number: i32,
pull_request: PullRequestFromJson,
}
#[derive(Debug, Deserialize)]
struct Repository... | IssueCommentEvent | identifier_name |
webhooks.rs | use std::io::Read;
use crypto::hmac::Hmac;
use crypto::mac::Mac;
use crypto::mac::MacResult;
use crypto::sha1::Sha1;
use hex::FromHex;
use iron;
use serde_json;
use DB_POOL;
use builds;
use config::CONFIG;
use error::DashResult;
use github::models::{CommentFromJson, IssueFromJson, PullRequestFromJson};
use github::{h... |
},
Payload::Unsupported => (),
}
Ok(())
}
#[derive(Debug)]
struct Event {
delivery_id: String,
event_name: String,
payload: Payload,
}
#[derive(Debug)]
enum Payload {
Issues(IssuesEvent),
IssueComment(IssueCommentEvent),
PullRequest(PullRequestEvent),
Status(Stat... | {
if let Some(url) = status_event.target_url {
builds::ingest_status_event(url)?
}
} | conditional_block |
webhooks.rs | use std::io::Read;
use crypto::hmac::Hmac;
use crypto::mac::Mac;
use crypto::mac::MacResult;
use crypto::sha1::Sha1;
use hex::FromHex;
use iron;
use serde_json;
use DB_POOL;
use builds;
use config::CONFIG;
use error::DashResult;
use github::models::{CommentFromJson, IssueFromJson, PullRequestFromJson};
use github::{h... | }
fn authenticate(secret: &str, payload: &str, signature: &str) -> bool {
// https://developer.github.com/webhooks/securing/#validating-payloads-from-github
let sans_prefix = signature[5..].as_bytes();
match Vec::from_hex(sans_prefix) {
Ok(sigbytes) => {
let mut mac = Hmac::new(Sha1::ne... | Ok(()) | random_line_split |
test.rs | use intern::intern;
use grammar::repr::*;
use test_util::{normalized_grammar};
use super::lalr_states;
use super::super::interpret::interpret;
fn | (t: &str) -> NonterminalString {
NonterminalString(intern(t))
}
macro_rules! tokens {
($($x:expr),*) => {
vec![$(TerminalString::Quoted(intern($x))),*].into_iter()
}
}
#[test]
fn figure9_23() {
let grammar = normalized_grammar(r#"
grammar;
extern { enum Tok { } }
S: () ... | nt | identifier_name |
test.rs | use intern::intern;
use grammar::repr::*;
use test_util::{normalized_grammar};
use super::lalr_states;
use super::super::interpret::interpret;
fn nt(t: &str) -> NonterminalString |
macro_rules! tokens {
($($x:expr),*) => {
vec![$(TerminalString::Quoted(intern($x))),*].into_iter()
}
}
#[test]
fn figure9_23() {
let grammar = normalized_grammar(r#"
grammar;
extern { enum Tok { } }
S: () = E => ();
E: () = {
E "-" T => ();
... | {
NonterminalString(intern(t))
} | identifier_body |
test.rs | use intern::intern;
use grammar::repr::*;
use test_util::{normalized_grammar};
use super::lalr_states;
use super::super::interpret::interpret;
fn nt(t: &str) -> NonterminalString {
NonterminalString(intern(t))
}
macro_rules! tokens {
($($x:expr),*) => {
vec![$(TerminalString::Quoted(intern($x))),*].in... | E "-" T => ();
T => ();
};
T: () = {
"N" => ();
"(" E ")" => ();
};
"#);
let states = lalr_states(&grammar, nt("S")).unwrap();
println!("{:#?}", states);
let tree = interpret(&states, tokens!["N", "-", "(", ... | extern { enum Tok { } }
S: () = E => ();
E: () = { | random_line_split |
setTextContent.js | /**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ... |
module.exports = setTextContent;
| {
if (!('textContent' in document.documentElement)) {
setTextContent = function(node, text) {
setInnerHTML(node, escapeTextContentForBrowser(text));
};
}
} | conditional_block |
setTextContent.js | /**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ... | /**
* Set the textContent property of a node, ensuring that whitespace is preserved
* even in IE8. innerText is a poor substitute for textContent and, among many
* issues, inserts <br> instead of the literal newline chars. innerHTML behaves
* as it should.
*
* @param {DOMElement} node
* @param {string} text
* @... |
var ExecutionEnvironment = require("./ExecutionEnvironment");
var escapeTextContentForBrowser = require("./escapeTextContentForBrowser");
var setInnerHTML = require("./setInnerHTML");
| random_line_split |
CreateUser.js | 'use strict'
exports.register = function(server, options, next){
server.route([
{
method: 'GET',
path: '/createuser',
config: {
// Uncomment for security
//auth: { | '<form method="post" action="/createuser">' +
'New Username:<br><input type="text" name="create_username" ><br>' +
'New Email:<br><input type="text" name="create_email" ><br>' +
'New Password:<br><input type="password" name="create_password"><br/><br/>' +
'Scope:<br><input type="text" name... | // strategy: 'standard',
// scope: 'admin'
//},
handler: function(request, reply) {
return reply('<html><head><title>User Creation</title></head><body>' + | random_line_split |
lib.rs | #![warn(rust_2018_idioms, missing_debug_implementations, missing_docs)]
//! `nib` provides useful abstractions for working with data that is described/structure in 4-bit
//! chunks.
//!
//!
//! ```
//! use quartet::NibSlice;
//! let nib_slice = NibSlice::from_bytes_skip_last(&[0x12, 0x34, 0x50]);
//! assert_eq!(nib_sli... | (self, slice: &NibSlice<'a>) -> Option<Self::Output> {
Some(*slice)
}
}
impl<'a> SliceIndex<'a> for ops::RangeInclusive<usize> {
type Output = NibSlice<'a>;
fn get(self, slice: &NibSlice<'a>) -> Option<Self::Output> {
(*self.start()..(*self.end() + 1)).get(slice)
}
}
impl<'a> SliceInd... | get | identifier_name |
lib.rs | #![warn(rust_2018_idioms, missing_debug_implementations, missing_docs)]
//! `nib` provides useful abstractions for working with data that is described/structure in 4-bit
//! chunks.
//!
//!
//! ```
//! use quartet::NibSlice;
//! let nib_slice = NibSlice::from_bytes_skip_last(&[0x12, 0x34, 0x50]);
//! assert_eq!(nib_sli... | else {
let v = self.inner.inner[0] >> 4;
self.inner.exclude = Exclude::from_excludes(true, self.inner.exclude.is_last_excluded());
v
};
if self.inner.inner.len() == 0 {
self.inner.exclude = Exclude::None_;
}
if self.inner.inner.len() == 1... | {
let v = self.inner.inner[0] & 0x0f;
self.inner.inner = &self.inner.inner[1..];
self.inner.exclude = Exclude::from_excludes(false, self.inner.exclude.is_last_excluded());
v
} | conditional_block |
lib.rs | #![warn(rust_2018_idioms, missing_debug_implementations, missing_docs)]
//! `nib` provides useful abstractions for working with data that is described/structure in 4-bit
//! chunks.
//!
//!
//! ```
//! use quartet::NibSlice;
//! let nib_slice = NibSlice::from_bytes_skip_last(&[0x12, 0x34, 0x50]);
//! assert_eq!(nib_sli... | }
#[test]
fn index_middle() {
let ns = NibSlice::from_bytes_exclude(&[0x12, 0x34, 0x56], Exclude::Both);
let n = ns.index(2..4);
assert_eq!(n, NibSlice::from_bytes(&[0x45]));
}
#[test]
fn iter() {
let ns = NibSlice::from_bytes_exclude(&[0x12, 0x34], Exclude::Bot... |
assert_eq!(nib, 0x2); | random_line_split |
lib.rs | #![warn(rust_2018_idioms, missing_debug_implementations, missing_docs)]
//! `nib` provides useful abstractions for working with data that is described/structure in 4-bit
//! chunks.
//!
//!
//! ```
//! use quartet::NibSlice;
//! let nib_slice = NibSlice::from_bytes_skip_last(&[0x12, 0x34, 0x50]);
//! assert_eq!(nib_sli... |
/// Decompose a nibble offset into byte oriented terms.
///
/// Returns `(byte_offset, is_low)`. `byte_offset` is a offset into a `[u8]`. `is_low` is true when
/// the `offs` refers to the lower nibble in the byte located at `byte_offset`.
pub fn decompose_offset(exclude: Exclude, offs: usize) -> (usize, bool) {
... | {
let index = offs + if exclude.is_first_excluded() { 1 } else { 0 };
let b_idx = index >> 1;
let is_low = index & 1 == 1;
(b_idx, is_low)
} | identifier_body |
command.rs | use std::error;
use clap;
use crate::config;
use super::executer::{Executer, ExecuterOptions};
pub struct Command<'c> {
config: &'c config::command::Config,
name: Option<&'c str>,
no_wait: bool,
all: bool,
}
impl<'c> Command<'c> {
pub fn from_args(config: &'c config::command::Config, args: &'c ... |
pub fn new(
config: &'c config::command::Config,
name: Option<&'c str>,
no_wait: bool,
all: bool,
) -> Self {
trace!("command::service::deploy::Command::new");
Command {
config: config,
name: name,
no_wait: no_wait,
... | {
trace!("command::service::deploy::Command::from_args");
Command {
config: config,
name: args.value_of("NAME"),
no_wait: args.is_present("NO_WAIT"),
all: args.is_present("ALL"),
}
} | identifier_body |
command.rs | use std::error;
use clap;
use crate::config;
use super::executer::{Executer, ExecuterOptions};
pub struct Command<'c> {
config: &'c config::command::Config,
name: Option<&'c str>, | }
impl<'c> Command<'c> {
pub fn from_args(config: &'c config::command::Config, args: &'c clap::ArgMatches<'c>) -> Self {
trace!("command::service::deploy::Command::from_args");
Command {
config: config,
name: args.value_of("NAME"),
no_wait: args.is_present("NO_W... | no_wait: bool,
all: bool, | random_line_split |
command.rs | use std::error;
use clap;
use crate::config;
use super::executer::{Executer, ExecuterOptions};
pub struct Command<'c> {
config: &'c config::command::Config,
name: Option<&'c str>,
no_wait: bool,
all: bool,
}
impl<'c> Command<'c> {
pub fn | (config: &'c config::command::Config, args: &'c clap::ArgMatches<'c>) -> Self {
trace!("command::service::deploy::Command::from_args");
Command {
config: config,
name: args.value_of("NAME"),
no_wait: args.is_present("NO_WAIT"),
all: args.is_present("ALL")... | from_args | identifier_name |
command.rs | use std::error;
use clap;
use crate::config;
use super::executer::{Executer, ExecuterOptions};
pub struct Command<'c> {
config: &'c config::command::Config,
name: Option<&'c str>,
no_wait: bool,
all: bool,
}
impl<'c> Command<'c> {
pub fn from_args(config: &'c config::command::Config, args: &'c ... |
Ok(())
}
}
| {
for service_config in service_config_group {
let mut runnable: bool = false;
if let Some(name) = self.name {
if name == service_config.name {
runnable = true;
}
}
if self.all {
... | conditional_block |
regions-proc-bound-capture.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 main() { } | random_line_split | |
regions-proc-bound-capture.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 static_proc(x: &isize) -> Box<FnMut()->(isize) + 'static> {
// This is illegal, because the region bound on `proc` is 'static.
Box::new(move|| { *x }) //~ ERROR captured variable `x` does not outlive the enclosing closure
}
fn main() { }
| {
// This is legal, because the region bound on `proc`
// states that it captures `x`.
Box::new(move|| { *x })
} | identifier_body |
regions-proc-bound-capture.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 ... | <'a>(x: &'a isize) -> Box<FnMut()->(isize) + 'a> {
// This is legal, because the region bound on `proc`
// states that it captures `x`.
Box::new(move|| { *x })
}
fn static_proc(x: &isize) -> Box<FnMut()->(isize) + 'static> {
// This is illegal, because the region bound on `proc` is 'static.
Box::ne... | borrowed_proc | identifier_name |
feeds.py | from django_ical.views import ICalFeed
from .models import Meeting
from datetime import timedelta
class MeetingFeed(ICalFeed):
"""
A iCal feed for meetings
"""
product_id = '-//chipy.org//Meeting//EN'
timezone = 'CST'
def items(self):
return Meeting.objects.order_by('-when').all()
... | (self, item):
return item.when + timedelta(hours=1)
def item_title(self, item):
return 'ChiPy Meeting'
| item_end_datetime | identifier_name |
feeds.py | from django_ical.views import ICalFeed
from .models import Meeting
from datetime import timedelta
class MeetingFeed(ICalFeed):
"""
A iCal feed for meetings
"""
product_id = '-//chipy.org//Meeting//EN'
timezone = 'CST'
def items(self):
return Meeting.objects.order_by('-when').all()
... |
def item_end_datetime(self, item):
return item.when + timedelta(hours=1)
def item_title(self, item):
return 'ChiPy Meeting'
| return item.when | identifier_body |
feeds.py | from django_ical.views import ICalFeed
from .models import Meeting
from datetime import timedelta
class MeetingFeed(ICalFeed):
"""
A iCal feed for meetings
"""
product_id = '-//chipy.org//Meeting//EN'
timezone = 'CST'
def items(self):
return Meeting.objects.order_by('-when').all()
... |
description += u'{title} by {speaker}\n{description}\n\n'.format(
title=topic.title,
speaker=presentor_name,
description=topic.description)
return description
def item_link(self, item):
return ''
def item_location(... | presentor_name = topic.presentors.all()[0].name | conditional_block |
feeds.py | from django_ical.views import ICalFeed
from .models import Meeting
from datetime import timedelta
class MeetingFeed(ICalFeed):
"""
A iCal feed for meetings
"""
product_id = '-//chipy.org//Meeting//EN'
timezone = 'CST'
def items(self):
return Meeting.objects.order_by('-when').all()
... | presentor_name = topic.presentors.all()[0].name
description += u'{title} by {speaker}\n{description}\n\n'.format(
title=topic.title,
speaker=presentor_name,
description=topic.description)
return description
def i... | if topic.presentors.count() > 0: | random_line_split |
models.py | # -*- coding:utf-8 -*-
from __future__ import unicode_literals
from django.db import models
from django.utils import timezone
from django.utils.text import slugify
from django.contrib.auth.models import User
ROOM_TYPE = (
(1, u'Privado'),
(2, u'Grupo'),
)
class Room(models.Model):
name = models.TextField(... |
def as_dict(self):
return {'handle': "%s - %s" % (self.handle.id, self.handle.get_full_name()), 'message': self.message, 'timestamp': self.formatted_timestamp}
SEXO = (
(1, u'Masculino'),
(2, u'Feminino'),
)
class UserProfile(models.Model):
user = models.ForeignKey(User, verbose_name=u'Usu... | turn self.timestamp.strftime('%d/%m/%Y %-I:%M')
| identifier_body |
models.py | # -*- coding:utf-8 -*-
from __future__ import unicode_literals
from django.db import models
from django.utils import timezone
from django.utils.text import slugify
from django.contrib.auth.models import User
ROOM_TYPE = (
(1, u'Privado'),
(2, u'Grupo'),
)
class Room(models.Model):
name = models.TextField(... | lf):
return unicode(self.user.first_name) | nicode__(se | identifier_name |
models.py | # -*- coding:utf-8 -*-
from __future__ import unicode_literals
from django.db import models
from django.utils import timezone
from django.utils.text import slugify
from django.contrib.auth.models import User
ROOM_TYPE = (
(1, u'Privado'),
(2, u'Grupo'),
)
class Room(models.Model):
name = models.TextField(... |
def __unicode__(self):
return self.label
class Message(models.Model):
room = models.ForeignKey(Room, verbose_name=u'Sala', related_name='messages')
handle = models.ForeignKey(User, verbose_name=u'Usuário', related_name='message_user')
message = models.TextField()
timestamp = models.DateTim... |
def save(self, *args, **kwargs):
self.label = slugify(self.name)
return super(Room, self).save(*args, **kwargs) | random_line_split |
mouseTracking.js | 'use strict';
angular.module('mismatchServices').factory('mouseTracking', ['$q', function($q) {
var tracker = {
position: {
'x': 0,
'y': 0
},
trackingTimer: null,
trackingData: "",
updatingFrequency: 17.0,
setUpdatingFrequency: function(updatingFrequency) {
tracker.updating... | if(deltaTime < 1000) {
deltaTimeSum += deltaTime;
// Mock processing
tracker.position.x = event.clientX;
tracker.position.y = event.clientY;
deltaTime = window.performance.now();
deltaSamples++;
}
// Stop calibration after 100 sample... | // Calculate delta
deltaTime = window.performance.now() - deltaTime;
// Remove deltas above one second | random_line_split |
mouseTracking.js | 'use strict';
angular.module('mismatchServices').factory('mouseTracking', ['$q', function($q) {
var tracker = {
position: {
'x': 0,
'y': 0
},
trackingTimer: null,
trackingData: "",
updatingFrequency: 17.0,
setUpdatingFrequency: function(updatingFrequency) {
tracker.updating... |
};
return defer.promise;
},
startTracking: function() {
console.log('Tracking at ' + 1000/tracker.updatingFrequency + ' hz');
document.onmousemove = function(event) {
tracker.position.x = event.clientX;
tracker.position.y = event.clientY;
};
tracker.track... | {
document.onmousemove = null;
// Caclulate mean delta and return
defer.resolve( deltaTimeSum/deltaSamples );
} | conditional_block |
html-literals.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | )
);
(
[$(:$tags:ident ($(:$tag_nodes:expr),*) )*];
[$(:$nodes:expr),*];
<$tag:ident> $($rest:tt)*
) => (
parse_node!(
[:$tag ($(:$nodes)*) $(: $tags ($(:$tag_nodes),*) )*];
[];
$($rest)*
)
);
(
[$(:$tags:i... | [$(: $tags ($(:$tag_nodes),*))*];
[$(:$head_nodes,)* :tag(stringify!($head).to_string(),
vec![$($nodes),*])];
$($rest)* | random_line_split |
html-literals.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {
let _page = html! (
<html>
<head><title>This is the title.</title></head>
<body>
<p>This is some text</p>
</body>
</html>
);
}
enum HTMLFragment {
tag(String, Vec<HTMLFragment> ),
text(String),
}
| main | identifier_name |
gr-copy-clipboard_test.ts | /**
* @license
* Copyright (C) 2017 The Android Open Source Project
*
* 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 require... | });
test('focusOnCopy', () => {
element.focusOnCopy();
const activeElement = element.shadowRoot!.activeElement;
const button = queryAndAssert(element, '.copyToClipboard');
assert.deepEqual(activeElement, button);
});
test('_handleInputClick', () => {
// iron-input as parent should never be... | MockInteractions.click(copyBtn);
assert.isTrue(clipboardSpy.called); | random_line_split |
intl.js | define(function (require, exports, module) {
'use strict';
var data = {
'defaultLocale': 'en-US',
'systemLocales': ['en-US']
}
/* I18n API TC39 6.2.2 */
function isStructurallyValidLanguageTag(locale) {
return true;
}
/* I18n API TC39 6.2.3 */
function canonicalizeLanguageTag(locale) {
... |
/* I18n API TC39 9.2.2 */
function bestAvailableLocale(availableLocales, locale) {
var candidate = locale;
while (1) {
if (availableLocales.indexOf(candidate) !== -1) {
return candidate;
}
var pos = candidate.lastIndexOf('-');
if (pos === -1) {
return undefined;
... | {
if (locales === undefined) {
return [];
}
var seen = [];
if (typeof(locales) == 'string') {
locales = new Array(locales);
}
var len = locales.length;
var k = 0;
while (k < len) {
var Pk = k.toString();
var kPresent = locales.hasOwnProperty(Pk);
... | identifier_body |
intl.js | define(function (require, exports, module) {
'use strict';
var data = {
'defaultLocale': 'en-US',
'systemLocales': ['en-US']
}
/* I18n API TC39 6.2.2 */
function isStructurallyValidLanguageTag(locale) {
return true;
}
/* I18n API TC39 6.2.3 */
function canonicalizeLanguageTag(locale) {
... |
}
if (supportedExtension.length > 2) {
var preExtension = foundLocale.substr(0, extensionIndex);
var postExtension = foundLocale.substr(extensionIndex+1);
var foundLocale = preExtension + supportedExtension + postExtension;
}
result.locale = foundLocale;
return result;
}
/**... | {
var optionsValue = options.key;
if (keyLocaleData.indexOf(optionsValue) !== -1) {
if (optionsValue !== value) {
value = optionsValue;
supportedExtensionAddition = "";
}
}
result.key = value;
supportedExtension += supportedExtensionAdd... | conditional_block |
intl.js | define(function (require, exports, module) {
'use strict';
var data = {
'defaultLocale': 'en-US',
'systemLocales': ['en-US']
}
/* I18n API TC39 6.2.2 */
function isStructurallyValidLanguageTag(locale) {
return true;
}
/* I18n API TC39 6.2.3 */
function canonicalizeLanguageTag(locale) {
... | var i = 0;
var len = 0;
if (relevantExtensionKeys !== undefined) {
len = relevantExtensionKeys.length;
}
while (i < len) {
var key = relevantExtensionKeys[i.toString()];
var foundLocaleData = localeData(foundLocale);
var keyLocaleData = foundLocaleData[foundLocale];
... | var result = {};
result.dataLocale = foundLocale;
var supportedExtension = "-u";
| random_line_split |
intl.js | define(function (require, exports, module) {
'use strict';
var data = {
'defaultLocale': 'en-US',
'systemLocales': ['en-US']
}
/* I18n API TC39 6.2.2 */
function isStructurallyValidLanguageTag(locale) {
return true;
}
/* I18n API TC39 6.2.3 */
function canonicalizeLanguageTag(locale) {
... | (availableLocales, requestedLocales) {
var options = {'localeMatcher': 'lookup'};
var tag = resolveLocale(availableLocales,
requestedLocales, options);
var pos = availableLocales.indexOf(tag.locale)
if (pos === -1) {
// not sure why resolveLocale can return a locale th... | prioritizeLocales | identifier_name |
__init__.py | """
GraphLab Create offers several data structures for data analysis.
| <https://dato.com/learn/userguide/>`_, `API Translator
<https://dato.com/learn/translator/>`_, `How-Tos
<https://dato.com/learn/how-to/>`_, and data science `Gallery
<https://dato.com/learn/gallery/>`_.
"""
'''
Copyright (C) 2015 Dato, Inc.
All rights reserved.
This software may be modified and distributed under the ... | Concise descriptions of the data structures and their methods are contained in
the API documentation, along with a small number of simple examples. For more
detailed descriptions and examples, please see the `User Guide | random_line_split |
sceper.py | # -*- coding: utf-8 -*-
'''
fantastic Add-on
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This pro... | try:
t = client.parseDOM(post, 'title')[0]
c = client.parseDOM(post, 'content.+?')[0]
s = re.findall('((?:\d+\.\d+|\d+\,\d+|\d+) (?:GB|GiB|MB|MiB))', c)
s = s[0] if s else '0'
u = zip(client.parseDOM(c... | hostDict = hostprDict
items = []
for post in posts: | random_line_split |
sceper.py | # -*- coding: utf-8 -*-
'''
fantastic Add-on
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This pro... |
url = client.replaceHTMLCodes(url)
url = url.encode('utf-8')
host = re.findall('([\w]+[.][\w]+)$', urlparse.urlparse(url.strip().lower()).netloc)[0]
if not host in hostDict: raise Exception()
host = client.replaceHTMLC... | raise Exception() | conditional_block |
sceper.py | # -*- coding: utf-8 -*-
'''
fantastic Add-on
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This pro... | (self):
self.priority = 1
self.language = ['en']
self.domains = ['sceper.ws','sceper.unblocked.pro']
self.base_link = 'https://sceper.unblocked.pro'
self.search_link = '/search/%s/feed/rss2/'
def movie(self, imdb, title, localtitle, aliases, year):
try:
u... | __init__ | identifier_name |
sceper.py | # -*- coding: utf-8 -*-
'''
fantastic Add-on
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This pro... |
def resolve(self, url):
return url
| try:
sources = []
if url == None: return sources
if debrid.status() == False: raise Exception()
data = urlparse.parse_qs(url)
data = dict([(i, data[i][0]) if data[i] else (i, '') for i in data])
title = data['tvshowtitle'] if 'tvshowtitle' in d... | identifier_body |
sensor.py | """Support for the Foobot indoor air quality monitor."""
import asyncio
from datetime import timedelta
import logging
import aiohttp
from foobot_async import FoobotClient
import voluptuous as vol
from homeassistant.const import (
ATTR_TEMPERATURE,
ATTR_TIME,
CONF_TOKEN,
CONF_USERNAME,
TEMP_CELSIUS... |
@property
def state(self):
"""Return the state of the device."""
try:
data = self.foobot_data.data[self.type]
except (KeyError, TypeError):
data = None
return data
@property
def unique_id(self):
"""Return the unique id of this entity."""
... | ""Icon to use in the frontend."""
return SENSOR_TYPES[self.type][2]
| identifier_body |
sensor.py | """Support for the Foobot indoor air quality monitor."""
import asyncio
from datetime import timedelta
import logging
import aiohttp
from foobot_async import FoobotClient
import voluptuous as vol
from homeassistant.const import (
ATTR_TEMPERATURE,
ATTR_TIME,
CONF_TOKEN,
CONF_USERNAME,
TEMP_CELSIUS... | except (
aiohttp.client_exceptions.ClientConnectorError,
asyncio.TimeoutError,
FoobotClient.TooManyRequests,
FoobotClient.InternalError,
):
_LOGGER.exception("Failed to connect to foobot servers.")
raise PlatformNotReady
except FoobotClient.ClientError:
... | oobot_data = FoobotData(client, device["uuid"])
for sensor_type in SENSOR_TYPES:
if sensor_type == "time":
continue
foobot_sensor = FoobotSensor(foobot_data, device, sensor_type)
dev.append(foobot_sensor)
| conditional_block |
sensor.py | """Support for the Foobot indoor air quality monitor."""
import asyncio
from datetime import timedelta
import logging
import aiohttp
from foobot_async import FoobotClient
import voluptuous as vol
from homeassistant.const import (
ATTR_TEMPERATURE,
ATTR_TIME,
CONF_TOKEN,
CONF_USERNAME,
TEMP_CELSIUS... | self):
"""Get the latest data."""
await self.foobot_data.async_update()
class FoobotData(Entity):
"""Get data from Foobot API."""
def __init__(self, client, uuid):
"""Initialize the data object."""
self._client = client
self._uuid = uuid
self.data = {}
@Th... | sync_update( | identifier_name |
sensor.py | """Support for the Foobot indoor air quality monitor."""
import asyncio
from datetime import timedelta
import logging
import aiohttp
from foobot_async import FoobotClient
import voluptuous as vol
from homeassistant.const import (
ATTR_TEMPERATURE,
ATTR_TIME,
CONF_TOKEN,
CONF_USERNAME,
TEMP_CELSIUS... | ATTR_PM2_5 = "PM2.5"
ATTR_CARBON_DIOXIDE = "CO2"
ATTR_VOLATILE_ORGANIC_COMPOUNDS = "VOC"
ATTR_FOOBOT_INDEX = "index"
SENSOR_TYPES = {
"time": [ATTR_TIME, "s"],
"pm": [ATTR_PM2_5, "µg/m3", "mdi:cloud"],
"tmp": [ATTR_TEMPERATURE, TEMP_CELSIUS, "mdi:thermometer"],
"hum": [ATTR_HUMIDITY, "%", "mdi:water-pe... | _LOGGER = logging.getLogger(__name__)
ATTR_HUMIDITY = "humidity" | random_line_split |
list_devices.rs | extern crate libudev;
use std::io;
fn main() {
let context = libudev::Context::new().unwrap();
list_devices(&context).unwrap();
}
fn list_devices(context: &libudev::Context) -> io::Result<()> | {
let mut enumerator = try!(libudev::Enumerator::new(&context));
for device in try!(enumerator.scan_devices()) {
println!("");
println!("initialized: {:?}", device.is_initialized());
println!(" devnum: {:?}", device.devnum());
println!(" syspath: {:?}", device.syspath());... | identifier_body | |
list_devices.rs | extern crate libudev;
use std::io;
fn | () {
let context = libudev::Context::new().unwrap();
list_devices(&context).unwrap();
}
fn list_devices(context: &libudev::Context) -> io::Result<()> {
let mut enumerator = try!(libudev::Enumerator::new(&context));
for device in try!(enumerator.scan_devices()) {
println!("");
println!(... | main | identifier_name |
list_devices.rs | extern crate libudev;
use std::io;
fn main() {
let context = libudev::Context::new().unwrap();
list_devices(&context).unwrap();
}
fn list_devices(context: &libudev::Context) -> io::Result<()> {
let mut enumerator = try!(libudev::Enumerator::new(&context));
for device in try!(enumerator.scan_devices(... |
println!(" [properties]");
for property in device.properties() {
println!(" - {:?} {:?}", property.name(), property.value());
}
println!(" [attributes]");
for attribute in device.attributes() {
println!(" - {:?} {:?}", attribute.name(), attribut... | {
println!(" parent: None");
} | conditional_block |
list_devices.rs | extern crate libudev;
use std::io;
fn main() {
let context = libudev::Context::new().unwrap();
list_devices(&context).unwrap();
}
fn list_devices(context: &libudev::Context) -> io::Result<()> {
let mut enumerator = try!(libudev::Enumerator::new(&context));
for device in try!(enumerator.scan_devices(... | println!(" sysnum: {:?}", device.sysnum());
println!(" devtype: {:?}", device.devtype());
println!(" driver: {:?}", device.driver());
println!(" devnode: {:?}", device.devnode());
if let Some(parent) = device.parent() {
println!(" parent: {:?}", par... | println!(" syspath: {:?}", device.syspath());
println!(" devpath: {:?}", device.devpath());
println!(" subsystem: {:?}", device.subsystem());
println!(" sysname: {:?}", device.sysname()); | random_line_split |
tag-set.min.js | /**
* keta 1.11.0
* Build 2021-04-21T15:24:16.331Z
*
* Copyright Kiwigrid GmbH 2014-2021
* http://kiwigrid.github.io/keta/
*
* Licensed under MIT License
* https://raw.githubusercontent.com/kiwigrid/keta/master/LICENSE
*/ | "use strict";angular.module("keta.services.TagSet",["keta.services.Tag"]).provider("ketaTagSet",function(){this.$get=function(){var TagSetInstance=function(){var that=this,tags=[],tagsAsHierarchy={};that.getTags=function(){return tags},that.getTagsAsHierarchy=function(){return tagsAsHierarchy},that.add=function(tag){re... | random_line_split | |
index.js | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you ... | }
}
}
}
})
;
$urlRouterProvider.otherwise('/');
}); | return serverService.getServer($stateParams.serverId);
},
serverDeliveryServices: function($stateParams, deliveryServiceService) {
return deliveryServiceService.getServerDeliveryServices($stateParams.serverId); | random_line_split |
mod.rs | use std::str::Chars;
use std::iter::Peekable;
/// The input stream operates on an input string and provides character-wise access.
pub struct InputStream<'a> {
/// The input string.
input: &'a str,
/// The position of the next character in the input string. | pos: usize,
/// The iterator over the input string.
iterator: Peekable<Chars<'a>>
}
impl<'a> InputStream<'a> {
/// Generates a new InputStream instance.
pub fn new(input: &'a str) -> InputStream<'a> {
InputStream{input: input, pos: 0, iterator: input.chars().peekable()}
}
/// Retu... | random_line_split | |
mod.rs |
use std::str::Chars;
use std::iter::Peekable;
/// The input stream operates on an input string and provides character-wise access.
pub struct InputStream<'a> {
/// The input string.
input: &'a str,
/// The position of the next character in the input string.
pos: usize,
/// The iterator over the in... | (& mut self) -> bool {
self.iterator.peek().is_none()
}
/// Returns the current position of the input string.
pub fn get_pos(& self) -> usize {
self.pos
}
/// Returns the input string.
pub fn get_input(& self) -> & str {
& self.input
}
}
| eof | identifier_name |
mod.rs |
use std::str::Chars;
use std::iter::Peekable;
/// The input stream operates on an input string and provides character-wise access.
pub struct InputStream<'a> {
/// The input string.
input: &'a str,
/// The position of the next character in the input string.
pos: usize,
/// The iterator over the in... |
/// Returns the character of the next position of the stream and advances the stream position.
pub fn next(& mut self) -> Option<char> {
match self.iterator.next() {
Some(x) => {
self.pos += 1;
Some(x)
},
None => None
}
}
... | {
self.iterator.peek().map(|x| *x)
} | identifier_body |
representative.py | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of ... |
return {'value': value, 'domain': domain}
@api.one
@api.depends("image")
def _get_image(self):
""" calculate the images sizes and set the images to the corresponding
fields
"""
image = self.image
# check if the context contains the magic `bin_size` key
if self.env.context.get("bi... | domain = {'title': [('domain', '=', 'contact')]} | conditional_block |
representative.py | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of ... | "resized as a 64x64px image, with aspect ratio preserved. "\
"Use this field anywhere a small image is required.")
has_image = fields.Boolean(compute=_has_image)
color = fields.Integer('Color Index')
@api.multi
def onchange_state(self, state_id):
if state_id... | "Use this field in form views or some kanban views.")
image_small = fields.Binary(compute="_get_image",
string="Small-sized image",
store= False,
help="Small-sized image of this contact. It is automatically "\
| random_line_split |
representative.py | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of ... | (self):
""" calculate the images sizes and set the images to the corresponding
fields
"""
image = self.image
# check if the context contains the magic `bin_size` key
if self.env.context.get("bin_size"):
# refetch the image with a clean context
image = self.env[self._name].with_context... | _get_image | identifier_name |
representative.py | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of ... | """Representative"""
_name = 'odisea.representative'
_description = 'Representative'
@api.multi
def _has_image(self):
return dict((p.id, bool(p.image)) for p in self)
name = fields.Char(string='Name', required=True)
cuit = fields.Char(string='CUIT', size=13)
title = fields.Many2one('res.pa... | identifier_body | |
melcatalog-annotator-buttons.js | //
//
//
tinymce.PluginManager.add('melcatalog', function( editor ) {
function search( mode, term ) {
var url = "catalog?term=" + encodeURI( term ) + "&onlyimages=" + ( ( mode == 'image' ) ? "true" : "false" );
// Open window
editor.windowManager.open({
width: 650,
... | ( ) {
var div = $( "div" )[ 0 ];
return( jQuery.data( div, "annotation" ) );
}
// get anything to be added from the catalog
function getReferenceDetails( ) {
var div = $( "div" )[ 0 ];
var result = jQuery.data( div, "catalog" )
jQuery.data( div, "catalog", "" );
... | getOriginalText | identifier_name |
melcatalog-annotator-buttons.js | //
//
//
tinymce.PluginManager.add('melcatalog', function( editor ) {
function search( mode, term ) {
var url = "catalog?term=" + encodeURI( term ) + "&onlyimages=" + ( ( mode == 'image' ) ? "true" : "false" );
// Open window
editor.windowManager.open({
width: 650,
... |
return( term );
}
editor.addButton('mellink', {
icon: 'link',
tooltip: 'Insert/edit link to MEL Catalog object',
onclick: function( ) {
search( 'reference', getSearchTerm( ) );
}
});
editor.addButton('melimage', {
icon: 'image',
tool... | { term = note; } | conditional_block |
melcatalog-annotator-buttons.js | //
//
//
tinymce.PluginManager.add('melcatalog', function( editor ) {
function search( mode, term ) {
var url = "catalog?term=" + encodeURI( term ) + "&onlyimages=" + ( ( mode == 'image' ) ? "true" : "false" );
// Open window
editor.windowManager.open({
width: 650,
... | }
}
}
// insert a link pointing to a catalog item whose title is the name or title of the entry from the catalog
function insertReference( eid, title ) {
var url = "/documents/catalog/reference/" + eid;
var tag = "<a class=\"catalog-popup\" data-parent data-gallery=\"rem... | random_line_split | |
melcatalog-annotator-buttons.js | //
//
//
tinymce.PluginManager.add('melcatalog', function( editor ) {
function search( mode, term ) |
// insert the selected item into the annotation text
function insertCatalogReference( mode ) {
var details = getReferenceDetails( );
if( details !== undefined && details.length != 0 ) {
//alert("Got [" + details + "] mode [" + mode + "]" );
var tokens = details.split( "... | {
var url = "catalog?term=" + encodeURI( term ) + "&onlyimages=" + ( ( mode == 'image' ) ? "true" : "false" );
// Open window
editor.windowManager.open({
width: 650,
height: 650,
url: url,
title: 'Search Melville Electronic Library',
... | identifier_body |
ovirt-vm-rolling-snapshot.py | #!/usr/bin/python
import sys
import time
import datetime
import re
import ConfigParser
import os
from operator import attrgetter
scriptdir = os.path.abspath(os.path.dirname(sys.argv[0]))
conffile = scriptdir + "/ovirt-vm-rolling-snapshot.conf"
Config = ConfigParser.ConfigParser()
if not os.path.isfile(conffile):
... |
if len(Config.sections()) < 1:
print "Config file is not valid. Exiting."
sys.exit(1)
basetime = datetime.datetime.now()
for vmname in Config.sections():
starttime = time.time()
try:
etime_to_keep = int(Config.get(vmname, 'etime_to_keep'))
hourly_to_keep = int(Config.get(vmname, 'h... | random_line_split | |
ovirt-vm-rolling-snapshot.py | #!/usr/bin/python
import sys
import time
import datetime
import re
import ConfigParser
import os
from operator import attrgetter
scriptdir = os.path.abspath(os.path.dirname(sys.argv[0]))
conffile = scriptdir + "/ovirt-vm-rolling-snapshot.conf"
Config = ConfigParser.ConfigParser()
if not os.path.isfile(conffile):
... | starttime = time.time()
try:
etime_to_keep = int(Config.get(vmname, 'etime_to_keep'))
hourly_to_keep = int(Config.get(vmname, 'hourly_to_keep'))
daily_to_keep = int(Config.get(vmname, 'daily_to_keep'))
weekly_to_keep = int(Config.get(vmname, 'weekly_to_keep'))
monthly_to_ke... | conditional_block | |
seqlib.py |
# python imports
import copy
import math
import random
# rasmus imports
from rasmus import util
class SeqDict (dict):
"""
A dictionary for molecular sequences. Also keeps track of their order,
useful for reading and writing sequences from fasta's. See fasta.FastaDict
for subclass that implements F... |
assert len(seq2) == len(seq), "probabilities do not add to one"
return "".join(seq2)
def evolveKimuraBase(base, time, alpha, beta):
probs = {
's': .25 * (1 - math.e**(-4 * beta * time)),
'u': .25 * (1 + math.e**(-4 * beta * time)
- 2*math.e**(-2*(alpha+beta... | seq2.append(INT2BASE[i])
break | conditional_block |
seqlib.py |
# python imports
import copy
import math
import random
# rasmus imports
from rasmus import util
class SeqDict (dict):
"""
A dictionary for molecular sequences. Also keeps track of their order,
useful for reading and writing sequences from fasta's. See fasta.FastaDict
for subclass that implements F... | (seq, time, alpha=1, beta=1):
probs = {
's': .25 * (1 - math.e**(-4 * beta * time)),
'u': .25 * (1 + math.e**(-4 * beta * time)
- 2*math.e**(-2*(alpha+beta)*time))
}
probs['r'] = 1 - 2*probs['s'] - probs['u']
seq2 = []
for base in seq:
cdf = 0... | evolveKimuraSeq | identifier_name |
seqlib.py |
# python imports
import copy
import math
import random
# rasmus imports
from rasmus import util
class SeqDict (dict):
"""
A dictionary for molecular sequences. Also keeps track of their order,
useful for reading and writing sequences from fasta's. See fasta.FastaDict
for subclass that implements F... |
def setdefault(self, key, value):
if key not in self.names:
self.names.append(key)
dict.setdefault(self, key, value)
def clear(self):
self.names = []
dict.clear(self)
# keys are always sorted in order added
def keys(self):
return list(self.... | for key in dct:
if key not in self.names:
self.names.append(key)
dict.update(self, dct) | identifier_body |
seqlib.py | # python imports
import copy
import math
import random
# rasmus imports
from rasmus import util
class SeqDict (dict):
"""
A dictionary for molecular sequences. Also keeps track of their order,
useful for reading and writing sequences from fasta's. See fasta.FastaDict
for subclass that implements FA... | 'M':-2, 'F':-3, 'P':-1, 'S': 0, 'T':-1, 'W':-3, 'Y':-2, 'V':-2, 'B': 1, 'Z': 4, 'X':-1, '*':-4},
'G': {'A': 0, 'R':-2, 'N': 0, 'D':-1, 'C':-3, 'Q':-2, 'E':-2, 'G': 6, 'H':-2, 'I':-4, 'L':-4, 'K':-2,
'M':-3, 'F':-3, 'P':-2, 'S': 0, 'T':-2, 'W':-2, 'Y':-3, 'V':-3, 'B':-1, 'Z':-2, 'X':-... | 'Q': {'A':-1, 'R': 1, 'N': 0, 'D': 0, 'C':-3, 'Q': 5, 'E': 2, 'G':-2, 'H': 0, 'I':-3, 'L':-2, 'K': 1,
'M': 0, 'F':-3, 'P':-1, 'S': 0, 'T':-1, 'W':-2, 'Y':-1, 'V':-2, 'B': 0, 'Z': 3, 'X':-1, '*':-4},
'E': {'A':-1, 'R': 0, 'N': 0, 'D': 2, 'C':-4, 'Q': 2, 'E': 5, 'G':-2, 'H': 0, 'I':-3, 'L':-... | random_line_split |
batch.rs | // Copyright 2018 TiKV Project Authors. Licensed under Apache-2.0.
use std::pin::Pin;
use std::ptr::null_mut;
use std::sync::atomic::{AtomicBool, AtomicPtr, AtomicUsize, Ordering};
use std::sync::Arc;
use std::time::Duration;
use crossbeam::channel::{
self, RecvError, RecvTimeoutError, SendError, TryRecvError, Tr... |
#[inline]
pub fn recv_timeout(&self, timeout: Duration) -> Result<T, RecvTimeoutError> {
self.receiver.recv_timeout(timeout)
}
}
/// Creates a unbounded channel with a given `notify_size`, which means if there are more pending
/// messages in the channel than `notify_size`, the `Sender` will auto... | {
self.receiver.try_recv()
} | identifier_body |
batch.rs | // Copyright 2018 TiKV Project Authors. Licensed under Apache-2.0.
use std::pin::Pin;
use std::ptr::null_mut;
use std::sync::atomic::{AtomicBool, AtomicPtr, AtomicUsize, Ordering};
use std::sync::Arc;
use std::time::Duration;
use crossbeam::channel::{
self, RecvError, RecvTimeoutError, SendError, TryRecvError, Tr... | I: Fn() -> E + Unpin,
C: BatchCollector<E, T> + Unpin,
{
/// Creates a new `BatchReceiver` with given `initializer` and `collector`. `initializer` is
/// used to generate a initial value, and `collector` will collect every (at most
/// `max_batch_size`) raw items into the batched value.
pub fn n... | where
T: Unpin,
E: Unpin, | random_line_split |
batch.rs | // Copyright 2018 TiKV Project Authors. Licensed under Apache-2.0.
use std::pin::Pin;
use std::ptr::null_mut;
use std::sync::atomic::{AtomicBool, AtomicPtr, AtomicUsize, Ordering};
use std::sync::Arc;
use std::time::Duration;
use crossbeam::channel::{
self, RecvError, RecvTimeoutError, SendError, TryRecvError, Tr... | (&self) {
let task = Arc::new(self.clone());
let mut future_slot = self.future.lock().unwrap();
if let Some(mut future) = future_slot.take() {
let waker = task::waker_ref(&task);
let cx = &mut Context::from_waker(&*waker);
match future.... | tick | identifier_name |
alignment-gep-tup-like-1.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | (&self) -> (A, u16) {
(self.a.clone(), self.b)
}
}
fn f<A:Clone + 'static>(a: A, b: u16) -> Box<Invokable<A>+'static> {
box Invoker {
a: a,
b: b,
} as (Box<Invokable<A>+'static>)
}
pub fn main() {
let (a, b) = f(22_u64, 44u16).f();
println!("a={} b={}", a, b);
assert_eq... | f | identifier_name |
alignment-gep-tup-like-1.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | {
let (a, b) = f(22_u64, 44u16).f();
println!("a={} b={}", a, b);
assert_eq!(a, 22u64);
assert_eq!(b, 44u16);
} | identifier_body | |
alignment-gep-tup-like-1.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
// | // except according to those terms.
struct pair<A,B> {
a: A, b: B
}
trait Invokable<A> {
fn f(&self) -> (A, u16);
}
struct Invoker<A> {
a: A,
b: u16,
}
impl<A:Clone> Invokable<A> for Invoker<A> {
fn f(&self) -> (A, u16) {
(self.a.clone(), self.b)
}
}
fn f<A:Clone + 'static>(a: A, b:... | // 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 | random_line_split |
AbilityAdapter.js | const ThenAbilityAction = require('./ThenAbilityAction');
/**
* Translates the methods of a standard game action to one that will take an
* ability context => properties factory method.
*/
class AbilityAdapter {
| (action, propertyFactory) {
this.action = action;
this.propertyFactory = propertyFactory;
this.thenExecuteHandlers = [];
}
allow(context) {
let properties = this.resolveProperties(context);
return this.action.allow(properties);
}
createEvent(context) {
c... | constructor | identifier_name |
AbilityAdapter.js | const ThenAbilityAction = require('./ThenAbilityAction');
/**
* Translates the methods of a standard game action to one that will take an
* ability context => properties factory method.
*/
class AbilityAdapter {
constructor(action, propertyFactory) {
this.action = action;
this.propertyFactory = ... |
}
module.exports = AbilityAdapter;
| {
this.thenExecuteHandlers.push(handler);
return this;
} | identifier_body |
AbilityAdapter.js | const ThenAbilityAction = require('./ThenAbilityAction');
/**
* Translates the methods of a standard game action to one that will take an
* ability context => properties factory method.
*/
class AbilityAdapter { | this.propertyFactory = propertyFactory;
this.thenExecuteHandlers = [];
}
allow(context) {
let properties = this.resolveProperties(context);
return this.action.allow(properties);
}
createEvent(context) {
const properties = this.resolveProperties(context);
... | constructor(action, propertyFactory) {
this.action = action; | random_line_split |
define.ts | /*
* This file is part of CoCalc: Copyright © 2020 Sagemath, Inc.
* License: AGPLv3 s.t. "Commons Clause" – see LICENSE.md for details
*/
import { Assign, RequiredKeys } from "utility-types";
import { Optionals } from "./types";
type Requireds<T> = Pick<T, RequiredKeys<T>>;
export const required = "__!!!!!!this... | const result: Assign<U, Requireds<T>> = {} as any;
for (const key in definition) {
if (props.hasOwnProperty(key) && props[key] != undefined) {
if (definition[key] === required && props[key] == undefined) {
return maybe_error(
`misc.defaults -- TypeError: property '${key}' must be specified... | return maybe_error(
`BUG -- Traceback -- misc.defaults -- TypeError: function takes inputs as an object`
);
}
| conditional_block |
define.ts | /*
* This file is part of CoCalc: Copyright © 2020 Sagemath, Inc.
* License: AGPLv3 s.t. "Commons Clause" – see LICENSE.md for details
*/
import { Assign, RequiredKeys } from "utility-types";
import { Optionals } from "./types";
type Requireds<T> = Pick<T, RequiredKeys<T>>;
export const required = "__!!!!!!this... | unction error_addendum(props: unknown, definition: unknown) {
try {
return `(obj1=${exports.trunc(
exports.to_json(props),
1024
)}, obj2=${exports.trunc(exports.to_json(definition), 1024)})`;
} catch (err) {
return "";
}
}
| // We put explicit traces before the errors in this function,
// since otherwise they can be very hard to debug.
function maybe_error(message: string): any {
const err = `${message} ${error_addendum(props, definition)}`;
if (strict) {
throw new Error(err);
} else {
console.log(err);
c... | identifier_body |
define.ts | /*
* This file is part of CoCalc: Copyright © 2020 Sagemath, Inc.
* License: AGPLv3 s.t. "Commons Clause" – see LICENSE.md for details
*/
import { Assign, RequiredKeys } from "utility-types";
import { Optionals } from "./types";
type Requireds<T> = Pick<T, RequiredKeys<T>>;
export const required = "__!!!!!!this... | );
}
const result: Assign<U, Requireds<T>> = {} as any;
for (const key in definition) {
if (props.hasOwnProperty(key) && props[key] != undefined) {
if (definition[key] === required && props[key] == undefined) {
return maybe_error(
`misc.defaults -- TypeError: property '${key}' must... | random_line_split | |
define.ts | /*
* This file is part of CoCalc: Copyright © 2020 Sagemath, Inc.
* License: AGPLv3 s.t. "Commons Clause" – see LICENSE.md for details
*/
import { Assign, RequiredKeys } from "utility-types";
import { Optionals } from "./types";
type Requireds<T> = Pick<T, RequiredKeys<T>>;
export const required = "__!!!!!!this... | ssage: string): any {
const err = `${message} ${error_addendum(props, definition)}`;
if (strict) {
throw new Error(err);
} else {
console.log(err);
console.trace();
return definition as any;
}
}
if (props == undefined) {
props = {};
}
// Undefined was checked above b... | be_error(me | identifier_name |
Luup.ts | export module Query
{
export const OK:string = "OK";
export module ParamNames
{
export const ACTION:string = "action"; // String
export const DEVICE:string = "device"; // Integer
export const DEVICE_NUM:string = "DeviceNum"; // Integer
export const ID:string = "id"; // String
export const NAME:string = "n... | export const FILE:string = "file";
export const VARIABLE_GET:string = "variableget";
export const VARIABLE_SET:string = "variableset";
export const FIND_DEVICE:string = "finddevice";
export const RELOAD:string = "reload";
export const ALIVE:string = "alive";
export const RESYNC:string = "resync";
exp... | export const ACTIONS:string = "actions";
export const ACTION:string = "action";
export const DEVICE:string = "device";
export const SCENE:string = "scene";
export const ROOM:string = "room"; | random_line_split |
Luup.ts | export module Query
{
export const OK:string = "OK";
export module ParamNames
{
export const ACTION:string = "action"; // String
export const DEVICE:string = "device"; // Integer
export const DEVICE_NUM:string = "DeviceNum"; // Integer
export const ID:string = "id"; // String
export const NAME:string = "n... | (from:string):string
{
var fromLC = from.toLowerCase();
for(var key of Object.keys(ParamNames))
{
if(key.toLowerCase()==fromLC) return key;
}
return from;
}
export function translateParamNames(from:IUriComponentMap):IUriComponentMap
{
var result:IUriComponentMap = {};
for(var key of Object.keys(... | translateParamName | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.