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 |
|---|---|---|---|---|
build.js | var relativeImports = /import\s*{[a-zA-Z\,\s]+}\s*from\s*'\.\/[a-zA-Z\-]+';\s*/g;
var nonRelativeImports = /import\s*{?[a-zA-Z\*\,\s]+}?\s*from\s*'[a-zA-Z\-]+';\s*/g;
var importGrouper = /import\s*{([a-zA-Z\,\s]+)}\s*from\s*'([a-zA-Z\-]+)'\s*;\s*/;
exports.extractImports = function(content, importsToAdd){
var matche... | ;
var theImports = groups[1].split(',');
var theSource = groups[2].trim();
var theList = finalImports[theSource] || (finalImports[theSource] = []);
theImports.forEach(function(item){
item = item.trim();
if(theList.indexOf(item) === -1){
theList.push(item);
}
});
});
... | {
toAdd = toAdd.trim();
if(importBlock.indexOf(toAdd) === -1){
importBlock += toAdd + '\n';
}
return;
} | conditional_block |
build.js | var relativeImports = /import\s*{[a-zA-Z\,\s]+}\s*from\s*'\.\/[a-zA-Z\-]+';\s*/g;
var nonRelativeImports = /import\s*{?[a-zA-Z\*\,\s]+}?\s*from\s*'[a-zA-Z\-]+';\s*/g;
var importGrouper = /import\s*{([a-zA-Z\,\s]+)}\s*from\s*'([a-zA-Z\-]+)'\s*;\s*/;
exports.extractImports = function(content, importsToAdd){
var matche... | }
});
});
Object.keys(finalImports).forEach(function(key) {
importBlock += 'import {' + finalImports[key].join(',') + '} from \'' + key + '\';\n';
});
return importBlock + '\n';
}; | random_line_split | |
jQuery.printElement.js | /// <reference path="http://code.jquery.com/jquery-1.4.1-vsdoc.js" />
/*
* Print Element Plugin 1.2
*
* Copyright (c) 2010 Erik Zaadi
*
* Inspired by PrintArea (http://plugins.jquery.com/project/PrintArea) and
* http://stackoverflow.com/questions/472951/how-do-i-print-an-iframe-from-javascript-in-safari-chrome
*
* Hom... | (element) {
var $element = $(element);
//Radiobuttons and checkboxes
$(":checked", $element).each(function () {
this.setAttribute('checked', 'checked');
});
//simple text inputs
$("input[type='text']", $element).each(function () {
this.setAttribute... | _getElementHTMLIncludingFormElements | identifier_name |
jQuery.printElement.js | /// <reference path="http://code.jquery.com/jquery-1.4.1-vsdoc.js" />
/*
* Print Element Plugin 1.2
*
* Copyright (c) 2010 Erik Zaadi
*
* Inspired by PrintArea (http://plugins.jquery.com/project/PrintArea) and
* http://stackoverflow.com/questions/472951/how-do-i-print-an-iframe-from-javascript-in-safari-chrome
*
* Hom... | }
//Remove previously printed iframe if exists
$("[id^='printElement_']").remove();
return this.each(function () {
//Support Metadata Plug-in if available
var opts = $.meta ? $.extend({}, mainOptions, $(this).data()) : mainOptions;
_printElement($(thi... | if (mainOptions["printMode"] == 'iframe') {
if ($.browser.opera || (/chrome/.test(navigator.userAgent.toLowerCase())))
mainOptions["printMode"] = 'popup'; | random_line_split |
jQuery.printElement.js | /// <reference path="http://code.jquery.com/jquery-1.4.1-vsdoc.js" />
/*
* Print Element Plugin 1.2
*
* Copyright (c) 2010 Erik Zaadi
*
* Inspired by PrintArea (http://plugins.jquery.com/project/PrintArea) and
* http://stackoverflow.com/questions/472951/how-do-i-print-an-iframe-from-javascript-in-safari-chrome
*
* Hom... | }).each(function () {
html.push('<link type="text/css" rel="stylesheet" href="' + $(this).attr("href") + '" media="' + $(this).attr('media') + '" >');
});
}
//Ensure that relative links work
html.push('<base href="' + _getBaseHref() + '" />');
html... | {
var $element = $(element);
var elementHtml = _getElementHTMLIncludingFormElements(element);
var html = new Array();
html.push('<html><head><title>' + opts["pageTitle"] + '</title>');
if (opts["overrideElementCSS"]) {
if (opts["overrideElementCSS"].length > 0) {
... | identifier_body |
html-preview.component.ts | // HTML-PREVIEW . COMPONENT . TS
import { Component, Input, OnInit } from "@angular/core";
import { ActivatedRoute, ParamMap } from "@angular/router";
import { Observable } from "rxjs";
import { switchMap } from 'rxjs/operators';
@Component({
moduleId: module.id,
selector: 'html-preview',
template: `
<div cla... | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ | random_line_split | |
html-preview.component.ts | // HTML-PREVIEW . COMPONENT . TS
import { Component, Input, OnInit } from "@angular/core";
import { ActivatedRoute, ParamMap } from "@angular/router";
import { Observable } from "rxjs";
import { switchMap } from 'rxjs/operators';
@Component({
moduleId: module.id,
selector: 'html-preview',
template: `
<div cla... | () {
this.route.paramMap.subscribe(params => {
this.id_ = params.get("id");
if (params.has("color")) {
let colorCandidate = params.get("color");
if (HTMLPreviewComponent.colorRegExp.test(colorCandidate)) {
this.color = colorCandidate;
}
}
});
}
}
/*
* Copyright 2018 Daniel Giribet
*
* L... | ngOnInit | identifier_name |
html-preview.component.ts | // HTML-PREVIEW . COMPONENT . TS
import { Component, Input, OnInit } from "@angular/core";
import { ActivatedRoute, ParamMap } from "@angular/router";
import { Observable } from "rxjs";
import { switchMap } from 'rxjs/operators';
@Component({
moduleId: module.id,
selector: 'html-preview',
template: `
<div cla... |
});
}
}
/*
* Copyright 2018 Daniel Giribet
*
* 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 applica... | {
let colorCandidate = params.get("color");
if (HTMLPreviewComponent.colorRegExp.test(colorCandidate)) {
this.color = colorCandidate;
}
} | conditional_block |
Debug.py | """SCons.Debug
Code for debugging SCons internal things. Not everything here is
guaranteed to work all the way back to Python 1.5.2, and shouldn't be
needed by most users.
"""
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009 The SCons Foundation
#
# Permission is hereby granted, free of charge... | l.append((-v,c))
l.sort()
leader = ' '*level
for v,c in l:
file.write("%s %6d %s:%d(%s)\n" % ((leader,-v) + func_shorten(c[-3:])))
if caller_dicts.has_key(c):
_dump_one_caller(c, file, level+1)
# print each call tree
def dump_caller_counts(file=sys.stdout):
key... |
# print a single caller and its callers, if any
def _dump_one_caller(key, file, level=0):
l = []
for c,v in caller_dicts[key].items(): | random_line_split |
Debug.py | """SCons.Debug
Code for debugging SCons internal things. Not everything here is
guaranteed to work all the way back to Python 1.5.2, and shouldn't be
needed by most users.
"""
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009 The SCons Foundation
#
# Permission is hereby granted, free of charge... |
if sys.platform[:5] == "linux":
# Linux doesn't actually support memory usage stats from getrusage().
def memory():
mstr = open('/proc/self/stat').read()
mstr = string.split(mstr)[22]
return int(mstr)
else:
try:
import resource
except ImportError:
try:
... | file.write(' %20s : %s\n' % (key, value)) | conditional_block |
Debug.py | """SCons.Debug
Code for debugging SCons internal things. Not everything here is
guaranteed to work all the way back to Python 1.5.2, and shouldn't be
needed by most users.
"""
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009 The SCons Foundation
#
# Permission is hereby granted, free of charge... | """Write a trace message to a file. Whenever a file is specified,
it becomes the default for the next call to Trace()."""
global TraceDefault
if file is None:
file = TraceDefault
else:
TraceDefault = file
try:
fp = TraceFP[file]
except KeyError:
try:
... | identifier_body | |
Debug.py | """SCons.Debug
Code for debugging SCons internal things. Not everything here is
guaranteed to work all the way back to Python 1.5.2, and shouldn't be
needed by most users.
"""
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009 The SCons Foundation
#
# Permission is hereby granted, free of charge... | (t):
return (string.replace(t[0], '/', os.sep), t[1])
shorten_list = map(platformize, shorten_list)
del platformize
def func_shorten(func_tuple):
f = func_tuple[0]
for t in shorten_list:
i = string.find(f, t[0])
if i >= 0:
if t[1]:
i = i + len(t[0])
... | platformize | identifier_name |
utils.rs | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use std::char;
use std::ops::Range;
pub fn get_prefix_bounds(prefix: impl AsRef<str>) -> Range<String> {
let mut upper = prefix.as_ref()... |
#[test]
fn test_get_prefix_bounds_multiple() {
let prefix = "comm"; // prefix of commit
let end = "comn";
let range = get_prefix_bounds(prefix);
assert_eq!(range.start.as_str(), prefix);
assert_eq!(range.end.as_str(), end);
}
#[test]
fn test_get_prefix_boun... | {
let prefix = "z";
let end = "{";
let range = get_prefix_bounds(prefix);
assert_eq!(range.start.as_str(), prefix);
assert_eq!(range.end.as_str(), end);
} | identifier_body |
utils.rs | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use std::char;
use std::ops::Range;
pub fn get_prefix_bounds(prefix: impl AsRef<str>) -> Range<String> {
let mut upper = prefix.as_ref()... | assert_eq!(range.end.as_str(), end);
}
} | fn test_get_prefix_bounds_unicode() {
let prefix = "\u{1F36A}"; // Cookie Emoji
let end = "\u{1F36B}";
let range = get_prefix_bounds(prefix);
assert_eq!(range.start.as_str(), prefix); | random_line_split |
utils.rs | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use std::char;
use std::ops::Range;
pub fn get_prefix_bounds(prefix: impl AsRef<str>) -> Range<String> {
let mut upper = prefix.as_ref()... | () {
let prefix = "a";
let end = "b";
let range = get_prefix_bounds(prefix);
assert_eq!(range.start.as_str(), prefix);
assert_eq!(range.end.as_str(), end);
}
#[test]
fn test_get_prefix_bounds_ending_with_z() {
let prefix = "z";
let end = "{";
... | test_get_prefix_bounds_one_letter | identifier_name |
utils.rs | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use std::char;
use std::ops::Range;
pub fn get_prefix_bounds(prefix: impl AsRef<str>) -> Range<String> {
let mut upper = prefix.as_ref()... |
last_char_code = next_val;
}
upper.push(last_char);
prefix.as_ref().to_string()..upper
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_get_prefix_bounds_one_letter() {
let prefix = "a";
let end = "b";
let range = get_prefix_bounds(prefix);
as... | {
last_char = c;
break;
} | conditional_block |
V8GaugeSet.test.ts | import {V8GaugeSet} from '../../../../src/metrics/node/V8GaugeSet';
import {expect} from 'chai';
//
// const keys = [
// "new_space.space_size",
// "new_space.space_used_size",
// "new_space.space_available_size",
// "new_space.physical_space_size",
// "old_space.space_size",
// "old_space.space_used_size",... | // "map_space.space_available_size",
// "map_space.physical_space_size",
// "large_object_space.space_size",
// "large_object_space.space_used_size",
// "large_object_space.space_available_size",
// "large_object_space.physical_space_size",
// "total_heap_size",
// "total_heap_size_executable",
// "to... | // "map_space.space_used_size", | random_line_split |
configureStore.js | import { createStore, compose, applyMiddleware } from 'redux';
import reduxImmutableStateInvariant from 'redux-immutable-state-invariant';
import thunk from 'redux-thunk';
import axios from 'axios';
import axiosMiddleware from 'redux-axios-middleware';
import rootReducer from '../reducers';
const client = axios.create... | window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose; // add support for Redux dev tools
const store = createStore(
rootReducer,
initialState,
composeEnhancers(applyMiddleware(...middlewares))
);
if (module.hot) {
// Enable Webpack hot module replacement for reducers
module.hot.accept('... |
const composeEnhancers = | random_line_split |
configureStore.js | import { createStore, compose, applyMiddleware } from 'redux';
import reduxImmutableStateInvariant from 'redux-immutable-state-invariant';
import thunk from 'redux-thunk';
import axios from 'axios';
import axiosMiddleware from 'redux-axios-middleware';
import rootReducer from '../reducers';
const client = axios.create... |
return store;
}
const configureStore =
process.env.NODE_ENV === 'production'
? configureStoreProd
: configureStoreDev;
export default configureStore;
| {
// Enable Webpack hot module replacement for reducers
module.hot.accept('../reducers', () => {
const nextReducer = require('../reducers').default; // eslint-disable-line global-require
store.replaceReducer(nextReducer);
});
} | conditional_block |
configureStore.js | import { createStore, compose, applyMiddleware } from 'redux';
import reduxImmutableStateInvariant from 'redux-immutable-state-invariant';
import thunk from 'redux-thunk';
import axios from 'axios';
import axiosMiddleware from 'redux-axios-middleware';
import rootReducer from '../reducers';
const client = axios.create... | (initialState) {
const middlewares = [
// Add other middleware on this line...
// Redux middleware that spits an error on you when you try to mutate your state either inside a dispatch or between dispatches.
reduxImmutableStateInvariant(),
// thunk middleware can also accept an extra argument to be ... | configureStoreDev | identifier_name |
configureStore.js | import { createStore, compose, applyMiddleware } from 'redux';
import reduxImmutableStateInvariant from 'redux-immutable-state-invariant';
import thunk from 'redux-thunk';
import axios from 'axios';
import axiosMiddleware from 'redux-axios-middleware';
import rootReducer from '../reducers';
const client = axios.create... |
function configureStoreDev(initialState) {
const middlewares = [
// Add other middleware on this line...
// Redux middleware that spits an error on you when you try to mutate your state either inside a dispatch or between dispatches.
reduxImmutableStateInvariant(),
// thunk middleware can also acc... | {
const middlewares = [
// Add other middleware on this line...
// thunk middleware can also accept an extra argument to be passed to each thunk action
// https://github.com/gaearon/redux-thunk#injecting-a-custom-argument
thunk,
axiosMiddleware(client)
];
return createStore(
rootReducer,... | identifier_body |
query_result_window.py | from PyQt4.QtGui import *
class QueryResultWindow:
def __init__(self):
self.__create_window_widget()
self.__create_ui()
def __create_window_widget(self):
self.__qt_widget_object = QWidget()
self.__qt_widget_object.resize(800, 600)
self.__qt_widget_object.setWindowTitle('Результат запроса')
def __create_... | [j]
item_text = str(item_value)
item = QTableWidgetItem(item_text)
self.__query_result_table.setItem(i, j, item)
| conditional_block | |
query_result_window.py | from PyQt4.QtGui import *
class QueryResultWindow:
def | (self):
self.__create_window_widget()
self.__create_ui()
def __create_window_widget(self):
self.__qt_widget_object = QWidget()
self.__qt_widget_object.resize(800, 600)
self.__qt_widget_object.setWindowTitle('Результат запроса')
def __create_ui(self):
query_result_table = QTableWidget()
layout = QVBox... | __init__ | identifier_name |
query_result_window.py | from PyQt4.QtGui import *
class QueryResultWindow:
def __init__(self):
self.__create_window_widget()
self.__create_ui()
def __create_window_widget(self):
| ui(self):
query_result_table = QTableWidget()
layout = QVBoxLayout()
self.__qt_widget_object.setLayout(layout)
layout.addWidget(query_result_table)
self.__query_result_table = query_result_table
def show(self):
self.__qt_widget_object.show()
def set_column_names(self, columns):
self.__query_result_... | self.__qt_widget_object = QWidget()
self.__qt_widget_object.resize(800, 600)
self.__qt_widget_object.setWindowTitle('Результат запроса')
def __create_ | identifier_body |
query_result_window.py | from PyQt4.QtGui import *
class QueryResultWindow:
def __init__(self):
self.__create_window_widget()
self.__create_ui()
def __create_window_widget(self):
self.__qt_widget_object = QWidget()
self.__qt_widget_object.resize(800, 600) | self.__qt_widget_object.setWindowTitle('Результат запроса')
def __create_ui(self):
query_result_table = QTableWidget()
layout = QVBoxLayout()
self.__qt_widget_object.setLayout(layout)
layout.addWidget(query_result_table)
self.__query_result_table = query_result_table
def show(self):
self.__qt_widge... | random_line_split | |
mr.js | // moment.js locale configuration
// locale : Marathi (mr)
// author : Harshad Kale : https://github.com/kalehv
(function (factory) {
if (typeof define === 'function' && define.amd) {
define(['moment'], factory); // AMD
} else if (typeof exports === 'object') {
module.exports = factory(... | conditional_block | ||
mr.js | // moment.js locale configuration
// locale : Marathi (mr)
// author : Harshad Kale : https://github.com/kalehv
| } else if (typeof exports === 'object') {
module.exports = factory(require('../moment')); // Node
} else {
factory(window.moment); // Browser global
}
}(function (moment) {
var symbolMap = {
'1': '१',
'2': '२',
'3': '३',
'4': '४',
'5': '... |
(function (factory) {
if (typeof define === 'function' && define.amd) {
define(['moment'], factory); // AMD
| random_line_split |
filematcher.ts | find execution.
*/
find(criteria: FindOptions): Promise<string[]> {
let files: Array<string> = [];
return new Promise(async (resolve, reject) => {
try {
this.init(criteria);
} catch (e) {
reject(e);
return;
}
... | random_line_split | ||
filematcher.ts | * - contentMatch: emitted when the content regex is matched.
*
* @example
* ``` ts
* let finder: FileFinder = new FileFinder();
*
* let criteria: FindOptions = {
* path: 'pathToSearch',
* fileFilter: {
* fileNamePattern: ['*.js'], // glob
* attributeFilters: [
* {
*... |
// Check file attributes as size, birth and modified date.
if (matchFilter && attributeFilters) {
attributeFilters.some(attributeFilter => {
let valueStat: number | string;
let valueFilter: number | string;
let operatorFilter: PredicateOperat... | {
matchFilter = mm([file], fileNamePattern).length > 0;
} | conditional_block |
filematcher.ts | least a filename pattern, fileattribute or file content regex should be declared!');
return;
}
try {
await this.readDirectory(this.path);
let files = await this.filterFileContent();
resolve(files);
} catch (error) {
... | readFileContent | identifier_name | |
reducer.ts | import {
Step,
Sequence,
SequenceReducerState,
ChanParams
} from "./interfaces";
import {
nullSequence,
EditCurrentSequence,
SpliceStepPayl,
MoveStepPayl
} from "./actions";
import { generateReducer } from "../redux/generate_reducer";
import { move } from "../util";
import * as _ from "l... | (s: SequenceReducerState) {
s.all[s.current].dirty = true;
};
| markDirty | identifier_name |
reducer.ts | import {
Step,
Sequence,
SequenceReducerState,
ChanParams
} from "./interfaces";
import {
nullSequence,
EditCurrentSequence,
SpliceStepPayl,
MoveStepPayl
} from "./actions";
import { generateReducer } from "../redux/generate_reducer";
import { move } from "../util";
import * as _ from "l... |
return s;
})
.add<SpliceStepPayl>("SPLICE_STEP", function (s, a) {
markDirty(s);
s.all[s.current].body.splice(a.payload.insertBefore, 0, a.payload.step);
return s;
});
function markDirty(s: SequenceReducerState) {
s.all[s.current].dirty = true;
};
| {
// EDGE CASE: If you drag a step upwards, it will end up in the
// wrong slot. As a fix, I swap the "to" index with the item below
// it an vice versa.
// I KNOW THERE ARE SHORTER WAYS TO SWAP AN ARRAY.
// DO NOT OPTOMIZE. INTENTIONALLY LENGTHENED FOR CLARIT... | conditional_block |
reducer.ts | import {
Step,
Sequence,
SequenceReducerState,
ChanParams
} from "./interfaces";
import {
nullSequence,
EditCurrentSequence,
SpliceStepPayl,
MoveStepPayl
} from "./actions";
import { generateReducer } from "../redux/generate_reducer";
import { move } from "../util";
import * as _ from "l... | ;
| {
s.all[s.current].dirty = true;
} | identifier_body |
reducer.ts | import {
Step,
Sequence,
SequenceReducerState,
ChanParams
} from "./interfaces";
import {
nullSequence,
EditCurrentSequence,
SpliceStepPayl,
MoveStepPayl
} from "./actions";
import { generateReducer } from "../redux/generate_reducer";
import { move } from "../util";
import * as _ from "l... | markDirty(s);
s.all[s.current].body = move<Step>(s.all[s.current].body,
a.payload.from,
a.payload.to);
if (from < to) {
// EDGE CASE: If you drag a step upwards, it will end up in the
// wrong slot. As a fix, I swap the "to" index with the item bel... | .add<MoveStepPayl>("MOVE_STEP", function (s, a) {
let { from, to } = a.payload; | random_line_split |
rx-collection.d.ts | import { RxQueryBase } from './rx-query';
import type { DataMigrator } from './plugins/migration';
import { Crypter } from './crypter'; | import type { KeyFunctionMap, RxCouchDBReplicationState, MigrationState, SyncOptions, RxCollection, RxDatabase, RxQuery, RxDocument, SyncOptionsGraphQL, RxDumpCollection, RxDumpCollectionAny, MangoQuery, MangoQueryNoLimit, RxCacheReplacementPolicy, RxStorageBulkWriteError, RxStorageKeyObjectInstance, RxChangeEvent, RxC... | import { DocCache } from './doc-cache';
import { QueryCache } from './query-cache';
import { ChangeEventBuffer } from './change-event-buffer';
import type { Subscription, Observable } from 'rxjs'; | random_line_split |
rx-collection.d.ts | import { RxQueryBase } from './rx-query';
import type { DataMigrator } from './plugins/migration';
import { Crypter } from './crypter';
import { DocCache } from './doc-cache';
import { QueryCache } from './query-cache';
import { ChangeEventBuffer } from './change-event-buffer';
import type { Subscription, Observable } ... | <InstanceCreationOptions, RxDocumentType = {
[prop: string]: any;
}, OrmMethods = {}, StaticMethods = {
[key: string]: any;
}> {
database: RxDatabase<CollectionsOfDatabase, any, InstanceCreationOptions>;
name: string;
schema: RxSchema<RxDocumentType>;
/**
* Stores all 'normal' documents
... | RxCollectionBase | identifier_name |
plugin.js | /*
* Copyright (c) 2013, Yahoo! Inc. All rights reserved.
* Copyrights licensed under the New BSD License.
* See the accompanying LICENSE.txt file for terms.
*/
/*jslint nomen:true, node:true */
'use strict';
var core = require('./core');
module.exports = {
describe: {
summary: 'Compile dust templ... | partials = partials || [];
partials.forEach(function (name) {
// adding prefix to each partial
dependencies.push(bundleName + '-templates-' + name);
});
return [
'YUI.add("' + moduleName + '",function(Y, NAME){',
' var dust = Y.config.gl... | // to become a dependency | random_line_split |
20140715214934_26d9c9c91542_add_cycletaskgroupobject_object.py | # Copyright (C) 2017 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
"""Add CycleTaskGroupObject.object
Revision ID: 26d9c9c91542
Revises: 19a67dc67c3
Create Date: 2014-07-15 21:49:34.073412
"""
# revision identifiers, used by Alembic.
revision = '26d9c9c91542'
down_revis... |
def downgrade():
op.drop_column('cycle_task_group_objects', 'object_type')
op.drop_column('cycle_task_group_objects', 'object_id')
| op.add_column('cycle_task_group_objects', sa.Column('object_id', sa.Integer(), nullable=False))
op.add_column('cycle_task_group_objects', sa.Column('object_type', sa.String(length=250), nullable=False))
op.execute('''
UPDATE cycle_task_group_objects
JOIN task_group_objects
O... | identifier_body |
20140715214934_26d9c9c91542_add_cycletaskgroupobject_object.py | # Copyright (C) 2017 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
"""Add CycleTaskGroupObject.object
Revision ID: 26d9c9c91542
Revises: 19a67dc67c3
Create Date: 2014-07-15 21:49:34.073412
"""
# revision identifiers, used by Alembic.
revision = '26d9c9c91542'
down_revis... | ():
op.add_column('cycle_task_group_objects', sa.Column('object_id', sa.Integer(), nullable=False))
op.add_column('cycle_task_group_objects', sa.Column('object_type', sa.String(length=250), nullable=False))
op.execute('''
UPDATE cycle_task_group_objects
JOIN task_group_objects
... | upgrade | identifier_name |
20140715214934_26d9c9c91542_add_cycletaskgroupobject_object.py | # Copyright (C) 2017 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
"""Add CycleTaskGroupObject.object
Revision ID: 26d9c9c91542
Revises: 19a67dc67c3
Create Date: 2014-07-15 21:49:34.073412
"""
# revision identifiers, used by Alembic.
revision = '26d9c9c91542'
down_revis... | def upgrade():
op.add_column('cycle_task_group_objects', sa.Column('object_id', sa.Integer(), nullable=False))
op.add_column('cycle_task_group_objects', sa.Column('object_type', sa.String(length=250), nullable=False))
op.execute('''
UPDATE cycle_task_group_objects
JOIN task_group_object... | random_line_split | |
cachekeys.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import json
import hashlib
from django.utils import six
URL_LIST_CACHE = 'powerpages:url_list'
SITEMAP_CONTENT = 'powerpages:sitemap'
def get_cache_name(prefix, name):
"""
Cache name constructor. Uses the same methods as django cache system
... | (page_pk, lang):
"""Create cache key for rendered page source based on current language"""
return 'powerpages:rendered_source_lang:{0}:{1}'.format(page_pk, lang)
def url_cache(name, *args, **kwargs):
"""
Creates cache key for url of CMS page or standard Django URL
based on hashed serialized name w... | rendered_source_for_lang | identifier_name |
cachekeys.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import json
import hashlib
from django.utils import six
URL_LIST_CACHE = 'powerpages:url_list' | SITEMAP_CONTENT = 'powerpages:sitemap'
def get_cache_name(prefix, name):
"""
Cache name constructor. Uses the same methods as django cache system
Examples:
*) prefix=profile.cache, name=<requestuser.id>
*) prefix=template.cache.sidebar, name=<requestuser.id>
"""
return '{0}.{1}'.format(
... | random_line_split | |
cachekeys.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import json
import hashlib
from django.utils import six
URL_LIST_CACHE = 'powerpages:url_list'
SITEMAP_CONTENT = 'powerpages:sitemap'
def get_cache_name(prefix, name):
"""
Cache name constructor. Uses the same methods as django cache system
... |
def rendered_source_for_lang(page_pk, lang):
"""Create cache key for rendered page source based on current language"""
return 'powerpages:rendered_source_lang:{0}:{1}'.format(page_pk, lang)
def url_cache(name, *args, **kwargs):
"""
Creates cache key for url of CMS page or standard Django URL
ba... | """Create cache key for rendered page source based on current user"""
return 'powerpages:rendered_source_user:{0}:{1}'.format(page_pk, user_id) | identifier_body |
macros.rs | //
//
//
/// Returns true if the passed exppression matches the pattern
#[macro_export]
macro_rules! is
{
($val:expr, $p:pat) => ( match $val { $p => true, _ => false } );
}
#[doc(hidden)]
#[macro_export]
macro_rules! _count
{
() => {0};
($a:expr) => {1};
($a:expr, $($b:expr),+) => {1+_count!($($b),+)};
}
/// Def... |
/// A safe wrapper around the `type_name` intrinsic
#[macro_export]
macro_rules! type_name
{
($t:ty) => ( $crate::macros::type_name::<$t>() );
}
/// Iterator helper, desugars to a.zip(b)
#[macro_export]
macro_rules! zip
{
($a:expr, $b:expr) => ( $a.zip($b) );
}
/// Iterator helper, desugars to a.chain(b).chain(b2... | {
// SAFE: All intrinsics are unsafe, no matter how safe they really are
unsafe { ::core::intrinsics::type_name::<T>() }
} | identifier_body |
macros.rs | //
//
//
/// Returns true if the passed exppression matches the pattern
#[macro_export]
macro_rules! is
{
($val:expr, $p:pat) => ( match $val { $p => true, _ => false } );
}
#[doc(hidden)]
#[macro_export]
macro_rules! _count
{
() => {0};
($a:expr) => {1};
($a:expr, $($b:expr),+) => {1+_count!($($b),+)};
}
/// Def... | <T: ?::core::marker::Sized>() -> &'static str {
// SAFE: All intrinsics are unsafe, no matter how safe they really are
unsafe { ::core::intrinsics::type_name::<T>() }
}
/// A safe wrapper around the `type_name` intrinsic
#[macro_export]
macro_rules! type_name
{
($t:ty) => ( $crate::macros::type_name::<$t>() );
}
... | type_name | identifier_name |
macros.rs | //
//
//
/// Returns true if the passed exppression matches the pattern
#[macro_export]
macro_rules! is
{
($val:expr, $p:pat) => ( match $val { $p => true, _ => false } );
}
#[doc(hidden)]
#[macro_export]
macro_rules! _count
{
() => {0};
($a:expr) => {1};
($a:expr, $($b:expr),+) => {1+_count!($($b),+)};
}
/// Def... | }
/// A safe wrapper around the `type_name` intrinsic
#[macro_export]
macro_rules! type_name
{
($t:ty) => ( $crate::macros::type_name::<$t>() );
}
/// Iterator helper, desugars to a.zip(b)
#[macro_export]
macro_rules! zip
{
($a:expr, $b:expr) => ( $a.zip($b) );
}
/// Iterator helper, desugars to a.chain(b).chain(b... | pub fn type_name<T: ?::core::marker::Sized>() -> &'static str {
// SAFE: All intrinsics are unsafe, no matter how safe they really are
unsafe { ::core::intrinsics::type_name::<T>() } | random_line_split |
helpers.js | /*
* Copyright 2021 ThoughtWorks, Inc.
*
* 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 agr... | }
function goToUrl(url) {
window.location = window.location.protocol + '//' + window.location.host + url;
}
function redirectToLoginPage(url) {
goToUrl(url);
} | random_line_split | |
helpers.js | /*
* Copyright 2021 ThoughtWorks, Inc.
*
* 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 agr... | (url) {
goToUrl(url);
}
| redirectToLoginPage | identifier_name |
helpers.js | /*
* Copyright 2021 ThoughtWorks, Inc.
*
* 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 agr... |
function redirectToLoginPage(url) {
goToUrl(url);
}
| {
window.location = window.location.protocol + '//' + window.location.host + url;
} | identifier_body |
acl.py | from __future__ import absolute_import
import itertools
__all__ = ["Registry"]
class Registry(object):
"""The registry of access control list."""
def __init__(self):
self._roles = {}
self._resources = {}
self._allowed = {}
self._denied = {}
# to allow additional sh... | (self, role, operation, resource, assertion=None):
"""Add a allowed rule.
The added rule will allow the role and its all children roles to
operate the resource.
"""
assert not role or role in self._roles
assert not resource or resource in self._resources
self._al... | allow | identifier_name |
acl.py | from __future__ import absolute_import
import itertools
__all__ = ["Registry"]
class Registry(object):
"""The registry of access control list."""
def __init__(self):
self._roles = {}
self._resources = {}
self._allowed = {}
self._denied = {}
# to allow additional sh... |
return is_allowed
def is_any_allowed(self, roles, operation, resource, **assertion_kwargs):
"""Check the permission with many roles."""
is_allowed = None # no matching rules
for i, role in enumerate(roles):
# if access not yet allowed and all remaining roles could
... | is_allowed = True # allowed by rule | conditional_block |
acl.py | from __future__ import absolute_import
import itertools
__all__ = ["Registry"]
class Registry(object):
"""The registry of access control list."""
def __init__(self):
self._roles = {}
self._resources = {}
self._allowed = {}
self._denied = {}
# to allow additional sh... | operate the resource.
"""
assert not role or role in self._roles
assert not resource or resource in self._resources
self._allowed[role, operation, resource] = assertion
# since we just allowed a permission, role and any children aren't
# denied-only
for r... | def allow(self, role, operation, resource, assertion=None):
"""Add a allowed rule.
The added rule will allow the role and its all children roles to | random_line_split |
acl.py | from __future__ import absolute_import
import itertools
__all__ = ["Registry"]
class Registry(object):
"""The registry of access control list."""
def __init__(self):
self._roles = {}
self._resources = {}
self._allowed = {}
self._denied = {}
# to allow additional sh... | if permission in self._denied:
assertion = self._denied[permission] or default_assertion
if assertion(self, role, operation, resource,
**assertion_kwargs):
return False # denied by rule immediately
if check_allowe... | """Check the permission.
If the access is denied, this method will return False; if the access
is allowed, this method will return True; if there is not any rule
for the access, this method will return None.
"""
assert not role or role in self._roles
assert not resource ... | identifier_body |
opts.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/. */
//! Configuration options for a single run of the servo application. Created
//! from command line arguments.
use... | {
/// The initial URLs to load.
pub urls: Vec<String>,
/// The rendering backend to use (`-r`).
pub render_backend: BackendType,
/// How many threads to use for CPU rendering (`-t`).
///
/// FIXME(pcwalton): This is not currently used. All rendering is sequential.
pub n_render_threads... | Opts | identifier_name |
opts.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/. */
//! Configuration options for a single run of the servo application. Created
//! from command line arguments.
use... |
pub fn from_cmdline_args(args: &[String]) -> Option<Opts> {
let app_name = args[0].to_str();
let args = args.tail();
let opts = vec!(
getopts::optflag("c", "cpu", "CPU rendering"),
getopts::optopt("o", "output", "Output file", "output.png"),
getopts::optopt("r", "rendering", "Rend... | {
io::stderr().write_line(msg).unwrap();
os::set_exit_status(1);
} | identifier_body |
opts.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/. */
//! Configuration options for a single run of the servo application. Created
//! from command line arguments.
use... | } else if "core-graphics" == backend_str.as_slice() {
CoreGraphicsBackend
} else if "core-graphics-accelerated" == backend_str.as_slice() {
CoreGraphicsAcceleratedBackend
} else if "cairo" == backend_str.as_slice() {
CairoBackend
... | Some(backend_str) => {
if "direct2d" == backend_str.as_slice() {
Direct2DBackend | random_line_split |
boot.ts | "use strict";
// import application
import {App} from "./app";
// import Angular 2
import {bootstrap} from "angular2/platform/browser";
import {provide, enableProdMode} from "angular2/core";
import {Http, HTTP_PROVIDERS} from "angular2/http";
import {ELEMENT_PROBE_PROVIDERS} from "angular2/platform/common_dom";
// i... | ELEMENT_PROBE_PROVIDERS, // remove in production
provide(LocationStrategy, { useClass: HashLocationStrategy }) // can be switched to HashLocationStrategy if you cannot configure your server appropriately for URL rewriting
]).then(
(success:any) => console.log("Bootstrap successful"),
(error:any) => console.error(e... | HTTP_PROVIDERS, | random_line_split |
directive.js | /*
* Data HUb Service (DHuS) - For Space data distribution.
* Copyright (C) 2013,2014,2015,2016 European Space Agency (ESA)
* Copyright (C) 2013,2014,2015,2016 GAEL Systems
* Copyright (C) 2013,2014,2015,2016 Serco Spa
*
* This file is part of DHuS software sources.
*
* This program is free software: you can ... |
.directive('odataSynchronizerList', function(ODataSynchronizerService,OdataSynchDetailsManager,OdataModel) {
return {
restrict: 'AE',
replace: true,
templateUrl: 'components/odata-synchronizer/odata-synchronizer-list/view.html',
compile: function(tElem, tAttrs){
var self = this;
return ... |
angular.module('DHuS-webclient') | random_line_split |
utils.rs | fsuid(uid: uid_t) -> c_int;
fn setfsgid(gid: gid_t) -> c_int;
}
pub fn temporary_change_root<T, F>(path: &Path, mut fun: F)
-> Result<T, String>
where F: FnMut() -> Result<T, String>
{
// The point is: if we gat fatal signal in the chroot, we have 2 issues:
//
// 1. Process can't actually rest... | {
if self.0 {
unsafe { setfsuid(0) };
if unsafe { setfsuid(0) } != 0 {
let err = io::Error::last_os_error();
error!("Can't return fs uid back to zero: {}. Aborting.", err);
panic!("Can't return fs uid back to zero: {}. Aborting.", err);
... | identifier_body | |
utils.rs | , SIGSEGV, SIGBUS, SIGHUP, SIGILL, SIGABRT};
use nix::sys::signal::{SIGFPE, SIGUSR1, SIGUSR2};
use libc::{c_int, c_char, timeval, c_void, mode_t, uid_t, gid_t};
use libc::{chmod, chdir, chown};
use signal::trap::Trap;
use range::Range;
use super::id_map::IdMap;
pub type Time = f64;
pub type SigNum = i32;
// TODO(tai... | (uid: u32, gid: u32) -> FsUidGuard {
if uid != 0 || gid != 0 {
unsafe { setfsuid(uid) };
if unsafe { setfsuid(uid) } != uid as i32 {
error!("Can't set fs gid to open socket: | set | identifier_name |
utils.rs | , SIGSEGV, SIGBUS, SIGHUP, SIGILL, SIGABRT};
use nix::sys::signal::{SIGFPE, SIGUSR1, SIGUSR2};
use libc::{c_int, c_char, timeval, c_void, mode_t, uid_t, gid_t};
use libc::{chmod, chdir, chown};
use signal::trap::Trap;
use range::Range;
use super::id_map::IdMap;
pub type Time = f64;
pub type SigNum = i32;
// TODO(tai... |
pub fn clean_dir(dir: &Path, remove_dir_itself: bool) -> Result<(), String> {
if let Err(e) = metadata(dir) {
if e.kind() == NotFound {
return Ok(());
} else {
return Err(format!("Can't stat dir {:?}: {}", dir, e));
}
}
// We temporarily change root, so that ... | return Err(format!(concat!("Can't create dir {:?}: {} ",
"path already exists but not a directory"), dir, e));
}
}
} | random_line_split |
AutoReplySection.tsx | import { useRef, useState } from 'react';
import { c } from 'ttag';
import { isMac } from '@proton/shared/lib/helpers/browser';
import { updateAutoresponder } from '@proton/shared/lib/api/mailSettings';
import { AutoReplyDuration, PLANS, PLAN_NAMES } from '@proton/shared/lib/constants';
import { removeImagesFromConte... |
await api(updateAutoresponder(toAutoResponder({ ...model, message })));
await call();
createNotification({ text: c('Success').t`Auto-reply updated` });
};
const handleEditorReady = () => {
if (editorRef.current) {
editorRef.current.value = model.message;
}
... | {
createNotification({
type: 'warning',
text: c('Info').t`Images have been removed because they are not allowed in auto-reply.`,
});
updateModel('message').bind(message);
// update the composer to remove the image from it
if (e... | conditional_block |
AutoReplySection.tsx | import { useRef, useState } from 'react';
import { c } from 'ttag';
import { isMac } from '@proton/shared/lib/helpers/browser';
import { updateAutoresponder } from '@proton/shared/lib/api/mailSettings';
import { AutoReplyDuration, PLANS, PLAN_NAMES } from '@proton/shared/lib/constants';
import { removeImagesFromConte... | }}
>
<DurationField value={model.duration} onChange={updateModel('duration')} />
{formRenderer(model.duration)}
<SettingsLayout>
<SettingsLayoutLeft>
<label className="text-semibold" onClick={() => editorRef.current?.focus()}>... | e.preventDefault();
await withUpdatingLoading(handleSubmit()); | random_line_split |
Example4.tsx | import React, { Component } from 'react';
import { Slider, Rail, Handles, Tracks, Ticks } from 'react-compound-slider';
import ValueViewer from '../ValueViewer';
import { SliderRail, Handle, Track, Tick } from './components';
const sliderStyle: React.CSSProperties = {
position: 'relative',
height: '400px',
margi... | <Tracks left={false} right={false}>
{({ tracks, getTrackProps }) => (
<div className="slider-tracks">
{tracks.map(({ id, source, target }) => (
<Track
key={id}
source={source}
target={target... | </Handles> | random_line_split |
ScriptContext.js | Clazz.declarePackage ("JS");
Clazz.load (null, "JS.ScriptContext", ["java.util.Hashtable", "JS.SV"], function () {
c$ = Clazz.decorateAsClass (function () {
this.aatoken = null;
this.allowJSThreads = false;
this.chk = false;
this.contextPath = " >> ";
this.vars = null;
this.displayLoadErrorsSave = false;
this.... | var context = this;
while (context != null && !context.isFunction) {
if (context.vars != null && context.vars.containsKey ($var)) return context.vars.get ($var);
context = context.parentContext;
}
return null;
}, "~S");
Clazz.defineMethod (c$, "getFullMap",
function () {
var ht = new java.util.Hashtable ();
... | sc = sc.parentContext;
}
});
Clazz.defineMethod (c$, "getVariable",
function ($var) {
| random_line_split |
page.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 dom::bindings::cell::DOMRefCell;
use dom::bindings::js::{JS, Root};
use dom::document::Document;
use dom::wind... |
}
/// Information for one frame in the browsing context.
#[derive(JSTraceable, HeapSizeOf)]
#[must_root]
pub struct Frame {
/// The document for this frame.
pub document: JS<Document>,
/// The window object for this frame.
pub window: JS<Window>,
}
| {
*self.frame.borrow_mut() = frame;
} | identifier_body |
page.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 dom::bindings::cell::DOMRefCell;
use dom::bindings::js::{JS, Root};
use dom::document::Document;
use dom::wind... | (&self) -> Root<Window> {
Root::from_ref(&*self.frame.borrow().as_ref().unwrap().window)
}
pub fn document(&self) -> Root<Document> {
Root::from_ref(&*self.frame.borrow().as_ref().unwrap().document)
}
// must handle root case separately
pub fn remove(&self, id: PipelineId) -> Optio... | window | identifier_name |
page.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 dom::bindings::cell::DOMRefCell;
use dom::bindings::js::{JS, Root};
use dom::document::Document;
use dom::wind... |
popped
}
}
impl Page {
pub fn set_reflow_status(&self, status: bool) -> bool {
let old = self.needs_reflow.get();
self.needs_reflow.set(status);
old
}
#[allow(unrooted_must_root)]
pub fn set_frame(&self, frame: Option<Frame>) {
*self.frame.borrow_mut() = fr... | {
self.stack.extend(page.children.borrow().iter().cloned());
} | conditional_block |
page.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 dom::bindings::cell::DOMRefCell;
use dom::bindings::js::{JS, Root};
use dom::document::Document;
use dom::wind... | pub window: JS<Window>,
} | /// The document for this frame.
pub document: JS<Document>,
/// The window object for this frame. | random_line_split |
main.py | _integer('batch_size', 128, 'The size of minibatch when training [128]')
flags.DEFINE_float('learning_rate', 2e-4, 'Learning rate of optimizer [2e-4]')
flags.DEFINE_string('optimizer', 'Adam', 'Optimizer used when training [Adam]')
flags.DEFINE_string('dataset_name', 'mnist', 'Image dataset used when trainging [mnist]'... |
def main(*args):
FLAGS = flags.FLAGS
pp = pprint.PrettyPrinter(indent=4)
print('Running flags:')
pp.pprint(FLAGS.__dict__['__flags'])
tf.logging.set_verbosity('INFO')
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
with tf.Graph().as_default():
provider = slim.dataset_data_provi... | """Extract the map between tensor and its updated version in update_ops"""
update_map = OrderedDict()
name_to_var = {v.name: v for v in tf.global_variables()}
for u in update_ops:
var_name = u.op.inputs[0].name
var = name_to_var[var_name]
value = u.op.inputs[1]
if u.op.type == 'Assign':
upda... | identifier_body |
main.py | _integer('batch_size', 128, 'The size of minibatch when training [128]')
flags.DEFINE_float('learning_rate', 2e-4, 'Learning rate of optimizer [2e-4]')
flags.DEFINE_string('optimizer', 'Adam', 'Optimizer used when training [Adam]') | flags.DEFINE_string('dataset_dir', './data/mnist/', 'Path to dataset directory [./data/mnist]')
flags.DEFINE_string('checkpoint_path', None, 'Path to checkpoint path [None]')
flags.DEFINE_string('train_dir', './train', 'Path to save new training result [./train]')
flags.DEFINE_integer('max_step', 1000, 'Maximum trainin... | flags.DEFINE_string('dataset_name', 'mnist', 'Image dataset used when trainging [mnist]')
flags.DEFINE_string('split_name', 'train', 'Split name of dataset [train]') | random_line_split |
main.py | _integer('batch_size', 128, 'The size of minibatch when training [128]')
flags.DEFINE_float('learning_rate', 2e-4, 'Learning rate of optimizer [2e-4]')
flags.DEFINE_string('optimizer', 'Adam', 'Optimizer used when training [Adam]')
flags.DEFINE_string('dataset_name', 'mnist', 'Image dataset used when trainging [mnist]'... | (update_ops):
"""Extract the map between tensor and its updated version in update_ops"""
update_map = OrderedDict()
name_to_var = {v.name: v for v in tf.global_variables()}
for u in update_ops:
var_name = u.op.inputs[0].name
var = name_to_var[var_name]
value = u.op.inputs[1]
if u.op.type == 'Ass... | extract_update_dict | identifier_name |
main.py | dataset [train]')
flags.DEFINE_string('dataset_dir', './data/mnist/', 'Path to dataset directory [./data/mnist]')
flags.DEFINE_string('checkpoint_path', None, 'Path to checkpoint path [None]')
flags.DEFINE_string('train_dir', './train', 'Path to save new training result [./train]')
flags.DEFINE_integer('max_step', 100... | restore_vars = slim.get_variables_to_restore(exclude_patterns=split(FLAGS.exclude_scope, ','))
sess.run(slim.assign_from_checkpoint(FLAGS.checkpoint_path, restore_vars, ignore_missing_vars=False)) | conditional_block | |
circular_counter.rs | fn | (a: &Vec<i32>) -> Vec<i32> {
let mut a2 = a.clone();
let mut i = 0;
let mut b = vec![];
while a2.len() > 0 {
i = (i + 2) % a2.len();
b.push(a2[i]);
a2.remove(i);
}
b
}
fn main() {
let a = vec![1, 2, 3, 4, 5, 6, 7, 8, 9];
let b = circular_counter(&a);
println!... | circular_counter | identifier_name |
circular_counter.rs | fn circular_counter(a: &Vec<i32>) -> Vec<i32> |
fn main() {
let a = vec![1, 2, 3, 4, 5, 6, 7, 8, 9];
let b = circular_counter(&a);
println!("{:?}", b);
}
#[test]
fn test() {
assert_eq!(
circular_counter(
&vec![1, 2, 3, 4, 5, 6, 7, 8, 9]
),
vec![3, 6, 9, 4, 8, 5, 2, 7, 1]
);
}
| {
let mut a2 = a.clone();
let mut i = 0;
let mut b = vec![];
while a2.len() > 0 {
i = (i + 2) % a2.len();
b.push(a2[i]);
a2.remove(i);
}
b
} | identifier_body |
circular_counter.rs | fn circular_counter(a: &Vec<i32>) -> Vec<i32> {
let mut a2 = a.clone();
let mut i = 0;
let mut b = vec![];
while a2.len() > 0 {
i = (i + 2) % a2.len();
b.push(a2[i]);
a2.remove(i);
}
b
}
fn main() {
let a = vec![1, 2, 3, 4, 5, 6, 7, 8, 9];
let b = circular_counte... | } | ); | random_line_split |
config.ts | import Debug from 'debug'
import { v4 as uuid } from 'uuid/v4'
import redis from 'redis'
import Crowi from 'server/crowi'
import ConfigEvent from 'server/events/config'
const debug = Debug('crowi:service:config')
export default class ConfigService {
crowi: Crowi
config: any
configModel: any
event: ConfigEv... | this.update({ ...this.config, [ns]: { ...this.config[ns], [key]: value } })
}
async deleteConfig(ns: string, key: string) {
await this.configModel.deleteConfig(ns, key)
delete this.config[ns][key]
this.update(this.config)
}
/**
* To update the property of ConfigService,
* the config seri... | random_line_split | |
config.ts | import Debug from 'debug'
import { v4 as uuid } from 'uuid/v4'
import redis from 'redis'
import Crowi from 'server/crowi'
import ConfigEvent from 'server/events/config'
const debug = Debug('crowi:service:config')
export default class ConfigService {
crowi: Crowi
config: any
configModel: any
event: ConfigEv... | (ns: string, key: string, value: any) {
debug('Save config value', ns, key, value)
await this.configModel.updateConfig(ns, key, value)
this.update({ ...this.config, [ns]: { ...this.config[ns], [key]: value } })
}
async deleteConfig(ns: string, key: string) {
await this.configModel.deleteConfig(ns, ... | saveConfigValue | identifier_name |
config.ts | import Debug from 'debug'
import { v4 as uuid } from 'uuid/v4'
import redis from 'redis'
import Crowi from 'server/crowi'
import ConfigEvent from 'server/events/config'
const debug = Debug('crowi:service:config')
export default class ConfigService {
crowi: Crowi
config: any
configModel: any
event: ConfigEv... |
async deleteConfig(ns: string, key: string) {
await this.configModel.deleteConfig(ns, key)
delete this.config[ns][key]
this.update(this.config)
}
/**
* To update the property of ConfigService,
* the config serice user (e.g. some controller, model, etc.) must call this update() method.
* Ot... | {
debug('Save config value', ns, key, value)
await this.configModel.updateConfig(ns, key, value)
this.update({ ...this.config, [ns]: { ...this.config[ns], [key]: value } })
} | identifier_body |
config.ts | import Debug from 'debug'
import { v4 as uuid } from 'uuid/v4'
import redis from 'redis'
import Crowi from 'server/crowi'
import ConfigEvent from 'server/events/config'
const debug = Debug('crowi:service:config')
export default class ConfigService {
crowi: Crowi
config: any
configModel: any
event: ConfigEv... | })
subscriber.subscribe(pubSub.channel)
}
}
}
}
| {
this.pubSub.publisher = redis.createClient(redisOpts)
this.pubSub.subscriber = redis.createClient(redisOpts)
const { pubSub } = this
const { subscriber } = pubSub
debug('PubSubId', pubSub.id)
if (subscriber) {
subscriber.on('message', async (channel, message) => {
... | conditional_block |
issue-51191.rs | // Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | }
fn immref(&self) {
(&mut self).bar();
//~^ ERROR cannot borrow `self` as mutable, as it is not declared as mutable [E0596]
//~^^ ERROR cannot borrow data in a `&` reference as mutable [E0596]
}
fn mtblref(&mut self) {
(&mut self).bar();
//~^ ERROR cannot borro... | //~^ ERROR cannot borrow `self` as mutable, as it is not declared as mutable [E0596]
}
fn mtbl(mut self) {
(&mut self).bar(); | random_line_split |
issue-51191.rs | // Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | (self) {
(&mut self).bar();
//~^ ERROR cannot borrow `self` as mutable, as it is not declared as mutable [E0596]
}
fn mtbl(mut self) {
(&mut self).bar();
}
fn immref(&self) {
(&mut self).bar();
//~^ ERROR cannot borrow `self` as mutable, as it is not declared as... | imm | identifier_name |
issue-51191.rs | // Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
fn imm(self) {
(&mut self).bar();
//~^ ERROR cannot borrow `self` as mutable, as it is not declared as mutable [E0596]
}
fn mtbl(mut self) {
(&mut self).bar();
}
fn immref(&self) {
(&mut self).bar();
//~^ ERROR cannot borrow `self` as mutable, as it is not... | {
//~^ WARN function cannot return without recursing
(&mut self).bar();
//~^ ERROR cannot borrow `self` as mutable, as it is not declared as mutable [E0596]
} | identifier_body |
lib.rs | // Copyright 2017 Pants project contributors (see CONTRIBUTORS.md).
// Licensed under the Apache License, Version 2.0 (see LICENSE).
#![deny(warnings)]
// Enable all clippy lints except for many of the pedantic ones. It's a shame this needs to be copied and pasted across crates, but there doesn't appear to be a way to... | /// The arguments to execute.
///
/// The first argument should be an absolute or relative path to the binary to execute.
///
/// No PATH lookup will be performed unless a PATH environment variable is specified.
///
/// No shell expansion will take place.
///
pub argv: Vec<String>,
///
/// The env... | random_line_split | |
lib.rs | // Copyright 2017 Pants project contributors (see CONTRIBUTORS.md).
// Licensed under the Apache License, Version 2.0 (see LICENSE).
#![deny(warnings)]
// Enable all clippy lints except for many of the pedantic ones. It's a shame this needs to be copied and pasted across crates, but there doesn't appear to be a way to... | (mut self) -> Self {
self.execution_attempts = vec![];
self
}
}
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub struct ExecutionStats {
uploaded_bytes: usize,
uploaded_file_count: usize,
upload: Duration,
remote_queue: Option<Duration>,
remote_input_fetch: Option<Duration>,
remote_execu... | without_execution_attempts | identifier_name |
AuthenticationInitializer.spec.ts | import { mock } from 'angular';
| import { SETTINGS } from 'core/config/settings';
declare const window: any;
describe('authenticationProvider: application startup', function() {
beforeEach(() => (SETTINGS.authEnabled = true));
beforeEach(() => (window.spinnakerSettings.authEnabled = true));
beforeEach(() => AuthenticationService.reset());
bef... | import { IDeckRootScope } from 'core/domain';
import { AuthenticationInitializer } from './AuthenticationInitializer';
import { AuthenticationService } from './AuthenticationService';
import { AUTHENTICATION_MODULE } from './authentication.module'; | random_line_split |
analyseboundary-Ts.py | #!/usr/bin/env python
from __future__ import print_function
from __future__ import division
from builtins import str
from builtins import range
from past.utils import old_div
from boututils import shell, launch, plotdata
from boutdata import collect
import numpy as np
from sys import argv
from math import sqrt, log, p... | data_path = str(argv[2])
else:
print("Arguments: '[end_index] [data_path]' or 'gamma [data_path]'")
Exit(1)
# Collect the data
Te = collect("T_electron", path=data_path, xind=2, info=True, yguards=True)
Ti = collect("T_ion", path=data_path, xind=2, info=True, yguards=True)
if end_index<0:
end_index = len(Te[:... | data_path = str(argv[1])
elif len(argv)==3:
end_index = int(argv[1]) | random_line_split |
analyseboundary-Ts.py | #!/usr/bin/env python
from __future__ import print_function
from __future__ import division
from builtins import str
from builtins import range
from past.utils import old_div
from boututils import shell, launch, plotdata
from boutdata import collect
import numpy as np
from sys import argv
from math import sqrt, log, p... |
elif len(argv)==2:
try:
end_index = int(argv[1])
data_path = "data"
except ValueError:
end_index = -1
data_path = str(argv[1])
elif len(argv)==3:
end_index = int(argv[1])
data_path = str(argv[2])
else:
print("Arguments: '[end_index] [data_path]' or 'gamma [data_path]'")
Exit(1)
# Collect t... | end_index = -1
data_path = "data" | conditional_block |
print.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
import sys
def get_color(color):
if 'default'==color:
return '\x1b[39;01m'
elif 'black'==color:
return '\x1b[30;01m'
elif 'red'==color:
return '\x1b[31;01m'
elif 'green'==color:
return ... |
return '\x1b[34;01m'
def main():
if 4==len(sys.argv):
color,cmd,action=get_color(sys.argv[1]),sys.argv[2],sys.argv[3]
if action=='stop':
action='exit'
template='\x1b[1m%s[ ΔOS : %s : make : %s ]\x1b[0m'
else:
action='init'
template='\x1b[... | return '\x1b[36;01m' | conditional_block |
print.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
import sys
def | (color):
if 'default'==color:
return '\x1b[39;01m'
elif 'black'==color:
return '\x1b[30;01m'
elif 'red'==color:
return '\x1b[31;01m'
elif 'green'==color:
return '\x1b[32;01m'
elif 'yellow'==color:
return '\x1b[33;01m'
elif 'blue'==color:
return '\x... | get_color | identifier_name |
print.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
import sys
def get_color(color):
|
def main():
if 4==len(sys.argv):
color,cmd,action=get_color(sys.argv[1]),sys.argv[2],sys.argv[3]
if action=='stop':
action='exit'
template='\x1b[1m%s[ ΔOS : %s : make : %s ]\x1b[0m'
else:
action='init'
template='\x1b[1m%s[ ΔOS : %s : make : %... | if 'default'==color:
return '\x1b[39;01m'
elif 'black'==color:
return '\x1b[30;01m'
elif 'red'==color:
return '\x1b[31;01m'
elif 'green'==color:
return '\x1b[32;01m'
elif 'yellow'==color:
return '\x1b[33;01m'
elif 'blue'==color:
return '\x1b[34;01m'
... | identifier_body |
print.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
import sys
def get_color(color):
if 'default'==color:
return '\x1b[39;01m'
elif 'black'==color:
return '\x1b[30;01m'
elif 'red'==color:
return '\x1b[31;01m'
elif 'green'==color:
return ... | return '\x1b[33;01m'
elif 'blue'==color:
return '\x1b[34;01m'
elif 'magenta'==color:
return '\x1b[35;01m'
elif 'cyan'==color:
return '\x1b[36;01m'
return '\x1b[34;01m'
def main():
if 4==len(sys.argv):
color,cmd,action=get_color(sys.argv[1]),sys.argv[2],sys.ar... | random_line_split | |
toast.ios.js | import React, {
View,
ActivityIndicatorIOS,
StyleSheet,
TouchableOpacity,
Text,
Component,
Dimensions
} from 'react-native';
var Overlay = require('react-native-overlay');
var BlurView = require('react-native-blur').BlurView;
var Icon = require('react-native-vector-icons/FontAwesome');
clas... |
var icon = added ?
( <Icon name = "check-circle-o" size = {80} color = "rgba(0,150,0,0.8)" style = {styles.icon} allowFontScaling={false}/> ):
( <Icon name = "times-circle-o" size = {80} color = "rgba(200,0,0,0.8)" style = {styles.icon} allowFontScaling={false}/> );
return (
... | {
added = true;
} | conditional_block |
toast.ios.js | import React, {
View,
ActivityIndicatorIOS,
StyleSheet,
TouchableOpacity,
Text,
Component,
Dimensions
} from 'react-native';
var Overlay = require('react-native-overlay');
var BlurView = require('react-native-blur').BlurView;
var Icon = require('react-native-vector-icons/FontAwesome');
clas... | var icon = added ?
( <Icon name = "check-circle-o" size = {80} color = "rgba(0,150,0,0.8)" style = {styles.icon} allowFontScaling={false}/> ):
( <Icon name = "times-circle-o" size = {80} color = "rgba(200,0,0,0.8)" style = {styles.icon} allowFontScaling={false}/> );
return (
... | if(this.props.children.props.children.props.children == "Added"){
added = true;
} | random_line_split |
toast.ios.js | import React, {
View,
ActivityIndicatorIOS,
StyleSheet,
TouchableOpacity,
Text,
Component,
Dimensions
} from 'react-native';
var Overlay = require('react-native-overlay');
var BlurView = require('react-native-blur').BlurView;
var Icon = require('react-native-vector-icons/FontAwesome');
clas... | extends Component {
render() {
var positionStyle;
if(this.props.position == 'top' || !this.props.position){
positionStyle = styles.top;
} else {
positionStyle = styles.bottom;
}
var top = (Dimensions.get('window').height/2) - 75;
// console.l... | Toast | identifier_name |
index.js | project: this.props.project})
}
getAllLayouts(props, widget_width){
widget_width = widget_width || (this.state || {}).widget_width || WIDGET_WIDTH
const layout = this.props.widgets && this.props.widgets.map( (w, idx) => this.getDefaultLayout(w, idx, widget_width))
// console.log("Layout is", layout)
... |
to | {
config[k].stale = true
} | conditional_block |
index.js | project: this.props.project})
}
getAllLayouts(props, widget_width){
widget_width = widget_width || (this.state || {}).widget_width || WIDGET_WIDTH
const layout = this.props.widgets && this.props.widgets.map( (w, idx) => this.getDefaultLayout(w, idx, widget_width))
// console.log("Layout is", layout)
... | // console.log("Got new props", this.props, newprops)
if (!object_is_equal(this.props.widgets, newprops.widgets)){
// console.log("update layout")
lo.debounce(this.updateLayout, 200)()
}
if (this.props.show_sidebar != newprops.show_sidebar){
// console.log("calculate board size")
... | random_line_split | |
index.js | project: this.props.project})
}
| (props, widget_width){
widget_width = widget_width || (this.state || {}).widget_width || WIDGET_WIDTH
const layout = this.props.widgets && this.props.widgets.map( (w, idx) => this.getDefaultLayout(w, idx, widget_width))
// console.log("Layout is", layout)
return layout
}
getDefaultLayout(widget, y, ... | getAllLayouts | identifier_name |
index.js |
handleAddWidget(){
set_modal('dashboard.widget.create',{project: this.props.project})
}
getAllLayouts(props, widget_width){
widget_width = widget_width || (this.state || {}).widget_width || WIDGET_WIDTH
const layout = this.props.widgets && this.props.widgets.map( (w, idx) => this.getDefaultLayout(w, ... | {
const widget=this.props.widgets.find( (w) => w.uuid == uuid )
set_modal("dashboard.widget.edit", {uuid, widget})
} | identifier_body | |
statisticsUtils.js | ///////////////////////////////////////////////////////////////////////////
// Copyright © 2014 - 2016 Esri. All Rights Reserved.
//
// Licensed under the Apache License Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// h... |
}); |
if(!params.fieldInfos || !params.fieldInfos[params.fieldName]){
return;
}
for(var p in attributes){
if(p === 'countField' || !esriLang.isDefined(attributes[p])){
continue;
}
if(attributes[p] === null || typeof attributes[p] === 'undefined'){
attributes[p] = '';
... | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.