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
cascaded-animation.d.ts
/** * DO NOT EDIT * * This file was automatically generated by
* * To modify these typings, edit the source file(s): * animations/cascaded-animation.html */ /// <reference path="../../polymer/types/polymer.d.ts" /> /// <reference path="../neon-animation-behavior.d.ts" /> /** * `<cascaded-animation>` applies an animation on an array of elements with a delay between each. ...
* https://github.com/Polymer/gen-typescript-declarations
random_line_split
headers.js
var specify = require('specify') , helpers = require('../helpers') , timeout = helpers.timeout , nano = helpers.nano , nock = helpers.nock ; var mock = nock(helpers.couch, "shared/headers") , db = nano.use("shared_headers") ; specify("shared_headers:setup", timeout, function (assert) { n...
function (error, helloWorld, rh) { assert.equal(error, undefined, "Should get the hello"); assert.equal(rh["status-code"], 200, "status is 'ok'"); }); }); }); specify("shared_headers:teardown", timeout, function (assert) { nano.db.destroy("shared_headers", function (err) { assert.equal(err,...
},
random_line_split
fetch.ts
import Message from '../components/Message'; import socket from '../socket'; import { SEAL_TEXT, SEAL_USER_TIMEOUT } from '../../../utils/const'; /** 用户是否被封禁 */ let isSeal = false; export default function fetch<T = any>( event: string, data = {}, { toast = true } = {}, ): Promise<[string | null, T | null...
al) { Message.error(SEAL_TEXT); return Promise.resolve([SEAL_TEXT, null]); } return new Promise((resolve) => { socket.emit(event, data, (res: any) => { if (typeof res === 'string') { if (toast) { Message.error(res); } ...
identifier_body
fetch.ts
import Message from '../components/Message'; import socket from '../socket'; import { SEAL_TEXT, SEAL_USER_TIMEOUT } from '../../../utils/const'; /** 用户是否被封禁 */ let isSeal = false; export default function fetch<T = any>
event: string, data = {}, { toast = true } = {}, ): Promise<[string | null, T | null]> { if (isSeal) { Message.error(SEAL_TEXT); return Promise.resolve([SEAL_TEXT, null]); } return new Promise((resolve) => { socket.emit(event, data, (res: any) => { if (typeof res...
(
identifier_name
fetch.ts
import Message from '../components/Message'; import socket from '../socket';
/** 用户是否被封禁 */ let isSeal = false; export default function fetch<T = any>( event: string, data = {}, { toast = true } = {}, ): Promise<[string | null, T | null]> { if (isSeal) { Message.error(SEAL_TEXT); return Promise.resolve([SEAL_TEXT, null]); } return new Promise((resolve) =...
import { SEAL_TEXT, SEAL_USER_TIMEOUT } from '../../../utils/const';
random_line_split
fetch.ts
import Message from '../components/Message'; import socket from '../socket'; import { SEAL_TEXT, SEAL_USER_TIMEOUT } from '../../../utils/const'; /** 用户是否被封禁 */ let isSeal = false; export default function fetch<T = any>( event: string, data = {}, { toast = true } = {}, ): Promise<[string | null, T | null...
}); }); }
里用的短时间 setTimeout(() => { isSeal = false; }, SEAL_USER_TIMEOUT); } resolve([res, null]); } else { resolve([null, res]); }
conditional_block
archive.py
from __future__ import print_function import sys, time import requests, urllib import demjson, shelve import os.path class Archiver: def __init__(self): """ A class for archiving URLS into the wayback machine """ self._machine = "http://archive.org/wa...
elif main is False: print("URL does not exist.") A.archive(args[1]) sys.exit(0) elif args[0] == "-outt": A.out_text(args[1]) sys.exit(0)...
print("URL exists.")
conditional_block
archive.py
from __future__ import print_function import sys, time import requests, urllib import demjson, shelve import os.path class Archiver: def __init__(self): """ A class for archiving URLS into the wayback machine """ self._machine = "http://archive.org/wa...
(self, filename): """ :param: filename Outputs a list of archived urls into text format """ map(open(filename, 'w').write, map(lambda x : x+"\n",self.archived_urls)) print("Done.") def save_data(self): """ Save...
out_text
identifier_name
archive.py
from __future__ import print_function import sys, time import requests, urllib import demjson, shelve import os.path class Archiver: def __init__(self): """ A class for archiving URLS into the wayback machine """ self._machine = "http://archive.org/wa...
sys.exit(0) elif args[0] == "-outt": A.out_text(args[1]) sys.exit(0) elif len(args) == 3: if args[0] == "-save": A.save_webpage(args[1], args[2]) sys.exi...
print("URL does not exist.") A.archive(args[1])
random_line_split
archive.py
from __future__ import print_function import sys, time import requests, urllib import demjson, shelve import os.path class Archiver: def __init__(self): """ A class for archiving URLS into the wayback machine """ self._machine = "http://archive.org/wa...
def load_data(self): """ Loads the archived URLS from a file called archived_urls.dat """ return shelve.open("archived_urls.dat")["main"] def out_text(self, filename): """ :param: filename Outputs a list of ...
""" :param: url :param: silent=False Checks if the given URL exists in the wayback machine. The silent argument if set True does not print anything to the console """ print("[Checking]: %s\n" % url) if silent == False else 0 data...
identifier_body
identity.rs
use std::ops::{Mul, MulAssign, Add, AddAssign, Div, DivAssign}; use std::marker::PhantomData; use std::cmp::{PartialOrd, Ordering}; use std::fmt; use num::{Num, Zero, One}; use num_complex::Complex; use approx::ApproxEq; use general::{AbstractMagma, AbstractGroup, AbstractLoop, AbstractMonoid, AbstractQuasigroup, ...
} impl<O: Operator> ApproxEq for Id<O> { type Epsilon = Id<O>; #[inline] fn default_epsilon() -> Self::Epsilon { Id::new() } #[inline] fn default_max_relative() -> Self::Epsilon { Id::new() } #[inline] fn default_max_ulps() -> u32 { 0 } #[inline]...
{ Id::new() }
identifier_body
identity.rs
use std::ops::{Mul, MulAssign, Add, AddAssign, Div, DivAssign}; use std::marker::PhantomData; use std::cmp::{PartialOrd, Ordering}; use std::fmt; use num::{Num, Zero, One}; use num_complex::Complex; use approx::ApproxEq; use general::{AbstractMagma, AbstractGroup, AbstractLoop, AbstractMonoid, AbstractQuasigroup, ...
(&self, _: &Self, _: Self::Epsilon, _: Self::Epsilon) -> bool { true } #[inline] fn ulps_eq(&self, _: &Self, _: Self::Epsilon, _: u32) -> bool { true } } /* * * Algebraic structures. * */ impl Mul<Id> for Id { type Output = Id; fn mul(self, _: Id) -> Id { self ...
relative_eq
identifier_name
identity.rs
use std::ops::{Mul, MulAssign, Add, AddAssign, Div, DivAssign}; use std::marker::PhantomData; use std::cmp::{PartialOrd, Ordering}; use std::fmt; use num::{Num, Zero, One}; use num_complex::Complex; use approx::ApproxEq; use general::{AbstractMagma, AbstractGroup, AbstractLoop, AbstractMonoid, AbstractQuasigroup, ...
// no-op } } impl<O: Operator> AbstractMagma<O> for Id<O> { #[inline] fn operate(&self, _: &Self) -> Id<O> { Id::new() } } impl<O: Operator> Inverse<O> for Id<O> { #[inline] fn inverse(&self) -> Self { Id::new() } #[inline] fn inverse_mut(&mut self) { ...
impl AddAssign<Id> for Id { fn add_assign(&mut self, _: Id) {
random_line_split
index.js
// external imports import axios from 'axios' import { Base64 } from 'js-base64' import path from 'path' import fm from 'front-matter' // local imports import zipObject from '../zipObject' import decrypt from '../decrypt' /** 从github调用并在本地缓存期刊内容,返回Promise。主要函数: * getContent: 调取特定期刊特定内容。如获取第1期“心智”子栏目中第2篇文章正文:getConten...
af node static appendLeaf(tree, location, leaf) { if (location.length === 0) { return leaf } else if (!tree) { tree = {} } return { ...tree, [location[0]]: magazineStorage.appendLeaf(tree[location[0]], location.slice(1), leaf) } } // build url for image imageURL = l...
// helper function to return tree with an extra le
identifier_body
index.js
// external imports import axios from 'axios' import { Base64 } from 'js-base64' import path from 'path' import fm from 'front-matter' // local imports import zipObject from '../zipObject' import decrypt from '../decrypt' /** 从github调用并在本地缓存期刊内容,返回Promise。主要函数: * getContent: 调取特定期刊特定内容。如获取第1期“心智”子栏目中第2篇文章正文:getConten...
* @return {object} 所有单篇文章。 * TODO: 仅返回一定数量各子栏目最新文章 */ getArticleAbstract = async () => { // 各栏目 const articlesContent = await Promise.all( this.columns.map(async column => { // 栏目文章列表 const articleList = Object.keys((await this.getContent(['articles', column])) || {}) //...
random_line_split
index.js
// external imports import axios from 'axios' import { Base64 } from 'js-base64' import path from 'path' import fm from 'front-matter' // local imports import zipObject from '../zipObject' import decrypt from '../decrypt' /** 从github调用并在本地缓存期刊内容,返回Promise。主要函数: * getContent: 调取特定期刊特定内容。如获取第1期“心智”子栏目中第2篇文章正文:getConten...
content from github with given path pullContent = async location => { try { const res = await this.github.get(`/repos/${this.owner}/${this.repo}/contents/${path.join(...location)}`) return res.data } catch (err) { console.warn(`Error pulling data from [${location.join(', ')}], null value wi...
...location)}` // pull
conditional_block
index.js
// external imports import axios from 'axios' import { Base64 } from 'js-base64' import path from 'path' import fm from 'front-matter' // local imports import zipObject from '../zipObject' import decrypt from '../decrypt' /** 从github调用并在本地缓存期刊内容,返回Promise。主要函数: * getContent: 调取特定期刊特定内容。如获取第1期“心智”子栏目中第2篇文章正文:getConten...
ate leaf note in a tree static locateLeaf(tree, location) { if (location.length === 0) { return tree } try { return magazineStorage.locateLeaf(tree[location[0]], location.slice(1)) } catch (err) { return null } } // helper function to return tree with an extra leaf node st...
// loc
identifier_name
125.rs
/// Quickest to just calculate sequences of squares less than the specified /// limit and determine if they are palindromic. /// /// The highest value needed to be calculated is 10^4, since 10^4*10^2 = 10^8. use std::collections::HashSet; fn is_palindrome(n: u64) -> bool { let mut nn = n; if n % 10 == 0 { ...
() { let mut seen = HashSet::new(); let mut total_sum = 0_u64; // Compute sequences from the specified start point 'outer: for n in 1..100_000 { let mut sum = n * n; for i in (n+1).. { // sequence must be at least length two sum += i * i; if sum >= 1...
main
identifier_name
125.rs
/// Quickest to just calculate sequences of squares less than the specified /// limit and determine if they are palindromic. /// /// The highest value needed to be calculated is 10^4, since 10^4*10^2 = 10^8. use std::collections::HashSet; fn is_palindrome(n: u64) -> bool { let mut nn = n; if n % 10 == 0 { ...
} } println!("{}", total_sum); }
{ total_sum += sum; seen.insert(sum); }
conditional_block
125.rs
/// Quickest to just calculate sequences of squares less than the specified /// limit and determine if they are palindromic. /// /// The highest value needed to be calculated is 10^4, since 10^4*10^2 = 10^8. use std::collections::HashSet; fn is_palindrome(n: u64) -> bool { let mut nn = n; if n % 10 == 0 { ...
let mut seen = HashSet::new(); let mut total_sum = 0_u64; // Compute sequences from the specified start point 'outer: for n in 1..100_000 { let mut sum = n * n; for i in (n+1).. { // sequence must be at least length two sum += i * i; if sum >= 100_00...
// Minor problem with something here fn main() {
random_line_split
125.rs
/// Quickest to just calculate sequences of squares less than the specified /// limit and determine if they are palindromic. /// /// The highest value needed to be calculated is 10^4, since 10^4*10^2 = 10^8. use std::collections::HashSet; fn is_palindrome(n: u64) -> bool
// Minor problem with something here fn main() { let mut seen = HashSet::new(); let mut total_sum = 0_u64; // Compute sequences from the specified start point 'outer: for n in 1..100_000 { let mut sum = n * n; for i in (n+1).. { // sequence must be at least length two ...
{ let mut nn = n; if n % 10 == 0 { false } else { let mut r = 0; while r < nn { r = 10 * r + nn % 10; nn /= 10; } nn == r || nn == r / 10 } }
identifier_body
GifPresenter.ts
/*! gifken Copyright (c) 2013 aaharu This software is released under the MIT License. https://raw.github.com/aaharu/gifken/master/LICENSE */ // @ts-ignore import { isBrowser, isWebWorker } from "browser-or-node"; export class GifPresenter { /** * Convert Gif to Blob. * * @return {Blob} BLOB */ pu...
}
{ if (isBrowser || isWebWorker) { let str = ""; bytes.forEach((buffer): void => { const codes: number[] = []; for (let i = 0, l = buffer.byteLength; i < l; ++i) { codes.push(buffer[i]); } str += String.fromCharCode.apply(null, codes); }); return "dat...
identifier_body
GifPresenter.ts
/*! gifken Copyright (c) 2013 aaharu This software is released under the MIT License. https://raw.github.com/aaharu/gifken/master/LICENSE */ // @ts-ignore import { isBrowser, isWebWorker } from "browser-or-node"; export class
{ /** * Convert Gif to Blob. * * @return {Blob} BLOB */ public static writeToBlob(bytes: Uint8Array[]): Blob { if (isBrowser || isWebWorker || typeof Blob === "function") { return new Blob(bytes, { type: "image/gif" }); } throw new Error("writeToBlob is browser-only function"); } ...
GifPresenter
identifier_name
GifPresenter.ts
/*! gifken Copyright (c) 2013 aaharu This software is released under the MIT License. https://raw.github.com/aaharu/gifken/master/LICENSE */ // @ts-ignore import { isBrowser, isWebWorker } from "browser-or-node"; export class GifPresenter { /** * Convert Gif to Blob. * * @return {Blob} BLOB */ pu...
}); return "data:image/gif;base64," + btoa(str); } return "data:image/gif;base64," + Buffer.from(bytes).toString("base64"); } }
str += String.fromCharCode.apply(null, codes);
random_line_split
GifPresenter.ts
/*! gifken Copyright (c) 2013 aaharu This software is released under the MIT License. https://raw.github.com/aaharu/gifken/master/LICENSE */ // @ts-ignore import { isBrowser, isWebWorker } from "browser-or-node"; export class GifPresenter { /** * Convert Gif to Blob. * * @return {Blob} BLOB */ pu...
throw new Error("writeToBlob is browser-only function"); } /** * Convert Gif to Data-URL string. * * @return {string} Data-URL string */ public static writeToDataUrl(bytes: Uint8Array[]): string { if (isBrowser || isWebWorker) { let str = ""; bytes.forEach((buffer): void => { ...
{ return new Blob(bytes, { type: "image/gif" }); }
conditional_block
decoding.rs
use serde::de::DeserializeOwned; use crate::algorithms::AlgorithmFamily; use crate::crypto::verify; use crate::errors::{new_error, ErrorKind, Result}; use crate::header::Header; #[cfg(feature = "use_pem")] use crate::pem::decoder::PemEncodedKey; use crate::serialization::{b64_decode, DecodedJwtPartClaims}; use crate::...
<T> { /// The decoded JWT header pub header: Header, /// The decoded JWT claims pub claims: T, } /// Takes the result of a rsplit and ensure we only get 2 parts /// Errors if we don't macro_rules! expect_two { ($iter:expr) => {{ let mut i = $iter; match (i.next(), i.next(), i.next()...
TokenData
identifier_name
decoding.rs
use serde::de::DeserializeOwned; use crate::algorithms::AlgorithmFamily; use crate::crypto::verify; use crate::errors::{new_error, ErrorKind, Result}; use crate::header::Header; #[cfg(feature = "use_pem")] use crate::pem::decoder::PemEncodedKey; use crate::serialization::{b64_decode, DecodedJwtPartClaims}; use crate::...
/// let token_message = decode::<Claims>(&token, &DecodingKey::from_secret("secret".as_ref()), &Validation::new(Algorithm::HS256)); /// ``` pub fn decode<T: DeserializeOwned>( token: &str, key: &DecodingKey, validation: &Validation, ) -> Result<TokenData<T>> { match verify_signature(token, key, validati...
/// let token = "a.jwt.token".to_string(); /// // Claims is a struct that implements Deserialize
random_line_split
decoding.rs
use serde::de::DeserializeOwned; use crate::algorithms::AlgorithmFamily; use crate::crypto::verify; use crate::errors::{new_error, ErrorKind, Result}; use crate::header::Header; #[cfg(feature = "use_pem")] use crate::pem::decoder::PemEncodedKey; use crate::serialization::{b64_decode, DecodedJwtPartClaims}; use crate::...
} /// Verify signature of a JWT, and return header object and raw payload /// /// If the token or its signature is invalid, it will return an error. fn verify_signature<'a>( token: &'a str, key: &DecodingKey, validation: &Validation, ) -> Result<(Header, &'a str)> { if validation.validate_signature &&...
{ match &self.kind { DecodingKeyKind::SecretOrDer(b) => b, DecodingKeyKind::RsaModulusExponent { .. } => unreachable!(), } }
identifier_body
trait-with-bounds-default.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
(&self) -> T { self.get_ref().clone() } } pub fn main() { assert_eq!(3.do_get2(), (3, 3)); assert_eq!(Some(~"hi").do_get2(), (~"hi", ~"hi")); }
do_get
identifier_name
trait-with-bounds-default.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
} impl<T: Clone> Getter<T> for Option<T> { fn do_get(&self) -> T { self.get_ref().clone() } } pub fn main() { assert_eq!(3.do_get2(), (3, 3)); assert_eq!(Some(~"hi").do_get2(), (~"hi", ~"hi")); }
{ *self }
identifier_body
trait-with-bounds-default.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
pub fn main() { assert_eq!(3.do_get2(), (3, 3)); assert_eq!(Some(~"hi").do_get2(), (~"hi", ~"hi")); }
} impl<T: Clone> Getter<T> for Option<T> { fn do_get(&self) -> T { self.get_ref().clone() } }
random_line_split
ajax.py
from django.utils import simplejson from dajaxice.decorators import dajaxice_register from django.utils.translation import ugettext as _ from django.template.loader import render_to_string from dajax.core import Dajax from django.db import transaction from darkoob.book.models import Book, Review @dajaxice_register(m...
(request, rate, review_id): print "review id",review_id done = False try: review = Review.objects.get(id=review_id) review.rating.add(score=rate, user=request.user, ip_address=request.META['REMOTE_ADDR']) except: errors.append('An error occoured in record in database') tr...
review_rate
identifier_name
ajax.py
from django.utils import simplejson from dajaxice.decorators import dajaxice_register from django.utils.translation import ugettext as _ from django.template.loader import render_to_string from dajax.core import Dajax from django.db import transaction from darkoob.book.models import Book, Review @dajaxice_register(m...
@dajaxice_register(method='POST') @transaction.commit_manually def review_rate(request, rate, review_id): print "review id",review_id done = False try: review = Review.objects.get(id=review_id) review.rating.add(score=rate, user=request.user, ip_address=request.META['REMOTE_ADDR']) exce...
random_line_split
ajax.py
from django.utils import simplejson from dajaxice.decorators import dajaxice_register from django.utils.translation import ugettext as _ from django.template.loader import render_to_string from dajax.core import Dajax from django.db import transaction from darkoob.book.models import Book, Review @dajaxice_register(m...
print "book_name", book_name return simplejson.dumps({'done': True})
identifier_body
ajax.py
from django.utils import simplejson from dajaxice.decorators import dajaxice_register from django.utils.translation import ugettext as _ from django.template.loader import render_to_string from dajax.core import Dajax from django.db import transaction from darkoob.book.models import Book, Review @dajaxice_register(m...
else: review = Review.objects.create(book=book, user=request.user, title=title, text=text) t_rendered = render_to_string('book/review.html', {'review': review}) dajax.prepend('#id_new_post_position', 'innerHTML', t_rendered) dajax.script(''' $...
transaction.rollback() dajax.script(''' $.pnotify({ title: 'Review', type:'error', text: 'Complete your review. We need some checks', opacity: .8 }); $('#id_text').val(''); $('#id_title'...
conditional_block
mconf.py
# Copyright 2014-2016 The Meson development team # 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 agree...
(self, options): result = {} for k, o in options.items(): subproject = '' if ':' in k: subproject, optname = k.split(':') if o.yielding and optname in options: self.yielding_options.add(k) self.all_subprojects.ad...
split_options_per_subproject
identifier_name
mconf.py
# Copyright 2014-2016 The Meson development team # 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 agree...
self.print_options('Directories', dir_options) self.print_options('Testing options', test_options) self.print_options('Project options', project_options.get('', {})) for subproject in sorted(self.all_subprojects): if subproject == '': continue sel...
self.print_options('', build_compiler_options.get('', {}))
conditional_block
mconf.py
# Copyright 2014-2016 The Meson development team # 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 agree...
def add_title(self, title): titles = {'descr': 'Description', 'value': 'Current Value', 'choices': 'Possible Values'} if self.default_values_only: titles['value'] = 'Default Value' self._add_line('', '', '', '') self._add_line(title, titles['value'], titles['choices'], ...
if isinstance(value, list): value = '[{0}]'.format(', '.join(make_lower_case(value))) else: value = make_lower_case(value) if choices: self.has_choices = True if isinstance(choices, list): choices_list = make_lower_case(choices) ...
identifier_body
mconf.py
# Copyright 2014-2016 The Meson development team # 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 agree...
for subproject in sorted(self.all_subprojects): if subproject == '': continue self.add_section('Subproject ' + subproject) if subproject in core_options: self.print_options('Core options', core_options[subproject]) if subproject in ...
self.print_options('Directories', dir_options) self.print_options('Testing options', test_options) self.print_options('Project options', project_options.get('', {}))
random_line_split
vm-installation-image-post-update-version.py
#!/usr/bin/python3 import os import sys INSTALLER_VERSION = '"latest"' def create_installer_config(path): """Create a basicl installation configuration file""" config = u"template=file:///etc/ister.json\n" jconfig = u'{"DestinationType" : "physical", "PartitionLayout" : \ [{"disk" : "vda", "partition...
(path): """Add a delay to the installer kernel commandline""" entry_path = path + "/boot/loader/entries/" entry_file = os.listdir(entry_path) if len(entry_file) != 1: raise Exception("Unable to find specific entry file in {0}, " "found {1} instead".format(entry_path, entr...
append_installer_rootwait
identifier_name
vm-installation-image-post-update-version.py
#!/usr/bin/python3 import os import sys INSTALLER_VERSION = '"latest"' def create_installer_config(path): """Create a basicl installation configuration file""" config = u"template=file:///etc/ister.json\n" jconfig = u'{"DestinationType" : "physical", "PartitionLayout" : \ [{"disk" : "vda", "partition...
file_full_path = entry_path + entry_file[0] with open(file_full_path, "r") as entry: entry_content = entry.readlines() options_line = entry_content[-1] if not options_line.startswith("options "): raise Exception("Last line of entry file is not the kernel " "comma...
raise Exception("Unable to find specific entry file in {0}, " "found {1} instead".format(entry_path, entry_file))
conditional_block
vm-installation-image-post-update-version.py
#!/usr/bin/python3 import os import sys INSTALLER_VERSION = '"latest"' def create_installer_config(path): """Create a basicl installation configuration file""" config = u"template=file:///etc/ister.json\n" jconfig = u'{"DestinationType" : "physical", "PartitionLayout" : \ [{"disk" : "vda", "partition...
jfile.write(jconfig.replace('"Version" : 0', '"Version" : ' + INSTALLER_VERSION)) def append_installer_rootwait(path): """Add a delay to the installer kernel commandline""" entry_path = path + "/boot/loader/entries/" entry_file = os.listdir(entry_path) if le...
random_line_split
vm-installation-image-post-update-version.py
#!/usr/bin/python3 import os import sys INSTALLER_VERSION = '"latest"' def create_installer_config(path):
def append_installer_rootwait(path): """Add a delay to the installer kernel commandline""" entry_path = path + "/boot/loader/entries/" entry_file = os.listdir(entry_path) if len(entry_file) != 1: raise Exception("Unable to find specific entry file in {0}, " "found {1} ...
"""Create a basicl installation configuration file""" config = u"template=file:///etc/ister.json\n" jconfig = u'{"DestinationType" : "physical", "PartitionLayout" : \ [{"disk" : "vda", "partition" : 1, "size" : "512M", "type" : "EFI"}, \ {"disk" : "vda", "partition" : 2, \ "size" : "512M", "type" : ...
identifier_body
pass-by-copy.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 ...
use std::gc::{GC, Gc}; fn magic(x: A) { println!("{:?}", x); } fn magic2(x: Gc<int>) { println!("{:?}", x); } struct A { a: Gc<int> } pub fn main() { let a = A {a: box(GC) 10}; let b = box(GC) 10; magic(a); magic(A {a: box(GC) 20}); magic2(b); magic2(box(GC) 20); }
random_line_split
pass-by-copy.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 = A {a: box(GC) 10}; let b = box(GC) 10; magic(a); magic(A {a: box(GC) 20}); magic2(b); magic2(box(GC) 20); }
identifier_body
pass-by-copy.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 ...
(x: A) { println!("{:?}", x); } fn magic2(x: Gc<int>) { println!("{:?}", x); } struct A { a: Gc<int> } pub fn main() { let a = A {a: box(GC) 10}; let b = box(GC) 10; magic(a); magic(A {a: box(GC) 20}); magic2(b); magic2(box(GC) 20); }
magic
identifier_name
step1.component.spec.ts
/* * Copyright (C) 2015 The Gravitee team (http://gravitee.io) * * 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 requi...
it('should create', () => { expect(component).toBeTruthy(); }); });
});
random_line_split
entity.js
"use strict"; var fs = require('fs'); var mkdirSync = function (path) { try { fs.mkdirSync(path); } catch (e) { if (e.code != 'EEXIST') throw e; } }; mkdirSync(iris.configPath + "/" + "entity"); /** * @file Includes for the entity module */ /** * @namespace entity */ iris.registerModule("entity"...
res.send(iris.entityTypes[req.params.type]); });
{ res.status(403); res.send("Access denied"); return false; }
conditional_block
entity.js
"use strict"; var fs = require('fs'); var mkdirSync = function (path) { try { fs.mkdirSync(path); } catch (e) { if (e.code != 'EEXIST') throw e; } }; mkdirSync(iris.configPath + "/" + "entity"); /** * @file Includes for the entity module */ /** * @namespace entity */ iris.registerModule("entity"...
return false; } var output = {}; Object.keys(iris.entityTypes).forEach(function (entityType) { output[entityType] = iris.entityTypes[entityType]; }); res.send(output); }); iris.route.get("/api/entitySchema/:type", function (req, res) { // If not admin, present 403 page if (req.authPass.r...
random_line_split
csvimporter.ts
// importcsv.ts import {InfoElement} from './infoelement'; import { ITransformArray, IBaseItem, IItemFactory} from 'infodata'; // //declare var Papa:any; import Papa = require('papaparse'); // export class CSVImporter extends InfoElement implements ITransformArray { // private _factory: IItemFactory;
// constructor(fact:IItemFactory) { super(); this._factory = fact; } protected get factory():IItemFactory { return (this._factory !== undefined) ? this._factory : null; } public transform_map(oMap: any): IBaseItem { if ((oMap === undefined) || (oMap === null)) { ...
random_line_split
csvimporter.ts
// importcsv.ts import {InfoElement} from './infoelement'; import { ITransformArray, IBaseItem, IItemFactory} from 'infodata'; // //declare var Papa:any; import Papa = require('papaparse'); // export class CSVImporter extends InfoElement implements ITransformArray { // private _factory: IItemFactory; // ...
let self = this; return new Promise((resolve, reject) => { Papa.parse(file, { header: true, // default: false dynamicTyping: true, // default: false skipEmptyLines: true, // default: false chunk: (results...
{ return Promise.resolve(oRet); }
conditional_block
csvimporter.ts
// importcsv.ts import {InfoElement} from './infoelement'; import { ITransformArray, IBaseItem, IItemFactory} from 'infodata'; // //declare var Papa:any; import Papa = require('papaparse'); // export class
extends InfoElement implements ITransformArray { // private _factory: IItemFactory; // constructor(fact:IItemFactory) { super(); this._factory = fact; } protected get factory():IItemFactory { return (this._factory !== undefined) ? this._factory : null; } public tra...
CSVImporter
identifier_name
lib.rs
extern crate bazel_protos; extern crate bytes; extern crate digest; extern crate hashing; extern crate protobuf; extern crate sha2; use bytes::Bytes; use std::io::Write; use std::os::unix::fs::PermissionsExt; use std::path::Path; pub mod data; pub mod file; pub fn owned_string_vec(args: &[&str]) -> Vec<String> { a...
pub fn as_bytes(str: &str) -> Bytes { Bytes::from(str.as_bytes()) } pub fn make_file(path: &Path, contents: &[u8], mode: u32) { let mut file = std::fs::File::create(&path).unwrap(); file.write(contents).unwrap(); let mut permissions = std::fs::metadata(path).unwrap().permissions(); permissions.set_mode(mod...
{ Vec::from(str.as_bytes()) }
identifier_body
lib.rs
extern crate bazel_protos; extern crate bytes; extern crate digest; extern crate hashing; extern crate protobuf; extern crate sha2; use bytes::Bytes; use std::io::Write; use std::os::unix::fs::PermissionsExt; use std::path::Path; pub mod data;
pub fn owned_string_vec(args: &[&str]) -> Vec<String> { args.into_iter().map(|s| s.to_string()).collect() } pub fn as_byte_owned_vec(str: &str) -> Vec<u8> { Vec::from(str.as_bytes()) } pub fn as_bytes(str: &str) -> Bytes { Bytes::from(str.as_bytes()) } pub fn make_file(path: &Path, contents: &[u8], mode: u32) ...
pub mod file;
random_line_split
lib.rs
extern crate bazel_protos; extern crate bytes; extern crate digest; extern crate hashing; extern crate protobuf; extern crate sha2; use bytes::Bytes; use std::io::Write; use std::os::unix::fs::PermissionsExt; use std::path::Path; pub mod data; pub mod file; pub fn owned_string_vec(args: &[&str]) -> Vec<String> { a...
(str: &str) -> Bytes { Bytes::from(str.as_bytes()) } pub fn make_file(path: &Path, contents: &[u8], mode: u32) { let mut file = std::fs::File::create(&path).unwrap(); file.write(contents).unwrap(); let mut permissions = std::fs::metadata(path).unwrap().permissions(); permissions.set_mode(mode); file.set_pe...
as_bytes
identifier_name
pastetext.js
/* Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ (function() { CKEDITOR.dialog.add( 'pastetext', function( editor ) { return { title : editor.lang.pasteText.title, minWidth : CKEDITOR.env.ie &&...
{ label : editor.lang.common.generalTab, id : 'general', elements : [ { type : 'html', id : 'pasteMsg', html : '<div style="white-space:normal;width:340px;">' + editor.lang.clipboard.pasteMsg + '</div...
onShow : function(){ this.setupContent(); }, onOk : function(){ this.commitContent(); }, contents : [
random_line_split
home-test.js
(function () { 'use strict'; /** * @ngdoc function * @name app.test:homeTest * @description * # homeTest
describe('homeCtrl', function () { var controller = null, $scope = null, $location; beforeEach(function () { module('g4mify-client-app'); }); beforeEach(inject(function ($controller, $rootScope, _$location_) { $scope = $rootScope.$new(); $location = _$location_; controller = $controller('HomeCt...
* Test of the app */
random_line_split
offer_011_xuan_zhuan_shu_zu_de_zui_xiao_shu_zi_lcof.rs
struct Solution; impl Solution { pub fn min_array(numbers: Vec<i32>) -> i32 { // 使用二分法 let (mut left, mut right) = (0, numbers.len() - 1); while left < right { let mid = (left + right) / 2; // 如果 mid 比 left 大,说明最小值在 [mid+1, right] 之间,也可能就是 left。 // 如果 mid ...
fn test_min_array4() { assert_eq!(Solution::min_array(vec![3, 3, 1, 3]), 1); } }
} #[test]
random_line_split
offer_011_xuan_zhuan_shu_zu_de_zui_xiao_shu_zi_lcof.rs
struct Solution; impl Solution { pub fn min_array(numbers: Vec<i32>) -> i32 { // 使用二分法 let (mut left, mut right) = (0, numbers.len() - 1); while left < right { let mid = (left + right) / 2; // 如果 mid 比 left 大,说明最小值在 [mid+1, right] 之间,也可能就是 left。 // 如果 mid ...
y4() { assert_eq!(Solution::min_array(vec![3, 3, 1, 3]), 1); } }
1); } #[test] fn test_min_arra
conditional_block
offer_011_xuan_zhuan_shu_zu_de_zui_xiao_shu_zi_lcof.rs
struct
; impl Solution { pub fn min_array(numbers: Vec<i32>) -> i32 { // 使用二分法 let (mut left, mut right) = (0, numbers.len() - 1); while left < right { let mid = (left + right) / 2; // 如果 mid 比 left 大,说明最小值在 [mid+1, right] 之间,也可能就是 left。 // 如果 mid 比 left 小,说明最小值在...
Solution
identifier_name
offer_011_xuan_zhuan_shu_zu_de_zui_xiao_shu_zi_lcof.rs
struct Solution; impl Solution { pub fn min_array(numbers: Vec<i32>) -> i32 { // 使用二分法 let (mut left, mut right) = (0, numbers.len() - 1); while left < right { let mid = (left + right) / 2; // 如果 mid 比 left 大,说明最小值在 [mid+1, right] 之间,也可能就是 left。 // 如果 mid ...
identifier_body
vortex_sensor_t.py
"""LCM type definitions This file automatically generated by lcm. DO NOT MODIFY BY HAND!!!! """ try: import cStringIO.StringIO as BytesIO except ImportError: from io import BytesIO import struct class vortex_sensor_t(object): __slots__ = ["sensor1", "sensor2", "velocity"] def __init__(self): ...
vortex_sensor_t._packed_fingerprint = struct.pack(">Q", vortex_sensor_t._get_hash_recursive([])) return vortex_sensor_t._packed_fingerprint _get_packed_fingerprint = staticmethod(_get_packed_fingerprint)
random_line_split
vortex_sensor_t.py
"""LCM type definitions This file automatically generated by lcm. DO NOT MODIFY BY HAND!!!! """ try: import cStringIO.StringIO as BytesIO except ImportError: from io import BytesIO import struct class vortex_sensor_t(object):
__slots__ = ["sensor1", "sensor2", "velocity"] def __init__(self): self.sensor1 = 0.0 self.sensor2 = 0.0 self.velocity = 0.0 def encode(self): buf = BytesIO() buf.write(vortex_sensor_t._get_packed_fingerprint()) self._encode_one(buf) return buf.getvalue(...
identifier_body
vortex_sensor_t.py
"""LCM type definitions This file automatically generated by lcm. DO NOT MODIFY BY HAND!!!! """ try: import cStringIO.StringIO as BytesIO except ImportError: from io import BytesIO import struct class vortex_sensor_t(object): __slots__ = ["sensor1", "sensor2", "velocity"] def __init__(self): ...
return vortex_sensor_t._decode_one(buf) decode = staticmethod(decode) def _decode_one(buf): self = vortex_sensor_t() self.sensor1, self.sensor2, self.velocity = struct.unpack(">ddd", buf.read(24)) return self _decode_one = staticmethod(_decode_one) _hash = None def...
raise ValueError("Decode error")
conditional_block
vortex_sensor_t.py
"""LCM type definitions This file automatically generated by lcm. DO NOT MODIFY BY HAND!!!! """ try: import cStringIO.StringIO as BytesIO except ImportError: from io import BytesIO import struct class vortex_sensor_t(object): __slots__ = ["sensor1", "sensor2", "velocity"] def __init__(self): ...
(parents): if vortex_sensor_t in parents: return 0 tmphash = (0x3525d46ae32101c3) & 0xffffffffffffffff tmphash = (((tmphash<<1)&0xffffffffffffffff) + (tmphash>>63)) & 0xffffffffffffffff return tmphash _get_hash_recursive = staticmethod(_get_hash_recursive) _packed_fingerprint =...
_get_hash_recursive
identifier_name
LineClipping.ts
/** * Uses the Cohen Sutherland algorithm for clipping lines with the sceen bounds. * * @author Guido Krömer <mail 64 cacodaemon 46 de> */ class LineClipping { private static INSIDE: number = 0; private static LEFT: number = 1; private static RIGHT: number = 2; private static BOTTOM: number = 4; ...
a: Vector3, b: Vector3): boolean { //http://en.wikipedia.org/wiki/Cohen%E2%80%93Sutherland_algorithm var areaCodeA: number = this.areaCode(a); var areaCodeB: number = this.areaCode(b); while (true) { if (!(areaCodeA | areaCodeB)) { return true; } ...
lip(
identifier_name
LineClipping.ts
/** * Uses the Cohen Sutherland algorithm for clipping lines with the sceen bounds. * * @author Guido Krömer <mail 64 cacodaemon 46 de> */ class LineClipping { private static INSIDE: number = 0; private static LEFT: number = 1; private static RIGHT: number = 2; private static BOTTOM: number = 4; ...
else if (tempAreaCode & LineClipping.BOTTOM) { tempPoint.x = a.x + (b.x - a.x) * (0.0 - a.y) / (b.y - a.y); tempPoint.y = 0.0; } else if (tempAreaCode & LineClipping.RIGHT) { tempPoint.y = a.y + (b.y - a.y) * (this.screen.width - a.x) / (b.x - a.x); ...
tempPoint.x = a.x + (b.x - a.x) * (this.screen.height - a.y) / (b.y - a.y); tempPoint.y = this.screen.height; }
conditional_block
LineClipping.ts
/** * Uses the Cohen Sutherland algorithm for clipping lines with the sceen bounds. * * @author Guido Krömer <mail 64 cacodaemon 46 de> */ class LineClipping { private static INSIDE: number = 0; private static LEFT: number = 1; private static RIGHT: number = 2; private static BOTTOM: number = 4; ...
if (!(areaCodeA | areaCodeB)) { return true; } if (areaCodeA & areaCodeB) { return false; } var tempPoint: Vector3 = new Vector3(); var tempAreaCode: number = areaCodeA ? areaCodeA : areaCodeB; if (tem...
while (true) {
random_line_split
LineClipping.ts
/** * Uses the Cohen Sutherland algorithm for clipping lines with the sceen bounds. * * @author Guido Krömer <mail 64 cacodaemon 46 de> */ class LineClipping { private static INSIDE: number = 0; private static LEFT: number = 1; private static RIGHT: number = 2; private static BOTTOM: number = 4; ...
}
var code = LineClipping.INSIDE; if (p.x < 0) { code |= LineClipping.LEFT; } else if (p.x > this.screen.width) { code |= LineClipping.RIGHT; } if (p.y < 0) { code |= LineClipping.BOTTOM; } else if (p.y > this.screen.height) { ...
identifier_body
font.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use geom::{Point2D, Rect, Size2D}; use std::mem; use std::string; use std::rc::Rc; use std::cell::RefCell; use ser...
use platform::font_context::FontContextHandle; use platform::font::{FontHandle, FontTable}; use text::glyph::{GlyphStore, GlyphId}; use text::shaping::ShaperMethods; use text::{Shaper, TextRun}; use font_template::FontTemplateDescriptor; use platform::font_template::FontTemplateData; // FontHandle encapsulates access ...
use sync::Arc; use servo_util::geometry::Au;
random_line_split
font.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use geom::{Point2D, Rect, Size2D}; use std::mem; use std::string; use std::rc::Rc; use std::cell::RefCell; use ser...
(advance: Au, ascent: Au, descent: Au) -> RunMetrics { let bounds = Rect(Point2D(Au(0), -ascent), Size2D(advance, ascent + descent)); // TODO(Issue #125): support loose and tight bounding boxes; using the // ascent+descent and advance is sometimes too generous and ...
new
identifier_name
cart.service.ts
import { Injectable } from '@angular/core'; import { Movie } from './../moviesList/movie.model'; @Injectable() export class CartService { public moviesCart: Array<Movie> = []; constructor() { let storedCart = JSON.parse(localStorage.getItem('currentCart')); this.moviesCart = storedCart || []; } updateLocal...
getAll(): Array<Movie> { return this.moviesCart; } }
{ return this.moviesCart.length; }
identifier_body
cart.service.ts
import { Injectable } from '@angular/core'; import { Movie } from './../moviesList/movie.model'; @Injectable()
public moviesCart: Array<Movie> = []; constructor() { let storedCart = JSON.parse(localStorage.getItem('currentCart')); this.moviesCart = storedCart || []; } updateLocalstorage() { localStorage.setItem('currentCart', JSON.stringify(this.moviesCart)); } addItem(movie: Movie): boolean { this.moviesCart.p...
export class CartService {
random_line_split
cart.service.ts
import { Injectable } from '@angular/core'; import { Movie } from './../moviesList/movie.model'; @Injectable() export class CartService { public moviesCart: Array<Movie> = []; constructor() { let storedCart = JSON.parse(localStorage.getItem('currentCart')); this.moviesCart = storedCart || []; } updateLocal...
} removeAll(): boolean { this.moviesCart = []; this.updateLocalstorage(); return true; } countAll(): number { return this.moviesCart.length; } getAll(): Array<Movie> { return this.moviesCart; } }
{ return false; }
conditional_block
cart.service.ts
import { Injectable } from '@angular/core'; import { Movie } from './../moviesList/movie.model'; @Injectable() export class CartService { public moviesCart: Array<Movie> = [];
() { let storedCart = JSON.parse(localStorage.getItem('currentCart')); this.moviesCart = storedCart || []; } updateLocalstorage() { localStorage.setItem('currentCart', JSON.stringify(this.moviesCart)); } addItem(movie: Movie): boolean { this.moviesCart.push(movie); this.updateLocalstorage(); return tr...
constructor
identifier_name
description-formatter.d.ts
/** * @license * Copyright (c) 2017 Google Inc. All rights reserved. * This code may only be used under the BSD style license found at * http://polymer.github.io/LICENSE.txt * Code distributed by Google as part of this project is also * subject to an additional IP rights grant found at * http://polymer.github.io...
seenParticles: Set<Particle>; excludeValues: boolean; constructor(particleDescriptions?: ParticleDescription[], storeDescById?: Dictionary<string>); getDescription(recipe: { patterns: string[]; particles: Particle[]; }): any; _isSelectedDescription(desc: ParticleDescription): boo...
private readonly particleDescriptions; private readonly storeDescById; private seenHandles;
random_line_split
description-formatter.d.ts
/** * @license * Copyright (c) 2017 Google Inc. All rights reserved. * This code may only be used under the BSD style license found at * http://polymer.github.io/LICENSE.txt * Code distributed by Google as part of this project is also * subject to an additional IP rights grant found at * http://polymer.github.io...
{ private readonly particleDescriptions; private readonly storeDescById; private seenHandles; seenParticles: Set<Particle>; excludeValues: boolean; constructor(particleDescriptions?: ParticleDescription[], storeDescById?: Dictionary<string>); getDescription(recipe: { patterns: strin...
DescriptionFormatter
identifier_name
order.py
# -*- encoding: utf-8 -*- from openerp.osv import fields, osv from openerp.tools.translate import _ class sale_order_line(osv.Model): """ OpenERP Model : sale_order_line """ _inherit = 'sale.order.line' _columns = { 'att_bro': fields.boolean('Attach Brochure', required=False, help="""If y...
(osv.Model): """ OpenERP Model : sale_order_line """ _inherit = 'sale.order' def print_with_attachment(self, cr, user, ids, context={}): for o in self.browse(cr, user, ids, context): for ol in o.order_line: if ol.att_bro: print "Im Here i will...
sale_order
identifier_name
order.py
# -*- encoding: utf-8 -*- from openerp.osv import fields, osv from openerp.tools.translate import _ class sale_order_line(osv.Model): """ OpenERP Model : sale_order_line """ _inherit = 'sale.order.line' _columns = { 'att_bro': fields.boolean('Attach Brochure', required=False, help="""If y...
return report.report_name def print_quotation(self, cr, uid, ids, context=None): pq = super(sale_order, self).print_quotation(cr,uid,ids, context) return {'type': 'ir.actions.report.xml', 'report_name': self._get_report_name(cr, uid, context), 'datas': pq['datas'], 'nodestroy'...
rep_id = self.pool.get("ir.actions.report.xml").search( cr, uid, [('model', '=', 'sale.order'), ], order="id")[0] report = self.pool.get( "ir.actions.report.xml").browse(cr, uid, rep_id)
conditional_block
order.py
# -*- encoding: utf-8 -*- from openerp.osv import fields, osv from openerp.tools.translate import _ class sale_order_line(osv.Model): """ OpenERP Model : sale_order_line """ _inherit = 'sale.order.line' _columns = { 'att_bro': fields.boolean('Attach Brochure', required=False, help="""If y...
""" _inherit = 'sale.order' def print_with_attachment(self, cr, user, ids, context={}): for o in self.browse(cr, user, ids, context): for ol in o.order_line: if ol.att_bro: print "Im Here i will go to print %s " % ol.name return True def ...
random_line_split
order.py
# -*- encoding: utf-8 -*- from openerp.osv import fields, osv from openerp.tools.translate import _ class sale_order_line(osv.Model): """ OpenERP Model : sale_order_line """ _inherit = 'sale.order.line' _columns = { 'att_bro': fields.boolean('Attach Brochure', required=False, help="""If y...
def __get_company_object(self, cr, uid): user = self.pool.get('res.users').browse(cr, uid, uid) print user if not user.company_id: raise except_osv(_('ERROR !'), _( 'There is no company configured for this user')) return user.company_id def _get_rep...
for o in self.browse(cr, user, ids, context): for ol in o.order_line: if ol.att_bro: print "Im Here i will go to print %s " % ol.name return True
identifier_body
SignIn.component.ts
import {Component} from 'angular2/core'; import {UserService} from '../services/user.services'; @Component({ selector: 'Sign-in', template: ` <div id="Signinmodal" class="modal fade" role="dialog" style="margin-left:4cm;"> <div class="modal-dialog"> <!-- Modal content--> <div class="moda...
</button> </div> <div [innerHTML]="htmlStr" style="margin-left: 5cm;"></div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> </div> </div> </div> `, styleUrls: ["../../assets/css/signinstyle.css"], ...
random_line_split
SignIn.component.ts
import {Component} from 'angular2/core'; import {UserService} from '../services/user.services'; @Component({ selector: 'Sign-in', template: ` <div id="Signinmodal" class="modal fade" role="dialog" style="margin-left:4cm;"> <div class="modal-dialog"> <!-- Modal content--> <div class="moda...
) ; } }
{ this.htmlStr = 'ahla wasahla'; }
conditional_block
SignIn.component.ts
import {Component} from 'angular2/core'; import {UserService} from '../services/user.services'; @Component({ selector: 'Sign-in', template: ` <div id="Signinmodal" class="modal fade" role="dialog" style="margin-left:4cm;"> <div class="modal-dialog"> <!-- Modal content--> <div class="moda...
{ private spinonbutt='Sign In' :string; private email:string; private Password:string; private htmlStr = '' : string; constructor(private _userservice:UserService) { } Connect() { this.spinonbutt = '<img src="../../assets/svgimages/ripple.svg" width="25px" he...
SignInComponent
identifier_name
tests.rs
use std::cmp::Ordering; use super::print_item::compare_names; use super::{AllTypes, Buffer}; #[test] fn test_compare_names()
#[test] fn test_name_sorting() { let names = [ "Apple", "Banana", "Fruit", "Fruit0", "Fruit00", "Fruit01", "Fruit1", "Fruit02", "Fruit2", "Fruit20", "Fruit30x", "Fruit100", "Pear", ]; let mut sorted = names.to_owned(); sorted.sort_by(|&l, r| compare_names(l, r)); assert_eq!(names, ...
{ for &(a, b) in &[ ("hello", "world"), ("", "world"), ("123", "hello"), ("123", ""), ("123test", "123"), ("hello", ""), ("hello", "hello"), ("hello123", "hello123"), ("hello123", "hello12"), ("hello12", "hello123"), ("hello01ab...
identifier_body
tests.rs
use std::cmp::Ordering; use super::print_item::compare_names; use super::{AllTypes, Buffer}; #[test] fn test_compare_names() { for &(a, b) in &[ ("hello", "world"), ("", "world"), ("123", "hello"), ("123", ""), ("123test", "123"), ("hello", ""), ("hello", "h...
() { // Regression test for #82477 let all_types = AllTypes::new(); let mut buffer = Buffer::new(); all_types.print(&mut buffer); assert_eq!(1, buffer.into_inner().matches("List of all items").count()); }
test_all_types_prints_header_once
identifier_name
tests.rs
use std::cmp::Ordering; use super::print_item::compare_names; use super::{AllTypes, Buffer}; #[test] fn test_compare_names() { for &(a, b) in &[ ("hello", "world"), ("", "world"), ("123", "hello"), ("123", ""), ("123test", "123"), ("hello", ""), ("hello", "h...
("hello01abc", "hello01xyz"), ("hello0abc", "hello0"), ("hello0", "hello0abc"), ("01", "1"), ] { assert_eq!(compare_names(a, b), a.cmp(b), "{:?} - {:?}", a, b); } assert_eq!(compare_names("u8", "u16"), Ordering::Less); assert_eq!(compare_names("u32", "u16"), Order...
("hello123", "hello12"), ("hello12", "hello123"),
random_line_split
rt-set-exit-status.rs
// // 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. // error-pattern...
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT.
random_line_split
rt-set-exit-status.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
{ error!("whatever"); // 101 is the code the runtime uses on thread panic and the value // compiletest expects run-fail tests to return. env::set_exit_status(101); }
identifier_body
rt-set-exit-status.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
() { error!("whatever"); // 101 is the code the runtime uses on thread panic and the value // compiletest expects run-fail tests to return. env::set_exit_status(101); }
main
identifier_name
delivery-page.component.ts
import { Component, OnInit, Input, Inject, forwardRef } from '@angular/core'; import { Delivery, RoundService } from '../round.service' import { DeliveryProductListPageComponent } from './delivery-product-list-page.component' import { DeliveryOrderListPageComponent } from './delivery-order-list-page.component' import {...
ngOnInit() { let deliveryId = +this.routeParams.params['deliveryId']; this.roundService.getDelivery(this.roundPage.round.id, deliveryId) .subscribe(delivery => { this.loading = false; this.page.delivery = delivery; this.delivery = delivery; }); } isCurrent(linkPara...
{ }
identifier_body
delivery-page.component.ts
import { Component, OnInit, Input, Inject, forwardRef } from '@angular/core'; import { Delivery, RoundService } from '../round.service' import { DeliveryProductListPageComponent } from './delivery-product-list-page.component' import { DeliveryOrderListPageComponent } from './delivery-order-list-page.component' import {...
() { let deliveryId = +this.routeParams.params['deliveryId']; this.roundService.getDelivery(this.roundPage.round.id, deliveryId) .subscribe(delivery => { this.loading = false; this.page.delivery = delivery; this.delivery = delivery; }); } isCurrent(linkParams: any[]): ...
ngOnInit
identifier_name
delivery-page.component.ts
import { Component, OnInit, Input, Inject, forwardRef } from '@angular/core'; import { Delivery, RoundService } from '../round.service' import { DeliveryProductListPageComponent } from './delivery-product-list-page.component' import { DeliveryOrderListPageComponent } from './delivery-order-list-page.component' import {...
}); } isCurrent(linkParams: any[]): boolean { //router.isRouteActive() isn't working here for some reason :( //need to switch to the new router anyway. let cleanUp = (s:string) => s.replace(/;[^\/]+\/?$/, ''); let pathname = cleanUp(this.router.generate(linkParams).toLinkUrl()); let curre...
.subscribe(delivery => { this.loading = false; this.page.delivery = delivery; this.delivery = delivery;
random_line_split
base.js
'use strict'; let path = require('path'); let defaultSettings = require('./defaults'); // Additional npm or bower modules to include in builds // Add all foreign plugins you may need into this array // @example: // let npmBase = path.join(__dirname, '../node_modules'); // let additionalPaths = [ path.join(npmB...
noInfo: false }, resolve: { extensions: ['', '.js', '.jsx', '.json'], alias: { api: `${defaultSettings.srcPath}/api/`, components: `${defaultSettings.srcPath}/components/`, containers: `${defaultSettings.srcPath}/containers/`, constants: `${defaultSettings.srcPath}/consta...
historyApiFallback: true, hot: true, port: defaultSettings.port, publicPath: defaultSettings.publicPath,
random_line_split
main.rs
use std::thread; fn test1() { let v = vec![1, 2, 3]; let handle = thread::spawn(move || { println!("Here's a vector: {:?}", v); }); handle.join().unwrap(); } use std::sync::mpsc; fn test2() { let (tx, rx) = mpsc::channel(); thread::spawn(move || { let val = String::from("[sen...
() { println!("main; -enter"); test5(); println!("main; -exit"); }
main
identifier_name
main.rs
use std::thread; fn test1() { let v = vec![1, 2, 3]; let handle = thread::spawn(move || { println!("Here's a vector: {:?}", v); }); handle.join().unwrap(); } use std::sync::mpsc; fn test2()
// use std::sync::mpsc; // use std::thread; use std::time::Duration; fn test3() { let (tx, rx) = mpsc::channel(); thread::spawn(move || { let vals = vec![ String::from("hi"), String::from("from"), String::from("the"), String::from("sub-thread"), ...
{ let (tx, rx) = mpsc::channel(); thread::spawn(move || { let val = String::from("[sender say]> hi"); println!("[sender] before send: {}", val); tx.send(val).unwrap(); // println!("[sender] before send: {}", val); //value borrowed here after move }); let received = rx.r...
identifier_body
main.rs
use std::thread; fn test1() { let v = vec![1, 2, 3]; let handle = thread::spawn(move || { println!("Here's a vector: {:?}", v); }); handle.join().unwrap(); } use std::sync::mpsc; fn test2() { let (tx, rx) = mpsc::channel(); thread::spawn(move || { let val = String::from("[sen...
thread::sleep(Duration::from_secs(1)); } }); for received in rx { println!("Got: {}", received); } } use std::sync::{Arc, Mutex}; fn test5() { let counter = Arc::new(Mutex::new(0)); let mut handles = vec![]; for _ in 0..10 { let counter = Arc::clone(&counte...
for val in vals { tx.send(val).unwrap();
random_line_split
day_6.rs
use std::borrow::Cow; use std::iter::Peekable; use std::num::ParseFloatError; use std::str::Chars; pub fn calculate<'s>(src: Cow<'s, str>) -> Result<f64, ParseFloatError> { let mut iter = src.chars().peekable(); parse_expression(&mut iter) } fn parse_expression(iter: &mut Peekable<Chars>) -> Result<f64, Parse...
} ret } fn parse_num(iter: &mut Peekable<Chars>) -> Result<f64, ParseFloatError> { let mut num = String::new(); loop { match iter.peek().cloned() { Some('+') | Some('×') | Some('÷') | Some(')') | None => break, Some('-') if !num.is_empty() => break, Some('(')...
ret = ret.and_then(|ret| parse_num(iter.by_ref()).map(|num| ret / num)) } _ => break }
random_line_split
day_6.rs
use std::borrow::Cow; use std::iter::Peekable; use std::num::ParseFloatError; use std::str::Chars; pub fn calculate<'s>(src: Cow<'s, str>) -> Result<f64, ParseFloatError> { let mut iter = src.chars().peekable(); parse_expression(&mut iter) } fn parse_expression(iter: &mut Peekable<Chars>) -> Result<f64, Parse...
ter: &mut Peekable<Chars>) -> Result<f64, ParseFloatError> { let mut num = String::new(); loop { match iter.peek().cloned() { Some('+') | Some('×') | Some('÷') | Some(')') | None => break, Some('-') if !num.is_empty() => break, Some('(') => { iter.next...
rse_num(i
identifier_name
day_6.rs
use std::borrow::Cow; use std::iter::Peekable; use std::num::ParseFloatError; use std::str::Chars; pub fn calculate<'s>(src: Cow<'s, str>) -> Result<f64, ParseFloatError> { let mut iter = src.chars().peekable(); parse_expression(&mut iter) } fn parse_expression(iter: &mut Peekable<Chars>) -> Result<f64, Parse...
Some('÷') => { iter.next(); ret = ret.and_then(|ret| parse_num(iter.by_ref()).map(|num| ret / num)) } _ => break } } ret } fn parse_num(iter: &mut Peekable<Chars>) -> Result<f64, ParseFloatError> { let mut num = String::new(); ...
iter.next(); ret = ret.and_then(|ret| parse_num(iter.by_ref()).map(|num| ret * num)) },
conditional_block