file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
12.1k
suffix
large_stringlengths
0
12k
middle
large_stringlengths
0
7.51k
fim_type
large_stringclasses
4 values
gulpfile.js
/** * Created by Pencroff on 04-Sep-16. */ var gulp = require('gulp'); var plumber = require('gulp-plumber'); var concat = require('gulp-concat'); var rename = require('gulp-rename'); var uglify = require('gulp-uglify'); var dotify = require('gulp-dotify'); var watch = require('gulp-watch'); var transform = require(...
watch(options.files, function () { gulp.start(options.name) }) } ); }
random_line_split
gulpfile.js
/** * Created by Pencroff on 04-Sep-16. */ var gulp = require('gulp'); var plumber = require('gulp-plumber'); var concat = require('gulp-concat'); var rename = require('gulp-rename'); var uglify = require('gulp-uglify'); var dotify = require('gulp-dotify'); var watch = require('gulp-watch'); var transform = require(...
return stream; }); gulp.task(options.name + '-watch', function () { watch(options.files, function () { gulp.start(options.name) }) } ); }
{ stream.pipe(rename(options.name + '.min.js')) .pipe(uglify()) .pipe(gulp.dest(options.destination)); }
conditional_block
gulpfile.js
/** * Created by Pencroff on 04-Sep-16. */ var gulp = require('gulp'); var plumber = require('gulp-plumber'); var concat = require('gulp-concat'); var rename = require('gulp-rename'); var uglify = require('gulp-uglify'); var dotify = require('gulp-dotify'); var watch = require('gulp-watch'); var transform = require(...
{ gulp.task(options.name, function() { var stream = gulp.src(options.files) .pipe(plumber()) .pipe(concat(options.name + '.js')) .pipe(gulp.dest(options.destination)); if (options.uglify) { stream.pipe(rename(options.name + '.min.js')) ...
identifier_body
DefaultEmptyTest.ts
import { describe, it } from '@ephox/bedrock-client'; import { TinyHooks, TinyUiActions } from '@ephox/wrap-mcagar'; import Editor from 'tinymce/core/api/Editor'; import Plugin from 'tinymce/plugins/image/Plugin'; import { assertCleanHtml, assertInputValue, fillActiveDialog, generalTabSelectors } from '../../module/H...
});
random_line_split
create_table_metaDatasetsUsed.py
import ReviewHelper import pandas as pd df = ReviewHelper.get_pandas_data_frame_created_from_bibtex_file() # find problematic ones df[df.metaDatasetsUsed.isnull()] list1 = df.metaDatasetsUsed.str.split(",").tolist() df1 = pd.DataFrame(list1) for i in range(df1.columns.size): df1[i] = df1[i].str.strip() stack...
\\label{table-metaDatasetsUsed} \\begin{tabular}{ll} \\toprule \\textbf{Dataset Name } & \\textbf{Article Count} \\\\ \\midrule """ table_content_end = """ \\bottomrule \\end{tabular} \\end{table} """ table_content_full = table_content_start + table_content_inside + table_content_end #print table_...
table_content_start = """ \\begin{table}[!ht] \\centering \\caption{ \\textbf{Most used Datasets}. * denotes IDS datasets. Datasets that are used less than three is not included.}
random_line_split
create_table_metaDatasetsUsed.py
import ReviewHelper import pandas as pd df = ReviewHelper.get_pandas_data_frame_created_from_bibtex_file() # find problematic ones df[df.metaDatasetsUsed.isnull()] list1 = df.metaDatasetsUsed.str.split(",").tolist() df1 = pd.DataFrame(list1) for i in range(df1.columns.size): df1[i] = df1[i].str.strip() stac...
table_content_start = """ \\begin{table}[!ht] \\centering \\caption{ \\textbf{Most used Datasets}. * denotes IDS datasets. Datasets that are used less than three is not included.} \\label{table-metaDatasetsUsed} \\begin{tabular}{ll} \\toprule \\textbf{Dataset Name } & \\textbf{Article Count} \\...
dataset_count = greater_than[dataset_name] dataset_name_in_table = dataset_name dataset_name_in_table = dataset_name if(dataset_name in list_ids_dataset_names): dataset_name_in_table = "\\rowcolor{Gray}\n" + dataset_name + "* " line = "{dataset_name} & {dataset_count} \\\\ \n".format( ...
conditional_block
WidgetizeStage.tsx
import React from 'react'; import type { IFormikStageConfigInjectedProps, IStage, IStageConfigProps, IStageTypeConfig } from '@spinnaker/core'; import { ExecutionDetailsTasks, FormikFormField, FormikStageConfig, FormValidator, HelpField, NumberInput, TextInput, Validators, } from '@spinnaker/core'; im...
help={<HelpField content="The email address of the user performing the widgetize operation" />} input={(props) => <TextInput {...props} />} /> </> ); } /** Example validation */ export function validate(stageConfig: IStage) { const validator = new FormValidator(stageConfig); validator ...
<FormikFormField name="user.email" label="User Email"
random_line_split
WidgetizeStage.tsx
import React from 'react'; import type { IFormikStageConfigInjectedProps, IStage, IStageConfigProps, IStageTypeConfig } from '@spinnaker/core'; import { ExecutionDetailsTasks, FormikFormField, FormikStageConfig, FormValidator, HelpField, NumberInput, TextInput, Validators, } from '@spinnaker/core'; im...
function WidgetizeStageForm(props: IFormikStageConfigInjectedProps) { return ( <> <FormikFormField name="instanceCount" label="Instance Count" help={<HelpField content="The number of instances to widgetize" />} input={(props) => <NumberInput {...props} />} /> <...
{ return ( <div className="WidgetizeStageConfig"> <FormikStageConfig {...props} validate={validate} onChange={props.updateStage} render={(props) => <WidgetizeStageForm {...props} />} /> </div> ); }
identifier_body
WidgetizeStage.tsx
import React from 'react'; import type { IFormikStageConfigInjectedProps, IStage, IStageConfigProps, IStageTypeConfig } from '@spinnaker/core'; import { ExecutionDetailsTasks, FormikFormField, FormikStageConfig, FormValidator, HelpField, NumberInput, TextInput, Validators, } from '@spinnaker/core'; im...
(props: IStageConfigProps) { return ( <div className="WidgetizeStageConfig"> <FormikStageConfig {...props} validate={validate} onChange={props.updateStage} render={(props) => <WidgetizeStageForm {...props} />} /> </div> ); } function WidgetizeStageForm(props: IFo...
WidgetizeStageConfig
identifier_name
main.rs
use std::fs::File; extern crate rustc_serialize; extern crate docopt;
mod vm; static USAGE: &'static str = " Usage: norn_rust <file> norn_rust (--help | --version) Options: -h, --help Show this message. -v, --version Show version of norn_rust. "; #[derive(RustcDecodable, Debug)] struct Args { arg_file: String, flag_help: bool, flag_version: bool } ...
use docopt::Docopt;
random_line_split
main.rs
use std::fs::File; extern crate rustc_serialize; extern crate docopt; use docopt::Docopt; mod vm; static USAGE: &'static str = " Usage: norn_rust <file> norn_rust (--help | --version) Options: -h, --help Show this message. -v, --version Show version of norn_rust. "; #[derive(RustcDecodable...
}) .and_then(|program| Ok(vm::execute(&program))) .unwrap(); }
{ let args: Args = Docopt::new(USAGE) .and_then(|d| d.decode()) .unwrap_or_else(|e| e.exit()); if args.flag_help { println!("{}", USAGE); return; } if args.flag_version { println!("norn_rust 0.0.3"); return; ...
identifier_body
main.rs
use std::fs::File; extern crate rustc_serialize; extern crate docopt; use docopt::Docopt; mod vm; static USAGE: &'static str = " Usage: norn_rust <file> norn_rust (--help | --version) Options: -h, --help Show this message. -v, --version Show version of norn_rust. "; #[derive(RustcDecodable...
{ arg_file: String, flag_help: bool, flag_version: bool } fn main() { let args: Args = Docopt::new(USAGE) .and_then(|d| d.decode()) .unwrap_or_else(|e| e.exit()); if args.flag_help { println!("{}", USAGE); return; } ...
Args
identifier_name
main.rs
use std::fs::File; extern crate rustc_serialize; extern crate docopt; use docopt::Docopt; mod vm; static USAGE: &'static str = " Usage: norn_rust <file> norn_rust (--help | --version) Options: -h, --help Show this message. -v, --version Show version of norn_rust. "; #[derive(RustcDecodable...
if args.flag_version { println!("norn_rust 0.0.3"); return; } File::open(args.arg_file) .map_err(|err| err.to_string()) .and_then(|file| { vm::ir::programs::Program::parse_textual_bytecode(file) .map_err(|err| err.to_string()) })...
{ println!("{}", USAGE); return; }
conditional_block
feature_maxuploadtarget.py
#!/usr/bin/env python3 # Copyright (c) 2015-2018 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test behavior of -maxuploadtarget. * Verify that getdata requests for old blocks (>1week) are dropped ...
assert_equal(p2p_conns[0].block_receive_map[big_old_block], i+1) assert_equal(len(self.nodes[0].getpeerinfo()), 3) # At most a couple more tries should succeed (depending on how long # the test has been running so far). for i in range(3): p2p_conns[0].send_messag...
random_line_split
feature_maxuploadtarget.py
#!/usr/bin/env python3 # Copyright (c) 2015-2018 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test behavior of -maxuploadtarget. * Verify that getdata requests for old blocks (>1week) are dropped ...
assert_equal(len(self.nodes[0].getpeerinfo()), 3) # At most a couple more tries should succeed (depending on how long # the test has been running so far). for i in range(3): p2p_conns[0].send_message(getdata_request) p2p_conns[0].wait_for_disconnect() assert...
p2p_conns[0].send_message(getdata_request) p2p_conns[0].sync_with_ping() assert_equal(p2p_conns[0].block_receive_map[big_old_block], i+1)
conditional_block
feature_maxuploadtarget.py
#!/usr/bin/env python3 # Copyright (c) 2015-2018 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test behavior of -maxuploadtarget. * Verify that getdata requests for old blocks (>1week) are dropped ...
class MaxUploadTest(GuldenTestFramework): def set_test_params(self): self.setup_clean_chain = True self.num_nodes = 1 self.extra_args = [["-maxuploadtarget=800"]] # Cache for utxos, as the listunspent may take a long time later in the test self.utxo_cache = [] def sk...
message.block.calc_sha256() self.block_receive_map[message.block.sha256] += 1
identifier_body
feature_maxuploadtarget.py
#!/usr/bin/env python3 # Copyright (c) 2015-2018 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test behavior of -maxuploadtarget. * Verify that getdata requests for old blocks (>1week) are dropped ...
(self): super().__init__() self.block_receive_map = defaultdict(int) def on_inv(self, message): pass def on_block(self, message): message.block.calc_sha256() self.block_receive_map[message.block.sha256] += 1 class MaxUploadTest(GuldenTestFramework): def set_test_p...
__init__
identifier_name
cmd.py
import subprocess class CmdArgument(object): _PREFIX = None _KEY = None def __init__(self, value): self._value = value @property def value(self): return self._value @property def prefix(self): return self._PREFIX @property def key(self): return s...
(self) -> [CmdArgument]: return self._args @property def options(self) -> str: raise NotImplementedError def _dump_args(self): return ' '.join(map(str, self._args)) def __str__(self): return '{} {}'.format(self._cmd, self._dump_args()) def run(self, **kwargs): ...
arguments
identifier_name
cmd.py
import subprocess class CmdArgument(object): _PREFIX = None _KEY = None def __init__(self, value): self._value = value @property def value(self): return self._value
@property def key(self): return self._KEY def format(self) -> str: raise NotImplementedError def __str__(self): try: return self.format() except NotImplementedError: return '{}{} "{}"'.format(self._PREFIX, self._KEY, self._value) class Cmd(obj...
@property def prefix(self): return self._PREFIX
random_line_split
cmd.py
import subprocess class CmdArgument(object): _PREFIX = None _KEY = None def __init__(self, value): self._value = value @property def value(self):
@property def prefix(self): return self._PREFIX @property def key(self): return self._KEY def format(self) -> str: raise NotImplementedError def __str__(self): try: return self.format() except NotImplementedError: return '{}{} ...
return self._value
identifier_body
cmd.py
import subprocess class CmdArgument(object): _PREFIX = None _KEY = None def __init__(self, value): self._value = value @property def value(self): return self._value @property def prefix(self): return self._PREFIX @property def key(self): return s...
cls._KEY = key if prefix: cls._PREFIX = prefix else: cls._PREFIX = '-' return cls return _cmm_argument
return TypeError('{!r} must deriving from CmdArgument'.format(cls))
conditional_block
card.py
# img # trigger = attributes[12] # http://ws-tcg.com/en/cardlist # edit import os import requests import sqlite3 def get_card(browser): attributes = browser.find_elements_by_xpath('//table[@class="status"]/tbody/tr/td') image = attributes[0].find_element_by_xpath('./img').get_attribute('src') if attri...
connection.close()
random_line_split
card.py
# img # trigger = attributes[12] # http://ws-tcg.com/en/cardlist # edit import os import requests import sqlite3 def
(browser): attributes = browser.find_elements_by_xpath('//table[@class="status"]/tbody/tr/td') image = attributes[0].find_element_by_xpath('./img').get_attribute('src') if attributes[1].find_element_by_xpath('./span[@class="kana"]').text: card_name = attributes[1].find_element_by_xpath('./span[@cl...
get_card
identifier_name
card.py
# img # trigger = attributes[12] # http://ws-tcg.com/en/cardlist # edit import os import requests import sqlite3 def get_card(browser): attributes = browser.find_elements_by_xpath('//table[@class="status"]/tbody/tr/td') image = attributes[0].find_element_by_xpath('./img').get_attribute('src') if attri...
card = (card_name, card_no, rarity, expansion, side, card_type, color, level, cost, power, soul, special_attribute, text, flavor_text) connection = sqlite3.connect('cards.sqlite3') cursor = connection.cursor() cursor.execute('INSERT INTO cards (name, no, rarity, expansion, side, type, colo...
ith open("images/" + card_no + ".jpg", 'wb') as f: for chunk in r: f.write(chunk)
conditional_block
card.py
# img # trigger = attributes[12] # http://ws-tcg.com/en/cardlist # edit import os import requests import sqlite3 def get_card(browser):
card_type = attributes[6].text if attributes[6].text else None if attributes[7].find_element_by_xpath('./img').get_attribute("src") == "http://ws-tcg.com/en/cardlist/partimages/yellow.gif": color = "Yellow" elif attributes[7].find_element_by_xpath('./img').get_attribute("src") == "http://ws-tcg.com...
attributes = browser.find_elements_by_xpath('//table[@class="status"]/tbody/tr/td') image = attributes[0].find_element_by_xpath('./img').get_attribute('src') if attributes[1].find_element_by_xpath('./span[@class="kana"]').text: card_name = attributes[1].find_element_by_xpath('./span[@class="kana"]').t...
identifier_body
connect_test.py
# 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 may not use ...
(KafkaTest): """ Simple test of Kafka Connect that produces data from a file in one standalone process and consumes it on another, validating the output is identical to the input. """ INPUT_FILE = "/mnt/connect.input" OUTPUT_FILE = "/mnt/connect.output" OFFSETS_FILE = "/mnt/connect.off...
ConnectStandaloneFileTest
identifier_name
connect_test.py
# 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 may not use ...
def __init__(self, test_context): super(ConnectStandaloneFileTest, self).__init__(test_context, num_zk=1, num_brokers=1, topics={ 'test' : { 'partitions': 1, 'replication-factor': 1 } }) self.source = ConnectStandaloneService(test_context, self.kafka, [self.INPUT_FILE, self.OFFS...
""" Simple test of Kafka Connect that produces data from a file in one standalone process and consumes it on another, validating the output is identical to the input. """ INPUT_FILE = "/mnt/connect.input" OUTPUT_FILE = "/mnt/connect.output" OFFSETS_FILE = "/mnt/connect.offsets" TOPIC ...
identifier_body
connect_test.py
# 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 may not use ...
""" Simple test of Kafka Connect that produces data from a file in one standalone process and consumes it on another, validating the output is identical to the input. """ INPUT_FILE = "/mnt/connect.input" OUTPUT_FILE = "/mnt/connect.output" OFFSETS_FILE = "/mnt/connect.offsets" TO...
from ducktape.mark import parametrize import hashlib, subprocess, json class ConnectStandaloneFileTest(KafkaTest):
random_line_split
nls.py
#! /usr/bin/env python # -*- coding: utf-8 -*- # Copyright (C) 2011 ~ 2012 Deepin, Inc. # 2011 ~ 2012 Hou Shaohui # # Author: Hou Shaohui <houshao55@gmail.com> # Maintainer: Hou Shaohui <houshao55@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under the ter...
(filepath, level=1): '''Get parent dir.''' parent_dir = os.path.realpath(filepath) while(level > 0): parent_dir = os.path.dirname(parent_dir) level -= 1 return parent_dir LOCALE_DIR=os.path.join(get_parent_dir(__file__, 2), "locale") if not os.path.exists(LOCALE_DIR): LOCA...
get_parent_dir
identifier_name
nls.py
#! /usr/bin/env python # -*- coding: utf-8 -*- # Copyright (C) 2011 ~ 2012 Deepin, Inc. # 2011 ~ 2012 Hou Shaohui # # Author: Hou Shaohui <houshao55@gmail.com> # Maintainer: Hou Shaohui <houshao55@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under the ter...
return parent_dir LOCALE_DIR=os.path.join(get_parent_dir(__file__, 2), "locale") if not os.path.exists(LOCALE_DIR): LOCALE_DIR="/usr/share/locale" _ = None try: _ = gettext.translation("deepin-music-player", LOCALE_DIR).gettext except Exception, e: _ = lambda i : i
parent_dir = os.path.dirname(parent_dir) level -= 1
conditional_block
nls.py
#! /usr/bin/env python # -*- coding: utf-8 -*- # Copyright (C) 2011 ~ 2012 Deepin, Inc. # 2011 ~ 2012 Hou Shaohui # # Author: Hou Shaohui <houshao55@gmail.com> # Maintainer: Hou Shaohui <houshao55@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under the ter...
parent_dir = os.path.realpath(filepath) while(level > 0): parent_dir = os.path.dirname(parent_dir) level -= 1 return parent_dir LOCALE_DIR=os.path.join(get_parent_dir(__file__, 2), "locale") if not os.path.exists(LOCALE_DIR): LOCALE_DIR="/usr/share/locale" _ = None tr...
import gettext import os def get_parent_dir(filepath, level=1): '''Get parent dir.'''
random_line_split
nls.py
#! /usr/bin/env python # -*- coding: utf-8 -*- # Copyright (C) 2011 ~ 2012 Deepin, Inc. # 2011 ~ 2012 Hou Shaohui # # Author: Hou Shaohui <houshao55@gmail.com> # Maintainer: Hou Shaohui <houshao55@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under the ter...
LOCALE_DIR=os.path.join(get_parent_dir(__file__, 2), "locale") if not os.path.exists(LOCALE_DIR): LOCALE_DIR="/usr/share/locale" _ = None try: _ = gettext.translation("deepin-music-player", LOCALE_DIR).gettext except Exception, e: _ = lambda i : i
'''Get parent dir.''' parent_dir = os.path.realpath(filepath) while(level > 0): parent_dir = os.path.dirname(parent_dir) level -= 1 return parent_dir
identifier_body
main.ts
/* * Providers provided by Angular */ import * as browser from 'angular2/platform/browser'; import * as ngCore from 'angular2/core'; import {ROUTER_PROVIDERS, ROUTER_DIRECTIVES} from 'angular2/router'; import {FORM_PROVIDERS} from 'angular2/common'; import {HTTP_PROVIDERS} from 'angular2/http'; // Import mo...
} else { bootstrapDomReady(); }
{ bootstrapDomReady(); }
conditional_block
main.ts
/* * Providers provided by Angular */ import * as browser from 'angular2/platform/browser'; import * as ngCore from 'angular2/core'; import {ROUTER_PROVIDERS, ROUTER_DIRECTIVES} from 'angular2/router'; import {FORM_PROVIDERS} from 'angular2/common'; import {HTTP_PROVIDERS} from 'angular2/http'; // Import mo...
if ('development' === ENV) { // activate hot module reload if (HMR) { if (document.readyState === 'complete') { main(); } else { bootstrapDomReady(); } module.hot.accept(); } else { bootstrapDomReady(); } } else { bootstrapDomR...
{ // bootstrap after document is ready return document.addEventListener('DOMContentLoaded', main); }
identifier_body
main.ts
/* * Providers provided by Angular */ import * as browser from 'angular2/platform/browser'; import * as ngCore from 'angular2/core'; import {ROUTER_PROVIDERS, ROUTER_DIRECTIVES} from 'angular2/router'; import {FORM_PROVIDERS} from 'angular2/common'; import {HTTP_PROVIDERS} from 'angular2/http'; // Import mo...
() { // bootstrap after document is ready return document.addEventListener('DOMContentLoaded', main); } if ('development' === ENV) { // activate hot module reload if (HMR) { if (document.readyState === 'complete') { main(); } else { bootstrapDomReady(); ...
bootstrapDomReady
identifier_name
main.ts
/* * Providers provided by Angular */ import * as browser from 'angular2/platform/browser'; import * as ngCore from 'angular2/core'; import {ROUTER_PROVIDERS, ROUTER_DIRECTIVES} from 'angular2/router';
import {provideStore} from '@ngrx/store'; // Import all of the files necessary for our `recipes` component /* * App Component * our top level component that holds all of our components */ import {App} from './app/app'; import {RouterActive} from './app/shared/directives/router-active'; /* * Application Providers...
import {FORM_PROVIDERS} from 'angular2/common'; import {HTTP_PROVIDERS} from 'angular2/http'; // Import module to provide an app `store` for the life-cycle of the app
random_line_split
app.module.ts
import { BrowserModule } from '@angular/platform-browser'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { ProfileComponent } from './profile/profile.component'; import { MsalModule, MsalInterceptor } from '@azure/msal-angular'; import { HTTP_INTERCEPTORS, HttpClientModule } from '@angular/common/http'; expor...
import { MatToolbarModule, MatButtonModule, MatListModule } from '@angular/material';
random_line_split
app.module.ts
import { BrowserModule } from '@angular/platform-browser'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { NgModule } from '@angular/core'; import { MatToolbarModule, MatButtonModule, MatListModule } from '@angular/material'; import { AppRoutingModule } from './app-routing.mod...
{ }
AppModule
identifier_name
supersized.images.js
jQuery(function($){ $.supersized({ // Functionality slideshow : 1, // Slideshow on/off autoplay : 1, // Slideshow starts playing automatically start_slide : 1, // Start slide (0 is random) stop_loop : 0, // Pauses slideshow on last slide...
thumbnail_navigation : 0, // Thumbnail navigation slides : [ // Slideshow Images {image : './images/feat-bg1.jpg', title : '<div class="major">Apollo</div><div class="slidedescription">Quisque non magna ac tortor tincidunt posuere. Vestibulum luctus aliquet gravida. Etiam non dol...
random_line_split
timestamp.rs
// Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0. use collections::HashSet; use std::fmt; use std::sync::Arc; use std::time::{SystemTime, UNIX_EPOCH}; #[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Ord, PartialOrd, Hash)] pub struct TimeStamp(u64); const TSO_PHYSICAL_SHIFT_BITS: u64 = 18; imp...
pub const fn max() -> TimeStamp { TimeStamp(std::u64::MAX) } pub const fn new(ts: u64) -> TimeStamp { TimeStamp(ts) } /// Extracts physical part of a timestamp, in milliseconds. pub fn physical(self) -> u64 { self.0 >> TSO_PHYSICAL_SHIFT_BITS } pub fn next(se...
{ TimeStamp(0) }
identifier_body
timestamp.rs
// Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0. use collections::HashSet; use std::fmt; use std::sync::Arc; use std::time::{SystemTime, UNIX_EPOCH}; #[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Ord, PartialOrd, Hash)] pub struct TimeStamp(u64); const TSO_PHYSICAL_SHIFT_BITS: u64 = 18; imp...
let big_ts_list: Vec<TimeStamp> = (0..=TS_SET_USE_VEC_LIMIT as u64).map(Into::into).collect(); let s = TsSet::new(big_ts_list.clone()); assert_eq!( s, TsSet::Set(Arc::new(big_ts_list.clone().into_iter().collect())) ); assert!(s.contains(1.into...
random_line_split
timestamp.rs
// Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0. use collections::HashSet; use std::fmt; use std::sync::Arc; use std::time::{SystemTime, UNIX_EPOCH}; #[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Ord, PartialOrd, Hash)] pub struct TimeStamp(u64); const TSO_PHYSICAL_SHIFT_BITS: u64 = 18; imp...
() -> TimeStamp { TimeStamp(0) } pub const fn max() -> TimeStamp { TimeStamp(std::u64::MAX) } pub const fn new(ts: u64) -> TimeStamp { TimeStamp(ts) } /// Extracts physical part of a timestamp, in milliseconds. pub fn physical(self) -> u64 { self.0 >> TSO_P...
zero
identifier_name
timestamp.rs
// Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0. use collections::HashSet; use std::fmt; use std::sync::Arc; use std::time::{SystemTime, UNIX_EPOCH}; #[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Ord, PartialOrd, Hash)] pub struct TimeStamp(u64); const TSO_PHYSICAL_SHIFT_BITS: u64 = 18; imp...
else { TsSet::Vec(ts.into()) } } /// Query whether the given timestamp is contained in the set. #[inline] pub fn contains(&self, ts: TimeStamp) -> bool { match self { TsSet::Empty => false, TsSet::Vec(vec) => vec.contains(&ts), TsSet::Set...
{ TsSet::Empty }
conditional_block
font_list.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 collections::hashmap::HashMap; use font::SpecifiedFontStyle; use gfx_font::FontHandleMethods; use platform::fo...
family_map: FontFamilyMap, handle: FontListHandle, prof_chan: ProfilerChan, } impl FontList { pub fn new(fctx: &FontContextHandle, prof_chan: ProfilerChan) -> FontList { let handle = FontListHandle::new(fctx); let mut list = FontList { handle: handle, ...
/// The platform-independent font list abstraction. pub struct FontList {
random_line_split
font_list.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 collections::hashmap::HashMap; use font::SpecifiedFontStyle; use gfx_font::FontHandleMethods; use platform::fo...
{ family_name: ~str, entries: ~[FontEntry], } impl FontFamily { pub fn new(family_name: &str) -> FontFamily { FontFamily { family_name: family_name.to_str(), entries: ~[], } } fn load_family_variations(&mut self, list: &FontListHandle) { if self.ent...
FontFamily
identifier_name
font_list.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 collections::hashmap::HashMap; use font::SpecifiedFontStyle; use gfx_font::FontHandleMethods; use platform::fo...
} None } } /// This struct summarizes an available font's features. In the future, this will include fiddly /// settings such as special font table handling. /// /// In the common case, each FontFamily will have a singleton FontEntry, or it will have the /// standard four faces: Normal, Bold, Ita...
{ return Some(entry); }
conditional_block
font_list.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 collections::hashmap::HashMap; use font::SpecifiedFontStyle; use gfx_font::FontHandleMethods; use platform::fo...
}
{ self.italic }
identifier_body
appearance.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Team: # J Phani Mahesh <phanimahesh@gmail.com> # Barneedhar (jokerdino) <barneedhar@ubuntu.com> # Amith KK <amithkumaran@gmail.com> # Georgi Karavasilev <motorslav@gmail.com> # Sam Tran <samvtran@gmail.com> # Sam Hewitt <hewittsamuel@gmail.com> # Angel Ar...
}) font_document= FontButton({ 'id' : 'font_document', 'builder' : Appearance.builder, 'schema' : 'org.gnome.desktop.interface', 'path' : None, 'key' : 'document-font-name', 'type' : 'string' }) font_monospace= FontButton({ 'id' : 'font_monospace', 'b...
'key' : 'font-name', 'type' : 'string'
random_line_split
pattern-in-closure.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: int, y: int } pub fn main() { let f = |(x, _): (int, int)| println((x + 1).to_str()); let g = |Foo { x: x, y: _y }: Foo| println((x + 1).to_str()); f((2, 3)); g(Foo { x: 1, y: 2 }); }
Foo
identifier_name
pattern-in-closure.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// 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. struct Foo { x: int, y: int } pub fn main() { let f = |(x, _): (int, int)| ...
// 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
random_line_split
asset_assign_category.py
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (C) 2012-2014 Didotech (<http://www.didotech.com>) # All Rights Reserved # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero Genera...
'lang': context['lang'], 'tz': context['tz'], 'uid': context['uid'], 'section_id': context['section_id'], 'project_id': context['project_id'], 'department_id': context['department_id'], 'asset_created': True } self.pool....
category = self.browse(cr, uid, ids, context=context)[0].category_id # add row to assets_product table asset_product_id = self.pool['asset.product'].create(cr, uid, { 'create_uid': uid, 'has_date_option': False, 'asset_category_id': category.id, 'product_...
identifier_body
asset_assign_category.py
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (C) 2012-2014 Didotech (<http://www.didotech.com>) # All Rights Reserved # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero Genera...
(orm.TransientModel): _name = 'asset.assign.category' _description = 'Assign category to a new asset product' _columns = { 'category_id': fields.many2one('asset.category', 'Asset Category', required=False), } def assign_category(self, cr, uid, ids, context=None): category =...
asset_assign_category
identifier_name
asset_assign_category.py
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (C) 2012-2014 Didotech (<http://www.didotech.com>) # All Rights Reserved # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero Genera...
def assign_category(self, cr, uid, ids, context=None): category = self.browse(cr, uid, ids, context=context)[0].category_id # add row to assets_product table asset_product_id = self.pool['asset.product'].create(cr, uid, { 'create_uid': uid, 'has_date_option': Fa...
'category_id': fields.many2one('asset.category', 'Asset Category', required=False), }
random_line_split
delete.ts
import { KeystoneContext } from '../../../types'; import { getOperationAccess, getAccessFilters } from '../access-control'; import { checkFilterOrderAccess } from '../filter-order-access'; import { accessDeniedError } from '../graphql-errors'; import { InitialisedList } from '../types-for-lists'; import { getWriteLimit...
// Validate and resolve the input filter const uniqueWhere = await resolveUniqueWhereInput(uniqueInput, list.fields, context); // Check filter access const fieldKey = Object.keys(uniqueWhere)[0]; await checkFilterOrderAccess([{ fieldKey, list }], context, 'filter'); // Filter and Item access control. Wi...
{ throw accessDeniedError( `You cannot perform the 'delete' operation on the list '${list.listKey}'.` ); }
conditional_block
delete.ts
import { KeystoneContext } from '../../../types'; import { getOperationAccess, getAccessFilters } from '../access-control'; import { checkFilterOrderAccess } from '../filter-order-access'; import { accessDeniedError } from '../graphql-errors'; import { InitialisedList } from '../types-for-lists'; import { getWriteLimit...
( uniqueInputs: UniqueInputFilter[], list: InitialisedList, context: KeystoneContext ) { // Check operation permission to pass into single operation const operationAccess = await getOperationAccess(list, context, 'delete'); // Check filter permission to pass into single operation const accessFilters = aw...
deleteMany
identifier_name
delete.ts
import { KeystoneContext } from '../../../types'; import { getOperationAccess, getAccessFilters } from '../access-control'; import { checkFilterOrderAccess } from '../filter-order-access'; import { accessDeniedError } from '../graphql-errors'; import { InitialisedList } from '../types-for-lists'; import { getWriteLimit...
return uniqueInputs.map(async uniqueInput => deleteSingle(uniqueInput, list, context, accessFilters, operationAccess) ); } export async function deleteOne( uniqueInput: UniqueInputFilter, list: InitialisedList, context: KeystoneContext ) { // Check operation permission to pass into single operation c...
const operationAccess = await getOperationAccess(list, context, 'delete'); // Check filter permission to pass into single operation const accessFilters = await getAccessFilters(list, context, 'delete');
random_line_split
delete.ts
import { KeystoneContext } from '../../../types'; import { getOperationAccess, getAccessFilters } from '../access-control'; import { checkFilterOrderAccess } from '../filter-order-access'; import { accessDeniedError } from '../graphql-errors'; import { InitialisedList } from '../types-for-lists'; import { getWriteLimit...
listKey: list.listKey, context, item, resolvedData: undefined, inputData: undefined, }; // Apply all validation checks await validateDelete({ list, hookArgs }); // Before operation await runSideEffectOnlyHook(list, 'beforeOperation', hookArgs); const writeLimit = getWriteLimit(context...
{ // Operation level access control if (!operationAccess) { throw accessDeniedError( `You cannot perform the 'delete' operation on the list '${list.listKey}'.` ); } // Validate and resolve the input filter const uniqueWhere = await resolveUniqueWhereInput(uniqueInput, list.fields, context); ...
identifier_body
test_tracking_events.py
# # test_tracking_events.py # # Copyright (C) 2017 Kano Computing Ltd. # License: http://www.gnu.org/licenses/gpl-2.0.txt GNU GPL v2 # # Unit tests for functions related to tracking events: # `kano_profile.tracker.tracking_events` # import os import json import time import pytest from kano_profile.paths import t...
(event_name, event_type, event_data): if os.path.exists(tracker_events_file): os.remove(tracker_events_file) tracking_events.generate_event(event_name) assert os.path.exists(tracker_events_file) events = [] with open(tracker_events_file, 'r') as events_f: events.append(json.loads...
test_generate_low_battery_event
identifier_name
test_tracking_events.py
# # test_tracking_events.py # # Copyright (C) 2017 Kano Computing Ltd. # License: http://www.gnu.org/licenses/gpl-2.0.txt GNU GPL v2 # # Unit tests for functions related to tracking events: # `kano_profile.tracker.tracking_events` # import os import json import time import pytest from kano_profile.paths import t...
'timezone_offset', 'cpu_id', 'os_version', 'token', 'time', 'data' ] for key in expected_keys: assert key in event assert event['name'] == event_type # language: en_GB, assert event['type'] == 'data' # timezone_offset: 3600, # cpu_id:...
if os.path.exists(tracker_events_file): os.remove(tracker_events_file) tracking_events.generate_event(event_name) assert os.path.exists(tracker_events_file) events = [] with open(tracker_events_file, 'r') as events_f: events.append(json.loads(events_f.readline())) assert len(eve...
identifier_body
test_tracking_events.py
# # test_tracking_events.py # # Copyright (C) 2017 Kano Computing Ltd. # License: http://www.gnu.org/licenses/gpl-2.0.txt GNU GPL v2 # # Unit tests for functions related to tracking events: # `kano_profile.tracker.tracking_events` # import os import json import time import pytest from kano_profile.paths import t...
# Allow some margin for time passing assert abs(time.time() - event['time']) < 5 assert event['data'] == json.loads(event_data)
random_line_split
test_tracking_events.py
# # test_tracking_events.py # # Copyright (C) 2017 Kano Computing Ltd. # License: http://www.gnu.org/licenses/gpl-2.0.txt GNU GPL v2 # # Unit tests for functions related to tracking events: # `kano_profile.tracker.tracking_events` # import os import json import time import pytest from kano_profile.paths import t...
tracking_events.generate_event(event_name) assert os.path.exists(tracker_events_file) events = [] with open(tracker_events_file, 'r') as events_f: events.append(json.loads(events_f.readline())) assert len(events) == 1 event = events[0] expected_keys = [ 'name', ...
os.remove(tracker_events_file)
conditional_block
runserver_plus.py
, tb): if has_ipdb(): import ipdb p = ipdb else: import pdb p = pdb print("Exception occured: %s, %s" % (exc_type, exc_value), file=sys.stderr) p.post_mortem(tb) # usu...
""" Checks to see if the set of migrations on disk matches the migrations in the database. Prints a warning if they don't match. """ executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) plan = executor.migration_plan(executor.loader.graph.leaf_nodes()) ...
identifier_body
runserver_plus.py
_exclusive_group() cert_group.add_argument('--cert', dest='cert_path', action="store", type=str, help='Deprecated alias for --cert-file option.') cert_group.add_argument('--cert-file', dest='cert_path', action="store", type=str, help='SSL ....
setup_logger(logger, self.stderr, filename=options.get('output_file', None)) # , fmt="[%(name)s] %(message)s") logredirect = RedirectHandler(__name__) # Redirect werkzeug log items werklogger = logging.getLogger('werkzeug') werklogger.setLevel(logging.INFO) werklogger...
self.stderr.ending = None
conditional_block
runserver_plus.py
_exclusive_group() cert_group.add_argument('--cert', dest='cert_path', action="store", type=str, help='Deprecated alias for --cert-file option.') cert_group.add_argument('--cert-file', dest='cert_path', action="store", type=str, help='SSL ....
self.show_startup_messages = not os.environ.get('RUNSERVER_PLUS_SHOW_MESSAGES') elif startup_messages == "never": self.show_startup_messages = False else: self.show_startup_messages = True os.environ['RUNSERVER_PLUS_SHOW_MESSAGES'] = '1' # Do not use...
elif startup_messages == "once":
random_line_split
runserver_plus.py
_exclusive_group() cert_group.add_argument('--cert', dest='cert_path', action="store", type=str, help='Deprecated alias for --cert-file option.') cert_group.add_argument('--cert-file', dest='cert_path', action="store", type=str, help='SSL ....
(self, options): try: from werkzeug import run_simple, DebuggedApplication from werkzeug.serving import WSGIRequestHandler as _WSGIRequestHandler # Set colored output if settings.DEBUG: try: set_werkzeug_log_color() ...
inner_run
identifier_name
test.py
import numpy as np import numpy.random as nr def draw_bg(size=(1,), snr_min=5.5, snr_std=2): bgs = nr.normal(loc=snr_min, scale=snr_std, size=size) sel = bgs < snr_min while np.count_nonzero(sel) > 0: bgs[sel] = nr.normal(loc=snr_min, scale=snr_std, size=np.count_nonzero(sel)) sel = bgs < ...
bgs = [draw_bg(size=nb) for nb in nbgs] nf = int(round(ncoinc*ffore)) fgs = [np.concatenate((draw_bg(ncoinc-nf), draw_fg(nf))) for nb in nbgs] return np.array(fgs), bgs
return snr_min/(1 - us)**(1.0/3.0) def data_set(ncoinc, ffore, nbgs):
random_line_split
test.py
import numpy as np import numpy.random as nr def draw_bg(size=(1,), snr_min=5.5, snr_std=2):
def draw_fg(size=(1,), snr_min=5.5): us = nr.uniform(size=size) return snr_min/(1 - us)**(1.0/3.0) def data_set(ncoinc, ffore, nbgs): bgs = [draw_bg(size=nb) for nb in nbgs] nf = int(round(ncoinc*ffore)) fgs = [np.concatenate((draw_bg(ncoinc-nf), draw_fg(nf))) for nb in nbgs] return np.arra...
bgs = nr.normal(loc=snr_min, scale=snr_std, size=size) sel = bgs < snr_min while np.count_nonzero(sel) > 0: bgs[sel] = nr.normal(loc=snr_min, scale=snr_std, size=np.count_nonzero(sel)) sel = bgs < snr_min return bgs
identifier_body
test.py
import numpy as np import numpy.random as nr def draw_bg(size=(1,), snr_min=5.5, snr_std=2): bgs = nr.normal(loc=snr_min, scale=snr_std, size=size) sel = bgs < snr_min while np.count_nonzero(sel) > 0:
return bgs def draw_fg(size=(1,), snr_min=5.5): us = nr.uniform(size=size) return snr_min/(1 - us)**(1.0/3.0) def data_set(ncoinc, ffore, nbgs): bgs = [draw_bg(size=nb) for nb in nbgs] nf = int(round(ncoinc*ffore)) fgs = [np.concatenate((draw_bg(ncoinc-nf), draw_fg(nf))) for nb in nbgs] ...
bgs[sel] = nr.normal(loc=snr_min, scale=snr_std, size=np.count_nonzero(sel)) sel = bgs < snr_min
conditional_block
test.py
import numpy as np import numpy.random as nr def draw_bg(size=(1,), snr_min=5.5, snr_std=2): bgs = nr.normal(loc=snr_min, scale=snr_std, size=size) sel = bgs < snr_min while np.count_nonzero(sel) > 0: bgs[sel] = nr.normal(loc=snr_min, scale=snr_std, size=np.count_nonzero(sel)) sel = bgs < ...
(ncoinc, ffore, nbgs): bgs = [draw_bg(size=nb) for nb in nbgs] nf = int(round(ncoinc*ffore)) fgs = [np.concatenate((draw_bg(ncoinc-nf), draw_fg(nf))) for nb in nbgs] return np.array(fgs), bgs
data_set
identifier_name
Plugin.js
Fixtures.DefaultPluginConfig = {foo: 'foo', bar: 'bar'}; Fixtures.Plugin = function(config) { var self = this; this.config = config; this.preUpdates = 0; this.postUpdates = 0; this.prefabsCreated = 0; this.prefabsDestroyed = 0; this.entitiesCreated = 0; this.entitiesDestroyed = 0; ...
this.$onRun = function() { self.runs++; }; this.$onStop = function() { self.stops++; }; this.$onFlush = function() { self.flushes++; }; this.$onPreUpdate = function(deltaTime) { self.preUpdates++; }; this.$onPostUpdate = function(deltaTime) { self.postUpdates++; }; this.$onPrefabCreate = func...
this.sceneLoads = false; this.$onLoad = function() { self.loaded = true; }; this.$onUnload = function() { self.unloaded = true; }; this.$onSceneLoaded = function() { self.sceneLoaded = true; };
random_line_split
dns_query.rs
// http://rosettacode.org/wiki/DNS_query #![feature(lookup_host)] use std::io; use std::net::{Ipv4Addr, Ipv6Addr}; #[derive(PartialEq)] enum Ips { IpV4(Ipv4Addr), IpV6(Ipv6Addr), } fn get_ips(host: &str) -> io::Result<Vec<Ips>>
#[cfg(not(test))] fn main() { for ip in &(get_ips("www.kame.net").unwrap()) { match ip { &Ips::IpV4(ip) => println!("ip v4: {}", ip), &Ips::IpV6(ip) => println!("ip v6: {}", ip) } } } #[cfg(test)] mod test { use super::{Ips, get_ips}; use std::net::{Ipv4Addr, I...
{ use std::net::{self, SocketAddr}; use Ips::{IpV4, IpV6}; let hosts = try!(net::lookup_host(host)); let ips: Vec<_> = hosts.filter_map(|h| match h { Ok(SocketAddr::V4(s_v4)) => Some(IpV4(s_v4.ip().clone())), Ok(SocketAddr::V6(s_v6)) => Some(IpV6(s_v6.ip().clone())), ...
identifier_body
dns_query.rs
// http://rosettacode.org/wiki/DNS_query #![feature(lookup_host)] use std::io; use std::net::{Ipv4Addr, Ipv6Addr}; #[derive(PartialEq)] enum Ips { IpV4(Ipv4Addr), IpV6(Ipv6Addr), } fn get_ips(host: &str) -> io::Result<Vec<Ips>> { use std::net::{self, SocketAddr}; use Ips::{IpV4, IpV6}; let hosts ...
Ok(ips) } #[cfg(not(test))] fn main() { for ip in &(get_ips("www.kame.net").unwrap()) { match ip { &Ips::IpV4(ip) => println!("ip v4: {}", ip), &Ips::IpV6(ip) => println!("ip v6: {}", ip) } } } #[cfg(test)] mod test { use super::{Ips, get_ips}; use std::net:...
random_line_split
dns_query.rs
// http://rosettacode.org/wiki/DNS_query #![feature(lookup_host)] use std::io; use std::net::{Ipv4Addr, Ipv6Addr}; #[derive(PartialEq)] enum
{ IpV4(Ipv4Addr), IpV6(Ipv6Addr), } fn get_ips(host: &str) -> io::Result<Vec<Ips>> { use std::net::{self, SocketAddr}; use Ips::{IpV4, IpV6}; let hosts = try!(net::lookup_host(host)); let ips: Vec<_> = hosts.filter_map(|h| match h { Ok(SocketAddr::V4(s_v4)) => Some(IpV4(s_...
Ips
identifier_name
Route.d.ts
import { IEventEmitter } from '../EventManager/IEventEmitter'; import { IEvent } from '../EventManager/IEvent'; export declare class
implements IEventEmitter { /** * вложенные роуты */ children: object; /** * имя переменной пути, начинается с ':', может быть нулл */ pathVariableName: string; /** * имя роута */ name: string; /** * часть адреса url, данного роута, если этот роут матчится...
Route
identifier_name
Route.d.ts
import { IEventEmitter } from '../EventManager/IEventEmitter'; import { IEvent } from '../EventManager/IEvent'; export declare class Route implements IEventEmitter { /** * вложенные роуты */ children: object; /** * имя переменной пути, начинается с ':', может быть нулл */ pathVariabl...
/** * вернуть реальный url * @param args объект с переменными пути * @returns {string} */ getPath(args: object): string; emitEvent(event: IEvent): void; }
random_line_split
polyfills.ts
/** * This file includes polyfills needed by Angular and is loaded before the app. * You can add your own extra polyfills to this file. * * This file is divided into 2 sections: * 1. Browser polyfills. These are applied before loading ZoneJS and are sorted by browsers. * 2. Application imports. Files imported...
* Needed for: All but Chrome, Firefox and Opera. http://caniuse.com/#feat=web-animation */ // import 'web-animations-js'; // Run `npm install --save web-animations-js`. /*************************************************************************************************** * Zone JS is required by Angular itself. */ ...
/** * Required to support Web Animations `@angular/platform-browser/animations`.
random_line_split
paginar.py
import flask.views from flask import request TAM_PAGINA=5 def calculoPrimeraPag(cant): """ Setea los valores correspondientes a la primera pagina de un paginar, recibe la cantidad de items, fases o proyectos que existen para dicho paginar """ if(cant!=0):#Si devolvio algo t=cant/TAM_PAGINA...
if flask.session['pagina']==1: flask.session['hayprev']=False else: flask.session['hayprev']=True m=flask.session['pagina'] infopag="Pagina "+ str(m) +" de " + str(t) return infopag def calculoDeAnterior(cant): """ Esta funcion es llamada cuando se hace click en el boton "A...
flask.session['haynext']=False
conditional_block
paginar.py
import flask.views from flask import request TAM_PAGINA=5 def calculoPrimeraPag(cant):
flask.session['hayprev']=True else:#si no pantalla vacia sin botones siguiente ni anterior flask.session['haynext']=False flask.session['hayprev']=False infopag="Pagina 1 de 1" return infopag def calculoDeSiguiente(cant): """ Esta funcion es llamada cuando se hace c...
""" Setea los valores correspondientes a la primera pagina de un paginar, recibe la cantidad de items, fases o proyectos que existen para dicho paginar """ if(cant!=0):#Si devolvio algo t=cant/TAM_PAGINA mod=cant%TAM_PAGINA if mod>0: t=int(t)+1#Total de paginas ...
identifier_body
paginar.py
import flask.views from flask import request TAM_PAGINA=5 def calculoPrimeraPag(cant): """ Setea los valores correspondientes a la primera pagina de un paginar, recibe la cantidad de items, fases o proyectos que existen para dicho paginar """ if(cant!=0):#Si devolvio algo t=cant/TAM_PAGINA...
infopag="Pagina "+ str(m) +" de " + str(t) return infopag def calculoDeAnterior(cant): """ Esta funcion es llamada cuando se hace click en el boton "Anterior" del paginar Setea los valores correspondientes para la siguiente pagina, calcula si hay siguiente para mostrar o no el boton de "Siguiente" ...
m=flask.session['pagina']
random_line_split
paginar.py
import flask.views from flask import request TAM_PAGINA=5 def calculoPrimeraPag(cant): """ Setea los valores correspondientes a la primera pagina de un paginar, recibe la cantidad de items, fases o proyectos que existen para dicho paginar """ if(cant!=0):#Si devolvio algo t=cant/TAM_PAGINA...
(cant): """ Esta funcion es llamada cuando se hace click en el boton "Siguiente" del paginar Setea los valores correspondientes para la siguiente pagina, calcula si hay siguiente para mostrar o no el boton de "Siguiente" """ t=cant/TAM_PAGINA mod=cant%TAM_PAGINA if mod>0: t=int(t)+1#...
calculoDeSiguiente
identifier_name
picidae-build.js
var nps = require('path'); var Picidae = require('../lib'); var getPath = require('./lib/getPath'); module.exports = function (commander) { if (!process.env.NODE_ENV)
var p = getPath(commander.config) var configPath = p.configPath, cwd = p.cwd var config = require(configPath) process.chdir(cwd) config.force = commander.force; config.noSpider = !commander.spider; config.noSw = !commander.sw; config.sourceMap = commander.sourceMap; config.id = r...
{ process.env.NODE_ENV = 'production' }
conditional_block
picidae-build.js
var nps = require('path'); var Picidae = require('../lib'); var getPath = require('./lib/getPath');
module.exports = function (commander) { if (!process.env.NODE_ENV) { process.env.NODE_ENV = 'production' } var p = getPath(commander.config) var configPath = p.configPath, cwd = p.cwd var config = require(configPath) process.chdir(cwd) config.force = commander.force; config.no...
random_line_split
views.py
from django.contrib import messages from django.db.models import Q from django.http import Http404 from django.views.generic.detail import DetailView from django.views.generic.list import ListView from django.shortcuts import render, get_object_or_404, redirect from django.utils import timezone # Create your views he...
(self, *args, **kwargs): context = super(ProductDetailView, self).get_context_data(*args, **kwargs) instance = self.get_object() #order_by("-title") context["related"] = sorted(Product.objects.get_related(instance)[:6], key= lambda x: random.random()) return context def product_detail_view_func(request, ...
get_context_data
identifier_name
views.py
from django.contrib import messages from django.db.models import Q from django.http import Http404 from django.views.generic.detail import DetailView from django.views.generic.list import ListView from django.shortcuts import render, get_object_or_404, redirect from django.utils import timezone # Create your views he...
import random class ProductDetailView(DetailView): model = Product #template_name = "product.html" #template_name = "<appname>/<modelname>_detail.html" def get_context_data(self, *args, **kwargs): context = super(ProductDetailView, self).get_context_data(*args, **kwargs) instance = self.get_object() #order...
qs = super(ProductListView, self).get_queryset(*args, **kwargs) query = self.request.GET.get("q") if query: qs = self.model.objects.filter( Q(title__icontains=query) | Q(description__icontains=query) ) try: qs2 = self.model.objects.filter( Q(price=query) ) qs = (qs | qs2).distinct...
identifier_body
views.py
from django.contrib import messages from django.db.models import Q from django.http import Http404 from django.views.generic.detail import DetailView from django.views.generic.list import ListView from django.shortcuts import render, get_object_or_404, redirect from django.utils import timezone # Create your views her...
def product_detail_view_func(request, id): #product_instance = Product.objects.get(id=id) product_instance = get_object_or_404(Product, id=id) try: product_instance = Product.objects.get(id=id) except Product.DoesNotExist: raise Http404 except: raise Http404 template = "products/product_detail.html" c...
instance = self.get_object() #order_by("-title") context["related"] = sorted(Product.objects.get_related(instance)[:6], key= lambda x: random.random()) return context
random_line_split
views.py
from django.contrib import messages from django.db.models import Q from django.http import Http404 from django.views.generic.detail import DetailView from django.views.generic.list import ListView from django.shortcuts import render, get_object_or_404, redirect from django.utils import timezone # Create your views he...
messages.success(request, "Your inventory and pricing has been updated.") return redirect("products") raise Http404 class ProductListView(ListView): model = Product queryset = Product.objects.all() def get_context_data(self, *args, **kwargs): context = super(ProductListView, self).get_context_da...
new_item = form.save(commit=False) #if new_item.title: product_pk = self.kwargs.get("pk") product = get_object_or_404(Product, pk=product_pk) new_item.product = product new_item.save()
conditional_block
models.py
import os from django.core.urlresolvers import reverse from django.db import models from django.utils import timezone from django.utils.translation import ugettext_lazy as _ from easy_thumbnails.fields import ThumbnailerImageField class VisibilityModel(models.Model): is_active = models.BooleanField(_('is active...
class PhotoManager(models.Manager): def active(self): return self.filter( is_active=True, album__is_active=True, ) def public(self): return self.filter( is_active=True, album__is_active=True, is_public=True, albu...
return reverse('chet_album_detail', kwargs={ 'year': self.date.strftime('%Y'), 'slug': self.slug, })
identifier_body
models.py
import os from django.core.urlresolvers import reverse from django.db import models from django.utils import timezone from django.utils.translation import ugettext_lazy as _ from easy_thumbnails.fields import ThumbnailerImageField class VisibilityModel(models.Model): is_active = models.BooleanField(_('is active...
album = models.ForeignKey( Album, verbose_name=_('album'), related_name='photos') shot_on = models.DateTimeField(_('shot on'), default=timezone.now) title = models.CharField(_('title'), max_length=200, blank=True) is_dark = models.BooleanField( _('is dark'), default=False, help_...
class Photo(VisibilityModel): created_on = models.DateTimeField(_('created on'), default=timezone.now) file = ThumbnailerImageField(_('file'), upload_to='chet/photos/%Y/%m/')
random_line_split
models.py
import os from django.core.urlresolvers import reverse from django.db import models from django.utils import timezone from django.utils.translation import ugettext_lazy as _ from easy_thumbnails.fields import ThumbnailerImageField class VisibilityModel(models.Model): is_active = models.BooleanField(_('is active...
(self): return reverse('chet_photo_detail', kwargs={ 'year': self.album.date.strftime('%Y'), 'slug': self.album.slug, 'photo': self.pk, })
get_absolute_url
identifier_name
command.py
# -*- coding: utf-8 -*- from datetime import datetime, timedelta from nextgisweb_compulink.compulink_video_producer.default_video_page import DefaultVideoPage, UNITS from nextgisweb_compulink.compulink_video_producer.model import VideoProduceTask from nextgisweb_compulink.compulink_video_producer.video_options import ...
(cls, parser, env): parser.add_argument('--res-id', required=True, type=int) parser.add_argument('--out-path', required=True, type=str) @classmethod def execute(cls, args, env): # TEST 18537 18395 vo = VideoOptions() vo.sound_enabled = False vp = DefaultVideoPag...
argparser_setup
identifier_name
command.py
# -*- coding: utf-8 -*- from datetime import datetime, timedelta from nextgisweb_compulink.compulink_video_producer.default_video_page import DefaultVideoPage, UNITS from nextgisweb_compulink.compulink_video_producer.model import VideoProduceTask from nextgisweb_compulink.compulink_video_producer.video_options import ...
@Command.registry.register class ProduceVideoCommand(): identity = 'compulink.produce_video' @classmethod def argparser_setup(cls, parser, env): parser.add_argument('--res-id', required=True, type=int) parser.add_argument('--out-path', required=True, type=str) @classmethod def e...
days = int(env.compulink_video_producer.settings.get('video_outdated_period', 7)) tasks = VideoProduceTask.filter(VideoProduceTask.creation_dt < datetime.now() - timedelta(days=days)) c = 0 for task in tasks: remove_video_entry(task.id) c += 1 print('Video removed...
identifier_body
command.py
# -*- coding: utf-8 -*- from datetime import datetime, timedelta from nextgisweb_compulink.compulink_video_producer.default_video_page import DefaultVideoPage, UNITS from nextgisweb_compulink.compulink_video_producer.model import VideoProduceTask from nextgisweb_compulink.compulink_video_producer.video_options import ...
print('Video removed: ' + str(c)) @Command.registry.register class ProduceVideoCommand(): identity = 'compulink.produce_video' @classmethod def argparser_setup(cls, parser, env): parser.add_argument('--res-id', required=True, type=int) parser.add_argument('--out-path', required=T...
remove_video_entry(task.id) c += 1
conditional_block
command.py
# -*- coding: utf-8 -*- from datetime import datetime, timedelta from nextgisweb_compulink.compulink_video_producer.default_video_page import DefaultVideoPage, UNITS from nextgisweb_compulink.compulink_video_producer.model import VideoProduceTask from nextgisweb_compulink.compulink_video_producer.video_options import ...
identity = 'compulink.produce_video' @classmethod def argparser_setup(cls, parser, env): parser.add_argument('--res-id', required=True, type=int) parser.add_argument('--out-path', required=True, type=str) @classmethod def execute(cls, args, env): # TEST 18537 18395 ...
print('Video removed: ' + str(c)) @Command.registry.register class ProduceVideoCommand():
random_line_split
libSMACOF_theano.py
optional, default: 10000 Maximum number of iterations of the SMACOF Alghorithm mode: string, optional, default: 'step' Whether to call Theano for each Iteration step or let Theano handle Iterations 'step' or 'all' floatX: string, optional, default: 'float32' Precision which Th...
Guttman Transformation: Update Function for X """ X = size_inv* T.dot(self.bCalc(distX, delta), Z) return X def solve(self, data, initX = None, eps = 1e-6): """ Performs Multidimensional Scaling Parameters --------- data: array-like ...
"""
random_line_split
libSMACOF_theano.py
optional, default: 10000 Maximum number of iterations of the SMACOF Alghorithm mode: string, optional, default: 'step' Whether to call Theano for each Iteration step or let Theano handle Iterations 'step' or 'all' floatX: string, optional, default: 'float32' Precision which Th...
def init_step(self): """compiles step as fstep""" Z = T.matrix() distZ = T.matrix() delta = T.matrix() size_inv = T.scalar() X = T.matrix() distX = T.matrix() s = T.scalar() s_old = T.scalar() X, distX, s = self.step(Z, distZ, s_old, ...
self.init_step()
conditional_block
libSMACOF_theano.py
(): """ Multidimensional Scaling Multidimensional Scaling using the "Scaling by MAjorizing a COmplicated Function" (SMACOF) alghorithm Parameters --------- data: array-like array containing high dimensional data points n_components: int, optional, default: 2 number of dime...
SMACOF
identifier_name
libSMACOF_theano.py
optional, default: 10000 Maximum number of iterations of the SMACOF Alghorithm mode: string, optional, default: 'step' Whether to call Theano for each Iteration step or let Theano handle Iterations 'step' or 'all' floatX: string, optional, default: 'float32' Precision which Th...
------- return: list list containing the following return values X: array-like updated low dimensional data distX: array-like distance matrix of updated X s: float updated stress between distX and delta ...
""" Body for Iteration loop This provides the Body for the Iteration Loop theano.scan uses this to create the actual Iteration loop Parameters ---------- Z: array-like X of previous iteration distZ: array-like Distance Matrix distX of pre...
identifier_body
_base.py
class PluginBase(object): name = '' doc = 'doc about this class' methods_subclass = {} def __init__(self, **kwargs): self.methods = { 'help': 'doc about help method', 'get_methods': 'doc about get_methods method' } self.methods.update(self.methods_subclas...
(text): fname, method, args, kwargs = '', '', [], {} if text: aspl = text.split(' ') fname = aspl[0] if len(aspl) > 1: method = aspl[1] if len(aspl) > 2: args, kwargs = PluginBase.get_args_kwargs_from_text( ...
get_method_args_kwargs
identifier_name
_base.py
class PluginBase(object): name = '' doc = 'doc about this class' methods_subclass = {} def __init__(self, **kwargs): self.methods = { 'help': 'doc about help method', 'get_methods': 'doc about get_methods method' } self.methods.update(self.methods_subclas...
@staticmethod def slice_fname(text): fname = '' text2 = '' args = '' if text: b = text.find(' ') if b != -1: text2 = text[b+1:] fname = text[:b] else: fname = text return fname, text2 ...
ret = term_system.exec_locals.get(text, None) if not ret: ret = term_system.get_globals().get(text, None) return ret
identifier_body
_base.py
class PluginBase(object): name = '' doc = 'doc about this class' methods_subclass = {}
} self.methods.update(self.methods_subclass) def on_import(self, term_system): pass def get_methods(self): return [key for key in self.methods] def help(self, method_name): doc = self.methods.get(method_name[0], None) if doc: ret = doc e...
def __init__(self, **kwargs): self.methods = { 'help': 'doc about help method', 'get_methods': 'doc about get_methods method'
random_line_split