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
calendar-state.ts
import ModulDate from './../../../../utils/modul-date/modul-date'; import { RangeDate, SingleDate } from './abstract-calendar-state'; export enum CalendarEvent { DAY_SELECT = 'day-select', DAY_MOUSE_ENTER = 'day-mouse-enter', DAY_MOUSE_LEAVE = 'day-mouse-leave', DAY_KEYBOARD_TAB = 'day-keyboard-tab', ...
isCurrent: boolean; isDisabled: boolean; } export interface YearMonthState { year: YearState; months: MonthState[]; } export interface DayState { date: ModulDate; day: number; month: number; year: number; isDisabled: boolean; isToday: boolean; isSelected: boolean; isSel...
random_line_split
Redeem.js
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0;
var _jsxRuntime = require("react/jsx-runtime"); var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", { d: "M20 6h-2.18c.11-.31.18-.65.18-1 0-1.66-1.34-3-3-3-1.05 0-1.96.54-2.5 1.35l-.5.67-.5-.68C10.96 2.54 10.05 2 9 2 7.34 2 6 3.34 6 5c0 .35.07.69.18 1H4c-1.11 0-1.99.89-1.99 2L2 19c0...
var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon"));
random_line_split
lib.rs
//! Low-level Rust lexer. //! //! The idea with `rustc_lexer` is to make a reusable library, //! by separating out pure lexing and rustc-specific concerns, like spans, //! error reporting, and interning. So, rustc_lexer operates directly on `&str`, //! produces simple tokens which are a pair of type-tag and a bit of o...
mut self, first_digit: char) -> LiteralKind { debug_assert!('0' <= self.prev() && self.prev() <= '9'); let mut base = Base::Decimal; if first_digit == '0' { // Attempt to parse encoding base. let has_digits = match self.first() { 'b' => { ...
mber(&
identifier_name
lib.rs
//! Low-level Rust lexer. //! //! The idea with `rustc_lexer` is to make a reusable library, //! by separating out pure lexing and rustc-specific concerns, like spans, //! error reporting, and interning. So, rustc_lexer operates directly on `&str`, //! produces simple tokens which are a pair of type-tag and a bit of o...
self.bump(); } _ => (), } } // End of file reached. false } /// Eats the double-quoted string and returns `n_hashes` and an error if encountered. fn raw_double_quoted_string(&mut self, prefix_len: usize) -> (u16, Option...
// Bump again to skip escaped character.
random_line_split
BigHistory.tsx
import Avatar from '@material-ui/core/Avatar'; import List from '@material-ui/core/List'; import ListItem from '@material-ui/core/ListItem'; import ListItemText from '@material-ui/core/ListItemText'; import { withStyles } from '@material-ui/core/styles'; import NotificationIcon from '@material-ui/icons/Notifications'; ...
class BigHistory extends React.Component<any, any> { state = { notifications: new Array<ZephyrNotification>() }; listItems() { return ( <div> {this.props.notifications.reverse().map((notification) => { return ( <ListItem key={notification.id}> <Avatar s...
random_line_split
portal.rs
use crate::compat::Mutex; use crate::screen::{Screen, ScreenBuffer}; use alloc::sync::Arc; use core::mem; use graphics_base::frame_buffer::{AsSurfaceMut, FrameBuffer}; use graphics_base::system::{DeletedIndex, System}; use graphics_base::types::Rect; use graphics_base::Result; use hecs::World; #[cfg(target_os = "rust_...
<S> { screen: Arc<Mutex<Screen<S>>>, input_state: Arc<Mutex<Option<PortalRef>>>, deleted_index: DeletedIndex<()>, } impl<S> ServerPortalSystem<S> { pub fn new(screen: Arc<Mutex<Screen<S>>>, input_state: Arc<Mutex<Option<PortalRef>>>) -> Self { ServerPortalSystem { screen, ...
ServerPortalSystem
identifier_name
portal.rs
use crate::compat::Mutex; use crate::screen::{Screen, ScreenBuffer}; use alloc::sync::Arc; use core::mem; use graphics_base::frame_buffer::{AsSurfaceMut, FrameBuffer}; use graphics_base::system::{DeletedIndex, System}; use graphics_base::types::Rect; use graphics_base::Result; use hecs::World; #[cfg(target_os = "rust_...
} *self.input_state.lock() = portals.last().map(|p| p.portal_ref.clone()); let deleted_entities = self .deleted_index .update(world.query::<()>().with::<ServerPortal>().iter()); if !deleted_entities.is_empty() || portals.iter().any(|p| p.needs_paint) { ...
{ portal.prev_pos = portal.pos; portal.needs_paint = true; }
conditional_block
portal.rs
use crate::compat::Mutex; use crate::screen::{Screen, ScreenBuffer}; use alloc::sync::Arc; use core::mem; use graphics_base::frame_buffer::{AsSurfaceMut, FrameBuffer}; use graphics_base::system::{DeletedIndex, System}; use graphics_base::types::Rect; use graphics_base::Result; use hecs::World; #[cfg(target_os = "rust_...
pub events: Rc<RefCell<VecDeque<Event>>>, } impl PartialEq for PortalRef { fn eq(&self, other: &Self) -> bool { self.portal_id == other.portal_id && Rc::ptr_eq(&self.events, &other.events) } } impl PortalRef { pub fn send_input(&self, input: EventInput) -> R...
#[derive(Clone)] pub struct PortalRef { pub portal_id: usize,
random_line_split
browserify.d.ts
// Type definitions for Browserify v12.0.1 // Project: http://browserify.org/ // Definitions by: Andrew Gaspar <https://github.com/AndrewGaspar/>, John Vilk <https://github.com/jvilk> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// <reference path="../node/node.d.ts" /> declare namespace Browse...
/** * Make file available from outside the bundle with require(file). * The file param is anything that can be resolved by require.resolve(). * file can also be a stream, but you should also use opts.basedir so that relative requires will be resolvable. * If file is an array, each item in file w...
* Add an entry file from file that will be executed when the bundle loads. * If file is an array, each item in file will be added as an entry file. */ add(file: InputFile[], opts?: FileOptions): BrowserifyObject; add(file: InputFile, opts?: FileOptions): BrowserifyObject;
random_line_split
country-telephone-info.js
/* 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/. */ /** * Country->phone number info. */ /** * Each country entry should have the fields listed below. */ /** * ...
module.exports = { // Austria // https://en.wikipedia.org/wiki/Telephone_numbers_in_Austria AT: { format: formatter('+43 ${serverPhoneNumber}'), normalize: ensurePrefix('+43'), pattern: /^(?:\+43)?\d{6,}$/, prefix: '+43', rolloutRate: 1 }, // Australia // https://en.wikipedia.org/wiki/...
{ return function (num) { if (hasPrefix(num, prefix)) { return num; } return `${prefix}${num}`; }; }
identifier_body
country-telephone-info.js
/* 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/. */ /** * Country->phone number info. */ /** * Each country entry should have the fields listed below. */ /** * ...
(num, prefix) { return num.indexOf(prefix) === 0; } function ensurePrefix (prefix) { return function (num) { if (hasPrefix(num, prefix)) { return num; } return `${prefix}${num}`; }; } module.exports = { // Austria // https://en.wikipedia.org/wiki/Telephone_numbers_in_Austria AT: { f...
hasPrefix
identifier_name
country-telephone-info.js
/* 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/. */ /** * Country->phone number info. */ /** * Each country entry should have the fields listed below. */ /** * ...
function hasPrefix (num, prefix) { return num.indexOf(prefix) === 0; } function ensurePrefix (prefix) { return function (num) { if (hasPrefix(num, prefix)) { return num; } return `${prefix}${num}`; }; } module.exports = { // Austria // https://en.wikipedia.org/wiki/Telephone_numbers_in_Aus...
}
random_line_split
ServerPreferencesFetcher.tsx
import { Component, InfernoNode } from "inferno"; import { resolveAsset } from "../../assets"; import { fetchRetry } from "../../http"; import { ServerData } from "./data"; // Cache response so it's only sent once let fetchServerData: Promise<ServerData> | undefined; export class ServerPreferencesFetcher extends Comp...
() { return this.props.render(this.state.serverData); } }
render
identifier_name
ServerPreferencesFetcher.tsx
import { Component, InfernoNode } from "inferno"; import { resolveAsset } from "../../assets"; import { fetchRetry } from "../../http"; import { ServerData } from "./data"; // Cache response so it's only sent once let fetchServerData: Promise<ServerData> | undefined; export class ServerPreferencesFetcher extends Comp...
const preferencesData: ServerData = await fetchServerData; this.setState({ serverData: preferencesData, }); } render() { return this.props.render(this.state.serverData); } }
{ fetchServerData = fetchRetry(resolveAsset("preferences.json")) .then(response => response.json()); }
conditional_block
ServerPreferencesFetcher.tsx
import { Component, InfernoNode } from "inferno"; import { resolveAsset } from "../../assets"; import { fetchRetry } from "../../http"; import { ServerData } from "./data"; // Cache response so it's only sent once let fetchServerData: Promise<ServerData> | undefined; export class ServerPreferencesFetcher extends Comp...
render() { return this.props.render(this.state.serverData); } }
random_line_split
jquery.effects.scale.js
/*! * jQuery UI Effects Scale 1.8.23 * * Copyright 2012, AUTHORS.txt (http://jqueryui.com/about) * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * http://docs.jquery.com/UI/Effects/Scale * * Depends: * jquery.effects.core.js */ (function( $, undefined ) { $.effects.puf...
var factor = { // Set scaling factor y: direction != 'horizontal' ? (percent / 100) : 1, x: direction != 'vertical' ? (percent / 100) : 1 }; el.to = {height: original.height * factor.y, width: original.width * factor.x}; // Set to state if (o.options.fade) { // Fade option to support puff if (mode == ...
// Adjust
random_line_split
memory.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any lat...
(&mut self, offset: U256, slice: &[u8]) { let off = offset.low_u64() as usize; // TODO [todr] Optimize? for pos in off..off + slice.len() { self[pos] = slice[pos - off]; } } fn write(&mut self, offset: U256, value: U256) { let off = offset.low_u64() as usize...
write_slice
identifier_name
memory.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any lat...
fn read_slice(&self, init_off_u: U256, init_size_u: U256) -> &[u8] { let off = init_off_u.low_u64() as usize; let size = init_size_u.low_u64() as usize; if !is_valid_range(off, size) { &self[0..0] } else { &self[off..off + size] } } fn read(&self, offset: U256) -> U256 { l...
{ self.len() }
identifier_body
memory.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any lat...
} fn write_slice(&mut self, offset: U256, slice: &[u8]) { let off = offset.low_u64() as usize; // TODO [todr] Optimize? for pos in off..off + slice.len() { self[pos] = slice[pos - off]; } } fn write(&mut self, offset: U256, value: U256) { let off =...
{ &mut self[off..off + s] }
conditional_block
memory.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITH...
random_line_split
day11.js
/* --- Day 11: Corporate Policy --- Santa's previous password expired, and he needs help choosing a new one. To help him remember his new password after the old one expires, Santa has devised a method of coming up with a password based on the previous one. Corporate policy dictates that passwords must be exactly...
Increase the rightmost letter one step; if it was z, it wraps around to a, and repeat with the next letter to the left until one doesn't wrap around. Unfortunately for Santa, a new Security-Elf recently started, and he has imposed some additional password requirements: Passwords must include one increasing straig...
Incrementing is just like counting with numbers: xx, xy, xz, ya, yb, and so on.
random_line_split
hello-world-leds.js
/* This is the example config file used to demonstrate turning leds of different types and protocols on and off. */ // converts a number to a hex function toHex(c) { var hex = c.toString(16); hex = hex.length == 1 ? "0" + hex : hex; return "0x" + hex; } // formats an input to be received by a tri-colo...
(c, cmd) { if(c === 1) return [0xff, 0xff, 0xff, 0xff]; else if(c === 0) return [0xff, 0x00, 0x00, 0x00]; return [0xff, toHex(c[2]), toHex(c[1]), toHex(c[0])]; } module.exports = { "name":"hello-world-leds", "i2c-path": '/dev/i2c-1', "components" : [{"type":"led", "name":"blue", "direction": "out", "a...
apa102Input
identifier_name
hello-world-leds.js
/* This is the example config file used to demonstrate turning leds of different types and protocols on and off. */ // converts a number to a hex function toHex(c) { var hex = c.toString(16); hex = hex.length == 1 ? "0" + hex : hex; return "0x" + hex; } // formats an input to be received by a tri-colo...
if(c === 1) return [0xff, 0xff, 0xff, 0xff]; else if(c === 0) return [0xff, 0x00, 0x00, 0x00]; return [0xff, toHex(c[2]), toHex(c[1]), toHex(c[0])]; } module.exports = { "name":"hello-world-leds", "i2c-path": '/dev/i2c-1', "components" : [{"type":"led", "name":"blue", "direction": "out", "address":17,...
// formats the input to be received by a 5050led (apa102) var apaIdx = 0; function apa102Input(c, cmd) {
random_line_split
hello-world-leds.js
/* This is the example config file used to demonstrate turning leds of different types and protocols on and off. */ // converts a number to a hex function toHex(c) { var hex = c.toString(16); hex = hex.length == 1 ? "0" + hex : hex; return "0x" + hex; } // formats an input to be received by a tri-colo...
module.exports = { "name":"hello-world-leds", "i2c-path": '/dev/i2c-1', "components" : [{"type":"led", "name":"blue", "direction": "out", "address":17, "interface": "gpio", "formatInput" : triGpioColor}, {"type":"led","name":"green", "address":27, "direction": "out", "interface": "gpio"...
{ if(c === 1) return [0xff, 0xff, 0xff, 0xff]; else if(c === 0) return [0xff, 0x00, 0x00, 0x00]; return [0xff, toHex(c[2]), toHex(c[1]), toHex(c[0])]; }
identifier_body
vitrine_quatro_horizontais.js
Ti.include("/api/config.js"); Ti.include("/api/category_render.js"); Ti.include("/database/produtos.js"); Ti.include("/database/imagens_produtos.js"); var args = arguments[0] || {}; var marca = args.marca || 0; var categoria = args.cat_id || 0; var template = args.template || 0; var current_page = 1; var itemsperpage ...
function anterior() { current_page--; if (current_page <= 0) current_page = paginas; cleanImages(); renderProducts(); } function proximo() { current_page++; if (current_page > paginas) current_page = 1; cleanImages(); renderProducts(); } function primeiro() { current_page = 1; cleanImages(); render...
{ categoryVoltar(); }
identifier_body
vitrine_quatro_horizontais.js
Ti.include("/api/config.js"); Ti.include("/api/category_render.js"); Ti.include("/database/produtos.js"); Ti.include("/database/imagens_produtos.js"); var args = arguments[0] || {}; var marca = args.marca || 0; var categoria = args.cat_id || 0; var template = args.template || 0; var current_page = 1; var itemsperpage ...
var alturaView = Math.round(alturaTela * 0.9); var larguraView = Math.round(LARGURA_PADRAO * alturaView / ALTURA_PADRAO); if (larguraView < larguraTela) { vitrine.width = larguraView; vitrine.height = alturaView; //alert('largura' + larguraView + ", width: " + v.size.width + ", height: " + v.size.height); ...
{ alturaTela -250; larguraTela -250; }
conditional_block
vitrine_quatro_horizontais.js
Ti.include("/api/config.js"); Ti.include("/api/category_render.js"); Ti.include("/database/produtos.js"); Ti.include("/database/imagens_produtos.js"); var args = arguments[0] || {}; var marca = args.marca || 0; var categoria = args.cat_id || 0; var template = args.template || 0; var current_page = 1; var itemsperpage ...
exclui.show(); exclui.addEventListener("click", function(e){ if(e.index == 0){ categoryClear($.quantidade); } else { alert("Continue comprando"); } }); } function voltar() { categoryVoltar(); } function anterior() { current_page--; if (current_page <= 0) current_page = paginas; ...
title: "Desmarcar itens", message: "Essa opcao ira desmarcar todos os itens selecionados em todas as paginas!" });
random_line_split
vitrine_quatro_horizontais.js
Ti.include("/api/config.js"); Ti.include("/api/category_render.js"); Ti.include("/database/produtos.js"); Ti.include("/database/imagens_produtos.js"); var args = arguments[0] || {}; var marca = args.marca || 0; var categoria = args.cat_id || 0; var template = args.template || 0; var current_page = 1; var itemsperpage ...
() { current_page = 1; cleanImages(); renderProducts(); } function ultimo() { current_page = paginas; cleanImages(); renderProducts(); } function cesta() { categoryCesta(); } var eventListener = function() { Ti.App.removeEventListener('removeBitmap', eventListener); Ti.API.info('Quatro horizontais'); clean...
primeiro
identifier_name
view_resolver_mock.d.ts
import { Type } from 'angular2/src/facade/lang'; import { ViewMetadata } from '../core/metadata'; import { ViewResolver } from 'angular2/src/core/linker/view_resolver'; export declare class
extends ViewResolver { constructor(); /** * Overrides the {@link ViewMetadata} for a component. * * @param {Type} component * @param {ViewDefinition} view */ setView(component: Type, view: ViewMetadata): void; /** * Overrides the inline template for a component -...
MockViewResolver
identifier_name
view_resolver_mock.d.ts
import { Type } from 'angular2/src/facade/lang'; import { ViewMetadata } from '../core/metadata'; import { ViewResolver } from 'angular2/src/core/linker/view_resolver'; export declare class MockViewResolver extends ViewResolver { constructor(); /** * Overrides the {@link ViewMetadata} for a component...
* @param {Type} from * @param {Type} to */ overrideViewDirective(component: Type, from: Type, to: Type): void; /** * Returns the {@link ViewMetadata} for a component: * - Set the {@link ViewMetadata} to the overridden view when it exists or fallback to the default * `ViewRes...
* Overrides a directive from the component {@link ViewMetadata}. * * @param {Type} component
random_line_split
err_2021_001_logging_perm.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, ...
The service account used by GKE nodes should have the logging.logWriter role, otherwise ingestion of logs won't work. """ from gcpdiag import lint, models from gcpdiag.queries import gke, iam ROLE = 'roles/logging.logWriter' def prefetch_rule(context: models.Context): # Make sure that we have the IAM policy in c...
# See the License for the specific language governing permissions and # limitations under the License. """GKE nodes service account permissions for logging.
random_line_split
err_2021_001_logging_perm.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, ...
clusters = gke.get_clusters(context) iam_policy = iam.get_project_policy(context.project_id) if not clusters: report.add_skipped(None, 'no clusters found') for _, c in sorted(clusters.items()): if not c.has_logging_enabled(): report.add_skipped(c, 'logging disabled') else: # Verify service...
identifier_body
err_2021_001_logging_perm.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, ...
report.add_ok(np)
conditional_block
err_2021_001_logging_perm.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, ...
(context: models.Context): # Make sure that we have the IAM policy in cache. project_ids = {c.project_id for c in gke.get_clusters(context).values()} for pid in project_ids: iam.get_project_policy(pid) def run_rule(context: models.Context, report: lint.LintReportRuleInterface): # Find all clusters with lo...
prefetch_rule
identifier_name
11.8.3-4.js
// Copyright (c) 2012 Ecma International. All rights reserved. // Ecma International makes this code available under the terms and conditions set // forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the // "Use Terms"). Any redistribution of this code must retain the above // copyright and this n...
() { var accessed = false; var obj1 = { toString: function () { accessed = true; return 3; } }; var obj2 = { toString: function () { if (accessed === true) { return 4; ...
testcase
identifier_name
11.8.3-4.js
// Copyright (c) 2012 Ecma International. All rights reserved. // Ecma International makes this code available under the terms and conditions set // forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the // "Use Terms"). Any redistribution of this code must retain the above // copyright and this n...
11.8.3 Less-than-or-equal Operator - Partial left to right order enforced when using Less-than-or-equal operator: toString <= toString includes: [runTestCase.js] ---*/ function testcase() { var accessed = false; var obj1 = { toString: function () { accessed = tru...
es5id: 11.8.3-4 description: >
random_line_split
11.8.3-4.js
// Copyright (c) 2012 Ecma International. All rights reserved. // Ecma International makes this code available under the terms and conditions set // forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the // "Use Terms"). Any redistribution of this code must retain the above // copyright and this n...
runTestCase(testcase);
{ var accessed = false; var obj1 = { toString: function () { accessed = true; return 3; } }; var obj2 = { toString: function () { if (accessed === true) { return 4; } e...
identifier_body
11.8.3-4.js
// Copyright (c) 2012 Ecma International. All rights reserved. // Ecma International makes this code available under the terms and conditions set // forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the // "Use Terms"). Any redistribution of this code must retain the above // copyright and this n...
} }; return (obj1 <= obj2); } runTestCase(testcase);
{ return 2; }
conditional_block
views.py
# -*- coding: utf-8 -*- from django.core.cache import cache from django.shortcuts import render from django.http import Http404 from styleguide.utils import (Styleguide, STYLEGUIDE_DIR_NAME, STYLEGUIDE_DEBUG, STYLEGUIDE_CACHE_NAME, STYLEGUIDE_ACCESS) def in...
if not STYLEGUIDE_ACCESS(request.user): raise Http404() styleguide = None if not STYLEGUIDE_DEBUG: styleguide = cache.get(STYLEGUIDE_CACHE_NAME) if styleguide is None: styleguide = Styleguide() cache.set(STYLEGUIDE_CACHE_NAME, styleguide, None) if module_name is not No...
identifier_body
views.py
# -*- coding: utf-8 -*- from django.core.cache import cache from django.shortcuts import render from django.http import Http404 from styleguide.utils import (Styleguide, STYLEGUIDE_DIR_NAME, STYLEGUIDE_DEBUG, STYLEGUIDE_CACHE_NAME, STYLEGUIDE_ACCESS) def
(request, module_name=None, component_name=None): if not STYLEGUIDE_ACCESS(request.user): raise Http404() styleguide = None if not STYLEGUIDE_DEBUG: styleguide = cache.get(STYLEGUIDE_CACHE_NAME) if styleguide is None: styleguide = Styleguide() cache.set(STYLEGUIDE_CACHE...
index
identifier_name
views.py
# -*- coding: utf-8 -*- from django.core.cache import cache from django.shortcuts import render from django.http import Http404 from styleguide.utils import (Styleguide, STYLEGUIDE_DIR_NAME, STYLEGUIDE_DEBUG, STYLEGUIDE_CACHE_NAME, STYLEGUIDE_ACCESS) def in...
raise Http404() styleguide = None if not STYLEGUIDE_DEBUG: styleguide = cache.get(STYLEGUIDE_CACHE_NAME) if styleguide is None: styleguide = Styleguide() cache.set(STYLEGUIDE_CACHE_NAME, styleguide, None) if module_name is not None: styleguide.set_current_modul...
random_line_split
views.py
# -*- coding: utf-8 -*- from django.core.cache import cache from django.shortcuts import render from django.http import Http404 from styleguide.utils import (Styleguide, STYLEGUIDE_DIR_NAME, STYLEGUIDE_DEBUG, STYLEGUIDE_CACHE_NAME, STYLEGUIDE_ACCESS) def in...
context = {'styleguide': styleguide} index_path = "%s/index.html" % STYLEGUIDE_DIR_NAME return render(request, index_path, context)
styleguide.set_current_module(module_name)
conditional_block
users.py
# Copyright 2011 OpenStack LLC. # Copyright 2011 Nebula, Inc. # 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 # # http://www.apache.org/licenses/LICENS...
return super(UserManager, self).list( base_url=base_url, domain_id=base.getid(domain), project_id=base.getid(project), **kwargs) def get(self, user): return super(UserManager, self).get( user_id=base.getid(user)) def update(self, us...
base_url = None
conditional_block
users.py
# Copyright 2011 OpenStack LLC. # Copyright 2011 Nebula, Inc. # 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 # # http://www.apache.org/licenses/LICENS...
(self, user, group): self._require_user_and_group(user, group) base_url = '/groups/%s' % base.getid(group) return super(UserManager, self).head( base_url=base_url, user_id=base.getid(user)) def remove_from_group(self, user, group): self._require_user_and_gro...
check_in_group
identifier_name
users.py
# Copyright 2011 OpenStack LLC. # Copyright 2011 Nebula, Inc. # 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 # # http://www.apache.org/licenses/LICENS...
enabled=enabled) def list(self, project=None, domain=None, group=None, **kwargs): """List users. If project, domain or group are provided, then filter users with those attributes. If ``**kwargs`` are provided, then filter users with attributes matching ``**kwar...
random_line_split
users.py
# Copyright 2011 OpenStack LLC. # Copyright 2011 Nebula, Inc. # 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 # # http://www.apache.org/licenses/LICENS...
def add_to_group(self, user, group): self._require_user_and_group(user, group) base_url = '/groups/%s' % base.getid(group) return super(UserManager, self).put( base_url=base_url, user_id=base.getid(user)) def check_in_group(self, user, group): self._re...
return super(UserManager, self).update( user_id=base.getid(user), name=name, domain_id=base.getid(domain), project_id=base.getid(project), password=password, email=email, description=description, enabled=enabled)
identifier_body
hibernate_state.rs
// Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0. use kvproto::metapb::Region; use pd_client::{Feature, FeatureGate}; use serde_derive::{Deserialize, Serialize}; /// Because negotiation protocol can't be recognized by old version of binaries, /// so enabling it directly can cause a lot of connection ...
pub fn should_bcast(&self, gate: &FeatureGate) -> bool { gate.can_enable(NEGOTIATION_HIBERNATE) } pub fn maybe_hibernate(&mut self, my_id: u64, region: &Region) -> bool { let peers = region.get_peers(); let v = match &mut self.leader { LeaderState::Awaken => { ...
{ if let LeaderState::Poll(v) = &mut self.leader { if !v.contains(&from) { v.push(from); } } }
identifier_body
hibernate_state.rs
// Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0. use kvproto::metapb::Region; use pd_client::{Feature, FeatureGate}; use serde_derive::{Deserialize, Serialize}; /// Because negotiation protocol can't be recognized by old version of binaries, /// so enabling it directly can cause a lot of connection ...
} } }
} else { false
random_line_split
hibernate_state.rs
// Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0. use kvproto::metapb::Region; use pd_client::{Feature, FeatureGate}; use serde_derive::{Deserialize, Serialize}; /// Because negotiation protocol can't be recognized by old version of binaries, /// so enabling it directly can cause a lot of connection ...
{ group: GroupState, leader: LeaderState, } impl HibernateState { pub fn ordered() -> HibernateState { HibernateState { group: GroupState::Ordered, leader: LeaderState::Awaken, } } pub fn group_state(&self) -> GroupState { self.group } pub ...
HibernateState
identifier_name
hibernate_state.rs
// Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0. use kvproto::metapb::Region; use pd_client::{Feature, FeatureGate}; use serde_derive::{Deserialize, Serialize}; /// Because negotiation protocol can't be recognized by old version of binaries, /// so enabling it directly can cause a lot of connection ...
else { false } } }
{ self.leader = LeaderState::Hibernated; true }
conditional_block
movie.js
// pages/movies/movie.js Page({
data: { }, /** * 生命周期函数--监听页面加载 */ onLoad: function (options) { }, /** * 生命周期函数--监听页面初次渲染完成 */ onReady: function () { }, /** * 生命周期函数--监听页面显示 */ onShow: function () { }, /** * 生命周期函数--监听页面隐藏 */ onHide: function () { }, /** * 生命周期函数--监听页面卸载 ...
/** * 页面的初始数据 */
random_line_split
matlab.py
r""" Functions that make it easier to deal with Matlab data. Notes ----- #. Written by David C. Stauffer in December 2018. """ #%% Imports from __future__ import annotations import doctest from pathlib import Path from typing import Any, Dict, List, Optional, Set, Tuple, Union import unittest from dstauffman.consta...
if not isinstance(filename, h5py.Group): with h5py.File(filename, 'r') as file: # normal method out = _load(file=file, varlist=varlist, squeeze=squeeze, enums=enums) else: # recursive call method where the file is already opened to a given group out = _load(file...
r"""Wrapped subfunction so it can be called recursively.""" # initialize output out: Dict[str, Any] = {} # loop through keys, keys are the MATLAB variable names, like TELM for key in file: # skip keys that are not in the given varlist if varlist is not None and ke...
identifier_body
matlab.py
r""" Functions that make it easier to deal with Matlab data. Notes ----- #. Written by David C. Stauffer in December 2018. """ #%% Imports from __future__ import annotations import doctest from pathlib import Path from typing import Any, Dict, List, Optional, Set, Tuple, Union import unittest from dstauffman.consta...
( file: h5py.Group, varlist: Optional[Union[List[str], Set[str], Tuple[str]]], squeeze: bool, enums: Optional[Dict[str, Any]], ) -> Dict[str, Any]: r"""Wrapped subfunction so it can be called recursively.""" # initialize output out: Dict[str, Any] = {} ...
_load
identifier_name
matlab.py
r""" Functions that make it easier to deal with Matlab data. Notes ----- #. Written by David C. Stauffer in December 2018. """ #%% Imports from __future__ import annotations import doctest from pathlib import Path from typing import Any, Dict, List, Optional, Set, Tuple, Union import unittest from dstauffman.consta...
if isinstance(values.flat[0], h5py.Reference): # TODO: for now, always collapse to 1D cell array as a list temp = [file[item] for item in values.flat] temp2 = [] for x in temp: if isinstance(x, h5py.G...
if isinstance(grp, h5py.Dataset): # Note: data is transposed due to how Matlab stores columnwise values = grp[()].T # check for cell array references
random_line_split
matlab.py
r""" Functions that make it easier to deal with Matlab data. Notes ----- #. Written by David C. Stauffer in December 2018. """ #%% Imports from __future__ import annotations import doctest from pathlib import Path from typing import Any, Dict, List, Optional, Set, Tuple, Union import unittest from dstauffman.consta...
else: # recursive call method where the file is already opened to a given group out = _load(file=filename, varlist=varlist, squeeze=squeeze, enums=enums) return out #%% Unit test if __name__ == '__main__': unittest.main(module='dstauffman.tests.test_matlab', exit=False) doctest.testmo...
with h5py.File(filename, 'r') as file: # normal method out = _load(file=file, varlist=varlist, squeeze=squeeze, enums=enums)
conditional_block
shootout-chameneos-redux.rs
// The Computer Language Benchmarks Game // http://benchmarksgame.alioth.debian.org/ // // contributed by the Rust Project Developers // Copyright (c) 2012-2014 The Rust Project Developers // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted...
( name: uint, mut color: Color, from_rendezvous: Receiver<CreatureInfo>, to_rendezvous: Sender<CreatureInfo>, to_rendezvous_log: Sender<String> ) { let mut creatures_met = 0i32; let mut evil_clones_met = 0; let mut rendezvous = from_rendezvous.iter(); loop { // ask for a pai...
creature
identifier_name
shootout-chameneos-redux.rs
// The Computer Language Benchmarks Game // http://benchmarksgame.alioth.debian.org/ // // contributed by the Rust Project Developers // Copyright (c) 2012-2014 The Rust Project Developers // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted...
7 => {" seven"} 8 => {" eight"} 9 => {" nine"} _ => {panic!("expected digits from 0 to 9...")} } } struct Number(uint); impl fmt::Show for Number { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let mut out = vec![]; let Number(mut num) = *self; ...
{" six"}
conditional_block
shootout-chameneos-redux.rs
// The Computer Language Benchmarks Game // http://benchmarksgame.alioth.debian.org/ // // contributed by the Rust Project Developers // Copyright (c) 2012-2014 The Rust Project Developers // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted...
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED // OF THE POSSIBILITY OF SUCH DAMAGE. // n...
random_line_split
shootout-chameneos-redux.rs
// The Computer Language Benchmarks Game // http://benchmarksgame.alioth.debian.org/ // // contributed by the Rust Project Developers // Copyright (c) 2012-2014 The Rust Project Developers // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted...
{ let nn = if std::os::getenv("RUST_BENCH").is_some() { 200000 } else { std::os::args().as_slice() .get(1) .and_then(|arg| arg.parse()) .unwrap_or(600u) }; print_complements(); println!(""); rendezvous(nn, vec...
identifier_body
ws_impl.rs
use flate2::read::ZlibDecoder; use serde_json; use websocket::message::OwnedMessage; use websocket::sync::stream::{TcpStream, TlsStream}; use websocket::sync::Client as WsClient; use gateway::GatewayError; use internal::prelude::*; pub trait ReceiverExt { fn recv_json<F, T>(&mut self, decode: F) -> Result<T> where...
OwnedMessage::Text(payload) => { let value = serde_json::from_str(&payload)?; Some(decode(value).map_err(|why| { warn!("(╯°□°)╯︵ ┻━┻ Error decoding: {}", payload); why })) }, OwnedMessage::Ping(...
why })) }, OwnedMessage::Close(data) => Some(Err(Error::Gateway(GatewayError::Closed(data)))),
random_line_split
ws_impl.rs
use flate2::read::ZlibDecoder; use serde_json; use websocket::message::OwnedMessage; use websocket::sync::stream::{TcpStream, TlsStream}; use websocket::sync::Client as WsClient; use gateway::GatewayError; use internal::prelude::*; pub trait ReceiverExt { fn recv_json<F, T>(&mut self, decode: F) -> Result<T> where...
tream<TcpStream>> { fn send_json(&mut self, value: &Value) -> Result<()> { serde_json::to_string(value) .map(OwnedMessage::Text) .map_err(Error::from) .and_then(|m| self.send_message(&m).map_err(Error::from)) } }
{ let message = self.recv_message()?; let res = match message { OwnedMessage::Binary(bytes) => { let value = serde_json::from_reader(ZlibDecoder::new(&bytes[..]))?; Some(decode(value).map_err(|why| { let s = String::from_utf8_lossy(&bytes...
identifier_body
ws_impl.rs
use flate2::read::ZlibDecoder; use serde_json; use websocket::message::OwnedMessage; use websocket::sync::stream::{TcpStream, TlsStream}; use websocket::sync::Client as WsClient; use gateway::GatewayError; use internal::prelude::*; pub trait ReceiverExt { fn recv_json<F, T>(&mut self, decode: F) -> Result<T> where...
<()> { serde_json::to_string(value) .map(OwnedMessage::Text) .map_err(Error::from) .and_then(|m| self.send_message(&m).map_err(Error::from)) } }
-> Result
identifier_name
tomcat.py
# This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # This program is distributed in the hope that it will be useful, # but...
else: self.add_copy_spec("/var/log/tomcat*/*") def postproc(self): serverXmlPasswordAttributes = ['keyPass', 'keystorePass', 'truststorePass', 'SSLPassword'] for attr in serverXmlPasswordAttributes: self.do_path_regex_sub( ...
log_glob = "/var/log/tomcat*/catalina.out" self.add_copy_spec(log_glob, sizelimit=limit) # get today's date in iso format so that days/months below 10 # prepend 0 today = datetime.date(datetime.now()).isoformat() log_glob = "/var/log/tomcat*/catalina.%s.log" ...
conditional_block
tomcat.py
# the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Publ...
# This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by
random_line_split
tomcat.py
# This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # This program is distributed in the hope that it will be useful, # but...
# vim: set et ts=4 sw=4 :
"""Apache Tomcat server """ plugin_name = 'tomcat' profiles = ('webserver', 'java', 'services', 'sysmgmt') packages = ('tomcat', 'tomcat6', 'tomcat7', 'tomcat8') def setup(self): self.add_copy_spec([ "/etc/tomcat", "/etc/tomcat6", "/etc/tomcat7", ...
identifier_body
tomcat.py
# This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # This program is distributed in the hope that it will be useful, # but...
(Plugin, RedHatPlugin): """Apache Tomcat server """ plugin_name = 'tomcat' profiles = ('webserver', 'java', 'services', 'sysmgmt') packages = ('tomcat', 'tomcat6', 'tomcat7', 'tomcat8') def setup(self): self.add_copy_spec([ "/etc/tomcat", "/etc/tomcat6", ...
Tomcat
identifier_name
diagrammeJoseph.js
"use strict"; // utilisation de : http://bl.ocks.org/brattonc/5e5ce9beee483220e2f6#index.html // les données var donneesJardinJoseph = { "printemps": [ {nomProduit: "Racines", poids: 12850}, {nomProduit: "Poids et Haricots", poids: 10934}, {nomProduit: "Choux", poids: 8760}, {nomP...
r mois = today.getMonth(); var jour = today.getDay(); // janvier: 0, fevrier: 1, ... if(mois >=2 && mois <= 5) { // entre mars et juin if(mois == 2 && jour < 20) return "hiver"; else if(mois == 5 && jour > 20) return "ete"; else return "printemps"; } else if(mois >= 5 &&...
identifier_body
diagrammeJoseph.js
"use strict"; // utilisation de : http://bl.ocks.org/brattonc/5e5ce9beee483220e2f6#index.html // les données var donneesJardinJoseph = { "printemps": [ {nomProduit: "Racines", poids: 12850}, {nomProduit: "Poids et Haricots", poids: 10934}, {nomProduit: "Choux", poids: 8760}, {nomP...
] }; var infosJardinJoseph = { "Racines": { idJauge: "jauge_racine", couleur: "#f7bd48", maximum: 20050, cheminImage: "./img/joseph/racines.svg" }, "Poids et Haricots": { idJauge: "jauge_haricots", couleur: "#c96d63", maximum: 16400, ch...
{nomProduit: "Aromatiques", poids: 3800}, {nomProduit: "Fruits", poids: 30010}, {nomProduit: "Autres", poids: 11965}
random_line_split
diagrammeJoseph.js
"use strict"; // utilisation de : http://bl.ocks.org/brattonc/5e5ce9beee483220e2f6#index.html // les données var donneesJardinJoseph = { "printemps": [ {nomProduit: "Racines", poids: 12850}, {nomProduit: "Poids et Haricots", poids: 10934}, {nomProduit: "Choux", poids: 8760}, {nomP...
.reduce(function(prec, elem, indice, tab) { return prec + elem.poids; }, 0); return (total * 0.001).toFixed(1); } /** * retourne la saison actuelle (la saison en fonction de la date actuelle) * @returns {string} la saison actuelle, peut être "printemps", "ete", "automne", "hiver" */ function getSa...
ar total = donnees
identifier_name
about.ts
/** * @module Core */ /// <reference path="corePlugin.ts"/> module Core { _module.controller("Core.AboutController", ["$scope", "$location", "jolokia", "branding", "localStorage", ($scope, $location, jolokia, branding, localStorage) => { var log:Logging.Logger = Logger.get("About"); // load the about.md ...
Core.$apply($scope); }, error: function (jqXHR, textStatus, errorThrown) { $scope.html = "Unable to download about.md"; Core.$apply($scope); } }) }]); }
{ $scope.html = marked(data); $scope.branding = branding; $scope.customBranding = branding.enabled; try { $scope.hawtioVersion = jolokia.request({ type: "read", mbean: "hawtio:type=About", attribute: "HawtioVersion" ...
conditional_block
about.ts
/** * @module Core */ /// <reference path="corePlugin.ts"/> module Core { _module.controller("Core.AboutController", ["$scope", "$location", "jolokia", "branding", "localStorage", ($scope, $location, jolokia, branding, localStorage) => { var log:Logging.Logger = Logger.get("About"); // load the about.md ...
$scope.branding = branding; $scope.customBranding = branding.enabled; try { $scope.hawtioVersion = jolokia.request({ type: "read", mbean: "hawtio:type=About", attribute: "HawtioVersion" }).value; } catch (Error) { ...
cache: false, success: function (data, textStatus, jqXHR) { $scope.html = "Unable to download about.md"; if (angular.isDefined(data)) { $scope.html = marked(data);
random_line_split
service.rs
use crate::protocol; #[cfg(windows)] use core::os::process::windows_child::{ChildStderr, ChildStdout, ExitStatus}; use core::util::BufReadLossy; use habitat_common::output::{self, StructuredOutput}; #[cfg(unix)] u...
(&self) -> u32 { self.process.id() } /// Attempt to gracefully terminate a proccess and then forcefully kill it after /// 8 seconds if it has not terminated. pub fn kill(&mut self) -> protocol::ShutdownMethod { self.process.kill() } pub fn name(&self) -> &str { &self.args.id } pub fn take_args(se...
id
identifier_name
service.rs
use crate::protocol; #[cfg(windows)] use core::os::process::windows_child::{ChildStderr, ChildStdout, ExitStatus}; use core::util::BufReadLossy; use habitat_common::output::{self, StructuredOutput}; #[cfg(unix)] u...
/// Consume standard error from a child process until EOF, then finish fn pipe_stderr<T>(err: T, id: &str) where T: Read { for line in BufReader::new(err).lines_lossy() { match line { Ok(line) => { let so = StructuredOutput::succinct(id, "E", output::get_format(), &line); ...
{ for line in BufReader::new(out).lines_lossy() { match line { Ok(line) => { let so = StructuredOutput::succinct(id, "O", output::get_format(), &line); if let Err(e) = so.println() { println!("printing output: '{}' to stdout resulted in error: ...
identifier_body
service.rs
use crate::protocol; #[cfg(windows)] use core::os::process::windows_child::{ChildStderr, ChildStdout, ExitStatus}; use core::util::BufReadLossy; use habitat_common::output::{self, StructuredOutput}; #[cfg(unix)] u...
impl Service { pub fn new(spawn: protocol::Spawn, process: Process, stdout: Option<ChildStdout>, stderr: Option<ChildStderr>) -> Self { if let Some(stdout) = stdout { let id = spawn.id.to_string(); thread::Builder::new().nam...
random_line_split
bind-by-move-neither-can-live-while-the-other-survives-4.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
{ x: (), } impl Drop for X { fn drop(&mut self) { println!("destructor runs"); } } fn main() { let x = Some((X { x: () }, X { x: () })); match x { Some((_y, ref _z)) => { }, //~ ERROR cannot bind by-move and by-ref in the same pattern None => fail!() } }
X
identifier_name
bind-by-move-neither-can-live-while-the-other-survives-4.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
{ let x = Some((X { x: () }, X { x: () })); match x { Some((_y, ref _z)) => { }, //~ ERROR cannot bind by-move and by-ref in the same pattern None => fail!() } }
identifier_body
bind-by-move-neither-can-live-while-the-other-survives-4.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
impl Drop for X { fn drop(&mut self) { println!("destructor runs"); } } fn main() { let x = Some((X { x: () }, X { x: () })); match x { Some((_y, ref _z)) => { }, //~ ERROR cannot bind by-move and by-ref in the same pattern None => fail!() } }
// option. This file may not be copied, modified, or distributed // except according to those terms. struct X { x: (), }
random_line_split
app.js
import React from 'react' import {render} from 'react-dom' import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider' import themeDefault from './themeDefault' import injectTapEventPlugin from 'react-tap-event-plugin' import router from './router.js' import IPFSDAO from './dao/IPFSDAO' import OrbitDAO from './d...
() { IPFSDAO.init().then(ipfsNode => { OrbitDAO.init(ipfsNode) /** Needed for onTouchTap @link http://stackoverflow.com/a/34015469/988941 */ injectTapEventPlugin() render( <MuiThemeProvider muiTheme={themeDefault}>{router}</MuiThemeProvider>, document.getElementById('react...
start
identifier_name
app.js
import React from 'react' import {render} from 'react-dom' import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider' import themeDefault from './themeDefault' import injectTapEventPlugin from 'react-tap-event-plugin' import router from './router.js' import IPFSDAO from './dao/IPFSDAO' import OrbitDAO from './d...
import ErrorPage from './pages/ErrorPage' class App { start () { IPFSDAO.init().then(ipfsNode => { OrbitDAO.init(ipfsNode) /** Needed for onTouchTap @link http://stackoverflow.com/a/34015469/988941 */ injectTapEventPlugin() render( <MuiThemeProvider muiTheme={themeDefault}>{rout...
random_line_split
main.py
#! /usr/bin/python import re import os import sys import time import pydas.communicator as apiMidas import pydas.exceptions as pydasException import uuid import json import shutil from zipfile import ZipFile, ZIP_DEFLATED from subprocess import Popen, PIPE, STDOUT from contextlib import closing # Load configuration fi...
else: time.sleep(120) else: time.sleep(120)
handleMidasResponse(response)
conditional_block
main.py
#! /usr/bin/python import re import os import sys import time import pydas.communicator as apiMidas import pydas.exceptions as pydasException import uuid import json import shutil from zipfile import ZipFile, ZIP_DEFLATED from subprocess import Popen, PIPE, STDOUT from contextlib import closing # Load configuration fi...
pathProcessingFolder = sys.path[0]+'/tmp/'+unique_name os.mkdir(pathProcessingFolder) os.mkdir(pathProcessingFolder+'/script') os.mkdir(pathProcessingFolder+'/results') #Create Script file try: scriptFile = open(pathProcessingFolder+'/script/script.py', "w") except Exception, e: raise s...
random_line_split
main.py
#! /usr/bin/python import re import os import sys import time import pydas.communicator as apiMidas import pydas.exceptions as pydasException import uuid import json import shutil from zipfile import ZipFile, ZIP_DEFLATED from subprocess import Popen, PIPE, STDOUT from contextlib import closing # Load configuration fi...
(basedir, archivename): assert os.path.isdir(basedir) with closing(ZipFile(archivename, "w", ZIP_DEFLATED)) as z: for root, dirs, files in os.walk(basedir): #NOTE: ignore empty directories for fn in files: absfn = os.path.join(root, fn) zfn = absfn[len(basedir)+...
zipdir
identifier_name
main.py
#! /usr/bin/python import re import os import sys import time import pydas.communicator as apiMidas import pydas.exceptions as pydasException import uuid import json import shutil from zipfile import ZipFile, ZIP_DEFLATED from subprocess import Popen, PIPE, STDOUT from contextlib import closing # Load configuration fi...
# Handle Midas command def handleMidasResponse(response): """ Handle response """ if response['action'] == 'wait': print "Wait" time.sleep(120) elif response['action'] == 'process': params = json.loads(response['params']) script = response['script'] #Create processing folder unique_...
""" Send Results """ cfg = loadConfig('config.cfg') cfginternal = loadConfig('config.internal.cfg') url = cfg['url'] interfaceMidas = apiMidas.Communicator (url) parameters = dict() parameters['token'] = cfginternal['token'] try: response = interfaceMidas.makeRequest('midas.remotepr...
identifier_body
res_partner.py
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models class Partner(models.Model): _inherit = 'res.partner' team_id = fields.Many2one('crm.team', string='Sales Team', oldname='section_id') opportunity_ids = fields.One2man...
rec = super(Partner, self).default_get(fields) active_model = self.env.context.get('active_model') if active_model == 'crm.lead': lead = self.env[active_model].browse(self.env.context.get('active_id')).exists() if lead: rec.update( phon...
random_line_split
res_partner.py
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models class Partner(models.Model): _inherit = 'res.partner' team_id = fields.Many2one('crm.team', string='Sales Team', oldname='section_id') opportunity_ids = fields.One2man...
return rec @api.multi def _compute_opportunity_count(self): for partner in self: operator = 'child_of' if partner.is_company else '=' # the opportunity count should counts the opportunities of this company and all its contacts partner.opportunity_count = self.env['crm....
rec.update( phone=lead.phone, mobile=lead.mobile, function=lead.function, title=lead.title.id, website=lead.website, street=lead.street, street2=lead.street2, c...
conditional_block
res_partner.py
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models class Partner(models.Model): _inherit = 'res.partner' team_id = fields.Many2one('crm.team', string='Sales Team', oldname='section_id') opportunity_ids = fields.One2man...
partner_ids = self.ids partner_ids.append(self.env.user.partner_id.id) action = self.env.ref('calendar.action_calendar_event').read()[0] action['context'] = { 'search_default_partner_ids': self._context['partner_name'], 'default_partner_ids': partner_ids, } ...
identifier_body
res_partner.py
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models class
(models.Model): _inherit = 'res.partner' team_id = fields.Many2one('crm.team', string='Sales Team', oldname='section_id') opportunity_ids = fields.One2many('crm.lead', 'partner_id', string='Opportunities', domain=[('type', '=', 'opportunity')]) meeting_ids = fields.Many2many('calendar.event', 'calenda...
Partner
identifier_name
p011.rs
//! [Problem 11](https://projecteuler.net/problem=11) solver. #![warn(bad_style, unused, unused_extern_crates, unused_import_braces, unused_qualifications, unused_results)] #![feature(iter_arith)] #[macro_use(problem)] extern crate common; const INPUT: &'static str = " 08 02 22 97 38 15 00 40 00 75 ...
let h = grid.len(); let mut lines: Vec<Vec<_>> = vec![]; // rows lines.extend((0 .. h).map(|y| (0 .. w).map(|x| (x, y)).collect())); // cols lines.extend((0 .. w).map(|x| (0 .. h).map(|y| (x, y)).collect())); // top 2 right diagonal lines.extend((0 .. w).map(|i| { let (x0, y0) =...
let w = grid[0].len();
random_line_split
p011.rs
//! [Problem 11](https://projecteuler.net/problem=11) solver. #![warn(bad_style, unused, unused_extern_crates, unused_import_braces, unused_qualifications, unused_results)] #![feature(iter_arith)] #[macro_use(problem)] extern crate common; const INPUT: &'static str = " 08 02 22 97 38 15 00 40 00 75 ...
() -> String { compute(4).to_string() } problem!("70600674", solve);
solve
identifier_name
p011.rs
//! [Problem 11](https://projecteuler.net/problem=11) solver. #![warn(bad_style, unused, unused_extern_crates, unused_import_braces, unused_qualifications, unused_results)] #![feature(iter_arith)] #[macro_use(problem)] extern crate common; const INPUT: &'static str = " 08 02 22 97 38 15 00 40 00 75 ...
fn solve() -> String { compute(4).to_string() } problem!("70600674", solve);
{ let grid: Vec<Vec<u32>> = INPUT .trim() .lines() .map(|line| { line.split_whitespace().filter_map(|s| s.parse().ok()).collect() }) .collect(); let w = grid[0].len(); let h = grid.len(); let mut lines: Vec<Vec<_>> = vec![]; // rows lines.ext...
identifier_body
api.js
var meetcute_api = require("ti.cloud.meetcute.api"), MC_API_TOKEN = '23#AFE92', Cloud = require('ti.cloud'); Cloud.debug = true; /** * 1. Filter by: age & _gender & !viewed Order by geo location. Limit 20 2. Find the current user's Facebook Friends who also registered in the same App. Then exclude them...
// liked var liked; if ( isLiked ) { liked = customFields.liked; if ( !liked ) { liked = userId; } else if ( liked.indexOf(userId) == -1 ) { liked += ':' + userId; } } Cloud.Users.update( { custom_fields: isLiked ? { viewed: viewed, liked: liked } : { viewed: viewed } }, function...
{ viewed += ':' + userId; }
conditional_block
api.js
var meetcute_api = require("ti.cloud.meetcute.api"), MC_API_TOKEN = '23#AFE92', Cloud = require('ti.cloud'); Cloud.debug = true; /** * 1. Filter by: age & _gender & !viewed Order by geo location. Limit 20 2. Find the current user's Facebook Friends who also registered in the same App. Then exclude them...
exports.onViewPhoto = onViewPhoto; /** * Mark photo as viewed & liked */ exports.onLikePhoto = function(userId) { onViewPhoto( userId, true ); }; exports.crossPath = function( data, callback ) { data.api_token = MC_API_TOKEN; // The default generated bindings file allows you to send payload data and a success...
{ if ( !userId ) { return; } var customFields = Ti.App.currentUser.custom_fields; // viewed var viewed = customFields.viewed; if ( !viewed ) { viewed = userId; } else if ( viewed.indexOf(userId) == -1 ) { viewed += ':' + userId; } // liked var liked; if ( isLiked ) { liked = customFields....
identifier_body
api.js
var meetcute_api = require("ti.cloud.meetcute.api"), MC_API_TOKEN = '23#AFE92', Cloud = require('ti.cloud'); Cloud.debug = true; /** * 1. Filter by: age & _gender & !viewed Order by geo location. Limit 20 2. Find the current user's Facebook Friends who also registered in the same App. Then exclude them...
type: 'accepted', crossPath: crossPath }); } else { // User not has a decision yet success({ has_active_cross_path: true, type: 'matcher', ...
}); } else if ( custom_fields.agree_users && custom_fields.agree_users.indexOf(userId) != -1 ) { //user has accepted this event success({ has_active_cross_path: true,
random_line_split
api.js
var meetcute_api = require("ti.cloud.meetcute.api"), MC_API_TOKEN = '23#AFE92', Cloud = require('ti.cloud'); Cloud.debug = true; /** * 1. Filter by: age & _gender & !viewed Order by geo location. Limit 20 2. Find the current user's Facebook Friends who also registered in the same App. Then exclude them...
( userId, isLiked ) { if ( !userId ) { return; } var customFields = Ti.App.currentUser.custom_fields; // viewed var viewed = customFields.viewed; if ( !viewed ) { viewed = userId; } else if ( viewed.indexOf(userId) == -1 ) { viewed += ':' + userId; } // liked var liked; if ( isLiked ) { l...
onViewPhoto
identifier_name
XMPCommonFwdDeclarations_8h.js
var XMPCommonFwdDeclarations_8h = [ [ "cIUTF8Strings", "XMPCommonFwdDeclarations_8h.html#aae5dbe164f71188aa24c87fa6306539a", null ], [ "IConfigurationManager_base", "XMPCommonFwdDeclarations_8h.html#ab6a71f81b4e3c8e5d2d0c90f82fbee08", null ],
[ "IErrorNotifier_base", "XMPCommonFwdDeclarations_8h.html#a692c91c0b558cbc476e43e7f0a9112e0", null ], [ "IMemoryAllocator_base", "XMPCommonFwdDeclarations_8h.html#ae79591aae25236208281cd3e48a2483d", null ], [ "IObjectFactory_base", "XMPCommonFwdDeclarations_8h.html#a25f44f5d5e5c651d20124037a7c3b5c3", null ...
[ "IError_base", "XMPCommonFwdDeclarations_8h.html#a5f4d698bf8beb5f6604b61aa1362d2c6", null ],
random_line_split
lib.rs
// Copyright 2017 Kam Y. Tse // // 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 w...
pub use self::client::Client; /// The Errors that may occur when communicating with Pomotodo server. pub mod errors { error_chain! { types { Error, ErrorKind, ResultExt; } foreign_links { ReqError(::reqwest::Error); } } }
pub use self::pomo::{Pomo, PomoBuilder, PomoParameter}; pub use self::todo::{Todo, SubTodo, TodoBuilder, SubTodoBuilder, TodoParameter};
random_line_split
GitLabApiRepository.ts
import { injectable } from 'inversify'; import * as request from 'superagent'; import { ISourceConfig } from '../../../IConfig'; @injectable() export class GitLabApiRepository { public async getUploadedFile( sourceConfig: ISourceConfig, projectPath: string, fileId: string, filename:...
return req; } private getUrl(baseUrl: string, path: string) { return ( `${baseUrl}/${path}` // Remove any duplicate slashes due to user config input .replace(/\/\//g, '/') // Make sure that the protocol at the start of the url is cor...
{ req.query(query); }
conditional_block
GitLabApiRepository.ts
import { injectable } from 'inversify'; import * as request from 'superagent'; import { ISourceConfig } from '../../../IConfig'; @injectable() export class GitLabApiRepository { public async getUploadedFile( sourceConfig: ISourceConfig, projectPath: string, fileId: string, filename:...
// Remove any duplicate slashes due to user config input .replace(/\/\//g, '/') // Make sure that the protocol at the start of the url is correctly // terminated with a double slash .replace('/', '//') ); } }
private getUrl(baseUrl: string, path: string) { return ( `${baseUrl}/${path}`
random_line_split
GitLabApiRepository.ts
import { injectable } from 'inversify'; import * as request from 'superagent'; import { ISourceConfig } from '../../../IConfig'; @injectable() export class
{ public async getUploadedFile( sourceConfig: ISourceConfig, projectPath: string, fileId: string, filename: string ): Promise<any[]> { const path = `${projectPath}/uploads/${fileId}/${filename}`; return await this.performRequest( this.getUrl(sourceCo...
GitLabApiRepository
identifier_name
cisco_nexus_configuration.py
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # # Copyright 2011 Cisco Systems, Inc. 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 # # http://www.apache...
SECTION = CP['DRIVER'] NEXUS_DRIVER = SECTION['name']
random_line_split