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
gotoSymbolQuickAccess.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
} else { symbolQuery = query; } // Convert to symbol picks and apply filtering const filteredSymbolPicks: IGotoSymbolQuickPickItem[] = []; for (let index = 0; index < symbols.length; index++) { const symbol = symbols[index]; const symbolLabel = trim(symbol.name); const symbolLabelWithIcon = `$(s...
let symbolQuery: IPreparedQuery; let containerQuery: IPreparedQuery | undefined; if (query.values && query.values.length > 1) { symbolQuery = pieceToQuery(query.values[0]); // symbol: only match on first part containerQuery = pieceToQuery(query.values.slice(1)); // container: match on all but first part...
random_line_split
gotoSymbolQuickAccess.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
lse { flatEntries = roots; } return flatEntries.sort((symbolA, symbolB) => Range.compareRangesUsingStarts(symbolA.range, symbolB.range)); } private flattenDocumentSymbols(bucket: DocumentSymbol[], entries: DocumentSymbol[], overrideContainerLabel: string): void { for (const entry of entries) { bucket.pu...
this.flattenDocumentSymbols(flatEntries, roots, ''); } e
conditional_block
sip.rs
/* Copyright (C) 2019-2020 Open Information Security Foundation * * You can copy, redistribute or modify this Program under the terms of * the GNU General Public License version 2 as published by the Free * Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY...
#[no_mangle] pub unsafe extern "C" fn rs_sip_register_parser() { let default_port = CString::new("5060").unwrap(); let parser = RustParser { name: PARSER_NAME.as_ptr() as *const std::os::raw::c_char, default_port: default_port.as_ptr(), ipproto: core::IPPROTO_UDP, probe_ts: Some...
export_tx_data_get!(rs_sip_get_tx_data, SIPTransaction); const PARSER_NAME: &'static [u8] = b"sip\0";
random_line_split
sip.rs
/* Copyright (C) 2019-2020 Open Information Security Foundation * * You can copy, redistribute or modify this Program under the terms of * the GNU General Public License version 2 as published by the Free * Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY...
(id: u64) -> SIPTransaction { SIPTransaction { id: id, de_state: None, request: None, response: None, request_line: None, response_line: None, events: std::ptr::null_mut(), tx_data: applayer::AppLayerTxData::new(), ...
new
identifier_name
sip.rs
/* Copyright (C) 2019-2020 Open Information Security Foundation * * You can copy, redistribute or modify this Program under the terms of * the GNU General Public License version 2 as published by the Free * Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY...
fn new_tx(&mut self) -> SIPTransaction { self.tx_id += 1; SIPTransaction::new(self.tx_id) } fn get_tx_by_id(&mut self, tx_id: u64) -> Option<&SIPTransaction> { self.transactions.iter().find(|&tx| tx.id == tx_id + 1) } fn free_tx(&mut self, tx_id: u64) { let tx = s...
{ self.transactions.clear(); }
identifier_body
sip.rs
/* Copyright (C) 2019-2020 Open Information Security Foundation * * You can copy, redistribute or modify this Program under the terms of * the GNU General Public License version 2 as published by the Free * Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY...
} fn set_event(&mut self, event: SIPEvent) { if let Some(tx) = self.transactions.last_mut() { let ev = event as u8; core::sc_app_layer_decoder_events_set_event_raw(&mut tx.events, ev); } } fn parse_request(&mut self, input: &[u8]) -> bool { match sip_pa...
{ let _ = self.transactions.remove(idx); }
conditional_block
ntp.rs
/* Copyright (C) 2017-2020 Open Information Security Foundation * * You can copy, redistribute or modify this Program under the terms of * the GNU General Public License version 2 as published by the Free * Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY...
(&mut self, i: &[u8], _direction: u8) -> i32 { match parse_ntp(i) { Ok((_,ref msg)) => { // SCLogDebug!("parse_ntp: {:?}",msg); if msg.mode == NtpMode::SymmetricActive || msg.mode == NtpMode::Client { let mut tx = self.new_tx(); ...
parse
identifier_name
ntp.rs
/* Copyright (C) 2017-2020 Open Information Security Foundation * * You can copy, redistribute or modify this Program under the terms of * the GNU General Public License version 2 as published by the Free * Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY...
max_depth : 16, state_new : rs_ntp_state_new, state_free : rs_ntp_state_free, tx_free : rs_ntp_state_tx_free, parse_ts : rs_ntp_parse_request, parse_tc : rs_ntp_parse_response, get_tx_count : rs_ntp_st...
probe_ts : Some(ntp_probing_parser), probe_tc : Some(ntp_probing_parser), min_depth : 0,
random_line_split
ntp.rs
/* Copyright (C) 2017-2020 Open Information Security Foundation * * You can copy, redistribute or modify this Program under the terms of * the GNU General Public License version 2 as published by the Free * Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY...
/// Set an event. The event is set on the most recent transaction. pub fn set_event(&mut self, event: NTPEvent) { if let Some(tx) = self.transactions.last_mut() { tx.tx_data.set_event(event as u8); self.events += 1; } } } impl NTPTransaction { pub fn new(id: u6...
{ let tx = self.transactions.iter().position(|tx| tx.id == tx_id + 1); debug_assert!(tx != None); if let Some(idx) = tx { let _ = self.transactions.remove(idx); } }
identifier_body
ntp.rs
/* Copyright (C) 2017-2020 Open Information Security Foundation * * You can copy, redistribute or modify this Program under the terms of * the GNU General Public License version 2 as published by the Free * Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY...
, Err(_) => { return unsafe{ALPROTO_FAILED}; }, } } export_tx_data_get!(rs_ntp_get_tx_data, NTPTransaction); const PARSER_NAME : &'static [u8] = b"ntp\0"; #[no_mangle] pub unsafe extern "C" fn rs_register_ntp_parser() { let default_port = CString::new("123").unwrap(); let pars...
{ return ALPROTO_UNKNOWN; }
conditional_block
task-comm-13.rs
// http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except accordin...
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at
random_line_split
task-comm-13.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...
{ println!("Check that we don't deadlock."); let (tx, rx) = channel(); let _ = Thread::scoped(move|| { start(&tx, 0, 10) }).join(); println!("Joined task"); }
identifier_body
task-comm-13.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...
() { println!("Check that we don't deadlock."); let (tx, rx) = channel(); let _ = Thread::scoped(move|| { start(&tx, 0, 10) }).join(); println!("Joined task"); }
main
identifier_name
user.js
'use strict'; var mongoose = require('mongoose'); var bcrypt = require('bcrypt');
required: true }, email: { type: String, required: true, unique: true, trim: true }, username: { type: String, required: true, unique: true, trim: true }, biography: { type: String }, location: { type: String }, auth: { basic: { username: String,...
var eat = require('eat'); var userSchema = new mongoose.Schema({ name: { type: String,
random_line_split
releases.py
#!/usr/bin/env python # Copyright 2014 the V8 project authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # This script retrieves the history of all V8 branches and trunk revisions and # their corresponding Chromium revisions. # Requires ...
class WriteOutput(Step): MESSAGE = "Print output." def Run(self): if self._options.csv: with open(self._options.csv, "w") as f: writer = csv.DictWriter(f, ["version", "branch", "revision", "chromium_revision", "patches_merged"], ...
MESSAGE = "Clean up." def RunStep(self): self.GitCheckout("master", cwd=self._options.chromium) self.GitDeleteBranch(self.Config("BRANCHNAME"), cwd=self._options.chromium) self.CommonCleanup()
identifier_body
releases.py
#!/usr/bin/env python # Copyright 2014 the V8 project authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # This script retrieves the history of all V8 branches and trunk revisions and # their corresponding Chromium revisions. # Requires ...
if cr_rev: v8_rev = ConvertToCommitNumber(self, match.group(1)) cr_releases.append([cr_rev, v8_rev]) # Stop after reaching beyond the last v8 revision we want to update. # We need a small buffer for possible revert/reland frenzies. # TODO(machenbach): Sub...
cr_rev = self.GetCommitPositionNumber(git_hash, cwd=cwd)
random_line_split
releases.py
#!/usr/bin/env python # Copyright 2014 the V8 project authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # This script retrieves the history of all V8 branches and trunk revisions and # their corresponding Chromium revisions. # Requires ...
else: patches = self.GetMergedPatches(body) title = self.GitLog(n=1, format="%s", git_hash=git_hash) bleeding_edge_revision = self.GetBleedingEdgeFromPush(title) bleeding_edge_git = "" if bleeding_edge_revision: bleeding_edge_git = self.vc.SvnGit(bleeding_edge_revision, ...
patches = self.GetMergedPatchesGit(body)
conditional_block
releases.py
#!/usr/bin/env python # Copyright 2014 the V8 project authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # This script retrieves the history of all V8 branches and trunk revisions and # their corresponding Chromium revisions. # Requires ...
(self): if self._options.csv: with open(self._options.csv, "w") as f: writer = csv.DictWriter(f, ["version", "branch", "revision", "chromium_revision", "patches_merged"], restval="", ...
Run
identifier_name
search.js
var apikey = "252044BE3886FE4A8E3BAA4F595114BB"; var inSearch = false; var lastSearchTerm = ''; var filterArray = []; var filterQuery=''; $(document).ready(function () { execSearch(); $('#searchbar').on('keyup', function (event) { if (inSearch != true) execSearch(); }); if(navigator.userAgent.match(/Windo...
var thumbNail = 'https://azsplayground.blob.core.windows.net/historicsites/img/nrhp_thumbnail.png'; if (data.value[item]["ImageCount"] > 0) thumbNail = 'https://azsplayground.blob.core.windows.net/historicsites/img/' + data.value[item]["NRIS_Refnum"] + '_1.jpeg'; ...
for (var item in data.value) {
random_line_split
search.js
var apikey = "252044BE3886FE4A8E3BAA4F595114BB"; var inSearch = false; var lastSearchTerm = ''; var filterArray = []; var filterQuery=''; $(document).ready(function () { execSearch(); $('#searchbar').on('keyup', function (event) { if (inSearch != true) execSearch(); }); if(navigator.userAgent.match(/Windo...
function updateFacets() { $("#FilterResType").html(''); $("#FilterResType").append('<legend>Type:</legend>').trigger('create');; for (var facet in facets.ResType) { // Check if this is a selected facet var checked = checkIfSelected('ResType', facets.ResType[facet].value); var html = getStaticHTM...
{ for (var filter in filterArray) { if ((filterArray[filter].facet == facet) && (filterArray[filter].value == value)) return 'checked'; } return ''; }
identifier_body
search.js
var apikey = "252044BE3886FE4A8E3BAA4F595114BB"; var inSearch = false; var lastSearchTerm = ''; var filterArray = []; var filterQuery=''; $(document).ready(function () { execSearch(); $('#searchbar').on('keyup', function (event) { if (inSearch != true) execSearch(); }); if(navigator.userAgent.match(/Windo...
} }); } function changePage(page, reverse, nrisRefnum) { $.mobile.changePage(page, { transition: 'slide', reverse: reverse }); if (page == "#pageDetails") { execLookup(nrisRefnum); } } function getStaticHTML(html) { if(Object.hasOwnProperty.call(window, "ActiveXObject")){ //using...
{ $("#detailsImages").append("<img style='width: 100%;height: auto;max-width: 100%;' src='https://azsplayground.blob.core.windows.net/historicsites/img/" + q + "_" + i + ".jpeg'>"); }
conditional_block
search.js
var apikey = "252044BE3886FE4A8E3BAA4F595114BB"; var inSearch = false; var lastSearchTerm = ''; var filterArray = []; var filterQuery=''; $(document).ready(function () { execSearch(); $('#searchbar').on('keyup', function (event) { if (inSearch != true) execSearch(); }); if(navigator.userAgent.match(/Windo...
() { inSearch = true; $.mobile.loading("show", { text: "Loading...", textVisible: true, textonly: true, theme: "b" }); lastSearchTerm = $("#searchbar").val(); // Append ~ to each word for fuzzy search if (lastSearchTerm == '') lastSearchTerm = '*'; var fuzzyQ = ""; if (lastSearch...
execSearch
identifier_name
tensor.rs
use std::ops::{Deref, DerefMut}; use enum_map::EnumMap; use crate::features::Layer; use tensorflow::{Tensor, TensorType}; /// Ad-hoc trait for shrinking batches. pub trait ShrinkBatch { fn shrink_batch(&self, n_instances: u64) -> Self; } impl<T> ShrinkBatch for Tensor<T> where T: Copy + TensorType, { fn...
let mut copy = Tensor::new(&new_shape); copy.copy_from_slice(&self[..new_shape.iter().cloned().product::<u64>() as usize]); copy } } impl<T> ShrinkBatch for TensorWrap<T> where T: Copy + TensorType, { fn shrink_batch(&self, n_instances: u64) -> Self { TensorWrap(self.0.shr...
let mut new_shape = self.dims().to_owned(); new_shape[0] = n_instances;
random_line_split
tensor.rs
use std::ops::{Deref, DerefMut}; use enum_map::EnumMap; use crate::features::Layer; use tensorflow::{Tensor, TensorType}; /// Ad-hoc trait for shrinking batches. pub trait ShrinkBatch { fn shrink_batch(&self, n_instances: u64) -> Self; } impl<T> ShrinkBatch for Tensor<T> where T: Copy + TensorType, { fn...
(&mut self, idx: usize) -> EnumMap<Layer, &mut [T]> { let mut slices = EnumMap::new(); for (layer, tensor) in self.iter_mut() { let layer_size = tensor.dims()[1] as usize; let offset = idx * layer_size; slices[layer] = &mut tensor[offset..offset + layer_size]; ...
to_instance_slices
identifier_name
tensor.rs
use std::ops::{Deref, DerefMut}; use enum_map::EnumMap; use crate::features::Layer; use tensorflow::{Tensor, TensorType}; /// Ad-hoc trait for shrinking batches. pub trait ShrinkBatch { fn shrink_batch(&self, n_instances: u64) -> Self; } impl<T> ShrinkBatch for Tensor<T> where T: Copy + TensorType, { fn...
} impl<T> Deref for TensorWrap<T> where T: TensorType, { type Target = Tensor<T>; fn deref(&self) -> &Self::Target { &self.0 } } impl<T> DerefMut for TensorWrap<T> where T: TensorType, { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } #[cfg(test)] mod test...
{ TensorWrap(tensor) }
identifier_body
promise-ensurer.js
/** * @author joel * 25-11-15. */ /// <reference path="../typings/tsd.d.ts" /> /// <reference path="../typings/app.d.ts" /> 'use strict'; var _ = require('lodash'); var Promise = require('bluebird'); var IsPromise = require('is-promise'); var PromiseEnsurer = (function () { function PromiseEnsurer()
PromiseEnsurer.isPromise = function (value) { return IsPromise(value); }; PromiseEnsurer.transformToPromise = function (value) { return new Promise(function (resolve, reject) { if (_.isUndefined(value)) { reject(undefined); } else if (_.is...
{ }
identifier_body
promise-ensurer.js
/** * @author joel * 25-11-15. */ /// <reference path="../typings/tsd.d.ts" /> /// <reference path="../typings/app.d.ts" /> 'use strict'; var _ = require('lodash'); var Promise = require('bluebird'); var IsPromise = require('is-promise'); var PromiseEnsurer = (function () { function PromiseEnsurer() { } ...
return new Promise(function (resolve, reject) { if (_.isUndefined(value)) { reject(undefined); } else if (_.isBoolean(value)) { value ? resolve(undefined) : reject(undefined); } else { resolve(value); ...
random_line_split
promise-ensurer.js
/** * @author joel * 25-11-15. */ /// <reference path="../typings/tsd.d.ts" /> /// <reference path="../typings/app.d.ts" /> 'use strict'; var _ = require('lodash'); var Promise = require('bluebird'); var IsPromise = require('is-promise'); var PromiseEnsurer = (function () { function
() { } PromiseEnsurer.isPromise = function (value) { return IsPromise(value); }; PromiseEnsurer.transformToPromise = function (value) { return new Promise(function (resolve, reject) { if (_.isUndefined(value)) { reject(undefined); } els...
PromiseEnsurer
identifier_name
sten_virtex.py
from uvscada.ngc import * import math ''' Need to account for endmill radius to make the die actualy fit w=0.805, h=0.789 em=0.0413 Actual used w/h: cos(45) * 0.0413 = 0.02920351 Total w/h: 0.0413 Wasted w/h: 0.0413 - 0.0292 = 0.0121 each corner Increase by ''' cnc = init( #em=0.0413, em=0.0625,...
y = fullh/2 + sep/2 # Find corner xy coordinate then calculate dist to center # Does not account for edge rounding (ie slightly underestimates) rx = fullw/2 ry = y + fullh/2 rd = (rx**2 + ry**2)**0.5 rsep = main_r - rd line('(Edge sep: %0.3f)' % (rsep,), verbose=True) line(' (r...
# Centering properly if 1: sep = 0.10 line('(Die sep: %0.3f)' % (sep,), verbose=True)
random_line_split
sten_virtex.py
from uvscada.ngc import * import math ''' Need to account for endmill radius to make the die actualy fit w=0.805, h=0.789 em=0.0413 Actual used w/h: cos(45) * 0.0413 = 0.02920351 Total w/h: 0.0413 Wasted w/h: 0.0413 - 0.0292 = 0.0121 each corner Increase by ''' cnc = init( #em=0.0413, em=0.0625,...
# Centering properly if 1: sep = 0.10 line('(Die sep: %0.3f)' % (sep,), verbose=True) y = fullh/2 + sep/2 # Find corner xy coordinate then calculate dist to center # Does not account for edge rounding (ie slightly underestimates) rx = fullw/2 ry = y + fullh/2 rd = (rx**2 + ry**2)**...
rect_in_ul(x=-0.403, y=-0.864, w=diew, h=dieh, finishes=1) rect_in_ul(x=-0.403, y=-0.075, w=diew, h=dieh, finishes=1)
conditional_block
__init__.py
# coding: utf-8 from collections import namedtuple from pandas.io.msgpack.exceptions import * # noqa from pandas.io.msgpack._version import version # noqa class
(namedtuple("ExtType", "code data")): """ExtType represents ext type in msgpack.""" def __new__(cls, code, data): if not isinstance(code, int): raise TypeError("code must be int") if not isinstance(data, bytes): raise TypeError("data must be bytes") if not 0 <= c...
ExtType
identifier_name
__init__.py
# coding: utf-8 from collections import namedtuple from pandas.io.msgpack.exceptions import * # noqa from pandas.io.msgpack._version import version # noqa class ExtType(namedtuple("ExtType", "code data")): """ExtType represents ext type in msgpack.""" def __new__(cls, code, data): if not isinstan...
return super().__new__(cls, code, data) import os # noqa from pandas.io.msgpack._packer import Packer # noqa from pandas.io.msgpack._unpacker import unpack, unpackb, Unpacker # noqa def pack(o, stream, **kwargs): """ Pack object `o` and write it to `stream` See :class:`Packer` for options....
raise ValueError("code must be 0~127")
conditional_block
__init__.py
# coding: utf-8
from pandas.io.msgpack._version import version # noqa class ExtType(namedtuple("ExtType", "code data")): """ExtType represents ext type in msgpack.""" def __new__(cls, code, data): if not isinstance(code, int): raise TypeError("code must be int") if not isinstance(data, bytes): ...
from collections import namedtuple from pandas.io.msgpack.exceptions import * # noqa
random_line_split
__init__.py
# coding: utf-8 from collections import namedtuple from pandas.io.msgpack.exceptions import * # noqa from pandas.io.msgpack._version import version # noqa class ExtType(namedtuple("ExtType", "code data")): """ExtType represents ext type in msgpack.""" def __new__(cls, code, data): if not isinstan...
# alias for compatibility to simplejson/marshal/pickle. load = unpack loads = unpackb dump = pack dumps = packb
""" Pack object `o` and return packed bytes See :class:`Packer` for options. """ return Packer(**kwargs).pack(o)
identifier_body
amf.py
# Copyright (c) The AcidSWF Project. # See LICENSE.txt for details. """ Support for creating a service which runs a web server. @since: 1.0 """ import logging from twisted.python import usage from twisted.application import service from acidswf.service import createAMFService
optParameters = [ ['log-level', None, logging.INFO, 'Log level.'], ['amf-transport', None, 'http', 'Run the AMF server on HTTP or HTTPS transport.'], ['amf-host', None, 'localhost', 'The interface for the AMF gateway to listen on.'], ['service', None, 'acidswf', 'The remote service name.'], ['amf-po...
random_line_split
amf.py
# Copyright (c) The AcidSWF Project. # See LICENSE.txt for details. """ Support for creating a service which runs a web server. @since: 1.0 """ import logging from twisted.python import usage from twisted.application import service from acidswf.service import createAMFService optParameters = [ ['log-level', ...
def makeService(options): top_service = service.MultiService() createAMFService(top_service, options) return top_service
""" Define the options accepted by the I{acidswf amf} plugin. """ synopsis = "[amf options]" optParameters = optParameters longdesc = """\ This starts an AMF server.""" def postOptions(self): """ Set up conditional defaults and check for dependencies. If SSL is n...
identifier_body
amf.py
# Copyright (c) The AcidSWF Project. # See LICENSE.txt for details. """ Support for creating a service which runs a web server. @since: 1.0 """ import logging from twisted.python import usage from twisted.application import service from acidswf.service import createAMFService optParameters = [ ['log-level', ...
(usage.Options): """ Define the options accepted by the I{acidswf amf} plugin. """ synopsis = "[amf options]" optParameters = optParameters longdesc = """\ This starts an AMF server.""" def postOptions(self): """ Set up conditional defaults and check for dependencies....
Options
identifier_name
bitops-nsieve-bits.js
var _sunSpiderStartDate = new Date(); // The Great Computer Language Shootout // http://shootout.alioth.debian.org // // Contributed by Ian Osgood function pad(n,width) { var s = n.toString(); while (s.length < width) s = ' ' + s; return s; }
function primes(isPrime, n) { var i, count = 0, m = 10000<<n, size = m+31>>5; for (i=0; i<size; i++) isPrime[i] = 0xffffffff; for (i=2; i<m; i++) if (isPrime[i>>5] & 1<<(i&31)) { for (var j=i+i; j<m; j+=i) isPrime[j>>5] &= ~(1<<(j&31)); count++; } } function sieve() { for (var i...
random_line_split
bitops-nsieve-bits.js
var _sunSpiderStartDate = new Date(); // The Great Computer Language Shootout // http://shootout.alioth.debian.org // // Contributed by Ian Osgood function pad(n,width) { var s = n.toString(); while (s.length < width) s = ' ' + s; return s; } function primes(isPrime, n) { var i, count = 0, m = 10000<<n, ...
sieve(); var _sunSpiderInterval = new Date() - _sunSpiderStartDate; dumpValue(_sunSpiderInterval);
{ for (var i = 4; i <= 4; i++) { var isPrime = new Array((10000<<i)+31>>5); primes(isPrime, i); } }
identifier_body
bitops-nsieve-bits.js
var _sunSpiderStartDate = new Date(); // The Great Computer Language Shootout // http://shootout.alioth.debian.org // // Contributed by Ian Osgood function
(n,width) { var s = n.toString(); while (s.length < width) s = ' ' + s; return s; } function primes(isPrime, n) { var i, count = 0, m = 10000<<n, size = m+31>>5; for (i=0; i<size; i++) isPrime[i] = 0xffffffff; for (i=2; i<m; i++) if (isPrime[i>>5] & 1<<(i&31)) { for (var j=i+i; j<m; j+=i) ...
pad
identifier_name
bitops-nsieve-bits.js
var _sunSpiderStartDate = new Date(); // The Great Computer Language Shootout // http://shootout.alioth.debian.org // // Contributed by Ian Osgood function pad(n,width) { var s = n.toString(); while (s.length < width) s = ' ' + s; return s; } function primes(isPrime, n) { var i, count = 0, m = 10000<<n, ...
} function sieve() { for (var i = 4; i <= 4; i++) { var isPrime = new Array((10000<<i)+31>>5); primes(isPrime, i); } } sieve(); var _sunSpiderInterval = new Date() - _sunSpiderStartDate; dumpValue(_sunSpiderInterval);
{ for (var j=i+i; j<m; j+=i) isPrime[j>>5] &= ~(1<<(j&31)); count++; }
conditional_block
ColossusHero.tsx
/* * 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/. */ import React, { useState } from 'react'; import { styled } from '@csegames/linaria/react'; const Hero = styl...
object-fit: cover; `; export function ColossusHero(props: {}) { const [isInitialVideo, setIsInitialVideo] = useState(true); function onVideoEnded() { setIsInitialVideo(false); } return ( <Hero> <Content> <Video src='videos/fsr-logo-4k-10q-loop.webm' poster='' onEnded={onVideoEnded} aut...
position: absolute; top: 0; left: 0; width: 100%; height: 100%;
random_line_split
ColossusHero.tsx
/* * 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/. */ import React, { useState } from 'react'; import { styled } from '@csegames/linaria/react'; const Hero = styl...
() { setIsInitialVideo(false); } return ( <Hero> <Content> <Video src='videos/fsr-logo-4k-10q-loop.webm' poster='' onEnded={onVideoEnded} autoPlay={isInitialVideo} loop></Video> {isInitialVideo && <Video src='videos/fsr-intro-4k-10q.webm' poster='images/cse/login-cse.jpg' onEnded={onVi...
onVideoEnded
identifier_name
ColossusHero.tsx
/* * 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/. */ import React, { useState } from 'react'; import { styled } from '@csegames/linaria/react'; const Hero = styl...
return ( <Hero> <Content> <Video src='videos/fsr-logo-4k-10q-loop.webm' poster='' onEnded={onVideoEnded} autoPlay={isInitialVideo} loop></Video> {isInitialVideo && <Video src='videos/fsr-intro-4k-10q.webm' poster='images/cse/login-cse.jpg' onEnded={onVideoEnded} autoPlay></Video>} </C...
{ setIsInitialVideo(false); }
identifier_body
JustPremium.py
# -*- coding: utf-8 -*- import re from module.plugins.internal.Addon import Addon class JustPremium(Addon):
__name__ = "JustPremium" __type__ = "hook" __version__ = "0.25" __status__ = "testing" __config__ = [("activated", "bool", "Activated" , False), ("excluded" , "str" , "Exclude hosters (comma separated)", "" ), ("included" , "str" , "In...
identifier_body
JustPremium.py
# -*- coding: utf-8 -*- import re from module.plugins.internal.Addon import Addon class JustPremium(Addon): __name__ = "JustPremium" __type__ = "hook" __version__ = "0.25" __status__ = "testing" __config__ = [("activated", "bool", "Activated" , False), ...
self.log_debug("Remove link: %s" % link) links.remove(link)
conditional_block
JustPremium.py
# -*- coding: utf-8 -*- import re from module.plugins.internal.Addon import Addon class
(Addon): __name__ = "JustPremium" __type__ = "hook" __version__ = "0.25" __status__ = "testing" __config__ = [("activated", "bool", "Activated" , False), ("excluded" , "str" , "Exclude hosters (comma separated)", "" ), ("included" ...
JustPremium
identifier_name
JustPremium.py
# -*- coding: utf-8 -*- import re from module.plugins.internal.Addon import Addon class JustPremium(Addon): __name__ = "JustPremium"
__config__ = [("activated", "bool", "Activated" , False), ("excluded" , "str" , "Exclude hosters (comma separated)", "" ), ("included" , "str" , "Include hosters (comma separated)", "" )] __description__ = """Remove not-premium links from added url...
__type__ = "hook" __version__ = "0.25" __status__ = "testing"
random_line_split
coherence_copy_like_err_fundamental_struct_ref.rs
// Copyright 2015 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: lib::MyCopy> MyTrait for T { } // `MyFundamentalStruct` is declared fundamental, so we can test that // // MyFundamentalStruct<&MyTrait>: !MyTrait // // Huzzah. impl<'a> MyTrait for lib::MyFundamentalStruct<&'a MyType> { } fn main() { }
foo
identifier_name
coherence_copy_like_err_fundamental_struct_ref.rs
// Copyright 2015 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 ...
extern crate coherence_copy_like_lib as lib; struct MyType { x: i32 } trait MyTrait { fn foo() {} } impl<T: lib::MyCopy> MyTrait for T { } // `MyFundamentalStruct` is declared fundamental, so we can test that // // MyFundamentalStruct<&MyTrait>: !MyTrait // // Huzzah. impl<'a> MyTrait for lib::MyFundamentalStruc...
random_line_split
coherence_copy_like_err_fundamental_struct_ref.rs
// Copyright 2015 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 ...
{ }
identifier_body
sigproc.py
# Copyright 2018 the V8 project authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # for py2/py3 compatibility from __future__ import print_function import signal from . import base from testrunner.local import utils class SignalProc(...
(self, _signum, _stack_frame): print('>>> SIGTERM received, early abort...') self.exit_code = utils.EXIT_CODE_TERMINATED self.stop()
_on_sigterm
identifier_name
sigproc.py
# Copyright 2018 the V8 project authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # for py2/py3 compatibility from __future__ import print_function import signal from . import base from testrunner.local import utils class SignalProc(...
super(SignalProc, self).__init__() self.exit_code = utils.EXIT_CODE_PASS def setup(self, *args, **kwargs): super(SignalProc, self).setup(*args, **kwargs) # It should be called after processors are chained together to not loose # catched signal. signal.signal(signal.SIGINT, self._on_ctrlc) ...
random_line_split
sigproc.py
# Copyright 2018 the V8 project authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # for py2/py3 compatibility from __future__ import print_function import signal from . import base from testrunner.local import utils class SignalProc(...
def _on_sigterm(self, _signum, _stack_frame): print('>>> SIGTERM received, early abort...') self.exit_code = utils.EXIT_CODE_TERMINATED self.stop()
print('>>> Ctrl-C detected, early abort...') self.exit_code = utils.EXIT_CODE_INTERRUPTED self.stop()
identifier_body
time_stepping.py
# Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
equation: ImplicitExplicitODE, time_step: float, ) -> TimeStepFn: """Time stepping via Crank-Nicolson and 2nd order Runge-Kutta (Heun). This method is second order accurate. Args: equation: equation to solve. time_step: time step. Returns: Function that performs a time step. Reference: C...
k_nicolson_rk2(
identifier_name
time_stepping.py
# Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
n def imex_rk_sil3( equation: ImplicitExplicitODE, time_step: float, ) -> TimeStepFn: """Time stepping with the SIL3 implicit-explicit RK scheme. This method is second-order accurate for the implicit terms and third-order accurate for the explicit terms. Args: equation: equation to solve. time_s...
steps g = [None] * num_steps f[0] = F(y0) g[0] = G(y0) for i in range(1, num_steps): ex_terms = dt * sum(a_ex[i-1][j] * f[j] for j in range(i) if a_ex[i-1][j]) im_terms = dt * sum(a_im[i-1][j] * g[j] for j in range(i) if a_im[i-1][j]) Y_star = y0 + ex_terms + im_terms Y = G_inv...
identifier_body
time_stepping.py
# Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
eturn step_fn def crank_nicolson_rk3( equation: ImplicitExplicitODE, time_step: float, ) -> TimeStepFn: """Time stepping via Crank-Nicolson and RK3 ("Williamson").""" return low_storage_runge_kutta_crank_nicolson( alphas=[0, 1/3, 3/4, 1], betas=[0, -5/9, -153/128], gammas=[1/3, 15/16, 8/15],...
β[k] * h µ = 0.5 * dt * (α[k + 1] - α[k]) u = G_inv(u + γ[k] * dt * h + µ * G(u), µ) return u r
conditional_block
time_stepping.py
# Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
This method is first order accurate. Args: equation: equation to solve. time_step: time step. Returns: Function that performs a time step. """ # pylint: disable=invalid-name dt = time_step F = tree_math.unwrap(equation.explicit_terms) G_inv = tree_math.unwrap(equation.implicit_solve, vect...
"""Time stepping via forward and backward Euler methods.
random_line_split
ogr2ogrtabletopostgislist.py
# -*- coding: utf-8 -*- """ *************************************************************************** ogr2ogrtabletopostgislist.py --------------------- Date : November 2012 Copyright : (C) 2012 by Victor Olaya Email : volayaf at gmail dot com ***********...
def defineCharacteristics(self): self.name, self.i18n_name = self.trAlgorithm('Import layer/table as geometryless table into PostgreSQL database') self.group, self.i18n_group = self.trAlgorithm('[OGR] Miscellaneous') self.DB_CONNECTIONS = self.dbConnectionNames() self.addParameter(...
settings = QSettings() settings.beginGroup('/PostgreSQL/connections/') return settings.childGroups()
identifier_body
ogr2ogrtabletopostgislist.py
# -*- coding: utf-8 -*- """ *************************************************************************** ogr2ogrtabletopostgislist.py --------------------- Date : November 2012 Copyright : (C) 2012 by Victor Olaya Email : volayaf at gmail dot com ***********...
(self): settings = QSettings() settings.beginGroup('/PostgreSQL/connections/') return settings.childGroups() def defineCharacteristics(self): self.name, self.i18n_name = self.trAlgorithm('Import layer/table as geometryless table into PostgreSQL database') self.group, self.i1...
dbConnectionNames
identifier_name
ogr2ogrtabletopostgislist.py
# -*- coding: utf-8 -*- """ *************************************************************************** ogr2ogrtabletopostgislist.py --------------------- Date : November 2012 Copyright : (C) 2012 by Victor Olaya Email : volayaf at gmail dot com ***********...
if len(gt) > 0: arguments.append('-gt') arguments.append(gt) if not precision: arguments.append('-lco PRECISION=NO') if len(options) > 0: arguments.append(options) commands = [] if isWindows(): commands = ['cmd.exe', '...
arguments.append(wherestring)
conditional_block
ogr2ogrtabletopostgislist.py
# -*- coding: utf-8 -*- """ *************************************************************************** ogr2ogrtabletopostgislist.py --------------------- Date : November 2012 Copyright : (C) 2012 by Victor Olaya Email : volayaf at gmail dot com ***********...
self.tr('Select features using a SQL "WHERE" statement (Ex: column=\'value\')'), '', optional=True)) self.addParameter(ParameterString(self.GT, self.tr('Group N features per transaction ...
self.addParameter(ParameterString(self.WHERE,
random_line_split
Fx-catalog-collapsible-menu.js
define([ "jquery", "fx-cat-br/widgets/Fx-widgets-commons", 'text!fx-cat-br/json/fx-catalog-collapsible-menu-config.json', "lib/bootstrap" ], function ($, W_Commons, conf) { var o = { }, defaultOptions = { widget: { lang: 'EN' }, events: { ...
if (modules[j].hasOwnProperty("id")) { $btn.attr("id", modules[j].id); } if (modules[j].hasOwnProperty("module")) { $btn.attr("data-module", modules[j].module); } //Keep it before the label to have ...
random_line_split
Fx-catalog-collapsible-menu.js
define([ "jquery", "fx-cat-br/widgets/Fx-widgets-commons", 'text!fx-cat-br/json/fx-catalog-collapsible-menu-config.json', "lib/bootstrap" ], function ($, W_Commons, conf) { var o = { }, defaultOptions = { widget: { lang: 'EN' }, events: { ...
return $bodyContainer.append($body); }; Fx_Catalog_Collapsible_Menu.prototype.disable = function (module) { $(o.container).find("[data-module='" + module + "']").attr("disabled", "disabled"); }; Fx_Catalog_Collapsible_Menu.prototype.activate = function (module) { $(o.contain...
{ var modules = panel["modules"]; for (var j = 0; j < modules.length; j++) { var $module = $("<div></div>"), $btn = $('<button type="button" class="btn btn-default btn-block"></button>'); $btn.on('click', {module: modules[j] }, function (e) ...
conditional_block
Fx-catalog-collapsible-menu.js
define([ "jquery", "fx-cat-br/widgets/Fx-widgets-commons", 'text!fx-cat-br/json/fx-catalog-collapsible-menu-config.json', "lib/bootstrap" ], function ($, W_Commons, conf) { var o = { }, defaultOptions = { widget: { lang: 'EN' }, events: { ...
() { w_Commons = new W_Commons(); } Fx_Catalog_Collapsible_Menu.prototype.init = function (options) { //Merge options $.extend(o, defaultOptions); $.extend(o, options); }; Fx_Catalog_Collapsible_Menu.prototype.render = function (options) { $.extend(o, options)...
Fx_Catalog_Collapsible_Menu
identifier_name
Fx-catalog-collapsible-menu.js
define([ "jquery", "fx-cat-br/widgets/Fx-widgets-commons", 'text!fx-cat-br/json/fx-catalog-collapsible-menu-config.json', "lib/bootstrap" ], function ($, W_Commons, conf) { var o = { }, defaultOptions = { widget: { lang: 'EN' }, events: { ...
Fx_Catalog_Collapsible_Menu.prototype.init = function (options) { //Merge options $.extend(o, defaultOptions); $.extend(o, options); }; Fx_Catalog_Collapsible_Menu.prototype.render = function (options) { $.extend(o, options); cache.json = JSON.parse(conf); ...
{ w_Commons = new W_Commons(); }
identifier_body
find_dependencies.py
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import fnmatch import imp import logging import modulefinder import optparse import os import sys import zipfile from telemetry import benchmark from teleme...
def IsPyc(path_string): return os.path.splitext(path_string)[1] == '.pyc' def IsInCloudStorage(path_string): return os.path.exists(path_string + '.sha1') def MatchesExcludeOptions(path_string): for pattern in options.exclude: if (fnmatch.fnmatch(path_string, pattern) or fnmatch.fnmatc...
for pathname_component in path_string.split(os.sep): if pathname_component.startswith('.'): return True return False
identifier_body
find_dependencies.py
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import fnmatch import imp import logging import modulefinder import optparse import os import sys import zipfile from telemetry import benchmark from teleme...
dependencies = path_set.PathSet() # Including Telemetry's major entry points will (hopefully) include Telemetry # and all its dependencies. If the user doesn't pass any arguments, we just # have Telemetry. dependencies |= FindPythonDependencies(os.path.realpath( os.path.join(path.GetTelemetryDir(), 'te...
raise ValueError('Path does not exist: %s' % target_path)
conditional_block
find_dependencies.py
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import fnmatch import imp import logging import modulefinder import optparse import os import sys import zipfile from telemetry import benchmark from teleme...
(target_paths, options): # Verify arguments. for target_path in target_paths: if not os.path.exists(target_path): raise ValueError('Path does not exist: %s' % target_path) dependencies = path_set.PathSet() # Including Telemetry's major entry points will (hopefully) include Telemetry # and all its ...
FindDependencies
identifier_name
find_dependencies.py
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import fnmatch import imp import logging import modulefinder import optparse import os import sys import zipfile from telemetry import benchmark from teleme...
gsutil_dependencies = path_set.PathSet() gsutil_dependencies.add(os.path.dirname(gsutil_path)) # Also add modules from depot_tools that are needed by gsutil. gsutil_dependencies.add(os.path.join(gsutil_base_dir, 'boto')) gsutil_dependencies.add(os.path.join(gsutil_base_dir, 'fancy_urllib')...
# location in the archive. This can be confusing for users. gsutil_path = os.path.realpath(cloud_storage.FindGsutil()) if cloud_storage.SupportsProdaccess(gsutil_path): gsutil_base_dir = os.path.join(os.path.dirname(gsutil_path), os.pardir)
random_line_split
app.module.ts
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { HttpModule } from '@angular/http'; // Imports for the fake backend. import {InMemoryWebApiModule} from 'angular-in-memory-web-api'; import {InMemoryDataService} fr...
{ }
AppModule
identifier_name
app.module.ts
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { HttpModule } from '@angular/http'; // Imports for the fake backend. import {InMemoryWebApiModule} from 'angular-in-memory-web-api'; import {InMemoryDataService} fr...
* App modules class. * @author Dmitry Noranovich */ @NgModule({ declarations: [ AppComponent, BookmarkDetailComponent, BookmarksComponent, AboutComponent, LoginFormComponent, RegisterFormComponent, BookmarkEditComponent, BookmarkViewComponent ], imports: [ BrowserModule, ...
import {BookmarkViewComponent} from './bm-view/bookmark-view.component'; import {BookmarkEditComponent} from './bm-edit/bookmark-edit.component'; /**
random_line_split
test_reset_password.py
from djangosanetesting.cases import HttpTestCase from django.conf import settings from django.core.urlresolvers import reverse from django.core import mail from accounts.tests import testdata class TestResetPassword(HttpTestCase): def
(self, *args, **kwargs): super(self.__class__, self).__init__(*args, **kwargs) self.host = 'localhost' self.port = 8000 def setUp(self): testdata.run() def test_reset_password(self): res = self.client.post(reverse('password_reset'), {'reg...
__init__
identifier_name
test_reset_password.py
from djangosanetesting.cases import HttpTestCase from django.conf import settings from django.core.urlresolvers import reverse from django.core import mail from accounts.tests import testdata class TestResetPassword(HttpTestCase): def __init__(self, *args, **kwargs): super(self.__class__, self).__init__(*a...
assert reverse('password_reset_done') in res.request['PATH_INFO'] assert len(mail.outbox) == 1 reset_url = [word for word in mail.outbox[0].body.split() if word.startswith('http')][0] res = self.client.get(reset_url, follow=True) assert res.status_code == 200 assert 'u...
follow=True)
random_line_split
test_reset_password.py
from djangosanetesting.cases import HttpTestCase from django.conf import settings from django.core.urlresolvers import reverse from django.core import mail from accounts.tests import testdata class TestResetPassword(HttpTestCase): def __init__(self, *args, **kwargs):
def setUp(self): testdata.run() def test_reset_password(self): res = self.client.post(reverse('password_reset'), {'register_number' : settings.TEST_USERNAME, }, follow=True) assert reverse('...
super(self.__class__, self).__init__(*args, **kwargs) self.host = 'localhost' self.port = 8000
identifier_body
manage.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import os from flask_script import Manager, Shell, Server from flask_migrate import MigrateCommand from app import create_app, db from app.models import User from app.settings import DevConfig, ProdConfig if os.environ.get("ENV") == 'prod': app = create_app(ProdConfi...
(): """Return context dict for a shell session so you can access app, db, and the User model by default. """ return {'app': app, 'db': db, 'User': User} manager.add_command('server', Server()) manager.add_command('shell', Shell(make_context=_make_context)) manager.add_command('db', MigrateCommand) if...
_make_context
identifier_name
manage.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import os from flask_script import Manager, Shell, Server
from app.settings import DevConfig, ProdConfig if os.environ.get("ENV") == 'prod': app = create_app(ProdConfig) else: app = create_app(DevConfig) HERE = os.path.abspath(os.path.dirname(__file__)) TEST_PATH = os.path.join(HERE, 'tests') manager = Manager(app) def _make_context(): """Return context dict...
from flask_migrate import MigrateCommand from app import create_app, db from app.models import User
random_line_split
manage.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import os from flask_script import Manager, Shell, Server from flask_migrate import MigrateCommand from app import create_app, db from app.models import User from app.settings import DevConfig, ProdConfig if os.environ.get("ENV") == 'prod':
else: app = create_app(DevConfig) HERE = os.path.abspath(os.path.dirname(__file__)) TEST_PATH = os.path.join(HERE, 'tests') manager = Manager(app) def _make_context(): """Return context dict for a shell session so you can access app, db, and the User model by default. """ return {'app': app, 'd...
app = create_app(ProdConfig)
conditional_block
manage.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import os from flask_script import Manager, Shell, Server from flask_migrate import MigrateCommand from app import create_app, db from app.models import User from app.settings import DevConfig, ProdConfig if os.environ.get("ENV") == 'prod': app = create_app(ProdConfi...
manager.add_command('server', Server()) manager.add_command('shell', Shell(make_context=_make_context)) manager.add_command('db', MigrateCommand) if __name__ == '__main__': manager.run()
"""Return context dict for a shell session so you can access app, db, and the User model by default. """ return {'app': app, 'db': db, 'User': User}
identifier_body
app.js
//Problem: Hints are shown even when form is valid //Solution: Hide and show them at appropriate times var $password = $("#password"); var $confirmPassword = $("#confirm_password"); //Hide hints $("form span").hide(); function isPasswordValid() { return $password.val().length > 8; } function arePasswordsMatching() ...
function enableSubmitEvent() { $("#submit").prop("disabled", !canSubmit()); } //When event happens on password input $password.focus(passwordEvent).keyup(passwordEvent).keyup(confirmPasswordEvent).keyup(enableSubmitEvent); //When event happens on confirmation input $confirmPassword.focus(confirmPasswordEvent)....
{ //find out if password and confirmation match if(arePasswordsMatching()) { //Hide hint if match $confirmPassword.next().hide(); } else { //else show hint $confirmPassword.next().show(); } }
identifier_body
app.js
//Problem: Hints are shown even when form is valid //Solution: Hide and show them at appropriate times var $password = $("#password"); var $confirmPassword = $("#confirm_password"); //Hide hints $("form span").hide(); function isPasswordValid() { return $password.val().length > 8; } function arePasswordsMatching() ...
} function enableSubmitEvent() { $("#submit").prop("disabled", !canSubmit()); } //When event happens on password input $password.focus(passwordEvent).keyup(passwordEvent).keyup(confirmPasswordEvent).keyup(enableSubmitEvent); //When event happens on confirmation input $confirmPassword.focus(confirmPasswordEvent...
{ //else show hint $confirmPassword.next().show(); }
conditional_block
app.js
//Problem: Hints are shown even when form is valid //Solution: Hide and show them at appropriate times var $password = $("#password"); var $confirmPassword = $("#confirm_password"); //Hide hints $("form span").hide(); function isPasswordValid() { return $password.val().length > 8; } function arePasswordsMatching() ...
() { $("#submit").prop("disabled", !canSubmit()); } //When event happens on password input $password.focus(passwordEvent).keyup(passwordEvent).keyup(confirmPasswordEvent).keyup(enableSubmitEvent); //When event happens on confirmation input $confirmPassword.focus(confirmPasswordEvent).keyup(confirmPasswordEvent)....
enableSubmitEvent
identifier_name
app.js
//Problem: Hints are shown even when form is valid //Solution: Hide and show them at appropriate times var $password = $("#password"); var $confirmPassword = $("#confirm_password"); //Hide hints $("form span").hide(); function isPasswordValid() { return $password.val().length > 8; } function arePasswordsMatching() ...
//Hide hint if valid $password.next().hide(); } else { //else show hint $password.next().show(); } } function confirmPasswordEvent() { //find out if password and confirmation match if(arePasswordsMatching()) { //Hide hint if match $confirmPassword.next().hide(); } else { //else sh...
function passwordEvent(){ //Find out if password is valid if(isPasswordValid()) {
random_line_split
model.rs
//! Defines the `JsonApiModel` trait. This is primarily used in conjunction with //! the [`jsonapi_model!`](../macro.jsonapi_model.html) macro to allow arbitrary //! structs which implement `Deserialize` to be converted to/from a //! [`JsonApiDocument`](../api/struct.JsonApiDocument.html) or //! [`Resource`](../api/str...
Some(IdentifierData::None) => Value::Null, Some(IdentifierData::Single(ref identifier)) => { let found = Self::lookup(identifier, inc) .map(|r| Self::resource_to_attrs(r, included, &this_visited) ); ...
random_line_split
model.rs
//! Defines the `JsonApiModel` trait. This is primarily used in conjunction with //! the [`jsonapi_model!`](../macro.jsonapi_model.html) macro to allow arbitrary //! structs which implement `Deserialize` to be converted to/from a //! [`JsonApiDocument`](../api/struct.JsonApiDocument.html) or //! [`Resource`](../api/str...
fn relationship_fields() -> Option<&'static [&'static str]> { M::relationship_fields() } fn build_relationships(&self) -> Option<Relationships> { self.as_ref().build_relationships() } fn build_included(&self) -> Option<Resources> { self.as_ref().build_included() } } ...
{ self.as_ref().jsonapi_id() }
identifier_body
model.rs
//! Defines the `JsonApiModel` trait. This is primarily used in conjunction with //! the [`jsonapi_model!`](../macro.jsonapi_model.html) macro to allow arbitrary //! structs which implement `Deserialize` to be converted to/from a //! [`JsonApiDocument`](../api/struct.JsonApiDocument.html) or //! [`Resource`](../api/str...
(&self) -> Resources { let (me, maybe_others) = self.to_jsonapi_resource(); let mut flattened = vec![me]; if let Some(mut others) = maybe_others { flattened.append(&mut others); } flattened } /// When passed a `ResourceIdentifier` (which contains a `type` and...
to_resources
identifier_name
UserController.ts
import e = require('express'); import BaseController from "./BaseController"; import { router } from "../decorators/Web"; import { Uc, UcGroup,User,UcGroupModel, UserModel,UserHelper} from '../models/index'; class
extends BaseController { @router({ method: 'post', path: '/api/user/setting' }) async create(req: e.Request, res: e.Response) { let result = await User.insert(req.body); res.send(super.wrapperRes(result)); } @router({ method: 'patch', path: '/api/user/setting' }) async update(req: e.R...
UserController
identifier_name
UserController.ts
import e = require('express'); import BaseController from "./BaseController"; import { router } from "../decorators/Web"; import { Uc, UcGroup,User,UcGroupModel, UserModel,UserHelper} from '../models/index'; class UserController extends BaseController { @router({ method: 'post', path: '/api/user/setting' ...
@router({ method: 'patch', path: '/api/user/setting' }) async update(req: e.Request, res: e.Response) { let user: UserModel = super.getUser(req); let userModel: UserModel = UserHelper.buildModel(req.body); userModel._id=user._id; userModel.setModifiedInfo(user); let result = await User.update(req.bod...
random_line_split
index.ts
import styled, { css as styledCss, keyframes } from 'styled-components' import type { TTestable } from '@/spec' import Img from '@/Img' import { theme } from '@/utils/themes' import css from '@/utils/css' const DURATION = '2.5s' const load = keyframes` 0% { top: 24px; } 70% { top: 10px; } 90% { ...
right: 0; border-right: 16px solid transparent; border-bottom: 22px solid rgba(255, 255, 255, 0.25); } } ` export const Liquid = styled.div` position: absolute; top: 23px; bottom: 0; left: 0; right: 0; width: 16px; background: ${theme('baseColor.green')}; ${Wrapper}:hover & { ...
content: ''; position: absolute; top: 0; bottom: 0; left: 0;
random_line_split
update.test.ts
import * as chai from 'chai'; import * as mongodb from 'mongodb'; import { Tyr } from 'tyranid'; const { ObjectId } = mongodb; const O = (ObjectId as any) as (id: string) => mongodb.ObjectId; const { expect } = chai; export function add() { describe('update.js', () => { const { intersection, matches, merge }...
}; const serverUpdate = Book.fromClientUpdate(clientUpdate); expect(serverUpdate.$set.title).to.be.eql(title); expect(serverUpdate.$set.isbn).to.be.an.instanceof(O); }); it('should support support paths strings', () => { const clientUpdate = { 'name.first':...
$set: { title, isbn: '5614c2f00000000000000000', },
random_line_split
update.test.ts
import * as chai from 'chai'; import * as mongodb from 'mongodb'; import { Tyr } from 'tyranid'; const { ObjectId } = mongodb; const O = (ObjectId as any) as (id: string) => mongodb.ObjectId; const { expect } = chai; export function
() { describe('update.js', () => { const { intersection, matches, merge } = Tyr.query, i1 = '111111111111111111111111', i2 = '222222222222222222222222', i3 = '333333333333333333333333', i4 = '444444444444444444444444'; describe('fromClientUpdate', () => { let Book: Tyr.BookColle...
add
identifier_name
update.test.ts
import * as chai from 'chai'; import * as mongodb from 'mongodb'; import { Tyr } from 'tyranid'; const { ObjectId } = mongodb; const O = (ObjectId as any) as (id: string) => mongodb.ObjectId; const { expect } = chai; export function add()
{ describe('update.js', () => { const { intersection, matches, merge } = Tyr.query, i1 = '111111111111111111111111', i2 = '222222222222222222222222', i3 = '333333333333333333333333', i4 = '444444444444444444444444'; describe('fromClientUpdate', () => { let Book: Tyr.BookCollecti...
identifier_body
0003_convert_recomended_articles.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations from molo.core.models import ArticlePage, ArticlePageRecommendedSections from wagtail.wagtailcore.blocks import StreamValue def create_recomended_articles(main_article, article_list): ''' Creates recommended arti...
stream_data.append(block) if linked_articles: create_recomended_articles(article, linked_articles) stream_block = article.body.stream_block article.body = StreamValue(stream_block, stream_data, is_lazy=True) article.save() section = article.get_paren...
else: # add block to new stream_data
random_line_split
0003_convert_recomended_articles.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations from molo.core.models import ArticlePage, ArticlePageRecommendedSections from wagtail.wagtailcore.blocks import StreamValue def create_recomended_articles(main_article, article_list): ''' Creates recommended arti...
(apps, schema_editor): ''' Derived from https://github.com/wagtail/wagtail/issues/2110 ''' articles = ArticlePage.objects.all().exact_type(ArticlePage) for article in articles: stream_data = [] linked_articles = [] for block in article.body.stream_data: if block[...
convert_articles
identifier_name
0003_convert_recomended_articles.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations from molo.core.models import ArticlePage, ArticlePageRecommendedSections from wagtail.wagtailcore.blocks import StreamValue def create_recomended_articles(main_article, article_list): ''' Creates recommended arti...
stream_block = article.body.stream_block article.body = StreamValue(stream_block, stream_data, is_lazy=True) article.save() section = article.get_parent().specific section.enable_recommended_section = True section.enable_next_section = True section.save() clas...
create_recomended_articles(article, linked_articles)
conditional_block
0003_convert_recomended_articles.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations from molo.core.models import ArticlePage, ArticlePageRecommendedSections from wagtail.wagtailcore.blocks import StreamValue def create_recomended_articles(main_article, article_list): ''' Creates recommended arti...
dependencies = [ ('iogt', '0002_create_importers_group'), ] operations = [ migrations.RunPython(convert_articles), ]
identifier_body
BucketsPage.ts
import { SelectionModel } from '@angular/cdk/collections'; import { AfterViewInit, ChangeDetectionStrategy, Component, ViewChild } from '@angular/core'; import { FormControl, FormGroup } from '@angular/forms'; import { MatDialog } from '@angular/material/dialog'; import { MatSort } from '@angular/material/sort'; import...
this.selection.toggle(row); } createBucket() { const dialogRef = this.dialog.open(CreateBucketDialog, { width: '400px', data: { bucketInstance: this.instance, }, }); dialogRef.afterClosed().subscribe(result => { if (result) { this.refreshDataSources(); ...
{ this.selection.clear(); }
conditional_block
BucketsPage.ts
import { SelectionModel } from '@angular/cdk/collections'; import { AfterViewInit, ChangeDetectionStrategy, Component, ViewChild } from '@angular/core'; import { FormControl, FormGroup } from '@angular/forms'; import { MatDialog } from '@angular/material/dialog'; import { MatSort } from '@angular/material/sort'; import...
if (!this.selection.isSelected(row) || this.selection.selected.length > 1) { this.selection.clear(); } this.selection.toggle(row); } createBucket() { const dialogRef = this.dialog.open(CreateBucketDialog, { width: '400px', data: { bucketInstance: this.instance, }, ...
this.dataSource.data.forEach(row => this.selection.select(row)); } toggleOne(row: Bucket) {
random_line_split
BucketsPage.ts
import { SelectionModel } from '@angular/cdk/collections'; import { AfterViewInit, ChangeDetectionStrategy, Component, ViewChild } from '@angular/core'; import { FormControl, FormGroup } from '@angular/forms'; import { MatDialog } from '@angular/material/dialog'; import { MatSort } from '@angular/material/sort'; import...
() { const queryParams = this.route.snapshot.queryParamMap; if (queryParams.has('instance')) { this.instance = queryParams.get('instance')!; this.filterForm.get('instance')!.setValue(this.instance); } } ngAfterViewInit() { this.dataSource.sort = this.sort; } isAllSelected() { c...
initializeOptions
identifier_name
BucketsPage.ts
import { SelectionModel } from '@angular/cdk/collections'; import { AfterViewInit, ChangeDetectionStrategy, Component, ViewChild } from '@angular/core'; import { FormControl, FormGroup } from '@angular/forms'; import { MatDialog } from '@angular/material/dialog'; import { MatSort } from '@angular/material/sort'; import...
}
{ this.router.navigate([], { replaceUrl: true, relativeTo: this.route, queryParams: { instance: this.instance || null, }, queryParamsHandling: 'merge', }); }
identifier_body