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
regress-137000.js
/* -*- Mode: javascript; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* 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/. */ /* * * Date: 03 June 2...
status = inSection(1); f.x = 12; actual = f.x; expect = 12; addThis(); /* * A more elaborate example, using the call() method * to chain constructors from child to parent. * * The key point is the use of the same name 'p' for both * the parameter to the constructor, and as a property name */ function parentO...
{ }
identifier_body
regress-137000.js
/* -*- Mode: javascript; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* 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/. */ /* * * Date: 03 June 2...
exitFunc ('test'); }
{ reportCompare(expectedvalues[i], actualvalues[i], statusitems[i]); }
conditional_block
form.ts
import { Result } from "@/api/ajax"; import { Ref, ref } from "vue" import { FormItemRule } from "naive-ui"; import { t } from "@/locales"; export function useForm<T>(form: Ref, action: () => Promise<Result<T>>, success?: (data: T) => void) { const submiting = ref(false) async function submit(e: Event) { ...
submiting.value = true; try { let r = await action() success ? success(<T>r.data) : window.message.info(t('texts.action_success')); } finally { submiting.value = false; } }); } return { submit, submiting }...
{ return }
conditional_block
form.ts
import { Result } from "@/api/ajax"; import { Ref, ref } from "vue" import { FormItemRule } from "naive-ui"; import { t } from "@/locales"; export function useForm<T>(form: Ref, action: () => Promise<Result<T>>, success?: (data: T) => void) { const submiting = ref(false) async function submit(e: Event) { ...
export function lengthRule(min: number, max: number, field?: string): FormItemRule { return createRule((rule: any, value: string): boolean => { return value.length >= min && value.length <= max }, t('tips.length_rule', { min, max }), field) } export function passwordRule(field?: string): FormItemRul...
{ const reg = /^[1][3,4,5,7,8][0-9]{9}$/; return regexRule(reg, t('tips.phone_rule'), field) }
identifier_body
form.ts
import { Result } from "@/api/ajax"; import { Ref, ref } from "vue" import { FormItemRule } from "naive-ui"; import { t } from "@/locales"; export function
<T>(form: Ref, action: () => Promise<Result<T>>, success?: (data: T) => void) { const submiting = ref(false) async function submit(e: Event) { e.preventDefault(); form.value.validate(async (errors: any) => { if (errors) { return } submiting.va...
useForm
identifier_name
form.ts
import { Result } from "@/api/ajax"; import { Ref, ref } from "vue" import { FormItemRule } from "naive-ui"; import { t } from "@/locales"; export function useForm<T>(form: Ref, action: () => Promise<Result<T>>, success?: (data: T) => void) { const submiting = ref(false) async function submit(e: Event) { ...
}
} function formatMessage(field?: string, message?: string) { return field ? `${field}: ${message}` : message
random_line_split
topic-viewer-backend-api.service.spec.ts
// Copyright 2018 The Oppia Authors. 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 //
// // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the Licen...
// http://www.apache.org/licenses/LICENSE-2.0
random_line_split
admin-item.js
import m from 'mithril';
oninit: function(vnode) { vnode.state = { displayDetailBox: h.toggleProp(false, true) }; }, view: function({state, attrs}) { const item = attrs.item, listWrapper = attrs.listWrapper || {}, selectedItem = (_.isFunction(listWrapper.isSelected) ? ...
import _ from 'underscore'; import h from '../h'; const adminItem = {
random_line_split
maintenance_visit.js
// Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors // License: GNU General Public License v3. See license.txt frappe.provide("erpnext.support"); frappe.require("assets/erpnext/js/utils.js"); frappe.ui.form.on_change("Maintenance Visit", "customer", function(frm) { erpnext.utils.get_party_details(f...
company: cur_frm.doc.company } }) }, "icon-download", "btn-default"); cur_frm.add_custom_button(__('From Warranty Claim'), function() { frappe.model.map_current_doc({ method: "erpnext.support.doctype.warranty_claim.warranty_claim.make_maintenance_visit", source_doctype: "Wa...
random_line_split
index.d.ts
import { Express, Router } from 'express-serve-static-core'; interface IInitializeOptions { document?: { [key: string]: any }; title?: string; description?: string; termsOfService?: string; contact?: { name?: string; url?: string; email?: string; }; licence?: { ...
export function ensureValid(data: any): void;
random_line_split
file.rs
use std::path::Path; use std::fs::File; use std::io::{Read, Write}; use encoding::{Encoding, DecoderTrap, EncoderTrap}; use encoding::all::WINDOWS_1252; pub fn
<P: AsRef<Path>>(path: P) -> String { let mut file = File::open(path).unwrap(); let mut data = String::new(); file.read_to_string(&mut data).unwrap(); data } pub fn write_all_text<P: AsRef<Path>>(path: P, text: &str) { let mut file = File::create(path).unwrap(); file.write_all(text.as_bytes()...
read_all_text
identifier_name
file.rs
use std::path::Path; use std::fs::File; use std::io::{Read, Write}; use encoding::{Encoding, DecoderTrap, EncoderTrap}; use encoding::all::WINDOWS_1252; pub fn read_all_text<P: AsRef<Path>>(path: P) -> String { let mut file = File::open(path).unwrap(); let mut data = String::new(); file.read_to_string(&mu...
pub fn write_all_win_1252<P: AsRef<Path>>(path: P, text: &str) { let mut file = File::create(path).unwrap(); let data = WINDOWS_1252.encode(&text, EncoderTrap::Strict).unwrap(); file.write_all(&data).unwrap(); }
{ let mut file = File::open(path).unwrap(); let mut data = Vec::new(); file.read_to_end(&mut data).unwrap(); WINDOWS_1252.decode(&data, DecoderTrap::Strict).unwrap() }
identifier_body
file.rs
use std::path::Path; use std::fs::File; use std::io::{Read, Write}; use encoding::{Encoding, DecoderTrap, EncoderTrap}; use encoding::all::WINDOWS_1252;
let mut data = String::new(); file.read_to_string(&mut data).unwrap(); data } pub fn write_all_text<P: AsRef<Path>>(path: P, text: &str) { let mut file = File::create(path).unwrap(); file.write_all(text.as_bytes()).unwrap(); } pub fn read_all_win_1252<P: AsRef<Path>>(path: P) -> String { let ...
pub fn read_all_text<P: AsRef<Path>>(path: P) -> String { let mut file = File::open(path).unwrap();
random_line_split
webpack.config.js
const path = require('path'); const webpack = require('webpack'); const WebpackBar = require('webpackbar'); const FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin'); const { CleanWebpackPlugin } = require('clean-webpack-plugin'); const HTMLWebpackPlugin = require('html-webpack-plugin'); const TerserPlugi...
new HTMLWebpackPlugin({ title: 'Webpack-Babel-IE8', template: 'src/index.ejs', }), new HtmlWebpackTagsPlugin({ tags: Object.keys(externals).map((k) => 'libs/' + k), append: false, }), ].concat(isProd ? [] : [new webpack.HotModuleReplacementPlugin()]), };
random_line_split
comparison_result_widget_spec.tsx
/* * Copyright 2022 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...
it('should showcase comparison result', () => { mount(comparison); expect(helper.byTestId("info-msg")).not.toBeInDOM(); expect(helper.byTestId("comparison-result-widget")).toBeInDOM(); expect(helper.byTestId("material-changes")).toBeInDOM(); expect(helper.byTestId("material-revisions-widget"))....
{ helper.mount(() => <ComparisonResultWidget comparisonResult={comparison} pipelineConfig={new PipelineConfig()}/>); }
identifier_body
comparison_result_widget_spec.tsx
/* * Copyright 2022 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...
(comparison: Comparison) { helper.mount(() => <ComparisonResultWidget comparisonResult={comparison} pipelineConfig={new PipelineConfig()}/>); } it('should showcase comparison result', () => { mount(comparison); expect(helper.byTestId("info-msg")).not.toBeInDOM(); expect(helper.byTestId("comparison...
mount
identifier_name
comparison_result_widget_spec.tsx
/* * Copyright 2022 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...
afterEach((done) => helper.unmount(done)); function mount(comparison: Comparison) { helper.mount(() => <ComparisonResultWidget comparisonResult={comparison} pipelineConfig={new PipelineConfig()}/>); } it('should showcase comparison result', () => { mount(comparison); expect(helper.byTestId("info-...
comparison = Comparison.fromJSON(ComparisonData.compare()); });
random_line_split
BaseModal.tsx
import * as React from 'react'; import classNames from 'classnames'; import { ownerDocument, activeElement, contains, getContainer, on } from 'dom-lib'; import canUseDom from 'dom-lib/lib/query/canUseDOM'; import Portal from '../Portal'; import ModalManager from './ModalManager'; import Fade from '../Animation/Fade'; i...
else if (!prevProps.show && this.props.show) { this.onShow(); } } componentWillUnmount() { const { show, transition } = this.props; if (show || (transition && !this.state.exited)) { this.onHide(); } } onShow() { const doc = ownerDocument(this); const container = getContai...
{ // Otherwise handleHidden will call this. this.onHide(); }
conditional_block
BaseModal.tsx
import * as React from 'react'; import classNames from 'classnames'; import { ownerDocument, activeElement, contains, getContainer, on } from 'dom-lib'; import canUseDom from 'dom-lib/lib/query/canUseDOM'; import Portal from '../Portal'; import ModalManager from './ModalManager'; import Fade from '../Animation/Fade'; i...
); } } export default BaseModal;
random_line_split
BaseModal.tsx
import * as React from 'react'; import classNames from 'classnames'; import { ownerDocument, activeElement, contains, getContainer, on } from 'dom-lib'; import canUseDom from 'dom-lib/lib/query/canUseDOM'; import Portal from '../Portal'; import ModalManager from './ModalManager'; import Fade from '../Animation/Fade'; i...
(prevProps: BaseModalProps) { const { transition } = this.props; if (prevProps.show && !this.props.show && !transition) { // Otherwise handleHidden will call this. this.onHide(); } else if (!prevProps.show && this.props.show) { this.onShow(); } } componentWillUnmount() { cons...
componentDidUpdate
identifier_name
BaseModal.tsx
import * as React from 'react'; import classNames from 'classnames'; import { ownerDocument, activeElement, contains, getContainer, on } from 'dom-lib'; import canUseDom from 'dom-lib/lib/query/canUseDOM'; import Portal from '../Portal'; import ModalManager from './ModalManager'; import Fade from '../Animation/Fade'; i...
getSnapshotBeforeUpdate(prevProps: BaseModalProps) { if (this.props.show && !prevProps.show) { this.checkForFocus(); } return null; } componentDidUpdate(prevProps: BaseModalProps) { const { transition } = this.props; if (prevProps.show && !this.props.show && !transition) { // O...
{ if (nextProps.show) { return { exited: false }; } else if (!nextProps.transition) { // Otherwise let handleHidden take care of marking exited. return { exited: true }; } return null; }
identifier_body
files.py
# -*- coding: utf-8 -*- # GMate - Plugin Based Programmer's Text Editor # Copyright © 2008 Alexandre da Silva / Carlos Antonio da Silva # # This file is part of Gmate. # # See LICENTE.TXT for licence information import os import gnomevfs from datetime import datetime def get_file_info(uri): """Return the File in...
def get_path_from_uri(uri): return gnomevfs.get_local_path_from_uri(uri) def get_last_modification(uri): """Gigen a file uri return the last modification date""" file_info = get_file_info(uri) if file_info: return datetime.fromtimestamp(file_info.mtime)
""Gets the mime type of given file uri""" return gnomevfs.get_mime_type(uri)
identifier_body
files.py
# -*- coding: utf-8 -*- # GMate - Plugin Based Programmer's Text Editor # Copyright © 2008 Alexandre da Silva / Carlos Antonio da Silva # # This file is part of Gmate. # # See LICENTE.TXT for licence information import os import gnomevfs from datetime import datetime def get_file_info(uri): """Return the File in...
return False def is_dir(file_info): """Checks to see if the file is a directory.""" if file_info is not None: return file_info.type == gnomevfs.FILE_TYPE_DIRECTORY return False def is_file(file_info): """Checks to see if the file is a directory.""" if file_info is not None: ret...
eturn is_dir(file_info)
conditional_block
files.py
# -*- coding: utf-8 -*- # GMate - Plugin Based Programmer's Text Editor # Copyright © 2008 Alexandre da Silva / Carlos Antonio da Silva # # This file is part of Gmate. # # See LICENTE.TXT for licence information import os import gnomevfs from datetime import datetime def get_file_info(uri): """Return the File in...
file_info): """Checks to see if the file is hidden.""" if file_info is not None: return file_info.name.startswith(u'.') or file_info.name.endswith(u'~') return False def is_hidden_dir(file_info): """Checks to see if the file is a hidden directory.""" return is_dir(file_info) and is_hidden(f...
s_hidden(
identifier_name
files.py
# -*- coding: utf-8 -*- # GMate - Plugin Based Programmer's Text Editor # Copyright © 2008 Alexandre da Silva / Carlos Antonio da Silva # # This file is part of Gmate. # # See LICENTE.TXT for licence information import os import gnomevfs from datetime import datetime def get_file_info(uri): """Return the File in...
return False def is_hidden_dir(file_info): """Checks to see if the file is a hidden directory.""" return is_dir(file_info) and is_hidden(file_info) def is_hidden_file(file_info): """Checks to see if the file is a hidden file.""" return not is_dir(file_info) and is_hidden(file_info) def is_visible...
random_line_split
page.rs
/* * Copyright 2019 Jeehoon Kang * * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed t...
Ok(Self::from_raw( new_begin as *mut RawPage, (new_end - new_begin) / PAGE_SIZE, )) } pub fn into_raw(self) -> *mut RawPage { let ptr = self.ptr; mem::forget(self); ptr as *mut _ } pub fn clear(&mut self) { for page in self.iter...
{ return Err(()); }
conditional_block
page.rs
/* * Copyright 2019 Jeehoon Kang * * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed t...
if new_begin >= new_end || new_end - new_begin < PAGE_SIZE { return Err(()); } Ok(Self::from_raw( new_begin as *mut RawPage, (new_end - new_begin) / PAGE_SIZE, )) } pub fn into_raw(self) -> *mut RawPage { let ptr = self.ptr; m...
// Round begin address up, and end address down. let new_begin = round_up(ptr as usize, PAGE_SIZE); let new_end = round_down(ptr as usize + size, PAGE_SIZE); // No pages if there isn't enough room for an entry.
random_line_split
page.rs
/* * Copyright 2019 Jeehoon Kang * * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed t...
() -> Self { Self { inner: [0; PAGE_SIZE], } } pub fn clear(&mut self) { for byte in self.inner.iter_mut() { *byte = 0; } } } impl Deref for RawPage { type Target = [u8; PAGE_SIZE]; fn deref(&self) -> &Self::Target { &self.inner ...
new
identifier_name
PRESUBMIT.py
# Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Top-level presubmit script for swarm_client. See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts for details on the presubmit...
(input_api, output_api): return CommonChecks(input_api, output_api)
CheckChangeOnCommit
identifier_name
PRESUBMIT.py
# Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Top-level presubmit script for swarm_client. See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts for details on the presubmit...
output = [] sys_path_backup = sys.path try: sys.path = [ join('tests', 'gtest_fake'), ] + sys.path output.extend(input_api.canned_checks.RunPylint(input_api, output_api)) finally: sys.path = sys_path_backup output.extend( input_api.canned_checks.RunUnitTestsInDirectory( ...
return input_api.os_path.join(input_api.PresubmitLocalPath(), *args)
identifier_body
PRESUBMIT.py
# Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Top-level presubmit script for swarm_client. See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts for details on the presubmit...
owners_check=False)) return output def CheckChangeOnUpload(input_api, output_api): return CommonChecks(input_api, output_api) def CheckChangeOnCommit(input_api, output_api): return CommonChecks(input_api, output_api)
random_line_split
PRESUBMIT.py
# Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Top-level presubmit script for swarm_client. See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts for details on the presubmit...
return output def CheckChangeOnUpload(input_api, output_api): return CommonChecks(input_api, output_api) def CheckChangeOnCommit(input_api, output_api): return CommonChecks(input_api, output_api)
output.extend(input_api.canned_checks.PanProjectChecks(input_api, output_api, owners_check=False))
conditional_block
app.component.ts
import { Component } from '@angular/core'; @Component({ selector: 'my-app', template:` <h1>{{title}}</h1> <ul class="heroes"> <li *ngFor="let hero of heroes" (click)="onSelect(hero)""> <span class="badge">{{hero.id}}</span> {{hero.name}} </li> </ul> <div *ngIf="selectedHero"> <h2>{{se...
{ title = 'Tour of Heroes'; heroes = HEROES; selectedHero : Hero; onSelect(hero: Hero): void { this.selectedHero = hero; } } export class Hero { id : number; name : string; } const HEROES: Hero[] = [ { id: 11, name: 'Mr. Nice' }, { id: 12, name: 'Narco' }, { id: 13, name: 'Bombasto' }, { ...
AppComponent
identifier_name
app.component.ts
import { Component } from '@angular/core'; @Component({ selector: 'my-app', template:` <h1>{{title}}</h1> <ul class="heroes"> <li *ngFor="let hero of heroes" (click)="onSelect(hero)""> <span class="badge">{{hero.id}}</span> {{hero.name}} </li> </ul> <div *ngIf="selectedHero"> <h2>{{se...
color: white; } .heroes { margin: 0 0 2em 0; list-style-type: none; padding: 0; width: 15em; } .heroes li { cursor: pointer; position: relative; left: 0; background-color: #EEE; margin: .5em; padding: .3em 0; height: 1.6em; bo...
styles: [` .selected { background-color: #CFD8DC !important;
random_line_split
inline-json-editor.component.ts
/** * @license * Copyright 2021 Red Hat * * 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 ...
} public codeEditorMode(): CodeEditorMode { return this._mode; } }
protected formatValue(value: string): string { return value;
random_line_split
inline-json-editor.component.ts
/** * @license * Copyright 2021 Red Hat * * 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 ...
}); } displayValue(): string { if (this.isEmpty()) { return this.noValueMessage; } return this.formatValue(this.value); } protected formatValue(value: string): string { return value; } public codeEditorMode(): CodeEditorMode { retur...
{ changes.last.focus(); }
conditional_block
inline-json-editor.component.ts
/** * @license * Copyright 2021 Red Hat * * 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 ...
extends TextAreaEditorComponent implements AfterViewInit { @ViewChildren("codeEditor") codeEditor: QueryList<CodeEditorComponent>; _mode: CodeEditorMode = CodeEditorMode.JSON; constructor(selectionService: SelectionService) { super(selectionService); } ngAfterViewInit(): void { ...
InlineJsonEditorComponent
identifier_name
inline-json-editor.component.ts
/** * @license * Copyright 2021 Red Hat * * 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 ...
public codeEditorMode(): CodeEditorMode { return this._mode; } }
{ return value; }
identifier_body
calendar-br.js
// ** I18N // Calendar pt-BR language
// Unicode is the answer to a real internationalized world. Also please // include your contact information in the header, as can be seen above. // full day names Calendar._DN = new Array ("Domingo", "Segunda", "Terça", "Quarta", "Quinta", "Sexta", "Sabádo", "Domingo"); // Please note that the following array...
// Author: Fernando Dourado, <fernando.dourado@ig.com.br> // Encoding: any // Distributed under the same terms as the calendar itself. // For translators: please use UTF-8 if possible. We strongly believe that
random_line_split
index.tsx
import { Component, ReactNode } from 'react'; type Props = { children: ReactNode; }; type State = Readonly<{ hasError: boolean; }>; export default class ErrorBoundary extends Component<Props, State> { static getDerivedStateFromError() { return { hasError: true }; } state = { hasError: false, }; ...
</div> ) : ( children ); } }
{ const { children } = this.props; const { hasError } = this.state; return hasError ? ( <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100vh', }} > <div> <h1>Unexpected Error</h1> ...
identifier_body
index.tsx
import { Component, ReactNode } from 'react';
type State = Readonly<{ hasError: boolean; }>; export default class ErrorBoundary extends Component<Props, State> { static getDerivedStateFromError() { return { hasError: true }; } state = { hasError: false, }; render() { const { children } = this.props; const { hasError } = this.state; ...
type Props = { children: ReactNode; };
random_line_split
index.tsx
import { Component, ReactNode } from 'react'; type Props = { children: ReactNode; }; type State = Readonly<{ hasError: boolean; }>; export default class ErrorBoundary extends Component<Props, State> { static
() { return { hasError: true }; } state = { hasError: false, }; render() { const { children } = this.props; const { hasError } = this.state; return hasError ? ( <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', ...
getDerivedStateFromError
identifier_name
pipe-pingpong-bounded.rs
// xfail-fast // 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 // <...
() { let (client_, server_) = ::pingpong::init(); let client_ = Cell(client_); let server_ = Cell(server_); do task::spawn { let client__ = client_.take(); test::client(client__); }; do task::spawn { let server__ = server_.take(); test::server(server__); }; }
main
identifier_name
pipe-pingpong-bounded.rs
// xfail-fast // 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 // <...
let server__ = server_.take(); test::server(server__); }; }
let client__ = client_.take(); test::client(client__); }; do task::spawn {
random_line_split
models.py
import datetime from django.db import models from django.core.exceptions import ValidationError def validate_year(year): if year is None:
if year < 1800 or year > datetime.datetime.now().year: raise ValidationError("Not a valid year.") def validate_day_of_month(day): if day is None: return # Days can be null elif day > 31 or day < 1: raise ValidationError("Not a valid day.") class Specimen(models.Model): """ ...
return # Years can be null
conditional_block
models.py
import datetime from django.db import models from django.core.exceptions import ValidationError def validate_year(year): if year is None: return # Years can be null if year < 1800 or year > datetime.datetime.now().year: raise ValidationError("Not a valid year.") def validate_day_of_month(d...
class Specimen(models.Model): """ A model of a herbarium_data specimen entry. """ MONTH_CHOICES = ( (1, "January"), (2, "February"), (3, "March"), (4, "April"), (5, "May"), (6, "June"), (7, "July"), (8, "August"), (9, "September...
if day is None: return # Days can be null elif day > 31 or day < 1: raise ValidationError("Not a valid day.")
identifier_body
models.py
import datetime from django.db import models from django.core.exceptions import ValidationError def validate_year(year): if year is None: return # Years can be null if year < 1800 or year > datetime.datetime.now().year: raise ValidationError("Not a valid year.") def validate_day_of_month(d...
year_collected = models.PositiveSmallIntegerField(null=True, validators=[validate_year]) month_collected = models.PositiveSmallIntegerField(null=True, choices=MONTH_CHOICES) day_collected = models.PositiveSmallIntegerField(null=True, validators=[validate_day_of_month]) collectors = models.TextField(def...
random_line_split
models.py
import datetime from django.db import models from django.core.exceptions import ValidationError def
(year): if year is None: return # Years can be null if year < 1800 or year > datetime.datetime.now().year: raise ValidationError("Not a valid year.") def validate_day_of_month(day): if day is None: return # Days can be null elif day > 31 or day < 1: raise ValidationEr...
validate_year
identifier_name
Control.py
# -*- coding: utf-8 -*- """ Created on Tue Dec 08 13:25:40 2015 @author: J. Alejandro Cardona """ from Board import * import pygame UP, LEFT, DOWN, RIGHT = 1, 2, 3, 4 juego = Board() _2 = pygame.image.load("2.jpg"); _2re = _2.get_rect() _4 = pygame.image.load("4.jpg"); _4re = _4.get_rect() _8 = pygam...
(key): # Este metodo se usa solo para jugar en modo consola if key == 'w': juego.move(UP) elif key == 's': juego.move(DOWN) elif key == 'a': juego.move(LEFT) elif key == 'd': juego.move(RIGHT)
read_key
identifier_name
Control.py
# -*- coding: utf-8 -*- """ Created on Tue Dec 08 13:25:40 2015 @author: J. Alejandro Cardona """ from Board import * import pygame UP, LEFT, DOWN, RIGHT = 1, 2, 3, 4 juego = Board() _2 = pygame.image.load("2.jpg"); _2re = _2.get_rect() _4 = pygame.image.load("4.jpg"); _4re = _4.get_rect() _8 = pygam...
juego.move(RIGHT)
conditional_block
Control.py
# -*- coding: utf-8 -*- """ Created on Tue Dec 08 13:25:40 2015 @author: J. Alejandro Cardona """ from Board import * import pygame UP, LEFT, DOWN, RIGHT = 1, 2, 3, 4 juego = Board() _2 = pygame.image.load("2.jpg"); _2re = _2.get_rect() _4 = pygame.image.load("4.jpg"); _4re = _4.get_rect() _8 = pygam...
if key == 'w': juego.move(UP) elif key == 's': juego.move(DOWN) elif key == 'a': juego.move(LEFT) elif key == 'd': juego.move(RIGHT)
identifier_body
Control.py
# -*- coding: utf-8 -*- """ Created on Tue Dec 08 13:25:40 2015 @author: J. Alejandro Cardona """ from Board import * import pygame UP, LEFT, DOWN, RIGHT = 1, 2, 3, 4 juego = Board() _2 = pygame.image.load("2.jpg"); _2re = _2.get_rect() _4 = pygame.image.load("4.jpg"); _4re = _4.get_rect() _8 = pygam...
if key == 'w': juego.move(UP) elif key == 's': juego.move(DOWN) elif key == 'a': juego.move(LEFT) elif key == 'd': juego.move(RIGHT)
512:(_512,_512re), 1024:(_1024,_1024re), 2048:(_2048,_2048re)} def read_key(key): # Este metodo se usa solo para jugar en modo consola
random_line_split
parser.rs
use std::io; use std::path::PathBuf; use super::read_config; use crate::modules::{ModuleResolutionError, ModuleResolutionErrorKind}; use crate::{ErrorKind, Input, Session}; #[test] fn parser_errors_in_submods_are_surfaced() { // See also https://github.com/rust-lang/rustfmt/issues/4126 let filename = "tests/...
(filename: &str) { let file = PathBuf::from(filename); let config = read_config(&file); let mut session = Session::<io::Stdout>::new(config, None); let _ = session.format(Input::File(filename.into())).unwrap(); assert!(session.has_parsing_errors()); } #[test] fn parser_creation_errors_on_entry_new_...
assert_parser_error
identifier_name
parser.rs
use std::io; use std::path::PathBuf; use super::read_config; use crate::modules::{ModuleResolutionError, ModuleResolutionErrorKind}; use crate::{ErrorKind, Input, Session}; #[test] fn parser_errors_in_submods_are_surfaced()
panic!("Expected parser error"); } } else { panic!("Expected ModuleResolution operation error"); } } fn assert_parser_error(filename: &str) { let file = PathBuf::from(filename); let config = read_config(&file); let mut session = Session::<io::Stdout>::new(config, None);...
{ // See also https://github.com/rust-lang/rustfmt/issues/4126 let filename = "tests/parser/issue-4126/lib.rs"; let input_file = PathBuf::from(filename); let exp_mod_name = "invalid"; let config = read_config(&input_file); let mut session = Session::<io::Stdout>::new(config, None); if let Er...
identifier_body
parser.rs
use std::io; use std::path::PathBuf; use super::read_config; use crate::modules::{ModuleResolutionError, ModuleResolutionErrorKind}; use crate::{ErrorKind, Input, Session}; #[test] fn parser_errors_in_submods_are_surfaced() { // See also https://github.com/rust-lang/rustfmt/issues/4126 let filename = "tests/...
#[test] fn crate_parsing_errors_on_unclosed_delims() { // See also https://github.com/rust-lang/rustfmt/issues/4466 let filename = "tests/parser/unclosed-delims/issue_4466.rs"; assert_parser_error(filename); }
}
random_line_split
parser.rs
use std::io; use std::path::PathBuf; use super::read_config; use crate::modules::{ModuleResolutionError, ModuleResolutionErrorKind}; use crate::{ErrorKind, Input, Session}; #[test] fn parser_errors_in_submods_are_surfaced() { // See also https://github.com/rust-lang/rustfmt/issues/4126 let filename = "tests/...
} fn assert_parser_error(filename: &str) { let file = PathBuf::from(filename); let config = read_config(&file); let mut session = Session::<io::Stdout>::new(config, None); let _ = session.format(Input::File(filename.into())).unwrap(); assert!(session.has_parsing_errors()); } #[test] fn parser_cre...
{ panic!("Expected ModuleResolution operation error"); }
conditional_block
CreateGroupDialog.tsx
import * as React from 'react'; import Button from '@material-ui/core/Button'; import BaseDialog from '../../Dialog/BaseDialog'; import CustomTextField from '../../common/CustomTextField'; export interface Props { className?: string; show: boolean; onInputChange: (e: React.ChangeEvent<HTMLInputElement>) =>...
export default CreateGroupDialog;
random_line_split
interact.rs
encila query report.Rmd --interact You can also print, set and clear the command prefix during the interactive session (see the shortcut keystrokes below). "#; help += &Yellow.paint("SHORTCUTS:\n").to_string(); for (keys, desc) in &[ ("--help", "Get help for the current command prefix"), ("^ ...
Owned(Yellow.dimmed().paint(candidate).to_string()) }
identifier_body
interact.rs
Style, }; let mut help = Style::new() .bold() .paint("Stencila CLI interactive mode\n\n") .to_string(); help += &Yellow.paint("ABOUT:").to_string(); help += r#" Interactive mode allows you to interact with the Stencila CLI without having to restart it. This is particula...
light_prompt<'b,
identifier_name
interact.rs
Style, }; let mut help = Style::new() .bold() .paint("Stencila CLI interactive mode\n\n") .to_string(); help += &Yellow.paint("ABOUT:").to_string(); help += r#" Interactive mode allows you to interact with the Stencila CLI without having to restart it. This is particula...
("Ctrl+C", "Cancel the current task (if any)"), ("Ctrl+D", "Exit interactive session"), ] { help += &format!(" {} {}\n", Green.paint(*keys), desc) } help } /// Run the interactive REPL #[tracing::instrument] pub async fn run<T>(mut prefix: Vec<String>, formats: &[String], histor...
("<< ", "Clear the command prefix"), ("$ ", "Ignore the command prefix for this command"), ("↑ ", "Go back through command history"), ("↓ ", "Go forward through command history"), ("? ", "Print this message"),
random_line_split
round.js
/*jslint browser: true, devel: true, node: true, ass: true, nomen: true, unparam: true, indent: 4 */ /** * @license * Copyright (c) 2015 The ExpandJS authors. All rights reserved. * This code may only be used under the BSD style license found at https://expandjs.github.io/LICENSE.txt * The complete set of authors ...
* ``` * * @function round * @param {number} number The reference number to format * @param {number} [precision = 0] The number of digits to be shown after the decimal point * @returns {number} Returns the number rounded up */ module.exports = function round(number, precision) { ...
random_line_split
hero.component.ts
import { ChangeDetectionStrategy, Component } from '@angular/core'; @Component({ selector: 'ngd-hero', styleUrls: ['./hero.component.scss'], template: ` <div class="block"> <h1>React Native: UI Kit, Theming and so on</h1> <div class="btns-wrapper"> <a class="btn get-started" routerLink="d...
{ }
NgdHeroComponent
identifier_name
hero.component.ts
import { ChangeDetectionStrategy, Component } from '@angular/core'; @Component({ selector: 'ngd-hero', styleUrls: ['./hero.component.scss'], template: ` <div class="block">
<a class="btn" href="https://play.google.com/store/apps/details?id=com.akveo.kittenTricks" target="_blank">Android Demo</a> </div> <div class="hero-features"> <div class="hero-feature"> <div class="feature-key"> 15+ </div> <h3 class="featu...
<h1>React Native: UI Kit, Theming and so on</h1> <div class="btns-wrapper"> <a class="btn get-started" routerLink="docs">Get Started</a> <a class="btn" href="https://itunes.apple.com/us/app/kitten-tricks/id1246143230" target="_blank">IOS Demo</a>
random_line_split
index.js
"use strict"; var yeoman = require('yeoman-generator'), glob = require('yeoman-generator/node_modules/glob'), _ = require('yeoman-generator/node_modules/lodash'), chalk = require('yeoman-generator/node_modules/chalk'), mkdirp = require('yeoman-generator/node_modules/mkdirp'), path = require('path'), exec = requir...
identifier_name
index.js
"use strict"; var yeoman = require('yeoman-generator'), glob = require('yeoman-generator/node_modules/glob'), _ = require('yeoman-generator/node_modules/lodash'), chalk = require('yeoman-generator/node_modules/chalk'), mkdirp = require('yeoman-generator/node_modules/mkdirp'), path = require('path'), exec = requir...
identifier_body
index.js
"use strict"; var yeoman = require('yeoman-generator'), glob = require('yeoman-generator/node_modules/glob'), _ = require('yeoman-generator/node_modules/lodash'), chalk = require('yeoman-generator/node_modules/chalk'), mkdirp = require('yeoman-generator/node_modules/mkdirp'), path = require('path'), exec = requir...
conditional_block
index.js
"use strict"; var yeoman = require('yeoman-generator'), glob = require('yeoman-generator/node_modules/glob'), _ = require('yeoman-generator/node_modules/lodash'), chalk = require('yeoman-generator/node_modules/chalk'), mkdirp = require('yeoman-generator/node_modules/mkdirp'), path = require('path'), exec = requir...
log(chalk.bold.green('资源已初始化,退出...')) setTimeout(function(){ process.exit(1) }, 200) } // 当前模板的全局配置数据,配置svn信息和命令执行的参数 this.gConfig = JSON.parse(fs.readFileSync(configPath, {encoding: 'utf8'})) }, // 2. 提问 prompting: function(){ var done = this.async() this.projectAuthor = process.env.USER ...
if(_.contains(dirs, 'src')){
random_line_split
AD_single.py
######################################################################## # # # Anomalous Diffusion # # # ############################...
sc.run()
random_line_split
GraphsLegendCustom.tsx
/* * SonarQube * Copyright (C) 2009-2019 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, o...
})} </div> ); }
);
random_line_split
CSV.js
module.exports = { doConvert: function(data) { return convert(data); } }; function
(data) { var converted = {}; converted.type = "FeatureCollection"; converted.features = []; var lines = data.split('\r\n'); // Skip first line, it is titles for(var i = 1;i < lines.length;i++) { var line = lines[i]; if(line.length === 0) { con...
convert
identifier_name
CSV.js
module.exports = { doConvert: function(data) { return convert(data); } };
{ var converted = {}; converted.type = "FeatureCollection"; converted.features = []; var lines = data.split('\r\n'); // Skip first line, it is titles for(var i = 1;i < lines.length;i++) { var line = lines[i]; if(line.length === 0) { continue; ...
function convert(data)
random_line_split
CSV.js
module.exports = { doConvert: function(data) { return convert(data); } }; function convert(data)
var feature = {}; var geometry = {}; var properties = {}; feature.type = "Feature"; feature.geometry = geometry; feature.properties = properties; geometry.type = "Point"; geometry.coordinates = [ parseFloat(field...
{ var converted = {}; converted.type = "FeatureCollection"; converted.features = []; var lines = data.split('\r\n'); // Skip first line, it is titles for(var i = 1;i < lines.length;i++) { var line = lines[i]; if(line.length === 0) { continue; ...
identifier_body
CSV.js
module.exports = { doConvert: function(data) { return convert(data); } }; function convert(data) { var converted = {}; converted.type = "FeatureCollection"; converted.features = []; var lines = data.split('\r\n'); // Skip first line, it is tit...
[ parseFloat(fields[4]), parseFloat(fields[5]) ]; properties.name = fields[0]; properties.address = fields[1]; properties.accessibilty = fields[2]; if(fields[3] !== "No") { properties.transitStop = parseInt(fields[3]); ...
{ var line = lines[i]; if(line.length === 0) { continue; } var fields = line.split(','); var feature = {}; var geometry = {}; var properties = {}; feature.type = "Feature"; feature.geometry = geometry; ...
conditional_block
Layout.js
import React, { Component, PropTypes } from "react" import LoginPage from "./LoginPage" import CollectPage from "./CollectPage" import CreateStreamPageConnected from "./CreateStream/index.js" import Message from "components/Message" import classnames from "classnames" import storage from 'storage' import Terms from "./...
} onLogOut = (e) => { e && typeof e.preventDefault === "function" && e.preventDefault() this.logOut() } logOut = () => { storage.clear(); this.setState({ user: null, token: null, error: null }); } handleTermsSubmit = ({ cookies, currentTab }) => { stor...
{ this.setState({ error }) }
conditional_block
Layout.js
import React, { Component, PropTypes } from "react" import LoginPage from "./LoginPage" import CollectPage from "./CollectPage" import CreateStreamPageConnected from "./CreateStream/index.js" import Message from "components/Message" import classnames from "classnames" import storage from 'storage' import Terms from "./...
(props) { super(props) this.state = { token: storage.getItem('token'), user: JSON.parse(storage.getItem('user')), cookies: JSON.parse(storage.getItem('cookies')), currentTab: JSON.parse(storage.getItem('currentTab')), isCreatingStream: false, ...
constructor
identifier_name
Layout.js
import React, { Component, PropTypes } from "react" import LoginPage from "./LoginPage" import CollectPage from "./CollectPage" import CreateStreamPageConnected from "./CreateStream/index.js" import Message from "components/Message" import classnames from "classnames" import storage from 'storage' import Terms from "./...
onClick = () => { this.setState({ loading: true }) this.props.fn() .then(() => this.setState({ loading: false })) .catch(() => this.setState({ loading: false })) } render() { return ( <button autoFocus className={classnames("...
} state = { loading: false, }
random_line_split
Layout.js
import React, { Component, PropTypes } from "react" import LoginPage from "./LoginPage" import CollectPage from "./CollectPage" import CreateStreamPageConnected from "./CreateStream/index.js" import Message from "components/Message" import classnames from "classnames" import storage from 'storage' import Terms from "./...
if (!user) { return null } return ( <div style={{width: '100%'}}> { isCreatingStream ? ( <CreateStreamPageConnected onDone={this.closeCreatingStream} ...
{ const { user, token, isCreatingStream, error, currentTab } = this.state if (!currentTab) { return ( <Terms onSubmit={this.handleTermsSubmit} /> ) } if (!token) { return ( <div> <LoginPage ...
identifier_body
mod.rs
.*` parameters listed below. //! //! ## `rust-rdkafka` producers //! //! `rust-rdkafka` (rdkafka for brevity) provides two sets of producers: low //! level and high level. //! //! ### Low-level producers //! //! The lowest level producer provided by rdkafka is called [`BaseProducer`]. //! The goal of the `BaseProducer`...
; impl ClientContext for DefaultProducerContext {} impl ProducerContext for DefaultProducerContext { type DeliveryOpaque = (); fn delivery(&self, _: &DeliveryResult<'_>, _: Self::DeliveryOpaque) {} } /// Common trait for all producers. pub trait Producer<C = DefaultProducerContext> where C: ProducerConte...
DefaultProducerContext
identifier_name
mod.rs
.max.*` parameters listed below. //! //! ## `rust-rdkafka` producers //! //! `rust-rdkafka` (rdkafka for brevity) provides two sets of producers: low //! level and high level. //! //! ### Low-level producers //! //! The lowest level producer provided by rdkafka is called [`BaseProducer`]. //! The goal of the `BaseProdu...
/// failed to). The `DeliveryOpaque` will be the one provided by the user /// when calling send. fn delivery(&self, delivery_result: &DeliveryResult<'_>, delivery_opaque: Self::DeliveryOpaque); } /// An inert producer context that can be used when customizations are not /// required. #[derive(Clone)] pub s...
/// the producer when producing a message, and returned to the `delivery` /// method once the message has been delivered, or failed to. type DeliveryOpaque: IntoOpaque; /// This method will be called once the message has been delivered (or
random_line_split
useObjectValuesAndEntries1.js
//// [useObjectValuesAndEntries1.ts] var o = { a: 1, b: 2 }; for (var x of Object.values(o)) { let y = x; } var entries = Object.entries(o); // <-- entries: ['a' | 'b', number][] var entries1 = Object.entries(1); // <-- entries: [string, any][] var entries2 = Object.entries({a: true, b: 2}) // ['a' | 'b', numb...
//// [useObjectValuesAndEntries1.js] var o = { a: 1, b: 2 }; for (var _i = 0, _a = Object.values(o); _i < _a.length; _i++) { var x = _a[_i]; var y = x; } var entries = Object.entries(o); // <-- entries: ['a' | 'b', number][] var entries1 = Object.entries(1); // <-- entries: [string, any][] var entries2 ...
random_line_split
useObjectValuesAndEntries1.js
//// [useObjectValuesAndEntries1.ts] var o = { a: 1, b: 2 }; for (var x of Object.values(o)) { let y = x; } var entries = Object.entries(o); // <-- entries: ['a' | 'b', number][] var entries1 = Object.entries(1); // <-- entries: [string, any][] var entries2 = Object.entries({a: true, b: 2}) // ['a' | 'b', numb...
var entries = Object.entries(o); // <-- entries: ['a' | 'b', number][] var entries1 = Object.entries(1); // <-- entries: [string, any][] var entries2 = Object.entries({ a: true, b: 2 }); // ['a' | 'b', number | boolean][] var entries3 = Object.entries({}); // [never, any][]
{ var x = _a[_i]; var y = x; }
conditional_block
cleanup_site_pins.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Copyright 2020-2022 F4PGA Authors # # 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 # # Unl...
tile_prefix = tile_name + '/' site_pin_to_wires = {} for node in nodes: if len(node['site_pins']) == 0: continue wire_names = [ wire for wire in node['wires'] if wire.startswith(tile_prefix) ] assert len(wire_names) == 1, (node, tile_prefix) ...
""" # Remove tile prefix (e.g. CLBLM_L_X8Y149/) from node names. # Routing resources will not have the prefix.
random_line_split
cleanup_site_pins.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Copyright 2020-2022 F4PGA Authors # # 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 # # Unl...
return min_x_coord, min_y_coord def create_site_pin_to_wire_maps(tile_name, nodes): """ Create a map from site_pin names to nodes. Create a mapping from site pins to tile local wires. For each node that is attached to a site pin, there should only be 1 tile local wire. """ # Remove tile prefix ...
""" Find the coordinates of each site within the tile, and then subtract the smallest coordinate to re-origin them all to be relative to the tile. """ if len(sites) == 0: return 0, 0 def inner_(): for site in sites: coordinate = SITE_COORDINATE_PATTERN.match(site['name']) ...
identifier_body
cleanup_site_pins.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Copyright 2020-2022 F4PGA Authors # # 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 # # Unl...
else: print( ('***WARNING***: Site pin {} for tile type {} is not connected, ' 'make sure all instaces of this tile type has this site_pin ' 'disconnected.').format(site_pin['name'], s...
site_pin['wire'] = site_pin_to_wires[site_pin['name']]
conditional_block
cleanup_site_pins.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Copyright 2020-2022 F4PGA Authors # # 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 # # Unl...
(): site_pins = json5.load(sys.stdin) output_site_pins = {} output_site_pins["tile_type"] = site_pins["tile_type"] output_site_pins["sites"] = copy.deepcopy(site_pins["sites"]) site_pin_to_wires = create_site_pin_to_wire_maps(site_pins['tile_name'], ...
main
identifier_name
pySpike.py
#!/bin/python2 """ ##################################### # iSpike-like joint conversion # ##################################### """ class sensNetIn(): #TODO: explain XD ''' This object gets as input and returns as output: ''' from sys import exit def __init__(self, ...
else: self._angle = input_angle # Set input current to neurons current_input = [] for i in range(self.size): current_input.append( (i , self._constant_current + self._current_factor * self._normal_distribution.pd...
print("ERROR: input angle not in range! (%d is too low)" % (input_angle)) self._angle = self._min_angle
conditional_block
pySpike.py
#!/bin/python2 """ ##################################### # iSpike-like joint conversion # ##################################### """ class sensNetIn(): #TODO: explain XD ''' This object gets as input and returns as output: ''' from sys import exit def __init__(self, ...
# Set up current variables current_variables = [0.0] * neuron_number # Populate the current variable angles current_variable_angles = [0.0] * neuron_number for n in range(neuron_number): current_variable_angles[n] = min_angle + n * angle_dist #Set globals ...
neuron_number = len(neuron_idx) if neuron_number < 2: exit("FATAL ERROR: pySpike - You need at least 2 output neurons") # Calculate angle covered by each current variable angle_dist = (max_angle - min_angle) / (neuron_number - 1)
random_line_split
pySpike.py
#!/bin/python2 """ ##################################### # iSpike-like joint conversion # ##################################### """ class sensNetIn(): #TODO: explain XD ''' This object gets as input and returns as output: ''' from sys import exit def __init__(self, ...
self.missing_steps = integration_steps self.current_angle = None def step(self, fired): #same as iSpike setFiring() pattern = [1 if n in fired else 0 for n in self.neuron_idx] self.current_variables =\ [x + y for x, y in zip(pattern, self.current_variables)] ...
self.neuron_idx = neuron_idx neuron_number = len(neuron_idx) if neuron_number < 2: exit("FATAL ERROR: pySpike - You need at least 2 output neurons") # Calculate angle covered by each current variable angle_dist = (max_angle - min_angle) / (neuron_number - 1) # Set up ...
identifier_body
pySpike.py
#!/bin/python2 """ ##################################### # iSpike-like joint conversion # ##################################### """ class sensNetIn(): #TODO: explain XD ''' This object gets as input and returns as output: ''' from sys import exit def __init__(self, ...
(self, fired): #same as iSpike setFiring() pattern = [1 if n in fired else 0 for n in self.neuron_idx] self.current_variables =\ [x + y for x, y in zip(pattern, self.current_variables)] self.missing_steps -= 1 #same as iSpike step() if not self.missing_steps: ...
step
identifier_name
logo-badge.tsx
import React from "react"; import posed from "react-pose"; const SouthwestAnglePath = posed.path({ end: { opacity: 1, transform: "translate(0, 0)", transition: { delay: 500, duration: 1000, ease: "anticipate" }, }, start: { opacity: 0, transform: "translate(10, -10)" }, }); const NortheastAnglePath ...
</svg> ); }; export default LogoBadge;
random_line_split
common.py
from contextlib import contextmanager from fnmatch import fnmatch import stat from pyrsistent import pset import attr from filesystems import Path, exceptions def _realpath(fs, path, seen=pset()): """ .. warning:: The ``os.path`` module's realpath does not error or warn about loops, but we ...
binary = attr.ib() @read.default def read_default(self): return self.activity == "r" @write.default def write_default(self): return self.activity == "w" @append.default def append_default(self): return self.activity == "a" @text.default def text_default(se...
random_line_split
common.py
from contextlib import contextmanager from fnmatch import fnmatch import stat from pyrsistent import pset import attr from filesystems import Path, exceptions def _realpath(fs, path, seen=pset()): """ .. warning:: The ``os.path`` module's realpath does not error or warn about loops, but we ...
@append.default def append_default(self): return self.activity == "a" @text.default def text_default(self): return self.mode == "t" @binary.default def binary_default(self): return self.mode == "b" @activity.validator def activity_validator(self, attribute, v...
return self.activity == "w"
identifier_body
common.py
from contextlib import contextmanager from fnmatch import fnmatch import stat from pyrsistent import pset import attr from filesystems import Path, exceptions def _realpath(fs, path, seen=pset()): """ .. warning:: The ``os.path`` module's realpath does not error or warn about loops, but we ...
(self): return self.mode == "b" @activity.validator def activity_validator(self, attribute, value): options = ("r", "w", "a") if value not in options: raise exceptions.InvalidMode( "Mode must start with one of {} but found {}".format( rep...
binary_default
identifier_name
common.py
from contextlib import contextmanager from fnmatch import fnmatch import stat from pyrsistent import pset import attr from filesystems import Path, exceptions def _realpath(fs, path, seen=pset()): """ .. warning:: The ``os.path`` module's realpath does not error or warn about loops, but we ...
return _FileMode(**parameters)
parameters["mode"] = rest
conditional_block
armv7s_apple_ios.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
() -> TargetResult { let base = opts(Arch::Armv7s)?; Ok(Target { llvm_target: "armv7s-apple-ios".to_string(), target_endian: "little".to_string(), target_pointer_width: "32".to_string(), target_c_int_width: "32".to_string(), data_layout: "e-m:o-p:32:32-f64:32:64-v64:32:64...
target
identifier_name
armv7s_apple_ios.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
options: TargetOptions { features: "+v7,+vfp4,+neon".to_string(), max_atomic_width: Some(64), abi_blacklist: super::arm_base::abi_blacklist(), .. base } }) }
target_env: String::new(), target_vendor: "apple".to_string(), linker_flavor: LinkerFlavor::Gcc,
random_line_split
armv7s_apple_ios.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
}
{ let base = opts(Arch::Armv7s)?; Ok(Target { llvm_target: "armv7s-apple-ios".to_string(), target_endian: "little".to_string(), target_pointer_width: "32".to_string(), target_c_int_width: "32".to_string(), data_layout: "e-m:o-p:32:32-f64:32:64-v64:32:64-v128:32:128-a:0:32...
identifier_body
store_test.py
from __future__ import absolute_import from __future__ import unicode_literals import io import os.path import sqlite3 import mock import pytest import six from pre_commit.store import _get_default_directory from pre_commit.store import Store from pre_commit.util import cmd_output from pre_commit.util import cwd fro...
def test_require_created_when_directory_exists_but_not_db(store): # In versions <= 0.3.5, there was no sqlite db causing a need for # backward compatibility os.makedirs(store.directory) store.require_created() assert os.path.exists(store.db_path)
store.require_created() with sqlite3.connect(store.db_path) as db: db.execute( 'INSERT INTO repos (repo, ref, path) ' 'VALUES ("fake_repo", "fake_ref", "fake_path")', ) assert store.clone('fake_repo', 'fake_ref') == 'fake_path'
identifier_body
store_test.py
from __future__ import absolute_import from __future__ import unicode_literals import io import os.path import sqlite3 import mock import pytest import six from pre_commit.store import _get_default_directory from pre_commit.store import Store from pre_commit.util import cmd_output from pre_commit.util import cwd fro...
if thing.startswith('repo') ] assert things_starting_with_repo == [] def test_clone_when_repo_already_exists(store): # Create an entry in the sqlite db that makes it look like the repo has # been cloned. store.require_created() with sqlite3.connect(store.db_path) as db: db.exe...
except Exception as e: assert '/i_dont_exist_lol' in six.text_type(e) things_starting_with_repo = [ thing for thing in os.listdir(store.directory)
random_line_split
store_test.py
from __future__ import absolute_import from __future__ import unicode_literals import io import os.path import sqlite3 import mock import pytest import six from pre_commit.store import _get_default_directory from pre_commit.store import Store from pre_commit.util import cmd_output from pre_commit.util import cwd fro...
def test_store_require_created_does_not_create_twice(store): assert not os.path.exists(store.directory) store.require_created() # We intentionally delete the directory here so we can figure out if it # calls it again. rmtree(store.directory) assert not os.path.exists(store.directory) # Ca...
assert text_line in readme_contents
conditional_block