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 |
|---|---|---|---|---|
4f8bd7cac829_clean_db.py | """Clean db
Revision ID: 4f8bd7cac829
Revises: 3f249e0d2769
Create Date: 2014-01-09 14:03:13.997656
"""
# revision identifiers, used by Alembic.
revision = '4f8bd7cac829'
down_revision = '3f249e0d2769'
from alembic import op
import sqlalchemy as sa
def upgrade():
''' Drop the columns calendar_multiple_meeting... | op.alter_column(
'meetings',
column_name='meeting_location',
name='meeting_region',
type_=sa.String(100),
existing_type=sa.Text)
| ''' Add the columns calendar_multiple_meetings and
calendar_regional_meetings and rename meeting_location into
meeting_region.
'''
op.add_column(
'calendars',
sa.Column(
'calendar_multiple_meetings',
sa.Boolean, default=False,
nullable=False
)
... | identifier_body |
4f8bd7cac829_clean_db.py | """Clean db
Revision ID: 4f8bd7cac829
Revises: 3f249e0d2769
Create Date: 2014-01-09 14:03:13.997656
""" |
from alembic import op
import sqlalchemy as sa
def upgrade():
''' Drop the columns calendar_multiple_meetings and
calendar_regional_meetings and rename meeting_region into
meeting_location.
'''
op.drop_column('calendars', 'calendar_multiple_meetings')
op.drop_column('calendars', 'calendar_reg... |
# revision identifiers, used by Alembic.
revision = '4f8bd7cac829'
down_revision = '3f249e0d2769' | random_line_split |
main.py | from os.path import dirname, join
from math import ceil
import numpy as np
from bokeh.io import curdoc
from bokeh.layouts import row, column, widgetbox
from bokeh.models import ColumnDataSource, Slider, Div
from bokeh.plotting import figure
import audio
from audio import MAX_FREQ, TIMESLICE, NUM_BINS
from waterfall ... | # all the x-values, if the length has not changed
if len(signal) == len(signal_source.data['y']):
signal_source.data['y'] = signal*gain.value
else:
t = np.linspace(0, TIMESLICE, len(signal))
signal_source.data = dict(t=t, y=signal*gain.value)
if len(spectrum) == len(spectrum_so... | # seems to be a problem with Array property, using List for now
waterfall_renderer.latest = spectrum.tolist()
waterfall_plot.y_range.end = freq.value*0.001
# the if-elses below are small optimization: avoid computing and sending | random_line_split |
main.py | from os.path import dirname, join
from math import ceil
import numpy as np
from bokeh.io import curdoc
from bokeh.layouts import row, column, widgetbox
from bokeh.models import ColumnDataSource, Slider, Div
from bokeh.plotting import figure
import audio
from audio import MAX_FREQ, TIMESLICE, NUM_BINS
from waterfall ... |
eq_source.data['alpha'] = np.hstack(alphas)
curdoc().add_periodic_callback(update, 80)
controls = row(widgetbox(gain), widgetbox(freq))
plots = column(waterfall_plot, row(column(signal_plot, spectrum_plot), eq))
curdoc().add_root(desc)
curdoc().add_root(controls)
curdoc().add_root(plots)
| a = np.zeros_like(eq_range)
N = int(ceil(x))
a[:N] = (1 - eq_range[:N]*0.05)
alphas.append(a) | conditional_block |
main.py | from os.path import dirname, join
from math import ceil
import numpy as np
from bokeh.io import curdoc
from bokeh.layouts import row, column, widgetbox
from bokeh.models import ColumnDataSource, Slider, Div
from bokeh.plotting import figure
import audio
from audio import MAX_FREQ, TIMESLICE, NUM_BINS
from waterfall ... | spectrum_plot.x_range.end = freq.value*0.001
alphas = []
for x in bins:
a = np.zeros_like(eq_range)
N = int(ceil(x))
a[:N] = (1 - eq_range[:N]*0.05)
alphas.append(a)
eq_source.data['alpha'] = np.hstack(alphas)
curdoc().add_periodic_callback(update, 80)
controls = row(w... | signal, spectrum, bins = audio.data['values']
# seems to be a problem with Array property, using List for now
waterfall_renderer.latest = spectrum.tolist()
waterfall_plot.y_range.end = freq.value*0.001
# the if-elses below are small optimization: avoid computing and sending
# all the x-values, if ... | identifier_body |
main.py | from os.path import dirname, join
from math import ceil
import numpy as np
from bokeh.io import curdoc
from bokeh.layouts import row, column, widgetbox
from bokeh.models import ColumnDataSource, Slider, Div
from bokeh.plotting import figure
import audio
from audio import MAX_FREQ, TIMESLICE, NUM_BINS
from waterfall ... | ():
signal, spectrum, bins = audio.data['values']
# seems to be a problem with Array property, using List for now
waterfall_renderer.latest = spectrum.tolist()
waterfall_plot.y_range.end = freq.value*0.001
# the if-elses below are small optimization: avoid computing and sending
# all the x-val... | update | identifier_name |
LastLocationProvider.tsx | import * as React from 'react';
import * as PropTypes from 'prop-types';
import { RouteComponentProps, withRouter } from 'react-router-dom';
import LastLocationContext, { LastLocationType } from './LastLocationContext';
import { Assign } from './types';
import { hasBeenPrevented, prevent, shouldPrevent } from './preven... | return {
currentLocation: props.location,
};
}
readonly state: State = {
currentLocation: null,
};
render() {
const { children } = this.props;
return (
<LastLocationContext.Provider value={lastLocation}>{children}</LastLocationContext.Provider>
);
}
}
export const getLa... | random_line_split | |
LastLocationProvider.tsx | import * as React from 'react';
import * as PropTypes from 'prop-types';
import { RouteComponentProps, withRouter } from 'react-router-dom';
import LastLocationContext, { LastLocationType } from './LastLocationContext';
import { Assign } from './types';
import { hasBeenPrevented, prevent, shouldPrevent } from './preven... |
if (shouldPrevent(nextLocation) && !hasBeenPrevented(nextLocation)) {
prevent(nextLocation);
return;
}
lastLocation = { ...location };
};
interface Props extends RouteComponentProps {
watchOnlyPathname: boolean;
children: React.ReactNode;
}
type State = Readonly<{
currentLocation: LastLocationT... | {
return;
} | conditional_block |
LastLocationProvider.tsx | import * as React from 'react';
import * as PropTypes from 'prop-types';
import { RouteComponentProps, withRouter } from 'react-router-dom';
import LastLocationContext, { LastLocationType } from './LastLocationContext';
import { Assign } from './types';
import { hasBeenPrevented, prevent, shouldPrevent } from './preven... | extends React.Component<Props, State> {
static propTypes = {
watchOnlyPathname: PropTypes.bool,
children: PropTypes.node.isRequired,
};
static defaultProps: Pick<Props, 'watchOnlyPathname'> = {
watchOnlyPathname: false,
};
static getDerivedStateFromProps(props: Props, state: State) {
update... | LastLocationProvider | identifier_name |
setup.py | #! /usr/bin/env python
import os
from setuptools import setup
readme = os.path.join(os.path.dirname(__file__), 'README.md')
setup(name = 'bottleneck',
version = '0.1.0',
description = 'performance report generator for OpenMP programs in GNU/Linux',
long_description = open(readme).read(),
auth... | zip_safe = False,
test_suite = 'tests',
# include_package_data = True,
# install_requires=[ 'numpy', 'scipy', 'matplotlib' ],
) | ], | random_line_split |
issue-60726.rs | use std::marker::PhantomData;
pub struct True;
pub struct False;
pub trait InterfaceType{
type Send;
}
|
pub struct DynTrait<I>{
_interface:PhantomData<fn()->I>,
_unsync_unsend:PhantomData<::std::rc::Rc<()>>,
}
unsafe impl<I> Send for DynTrait<I>
where
I:InterfaceType<Send=True>
{}
// @has issue_60726/struct.IntoIter.html
// @has - '//*[@id="synthetic-implementations-list"]//*[@class="impl has-srclink"]//h... | pub struct FooInterface<T>(PhantomData<fn()->T>);
impl<T> InterfaceType for FooInterface<T> {
type Send=False;
} | random_line_split |
issue-60726.rs | use std::marker::PhantomData;
pub struct True;
pub struct | ;
pub trait InterfaceType{
type Send;
}
pub struct FooInterface<T>(PhantomData<fn()->T>);
impl<T> InterfaceType for FooInterface<T> {
type Send=False;
}
pub struct DynTrait<I>{
_interface:PhantomData<fn()->I>,
_unsync_unsend:PhantomData<::std::rc::Rc<()>>,
}
unsafe impl<I> Send for DynTrait<I>
wh... | False | identifier_name |
duplicate.rs | // Copyright 2014 Pierre Talbot (IRCAM)
// 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... |
}
struct DuplicateItem<'a, Item>
{
cx: &'a ExtCtxt<'a>,
items: HashMap<Ident, Item>,
has_duplicate: bool,
what_is_duplicated: String
}
impl<'a, Item> DuplicateItem<'a, Item> where
Item: ItemIdent + ItemSpan
{
pub fn analyse<ItemIter>(cx: &'a ExtCtxt<'a>, iter: ItemIter, item_kind: String)
-> Partial<H... | {
self.name.span.clone()
} | identifier_body |
duplicate.rs | // Copyright 2014 Pierre Talbot (IRCAM)
// 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... |
else {
others.push(item);
}
}
DuplicateItem::analyse(cx, functions.into_iter(), String::from("rust function"))
.map(move |functions| {
grammar.rust_functions = functions;
grammar.rust_items = others;
grammar
})
}
impl ItemIdent for rust::Item {
fn ident(&self) -> Ident {
... | {
functions.push(item);
} | conditional_block |
duplicate.rs | // Copyright 2014 Pierre Talbot (IRCAM)
// 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... | (&self) -> Ident {
self.deref().ident()
}
}
impl<InnerItem: ItemSpan> ItemSpan for rust::P<InnerItem> {
fn span(&self) -> Span {
self.deref().span()
}
}
impl ItemIdent for Rule {
fn ident(&self) -> Ident {
self.name.node.clone()
}
}
impl ItemSpan for Rule {
fn span(&self) -> Span {
self.n... | ident | identifier_name |
duplicate.rs | // Copyright 2014 Pierre Talbot (IRCAM)
// 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... | }
fn duplicate_items(&self, pre: &Item, current: Item) {
self.cx.span_err(current.span(), format!(
"duplicate definition of {} `{}`",
self.what_is_duplicated, current.ident()).as_str());
self.cx.span_note(pre.span(), format!(
"previous definition of {} `{}` here",
self.what_is_dupli... | } else {
self.items.insert(ident, item);
}
}
self | random_line_split |
glass_ard_ground_truth.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 3 of the License, or
(at your option) any later version.
Written (W) 2013 Heiko Strathmann
"""
from kameleon_mcmc.distribution.Gauss... | experiment_dir = experiment_dir_base + str(os.path.abspath(sys.argv[0])).split(os.sep)[-1].split(".")[0] + os.sep
print "running experiments", n, "times at base", experiment_dir
# load data
data,labels=GPData.get_glass_data()
# normalise and whiten dataset
data-=mean(data, 0)
L=cholesky... | # loop over parameters here
| random_line_split |
glass_ard_ground_truth.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 3 of the License, or
(at your option) any later version.
Written (W) 2013 Heiko Strathmann
"""
from kameleon_mcmc.distribution.Gauss... |
experiment_dir_base = str(sys.argv[1])
n = int(str(sys.argv[2]))
# loop over parameters here
experiment_dir = experiment_dir_base + str(os.path.abspath(sys.argv[0])).split(os.sep)[-1].split(".")[0] + os.sep
print "running experiments", n, "times at base", experiment_dir
# loa... | print "usage:", str(sys.argv[0]).split(os.sep)[-1], "<experiment_dir_base> <number_of_experiments>"
print "example:"
print "python " + str(sys.argv[0]).split(os.sep)[-1] + " /nfs/nhome/live/ucabhst/kameleon_experiments/ 3"
exit() | conditional_block |
sudoku_solve.rs | // Part of Cosmos by OpenGenus
const N: usize = 9;
const UNASSIGNED: u8 = 0;
type Board = [[u8; N]; N];
fn solve_sudoku(grid: &mut Board) -> bool {
let row;
let col;
if let Some((r, c)) = find_unassigned_cells(&grid) {
row = r;
col = c;
} else {
// SOLVED
return true;
... |
fn print_grid(grid: &Board) {
for row in grid.iter().take(N) {
for col in 0..N {
print!("{} ", row[col]);
}
println!();
}
}
#[test]
fn test1() {
let mut board = [
[3, 0, 6, 5, 0, 8, 4, 0, 0],
[5, 2, 0, 0, 0, 0, 0, 0, 0],
[0, 8, 7, 0, 0, 0, 0, ... | {
for (row, _) in grid.iter().enumerate().take(N) {
for col in 0..N {
if grid[row][col] == UNASSIGNED {
return Some((row, col));
}
}
}
None
} | identifier_body |
sudoku_solve.rs | // Part of Cosmos by OpenGenus
const N: usize = 9;
const UNASSIGNED: u8 = 0;
type Board = [[u8; N]; N];
fn solve_sudoku(grid: &mut Board) -> bool {
let row;
let col;
if let Some((r, c)) = find_unassigned_cells(&grid) {
row = r;
col = c;
} else {
// SOLVED
return true;
... | (grid: &Board) -> Option<(usize, usize)> {
for (row, _) in grid.iter().enumerate().take(N) {
for col in 0..N {
if grid[row][col] == UNASSIGNED {
return Some((row, col));
}
}
}
None
}
fn print_grid(grid: &Board) {
for row in grid.iter().take(N) {
... | find_unassigned_cells | identifier_name |
sudoku_solve.rs | // Part of Cosmos by OpenGenus
const N: usize = 9;
const UNASSIGNED: u8 = 0;
type Board = [[u8; N]; N];
fn solve_sudoku(grid: &mut Board) -> bool {
let row;
let col;
if let Some((r, c)) = find_unassigned_cells(&grid) {
row = r;
col = c;
} else {
// SOLVED
return true;
... | [4, 1, 6, 5, 3, 7, 2, 9, 8],
[5, 7, 9, 1, 8, 2, 4, 6, 3],
[3, 2, 8, 6, 9, 4, 7, 5, 1],
[9, 4, 1, 8, 2, 5, 6, 3, 7],
[7, 5, 2, 4, 6, 3, 8, 1, 9],
[8, 6, 3, 7, 1, 9, 5, 4, 2],
];
assert_eq!(board, solved);
} | random_line_split | |
sudoku_solve.rs | // Part of Cosmos by OpenGenus
const N: usize = 9;
const UNASSIGNED: u8 = 0;
type Board = [[u8; N]; N];
fn solve_sudoku(grid: &mut Board) -> bool {
let row;
let col;
if let Some((r, c)) = find_unassigned_cells(&grid) {
row = r;
col = c;
} else |
for num in 1..=9 {
if is_safe(&grid, row, col, num) {
grid[row][col] = num;
if solve_sudoku(grid) {
return true;
}
// Failed, try again
grid[row][col] = UNASSIGNED;
}
}
false
}
fn used_in_row(grid: &Board, row: u... | {
// SOLVED
return true;
} | conditional_block |
actionRegistry.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... |
public getWorkbenchAction(id: string): SyncActionDescriptor {
return this.workbenchActions[id] || null;
}
public getCategory(id: string): string {
return (this.mapActionIdToMeta[id] && this.mapActionIdToMeta[id].category) || null;
}
public getAlias(id: string): string {
return (this.mapActionIdToMeta[id]... | {
if (!this.workbenchActions[id]) {
return false;
}
delete this.workbenchActions[id];
delete this.mapActionIdToMeta[id];
return true;
} | identifier_body |
actionRegistry.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | implements IWorkbenchActionRegistry {
private workbenchActions: collections.IStringDictionary<SyncActionDescriptor>;
private mapActionIdToMeta: { [id: string]: IActionMeta; };
constructor() {
this.workbenchActions = Object.create(null);
this.mapActionIdToMeta = Object.create(null);
}
public registerWorkbenc... | WorkbenchActionRegistry | identifier_name |
actionRegistry.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... |
}
public unregisterWorkbenchAction(id: string): boolean {
if (!this.workbenchActions[id]) {
return false;
}
delete this.workbenchActions[id];
delete this.mapActionIdToMeta[id];
return true;
}
public getWorkbenchAction(id: string): SyncActionDescriptor {
return this.workbenchActions[id] || null;
... | {
this.workbenchActions[descriptor.id] = descriptor;
registerWorkbenchCommandFromAction(descriptor);
let meta: IActionMeta = { alias };
if (typeof category === 'string') {
meta.category = category;
}
this.mapActionIdToMeta[descriptor.id] = meta;
} | conditional_block |
actionRegistry.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | weight: weight,
when: when,
primary: keybindings && keybindings.primary,
secondary: keybindings && keybindings.secondary,
win: keybindings && keybindings.win,
mac: keybindings && keybindings.mac,
linux: keybindings && keybindings.linux
};
KeybindingsRegistry.registerCommandDesc(desc);
}
export functio... | let desc: ICommandDescriptor = {
id: descriptor.id,
handler: createCommandHandler(descriptor), | random_line_split |
menu.js | with a border
target.siblings().children( ".ui-state-active" ).removeClass( "ui-state-active" );
this.focus( event, target );
},
mouseleave: "collapseAll",
"mouseleave .ui-menu": "collapseAll",
focus: function( event, keepActiveItem ) {
// If there's already an active item, keep it active
/... |
switch ( event.keyCode ) {
case $.ui.keyCode.PAGE_UP:
this.previousPage( event );
break;
case $.ui.keyCode.PAGE_DOWN:
this.nextPage( event );
break;
case $.ui.keyCode.HOME:
this._move( "first", "first", event );
break;
case $.ui.keyCode.END:
this._move( "last", "last", event );
break... | {
return value.replace( /[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&" );
} | identifier_body |
menu.js | ) );
});
menus = submenus.add( this.element );
// Don't refresh list items that are already adapted
menus.children( ":not(.ui-menu-item):has(a)" )
.addClass( "ui-menu-item" )
.attr( "role", "presentation" )
.children( "a" )
.uniqueId()
.addClass( "ui-corner-all" )
.attr({
tabIndex:... | } else {
this.focus( event, this.activeMenu.children( ".ui-menu-item" )
[ !this.active ? "first" : "last" ]() ); | random_line_split | |
menu.js | class with a border
target.siblings().children( ".ui-state-active" ).removeClass( "ui-state-active" );
this.focus( event, target );
},
mouseleave: "collapseAll",
"mouseleave .ui-menu": "collapseAll",
focus: function( event, keepActiveItem ) {
// If there's already an active item, keep it active... | ( value ) {
return value.replace( /[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&" );
}
switch ( event.keyCode ) {
case $.ui.keyCode.PAGE_UP:
this.previousPage( event );
break;
case $.ui.keyCode.PAGE_DOWN:
this.nextPage( event );
break;
case $.ui.keyCode.HOME:
this._move( "first", "first", event );
... | escape | identifier_name |
menu.js | with a border
target.siblings().children( ".ui-state-active" ).removeClass( "ui-state-active" );
this.focus( event, target );
},
mouseleave: "collapseAll",
"mouseleave .ui-menu": "collapseAll",
focus: function( event, keepActiveItem ) {
// If there's already an active item, keep it active
/... |
break;
case $.ui.keyCode.ENTER:
case $.ui.keyCode.SPACE:
this._activate( event );
break;
case $.ui.keyCode.ESCAPE:
this.collapse( event );
break;
default:
preventDefault = false;
prev = this.previousFilter || "";
character = String.fromCharCode( event.keyCode );
skip = false;
cle... | {
this.expand( event );
} | conditional_block |
autocomplete.js | /* --- Made by justgoscha and licensed under MIT license --- */
var app = angular.module('autocomplete', []);
app.directive('autocomplete', function() {
var index = -1;
return {
restrict: 'E',
scope: {
searchParam: '=ngModel',
suggestions: '=data',
onType: '=onType',
onSelect: '=o... |
}
return $sce.trustAsHtml(input);
};
}]);
app.directive('suggestion', function(){
return {
restrict: 'A',
require: '^autocomplete', // ^look for controller on parents element
link: function(scope, element, attrs, autoCtrl){
element.bind('mouseenter', function() {
autoCtrl.preSele... | {
input = input.replace(exp, "<span class=\"highlight\">$1</span>");
} | conditional_block |
autocomplete.js | /* --- Made by justgoscha and licensed under MIT license --- */
var app = angular.module('autocomplete', []);
app.directive('autocomplete', function() {
var index = -1;
return {
restrict: 'E',
scope: {
searchParam: '=ngModel',
suggestions: '=data',
onType: '=onType',
onSelect: '=o... | }]);
app.directive('suggestion', function(){
return {
restrict: 'A',
require: '^autocomplete', // ^look for controller on parents element
link: function(scope, element, attrs, autoCtrl){
element.bind('mouseenter', function() {
autoCtrl.preSelect(attrs.val);
autoCtrl.setIndex(attrs.i... | return $sce.trustAsHtml(input);
}; | random_line_split |
customdestroy.py | from gi.repository import Gtk
"""
Since GTK+3 Gtk.CellRenderer doesn't have a destroy signal anymore.
We can do the cleanup in the python destructor method instead.
"""
class MyCellRenderer(Gtk.CellRenderer):
def __init__(self):
Gtk.CellRenderer.__init__(self)
def __del__(self):
print "cell... | treeview.connect("destroy", treeview_destroy_cb)
window.add(treeview)
treeview.show()
col = Gtk.TreeViewColumn()
treeview.append_column(col)
cel = MyCellRenderer()
col.pack_start(cel, expand=True)
Gtk.main() | treeview = Gtk.TreeView() | random_line_split |
customdestroy.py | from gi.repository import Gtk
"""
Since GTK+3 Gtk.CellRenderer doesn't have a destroy signal anymore.
We can do the cleanup in the python destructor method instead.
"""
class MyCellRenderer(Gtk.CellRenderer):
|
def window_destroy_cb(*kwargs):
print "window destroy"
Gtk.main_quit()
window = Gtk.Window(Gtk.WindowType.TOPLEVEL)
window.connect("destroy", window_destroy_cb)
window.show()
def treeview_destroy_cb(*kwargs):
print "treeview destroy"
treeview = Gtk.TreeView()
treeview.connect("destroy", treeview_dest... | def __init__(self):
Gtk.CellRenderer.__init__(self)
def __del__(self):
print "cellrenderer destroy"
def do_render(self, cairo_t, widget, background_area, cell_area, flags):
pass | identifier_body |
customdestroy.py | from gi.repository import Gtk
"""
Since GTK+3 Gtk.CellRenderer doesn't have a destroy signal anymore.
We can do the cleanup in the python destructor method instead.
"""
class | (Gtk.CellRenderer):
def __init__(self):
Gtk.CellRenderer.__init__(self)
def __del__(self):
print "cellrenderer destroy"
def do_render(self, cairo_t, widget, background_area, cell_area, flags):
pass
def window_destroy_cb(*kwargs):
print "window destroy"
Gtk.main_quit()
wi... | MyCellRenderer | identifier_name |
passwords_deletion_dialog.ts | // Copyright 2020 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.
/**
* @fileoverview 'settings-passwords-deletion-dialog' is a dialog that is
* optionally shown inside settings-clear-browsing-data-dialog after deletin... | () {
this.$.dialog.close();
}
}
customElements.define(
SettingsPasswordsDeletionDialogElement.is,
SettingsPasswordsDeletionDialogElement);
| onOkClick_ | identifier_name |
passwords_deletion_dialog.ts | // Copyright 2020 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.
/**
* @fileoverview 'settings-passwords-deletion-dialog' is a dialog that is
* optionally shown inside settings-clear-browsing-data-dialog after deletin... | customElements.define(
SettingsPasswordsDeletionDialogElement.is,
SettingsPasswordsDeletionDialogElement); | random_line_split | |
passwords_deletion_dialog.ts | // Copyright 2020 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.
/**
* @fileoverview 'settings-passwords-deletion-dialog' is a dialog that is
* optionally shown inside settings-clear-browsing-data-dialog after deletin... |
}
customElements.define(
SettingsPasswordsDeletionDialogElement.is,
SettingsPasswordsDeletionDialogElement);
| {
this.$.dialog.close();
} | identifier_body |
ProfilePicture.js | import React, { Component, PropTypes } from 'react';
import {
View,
Image,
Text,
StyleSheet
} from 'react-native';
import LinearGradient from 'react-native-linear-gradient';
const glassPrimary = '#d5d2da';
const glassSecondary = '#bb2130';
class | extends Component {
render() {
const profileImage = this.props.image;
return (
<View style={Styles.container}>
<Image
source={profileImage}
resizeMode='contain'
style={Styles.profilePic}>
</Image>
<LinearGradient
colors={[glassPrimary, gla... | ProfilePicture | identifier_name |
ProfilePicture.js | import React, { Component, PropTypes } from 'react';
import {
View,
Image,
Text,
StyleSheet
} from 'react-native';
import LinearGradient from 'react-native-linear-gradient';
const glassPrimary = '#d5d2da';
const glassSecondary = '#bb2130';
class ProfilePicture extends Component {
render() {
const profi... | colors={[glassPrimary, glassSecondary, glassPrimary]}
start={{x: 0.0, y: 0.1}} end={{x: 0.5, y: 1.0}}
style={Styles.frame}>
</LinearGradient>
</View>
)
}
}
const Styles = StyleSheet.create({
container: {
height: 120,
width: 70,
shadowColor: '#000',
shad... | </Image>
<LinearGradient | random_line_split |
ProfilePicture.js | import React, { Component, PropTypes } from 'react';
import {
View,
Image,
Text,
StyleSheet
} from 'react-native';
import LinearGradient from 'react-native-linear-gradient';
const glassPrimary = '#d5d2da';
const glassSecondary = '#bb2130';
class ProfilePicture extends Component {
render() |
}
const Styles = StyleSheet.create({
container: {
height: 120,
width: 70,
shadowColor: '#000',
shadowOffset: { width: 2, height: 2 },
shadowOpacity: 0.7,
shadowRadius: 2,
elevation: 3,
backgroundColor: 'transparent'
},
profilePic: {
height: 120,
width: 70,
shadowRadius: 2,
... | {
const profileImage = this.props.image;
return (
<View style={Styles.container}>
<Image
source={profileImage}
resizeMode='contain'
style={Styles.profilePic}>
</Image>
<LinearGradient
colors={[glassPrimary, glassSecondary, glassPrimary]}
... | identifier_body |
basic.rs | // run-pass
#![feature(trait_upcasting)]
#![allow(incomplete_features)]
trait Foo: PartialEq<i32> + std::fmt::Debug + Send + Sync {
fn a(&self) -> i32 {
10
}
fn z(&self) -> i32 {
11
}
fn y(&self) -> i32 {
12
}
}
trait Bar: Foo { | fn b(&self) -> i32 {
20
}
fn w(&self) -> i32 {
21
}
}
trait Baz: Bar {
fn c(&self) -> i32 {
30
}
}
impl Foo for i32 {
fn a(&self) -> i32 {
100
}
}
impl Bar for i32 {
fn b(&self) -> i32 {
200
}
}
impl Baz for i32 {
fn c(&self) -> i3... | random_line_split | |
basic.rs | // run-pass
#![feature(trait_upcasting)]
#![allow(incomplete_features)]
trait Foo: PartialEq<i32> + std::fmt::Debug + Send + Sync {
fn a(&self) -> i32 {
10
}
fn z(&self) -> i32 |
fn y(&self) -> i32 {
12
}
}
trait Bar: Foo {
fn b(&self) -> i32 {
20
}
fn w(&self) -> i32 {
21
}
}
trait Baz: Bar {
fn c(&self) -> i32 {
30
}
}
impl Foo for i32 {
fn a(&self) -> i32 {
100
}
}
impl Bar for i32 {
fn b(&self) -> i32... | {
11
} | identifier_body |
basic.rs | // run-pass
#![feature(trait_upcasting)]
#![allow(incomplete_features)]
trait Foo: PartialEq<i32> + std::fmt::Debug + Send + Sync {
fn a(&self) -> i32 {
10
}
fn z(&self) -> i32 {
11
}
fn y(&self) -> i32 {
12
}
}
trait Bar: Foo {
fn b(&self) -> i32 {
20
... | (&self) -> i32 {
100
}
}
impl Bar for i32 {
fn b(&self) -> i32 {
200
}
}
impl Baz for i32 {
fn c(&self) -> i32 {
300
}
}
fn main() {
let baz: &dyn Baz = &1;
let _: &dyn std::fmt::Debug = baz;
assert_eq!(*baz, 1);
assert_eq!(baz.a(), 100);
assert_eq!(baz... | a | identifier_name |
Main.js | import React, {Component, PropTypes} from 'react';
import MiddleArticleList from './MiddleArticleList';
import RightDetail from '../RightDetail';
import NoMatchImg from '../NoMatchImg';
import Detail from './Detail';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import {selectArticle... |
shouldComponentUpdate () {
return true;
}
componentWillUpdate () {
}
componentDidUpdate () {
}
componentWillUnmount () {
}
render () {
let children = (() => {
if (this.props.state.selectIdx != -1) {
return <Detail data={this.props.s... | {
} | identifier_body |
Main.js | import React, {Component, PropTypes} from 'react';
import MiddleArticleList from './MiddleArticleList';
import RightDetail from '../RightDetail';
import NoMatchImg from '../NoMatchImg';
import Detail from './Detail';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import {selectArticle... | } | random_line_split | |
Main.js | import React, {Component, PropTypes} from 'react';
import MiddleArticleList from './MiddleArticleList';
import RightDetail from '../RightDetail';
import NoMatchImg from '../NoMatchImg';
import Detail from './Detail';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import {selectArticle... | else {
return <NoMatchImg/>;
}
})();
return (<div className={styles.Main}>
<MiddleArticleList/>
<RightDetail>
{children}
</RightDetail>
</div>);
}
} | {
return <Detail data={this.props.state.select} save={this.props.saveArticle}
delete={this.props.deleteArticle}
saveing={this.props.state.saveing}
/>;
} | conditional_block |
Main.js | import React, {Component, PropTypes} from 'react';
import MiddleArticleList from './MiddleArticleList';
import RightDetail from '../RightDetail';
import NoMatchImg from '../NoMatchImg';
import Detail from './Detail';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import {selectArticle... | () {
}
componentDidUpdate () {
}
componentWillUnmount () {
}
render () {
let children = (() => {
if (this.props.state.selectIdx != -1) {
return <Detail data={this.props.state.select} save={this.props.saveArticle}
delete={th... | componentWillUpdate | identifier_name |
test_send_email_base_command.py | """
Tests for send_email_base_command
"""
import datetime
from unittest import skipUnless
import ddt
import pytz
from django.conf import settings
from mock import DEFAULT, Mock, patch
from openedx.core.djangoapps.schedules.management.commands import SendEmailBaseCommand
from openedx.core.djangoapps.site_configurati... | @skipUnless('openedx.core.djangoapps.schedules.apps.SchedulesConfig' in settings.INSTALLED_APPS,
"Can't test schedules if the app isn't installed")
class TestSendEmailBaseCommand(CacheIsolationTestCase): # lint-amnesty, pylint: disable=missing-class-docstring
def setUp(self): # lint-amnesty, pylint: ... |
@ddt.ddt
@skip_unless_lms | random_line_split |
test_send_email_base_command.py | """
Tests for send_email_base_command
"""
import datetime
from unittest import skipUnless
import ddt
import pytz
from django.conf import settings
from mock import DEFAULT, Mock, patch
from openedx.core.djangoapps.schedules.management.commands import SendEmailBaseCommand
from openedx.core.djangoapps.site_configurati... | self.command.enqueue.assert_any_call(offset, arg, kwarg=kwarg) # lint-amnesty, pylint: disable=no-member | conditional_block | |
test_send_email_base_command.py | """
Tests for send_email_base_command
"""
import datetime
from unittest import skipUnless
import ddt
import pytz
from django.conf import settings
from mock import DEFAULT, Mock, patch
from openedx.core.djangoapps.schedules.management.commands import SendEmailBaseCommand
from openedx.core.djangoapps.site_configurati... | (self):
with patch.object(self.command, 'send_emails') as send_emails:
self.command.handle(site_domain_name=self.site.domain, date='2017-09-29')
send_emails.assert_called_once_with(
self.site,
datetime.datetime(2017, 9, 29, tzinfo=pytz.UTC),
... | test_handle | identifier_name |
test_send_email_base_command.py | """
Tests for send_email_base_command
"""
import datetime
from unittest import skipUnless
import ddt
import pytz
from django.conf import settings
from mock import DEFAULT, Mock, patch
from openedx.core.djangoapps.schedules.management.commands import SendEmailBaseCommand
from openedx.core.djangoapps.site_configurati... |
def test_weeks_option(self):
with patch.object(self.command, 'enqueue') as enqueue:
self.command.handle(site_domain_name=self.site.domain, date='2017-09-29', weeks=12)
assert enqueue.call_count == 12
def test_send_emails(self):
with patch.multiple(
self.com... | with patch.object(self.command, 'send_emails') as send_emails:
self.command.handle(site_domain_name=self.site.domain, date='2017-09-29')
send_emails.assert_called_once_with(
self.site,
datetime.datetime(2017, 9, 29, tzinfo=pytz.UTC),
None
... | identifier_body |
game.ts | ///// <reference path="babylon.2.5.d.ts" />
import * as BABYLON from 'babylonjs';
import * as firebase from 'firebase';
// import { LeftPanel } from './ui/left-panel';
import { Gamer } from "./gamer";
import { UIService } from "../../providers/providers";
import { STATE } from "./logic/state";
import { AngularFireDa... | (
public canvasElement: HTMLElement) {
if (canvasElement != null) { this.setCanvas(canvasElement); }
this.creator = new Gamer();
this.joiner = new Gamer();
}
setCanvas(canvasElement: HTMLElement) {
this._canvas = canvasElement as HTMLCanvasElement;
this._engine = new BABYLON.Engine(this._... | constructor | identifier_name |
game.ts | ///// <reference path="babylon.2.5.d.ts" />
import * as BABYLON from 'babylonjs';
import * as firebase from 'firebase';
// import { LeftPanel } from './ui/left-panel';
import { Gamer } from "./gamer";
import { UIService } from "../../providers/providers";
import { STATE } from "./logic/state";
import { AngularFireDa... | },
(error: Error, committed: boolean, snapshot: firebase.database.DataSnapshot) => {
if (committed) {
if (snapshot.val().joiner.uid == user.uid) {
this.watchGame(key, ui);
} else {
ui.toastCreate("Game already joined. Please choose another.");
... | random_line_split | |
game.ts | ///// <reference path="babylon.2.5.d.ts" />
import * as BABYLON from 'babylonjs';
import * as firebase from 'firebase';
// import { LeftPanel } from './ui/left-panel';
import { Gamer } from "./gamer";
import { UIService } from "../../providers/providers";
import { STATE } from "./logic/state";
import { AngularFireDa... |
// switch (game.state) {
// case STATE.JOINED:
// joinedGame(game, gameRef);
// break;
// case STATE.TAKE_PICTURE:
// countDownToTakingPicture(gameRef, game);
// break;
// case STATE.UPLOADED_PICTURE:
// displayUploadedPicture(game);
... | {
let gameRef = this._ref.child(key);
gameRef.on("value", (snapshot) => {
let game = snapshot.val();
console.log("Game update:", game);
if (!game) {
ui.toastCreate("Game has finished. Please play again.");
let currentGame = {
state: STATE.COMPLETE
};
... | identifier_body |
game.ts | ///// <reference path="babylon.2.5.d.ts" />
import * as BABYLON from 'babylonjs';
import * as firebase from 'firebase';
// import { LeftPanel } from './ui/left-panel';
import { Gamer } from "./gamer";
import { UIService } from "../../providers/providers";
import { STATE } from "./logic/state";
import { AngularFireDa... |
this.creator = new Gamer();
this.joiner = new Gamer();
}
setCanvas(canvasElement: HTMLElement) {
this._canvas = canvasElement as HTMLCanvasElement;
this._engine = new BABYLON.Engine(this._canvas, true);
this._scene = new BABYLON.Scene(this._engine);
this._camera = new BABYLON.ArcRotateCam... | { this.setCanvas(canvasElement); } | conditional_block |
PermissionsWindow.js | /* | Copyright 2010-2012 Infracom & Eurotechnia (support@webcampak.com)
This file is part of the Webcampak project.
Webcampak 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 y... | random_line_split | |
__init__.py | #Made by Kerb
import sys
from com.l2scoria import Config
from com.l2scoria.gameserver.model.quest import State
from com.l2scoria.gameserver.model.quest import QuestState
from com.l2scoria.gameserver.model.quest.jython import QuestJython as JQuest
qn = "644_GraveRobberAnnihilation"
#Drop rate
DROP_CHANCE = 75
#Npc
... | def onTalk (self,npc,player):
htmltext = "<html><body>You are either not carrying out your quest or don't meet the criteria.</body></html>"
st = player.getQuestState(qn)
if st :
npcId = npc.getNpcId()
id = st.getState()
cond = st.getInt("cond")
if cond == 0 :
htmltext = "32017-01.... | def onEvent (self,event,st) :
cond = st.getInt("cond")
htmltext = event
if event == "32017-03.htm" :
if st.getPlayer().getLevel() < 20 :
htmltext = "32017-02.htm"
st.exitQuest(1)
else :
st.set("cond","1")
st.setState(STARTED)
st.playSound("ItemSound.que... | identifier_body |
__init__.py | #Made by Kerb
import sys
from com.l2scoria import Config
from com.l2scoria.gameserver.model.quest import State
from com.l2scoria.gameserver.model.quest import QuestState
from com.l2scoria.gameserver.model.quest.jython import QuestJython as JQuest
qn = "644_GraveRobberAnnihilation"
#Drop rate
DROP_CHANCE = 75
#Npc
... |
return
QUEST = Quest(644, qn, "Grave Robber Annihilation")
CREATED = State('Start', QUEST)
STARTED = State('Started', QUEST)
QUEST.setInitialState(CREATED)
QUEST.addStartNpc(KARUDA)
QUEST.addTalkId(KARUDA)
for i in MOBS :
QUEST.addKillId(i)
STARTED.addQuestDrop(KARUDA,ORC_GOODS,1) | if st.getState() == STARTED :
count = st.getQuestItemsCount(ORC_GOODS)
if st.getInt("cond") == 1 and count < 120 :
chance = DROP_CHANCE * Config.RATE_DROP_QUEST
numItems, chance = divmod(chance,100)
if st.getRandom(100) < chance :
numItems += 1
... | conditional_block |
__init__.py | #Made by Kerb
import sys
from com.l2scoria import Config
from com.l2scoria.gameserver.model.quest import State
from com.l2scoria.gameserver.model.quest import QuestState
from com.l2scoria.gameserver.model.quest.jython import QuestJython as JQuest
qn = "644_GraveRobberAnnihilation"
#Drop rate
DROP_CHANCE = 75
#Npc
... | (self,npc,player,isPet):
partyMember = self.getRandomPartyMember(player,"1")
if not partyMember: return
st = partyMember.getQuestState(qn)
if st :
if st.getState() == STARTED :
count = st.getQuestItemsCount(ORC_GOODS)
if st.getInt("cond") == 1 and count < 120 :
chance = D... | onKill | identifier_name |
__init__.py | #Made by Kerb
import sys
from com.l2scoria import Config
from com.l2scoria.gameserver.model.quest import State
from com.l2scoria.gameserver.model.quest import QuestState
from com.l2scoria.gameserver.model.quest.jython import QuestJython as JQuest
qn = "644_GraveRobberAnnihilation"
#Drop rate
DROP_CHANCE = 75
#Npc
... | if st :
if st.getState() == STARTED :
count = st.getQuestItemsCount(ORC_GOODS)
if st.getInt("cond") == 1 and count < 120 :
chance = DROP_CHANCE * Config.RATE_DROP_QUEST
numItems, chance = divmod(chance,100)
if st.getRandom(100) < chance :
nu... |
def onKill(self,npc,player,isPet):
partyMember = self.getRandomPartyMember(player,"1")
if not partyMember: return
st = partyMember.getQuestState(qn) | random_line_split |
__init__.py | import PyQt5 # this force pyqtgraph to deal with Qt5
# For matplotlib to Qt5 :
# * this avoid tinker problem when not installed
# * work better with GUI
# * trigger a warning on notebook
import matplotlib
import warnings
with warnings.catch_warnings():
try: ... | from .crosscorrelogramviewer import CrossCorrelogramViewer
from .peelerwindow import PeelerWindow
#main window
from .mainwindow import MainWindow
from .initializedatasetwindow import InitializeDatasetWindow, ChannelGroupWidget
from .probegeometryview import ProbeGeometryView
from .gpuselector import GpuSelector | from .traceviewer import PeelerTraceViewer
from .spikelists import SpikeList, ClusterSpikeList
from .waveformviewer import PeelerWaveformViewer
from .isiviewer import ISIViewer | random_line_split |
Analyzer.js | var Analyzer = function(sequelize) {
this.sequelize = sequelize;
this.dbName = sequelize.config.database;
};
Analyzer.prototype = {
sequelize: null,
dbName: null,
getInfo: function(cb) {
var self = this;
var db = {};
this.getTables(function(tables) {
var tablesLength = tables.length;
for(var i=0; i<t... | resultsFiltered.push(results[0][i][key]);
}
cb(resultsFiltered);
});
},
getFields: function(table, cb) {
this.sequelize.query('SHOW FULL COLUMNS FROM '+table).then(function(results) {
cb(results[0]);
});
},
setAssociations: function(db, cb) {
var self = this;
var tables = Object.keys(db);
v... | random_line_split | |
Analyzer.js | var Analyzer = function(sequelize) {
this.sequelize = sequelize;
this.dbName = sequelize.config.database;
};
Analyzer.prototype = {
sequelize: null,
dbName: null,
getInfo: function(cb) {
var self = this;
var db = {};
this.getTables(function(tables) {
var tablesLength = tables.length;
for(var i=0; i<t... | else {
ts.hasMany.push({
foreignTable: as.TABLE_NAME,
foreignKey: as.COLUMN_NAME,
});
db[as.TABLE_NAME].associations.belongsTo.push({
foreignTable: as.REFERENCED_TABLE_NAME,
foreignKey: as.COLUMN_NAME,
});
}
}
}
}
if(tablesNo... | {
ts.hasOne.push({
foreignTable: as.TABLE_NAME,
foreignKey: as.COLUMN_NAME,
});
db[as.TABLE_NAME].associations.hasOne.push({
foreignTable: as.REFERENCED_TABLE_NAME,
foreignKey: as.REFERENCED_COLUMN_NAME,
});
} | conditional_block |
main.rs | extern crate paint;
use paint::{ Layer, Canvas, Projection, Color, Size };
struct BigWhiteCircle;
impl Layer for BigWhiteCircle {
fn draw(&self, projection: Projection)->Color {
use std::cmp:: { max, min };
let origin_x = std::u32::MAX / 2;
let offset_x = max(projection.x, origin_x) - min(projection.x, origin_... |
}
struct TwoLayer<U: Layer, V: Layer> {
a: U, b: V
}
impl<U: Layer, V: Layer> Layer for TwoLayer<U, V> {
fn draw(&self, projection: Projection)->Color {
projection.proxy_split(|p|self.a.draw(p), |p|self.b.draw(p))
}
}
fn main() {
let args = std::os::args();
if args.len() == 2 {
match std::path::Path::new_o... | {
let ball = Ball { origin: Position(3f32, 30f32, 3f32), radius: 3f32 };
let light = Light { origin: Position(0f32, 0f32, 0f32) };
let eye = Position(3f32, 0f32, 3f32);
Scene { ball: ball, light: light, eye: eye }
} | identifier_body |
main.rs | extern crate paint;
use paint::{ Layer, Canvas, Projection, Color, Size };
struct BigWhiteCircle;
impl Layer for BigWhiteCircle {
fn draw(&self, projection: Projection)->Color {
use std::cmp:: { max, min };
let origin_x = std::u32::MAX / 2;
let offset_x = max(projection.x, origin_x) - min(projection.x, origin_... | }
fn main() {
let args = std::os::args();
if args.len() == 2 {
match std::path::Path::new_opt(&*args[1]) {
Some(ref path) => {
match std::io::fs::File::create(path) {
Ok(ref mut file) => {
let canvas = Canvas::new(Color::rgb(0, 200, 0), Size::new(260, 520));
let layer = TwoLayer { a: BigWhi... | } | random_line_split |
main.rs | extern crate paint;
use paint::{ Layer, Canvas, Projection, Color, Size };
struct BigWhiteCircle;
impl Layer for BigWhiteCircle {
fn draw(&self, projection: Projection)->Color {
use std::cmp:: { max, min };
let origin_x = std::u32::MAX / 2;
let offset_x = max(projection.x, origin_x) - min(projection.x, origin_... | ,
Err(x)=>println!(" {}", x)
}
},
None =>println!("failed to open path")
}
} else {
println!("Usage: {} file_path \t write a ppm file", &*args[0])
}
} | {
let canvas = Canvas::new(Color::rgb(0, 200, 0), Size::new(260, 520));
let layer = TwoLayer { a: BigWhiteCircle, b: BigWhiteCircle };
canvas.render(layer, file);
} | conditional_block |
main.rs | extern crate paint;
use paint::{ Layer, Canvas, Projection, Color, Size };
struct BigWhiteCircle;
impl Layer for BigWhiteCircle {
fn draw(&self, projection: Projection)->Color {
use std::cmp:: { max, min };
let origin_x = std::u32::MAX / 2;
let offset_x = max(projection.x, origin_x) - min(projection.x, origin_... | ()->Scene {
let ball = Ball { origin: Position(3f32, 30f32, 3f32), radius: 3f32 };
let light = Light { origin: Position(0f32, 0f32, 0f32) };
let eye = Position(3f32, 0f32, 3f32);
Scene { ball: ball, light: light, eye: eye }
}
}
struct TwoLayer<U: Layer, V: Layer> {
a: U, b: V
}
impl<U: Layer, V: Layer> Laye... | new | identifier_name |
landing-page.js | // jQuery for page scrolling feature - requires jQuery Easing plugin
$(function() {
$('a.page-scroll').bind('click', function(event) {
var $anchor = $(this);
$('html, body').stop().animate({
scrollTop: $($anchor.attr('href')).offset().top
}, 1500, 'easeInOutExpo');
event.... |
}
});
// var images = [
// 'master-Chieu-blue-belt-exam-berlin-04-2017.jpg',
// 'master-Chieu-Du-training-with-vovinam-berlin-team-09-2017.jpg',
// 'master-Chieu-training-11-2016.jpg',
// 'Olympicpark_08_2016.jpg',
// 'vovinam-berlin-christmas-party-12-2016.jpg',
// 'vovinamberlin-team-nov201... | {
$(modal).modal('hide');
} | conditional_block |
landing-page.js | // jQuery for page scrolling feature - requires jQuery Easing plugin
$(function() {
$('a.page-scroll').bind('click', function(event) {
var $anchor = $(this);
$('html, body').stop().animate({
scrollTop: $($anchor.attr('href')).offset().top
}, 1500, 'easeInOutExpo');
event.... | // 'vovinam-berlin-christmas-party-12-2016.jpg',
// 'vovinamberlin-team-nov2017.jpg',
// ];
// var index = 0;
// setInterval(rotateBannerBackgroundImages, 5000);
// function rotateBannerBackgroundImages(){
// index = (index + 1 < images.length) ? index + 1 : 0;
// $('.intro-header').fadeOut(300, fu... | // 'master-Chieu-training-11-2016.jpg',
// 'Olympicpark_08_2016.jpg', | random_line_split |
range-knob.ts | import { Component, EventEmitter, HostListener, Input, Output } from '@angular/core';
import { Key } from '../../platform/key';
/**
* @private
*/
@Component({
selector: '.range-knob-handle',
template:
'<div class="range-pin" *ngIf="pin" role="presentation">{{val}}</div>' +
'<div class="range-knob" role=... |
}
| {
const keyCode = ev.keyCode;
if (keyCode === Key.LEFT || keyCode === Key.DOWN) {
console.debug(`range-knob, decrease, keyCode: ${keyCode}`);
this.ionDecrease.emit();
ev.preventDefault();
ev.stopPropagation();
} else if (keyCode === Key.RIGHT || keyCode === Key.UP) {
console.d... | identifier_body |
range-knob.ts | import { Component, EventEmitter, HostListener, Input, Output } from '@angular/core';
import { Key } from '../../platform/key';
/**
* @private
*/
@Component({
selector: '.range-knob-handle',
template:
'<div class="range-pin" *ngIf="pin" role="presentation">{{val}}</div>' +
'<div class="range-knob" role=... | else if (keyCode === Key.RIGHT || keyCode === Key.UP) {
console.debug(`range-knob, increase, keyCode: ${keyCode}`);
this.ionIncrease.emit();
ev.preventDefault();
ev.stopPropagation();
}
}
}
| {
console.debug(`range-knob, decrease, keyCode: ${keyCode}`);
this.ionDecrease.emit();
ev.preventDefault();
ev.stopPropagation();
} | conditional_block |
range-knob.ts | import { Component, EventEmitter, HostListener, Input, Output } from '@angular/core';
import { Key } from '../../platform/key';
/**
* @private
*/
@Component({
selector: '.range-knob-handle',
template:
'<div class="range-pin" *ngIf="pin" role="presentation">{{val}}</div>' +
'<div class="range-knob" role=... | {
_x: string;
@Input() set ratio(r: number) {
this._x = `${r * 100}%`;
}
@Input() pressed: boolean;
@Input() pin: boolean;
@Input() min: number;
@Input() max: number;
@Input() val: number;
@Input() disabled: boolean;
@Input() labelId: string;
@Output() ionIncrease = new EventEmitter();
@O... | RangeKnob | identifier_name |
range-knob.ts | import { Component, EventEmitter, HostListener, Input, Output } from '@angular/core';
import { Key } from '../../platform/key';
/**
* @private
*/
@Component({
selector: '.range-knob-handle',
template:
'<div class="range-pin" *ngIf="pin" role="presentation">{{val}}</div>' +
'<div class="range-knob" role=... | this.ionIncrease.emit();
ev.preventDefault();
ev.stopPropagation();
}
}
} |
} else if (keyCode === Key.RIGHT || keyCode === Key.UP) {
console.debug(`range-knob, increase, keyCode: ${keyCode}`); | random_line_split |
reports.component.ts | import { Component, OnInit } from '@angular/core';
import { DataService } from '../service/data.service';
import { ReportModel } from '../model/reportmodel';
import { Utils } from '../util/utils'
import { RouterModule, Routes, Router, ActivatedRoute } from '@angular/router';
@Component({
selector: 'app-reports',
t... | }
}
} | private openReport(report : ReportModel) {
if(Utils.checkNullEmpty(report.sub_type)) {
this.router.navigate(['../report', report.type], { relativeTo: this.route });
} else {
this.router.navigate(['../report', report.type, report.sub_type], { relativeTo: this.route }); | random_line_split |
reports.component.ts | import { Component, OnInit } from '@angular/core';
import { DataService } from '../service/data.service';
import { ReportModel } from '../model/reportmodel';
import { Utils } from '../util/utils'
import { RouterModule, Routes, Router, ActivatedRoute } from '@angular/router';
@Component({
selector: 'app-reports',
t... |
}
}
| {
this.router.navigate(['../report', report.type, report.sub_type], { relativeTo: this.route });
} | conditional_block |
reports.component.ts | import { Component, OnInit } from '@angular/core';
import { DataService } from '../service/data.service';
import { ReportModel } from '../model/reportmodel';
import { Utils } from '../util/utils'
import { RouterModule, Routes, Router, ActivatedRoute } from '@angular/router';
@Component({
selector: 'app-reports',
t... | implements OnInit {
constructor(private dataService: DataService, private router: Router, private route: ActivatedRoute) {
}
reports: ReportModel[];
ngOnInit() {
this.dataService.getReports()
.subscribe(res => {
this.reports = res as Array<ReportModel>;
});
}
navigateToNewRep... | ReportsComponent | identifier_name |
reports.component.ts | import { Component, OnInit } from '@angular/core';
import { DataService } from '../service/data.service';
import { ReportModel } from '../model/reportmodel';
import { Utils } from '../util/utils'
import { RouterModule, Routes, Router, ActivatedRoute } from '@angular/router';
@Component({
selector: 'app-reports',
t... |
}
| {
if(Utils.checkNullEmpty(report.sub_type)) {
this.router.navigate(['../report', report.type], { relativeTo: this.route });
} else {
this.router.navigate(['../report', report.type, report.sub_type], { relativeTo: this.route });
}
} | identifier_body |
isNative.js | var isFunction = require('lodash/lang/isFunction'),
isObjectLike = require('lodash/internal/isObjectLike');
/** Used to detect host constructors (Safari > 5). */
var reIsHostCtor = /^\[object .+?Constructor\]$/;
/** Used for native method references. */
var objectProto = Object.prototype;
/** Used to resolve the... |
return isObjectLike(value) && reIsHostCtor.test(value);
}
module.exports = isNative;
| {
return reIsNative.test(fnToString.call(value));
} | conditional_block |
isNative.js | var isFunction = require('lodash/lang/isFunction'),
isObjectLike = require('lodash/internal/isObjectLike');
/** Used to detect host constructors (Safari > 5). */
var reIsHostCtor = /^\[object .+?Constructor\]$/;
/** Used for native method references. */
var objectProto = Object.prototype;
/** Used to resolve the... |
module.exports = isNative;
| {
if (value == null) {
return false;
}
if (isFunction(value)) {
return reIsNative.test(fnToString.call(value));
}
return isObjectLike(value) && reIsHostCtor.test(value);
} | identifier_body |
isNative.js | var isFunction = require('lodash/lang/isFunction'),
isObjectLike = require('lodash/internal/isObjectLike');
/** Used to detect host constructors (Safari > 5). */
var reIsHostCtor = /^\[object .+?Constructor\]$/;
/** Used for native method references. */
var objectProto = Object.prototype;
/** Used to resolve the... | );
/**
* Checks if `value` is a native function.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a native function, else `false`.
* @example
*
* _.isNative(Array.prototype.push);
* // => true
*
* _.isNative(_);
* // => fa... |
/** Used to detect if a method is native. */
var reIsNative = RegExp('^' +
fnToString.call(hasOwnProperty).replace(/[\\^$.*+?()[\]{}|]/g, '\\$&')
.replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' | random_line_split |
isNative.js | var isFunction = require('lodash/lang/isFunction'),
isObjectLike = require('lodash/internal/isObjectLike');
/** Used to detect host constructors (Safari > 5). */
var reIsHostCtor = /^\[object .+?Constructor\]$/;
/** Used for native method references. */
var objectProto = Object.prototype;
/** Used to resolve the... | (value) {
if (value == null) {
return false;
}
if (isFunction(value)) {
return reIsNative.test(fnToString.call(value));
}
return isObjectLike(value) && reIsHostCtor.test(value);
}
module.exports = isNative;
| isNative | identifier_name |
common.rs | use std::str::FromStr;
use std::fmt::{Show, Formatter, Error};
use std::error;
use simple::parse;
#[deriving(Show)]
pub struct AddrError {
pub msg: String
}
impl error::Error for AddrError {
fn | (&self) -> &str {
self.msg.as_slice()
}
}
#[deriving(PartialEq)]
pub struct EmailAddress {
pub local: String,
pub domain: String,
}
impl EmailAddress {
pub fn new(string: &str) -> EmailAddress {
parse(string).unwrap()
}
}
impl Show for EmailAddress {
fn fmt(&self, f: &mut Form... | description | identifier_name |
common.rs | use std::str::FromStr;
use std::fmt::{Show, Formatter, Error};
use std::error;
use simple::parse;
#[deriving(Show)]
pub struct AddrError {
pub msg: String
}
impl error::Error for AddrError {
fn description(&self) -> &str {
self.msg.as_slice()
}
}
#[deriving(PartialEq)]
pub struct EmailAddress {
... | fn from_str(string: &str) -> Option<EmailAddress> {
match parse(string) {
Ok(s) => Some(s),
Err(_) => None,
}
}
} | random_line_split | |
common.rs | use std::str::FromStr;
use std::fmt::{Show, Formatter, Error};
use std::error;
use simple::parse;
#[deriving(Show)]
pub struct AddrError {
pub msg: String
}
impl error::Error for AddrError {
fn description(&self) -> &str {
self.msg.as_slice()
}
}
#[deriving(PartialEq)]
pub struct EmailAddress {
... |
}
impl FromStr for EmailAddress {
fn from_str(string: &str) -> Option<EmailAddress> {
match parse(string) {
Ok(s) => Some(s),
Err(_) => None,
}
}
}
| {
write!(f, "{}@{}", self.local, self.domain)
} | identifier_body |
any.ts | /**
* @license
* Copyright 2020 Google LLC. 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/LICENSE-2.0
*
* Unless required by a... | <T extends Tensor>(
x: Tensor|TensorLike, axis: number|number[] = null, keepDims = false): T {
const $x = convertToTensor(x, 'x', 'any', 'bool');
const inputs: AnyInputs = {x: $x};
const attrs: AnyAttrs = {axis, keepDims};
return ENGINE.runKernel(
Any, inputs as {} as NamedTensorMap, attrs as {} as ... | any_ | identifier_name |
any.ts | /**
* @license
* Copyright 2020 Google LLC. 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/LICENSE-2.0
*
* Unless required by a... |
// tslint:disable-next-line:variable-name
export const any = op({any_});
| {
const $x = convertToTensor(x, 'x', 'any', 'bool');
const inputs: AnyInputs = {x: $x};
const attrs: AnyAttrs = {axis, keepDims};
return ENGINE.runKernel(
Any, inputs as {} as NamedTensorMap, attrs as {} as NamedAttrMap);
} | identifier_body |
any.ts | /**
* @license
* Copyright 2020 Google LLC. 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/LICENSE-2.0
*
* Unless required by a... | import {op} from './operation';
/**
* Computes the logical or of elements across dimensions of a `tf.Tensor`.
*
* Reduces the input along the dimensions given in `axes`. Unless `keepDims`
* is true, the rank of the `tf.Tensor` is reduced by 1 for each entry in
* `axes`. If `keepDims` is true, the reduced dimensio... | random_line_split | |
trans_frater_augmentation.py | #!/usr/bin/python
#
# This file is part of CONCUSS, https://github.com/theoryinpractice/concuss/,
# and is Copyright (C) North Carolina State University, 2015. It is licensed
# under the three-clause BSD license; see LICENSE.
#
from lib.util.memorized import memorized
from lib.graph.graph import Graph
# Calculate ... |
for x, y, _ in g.frat_trips(v):
fratGraph.add_edge(x, y)
assert (not g.adjacent(x, y)), \
"{0} {1} fraternal but adjacent".format(x, y)
for (s, t) in newTrans.keys():
g.add_arc(s, t, 1)
fratGraph.remove_edge(s, t)
# TODO: support dict to see cur... | newTrans[(x, y)] = step
assert (not g.adjacent(x, y)), \
"{0} {1} transitive but adjacent".format(x, y) | conditional_block |
trans_frater_augmentation.py | #!/usr/bin/python
#
# This file is part of CONCUSS, https://github.com/theoryinpractice/concuss/,
# and is Copyright (C) North Carolina State University, 2015. It is licensed
# under the three-clause BSD license; see LICENSE.
#
from lib.util.memorized import memorized
from lib.graph.graph import Graph
# Calculate ... | # calculate result
trans.update(newTrans)
for s, t, _ in fratDigraph.arcs():
frat[(s, t)] = step
g.add_arc(s, t, 1)
return (g, trans, frat)
# end def
| fratGraph = Graph()
newTrans = {}
for v in g:
for x, y, _, in g.trans_trips(v):
newTrans[(x, y)] = step
assert (not g.adjacent(x, y)), \
"{0} {1} transitive but adjacent".format(x, y)
for x, y, _ in g.frat_trips(v):
fratGraph.add_edge(x, y)
... | identifier_body |
trans_frater_augmentation.py | #!/usr/bin/python
#
# This file is part of CONCUSS, https://github.com/theoryinpractice/concuss/,
# and is Copyright (C) North Carolina State University, 2015. It is licensed
# under the three-clause BSD license; see LICENSE.
#
from lib.util.memorized import memorized
from lib.graph.graph import Graph
# Calculate ... | (orig, g, trans, frat, col,
nodes, step, td, ldoFunc):
fratGraph = Graph()
newTrans = {}
for v in g:
for x, y, _, in g.trans_trips(v):
newTrans[(x, y)] = step
assert (not g.adjacent(x, y)), \
"{0} {1} transitive but adjacent".for... | trans_frater_augmentation | identifier_name |
trans_frater_augmentation.py | #!/usr/bin/python
#
# This file is part of CONCUSS, https://github.com/theoryinpractice/concuss/,
# and is Copyright (C) North Carolina State University, 2015. It is licensed
# under the three-clause BSD license; see LICENSE.
#
from lib.util.memorized import memorized
from lib.graph.graph import Graph
# Calculate ... | trans.update(newTrans)
for s, t, _ in fratDigraph.arcs():
frat[(s, t)] = step
g.add_arc(s, t, 1)
return (g, trans, frat)
# end def |
# TODO: support dict to see current in-degree...
fratDigraph = ldoFunc(fratGraph)
# calculate result | random_line_split |
xamarincomponent.ts | import path = require('path');
import tl = require('vsts-task-lib/task');
import os = require('os');
import fs = require('fs');
tl.setResourcePath(path.join( __dirname, 'task.json'));
var xamarinComponentExe = path.join(__dirname, "xpkg", "xamarin-component.exe")
var isWin = /^win/.test(process.platform);
var xamar... | else {
solutionPath = undefined;
}
}
if (!solutionPath) {
tl.error(tl.loc('XamarinComponentRestoreFailed', 'No solutions found matching the input: ' + solutionInput));
tl.exit(1);
}
tl.debug("Restoring components for " + solutionPath);
tl.cd(path.dirname(solutionPath));
xamarinComponentTool.arg... | {
if(solutionMatches.length > 1) {
tl.warning('multiple solution matches, using ' + solutionMatches[0]);
}
solutionPath = solutionMatches[0];
} | conditional_block |
xamarincomponent.ts | import path = require('path');
import tl = require('vsts-task-lib/task');
import os = require('os');
import fs = require('fs');
tl.setResourcePath(path.join( __dirname, 'task.json'));
var xamarinComponentExe = path.join(__dirname, "xpkg", "xamarin-component.exe")
var isWin = /^win/.test(process.platform);
var xamar... | .fail(function(err) {
tl.debug('taskRunner fail');
tl.error( tl.loc('XamarinComponentRestoreFailed', err.message));
tl.setResult(tl.TaskResult.Failed, tl.loc('XamarinComponentRestoreFailed', err.message));
}) | }
}) | random_line_split |
embeddings_module.ts | '},
'umap': {displayName: 'UMAP', interpreterName: 'umap'},
};
static override numCols = 3;
// Selection of one of the above configs.
@observable private projectorName: string = 'umap';
@computed
get projector(): ProjectorOptions {
return EmbeddingsModule.projectorChoices[this.projectorName];
}
... |
override firstUpdated() {
const scatterContainer =
this.shadowRoot!.getElementById('scatter-gl-container')!;
this.scatterGL = new ScatterGL(scatterContainer, {
pointColorer: (i, selectedIndices, hoverIndex) =>
this.pointColorer(i, selectedIndices, hoverIndex),
onSelect: this.o... | {
super();
// Default to PCA on large datasets.
if (this.appState.currentInputData.length > 1000) {
this.projectorName = 'pca';
}
} | identifier_body |
embeddings_module.ts | this.shadowRoot!.getElementById('scatter-gl-container')!;
this.scatterGL = new ScatterGL(scatterContainer, {
pointColorer: (i, selectedIndices, hoverIndex) =>
this.pointColorer(i, selectedIndices, hoverIndex),
onSelect: this.onSelect.bind(this),
onHover: this.onHover.bind(this),... | renderSelect | identifier_name | |
embeddings_module.ts | '},
'umap': {displayName: 'UMAP', interpreterName: 'umap'},
};
static override numCols = 3;
// Selection of one of the above configs.
@observable private projectorName: string = 'umap';
@computed
get projector(): ProjectorOptions {
return EmbeddingsModule.projectorChoices[this.projectorName];
}
... | const embeddingRequestCache = this.getEmbeddingCache(
datasetName, modelName, this.projector.interpreterName, projConfig);
const promise = embeddingRequestCache.call(this.appState.currentInputData);
const results =
await this.loadLatest(`proj-${JSON.stringify(projConfig)}`, promise);
if ... | // Projections will be returned for the whole dataset, including generated
// examples, but the backend will ensure that the projection is trained on
// only the original dataset. See components/projection.py. | random_line_split |
poxliff.py | self._rich_target = None
self._state_n = 0
self.units = []
if empty:
return
if not hasplurals(source):
super().__init__(source)
return
self.xmlelement = etree.Element(self.namespaced("group"))
self.xmlelement.set("restype", "... | (self):
return super().istranslatable() and not self.isheader()
@classmethod
def createfromxmlElement(cls, element, namespace=None):
if element.tag.endswith("trans-unit"):
object = cls(None, empty=True)
object.xmlelement = element
object.namespace = namespace... | istranslatable | identifier_name |
poxliff.py | _to_multistring
rich_source = base.TranslationUnit.rich_source
rich_target = base.TranslationUnit.rich_target
def gettarget(self, lang=None):
if self.hasplural():
strings = [unit.target for unit in self.units]
if strings:
return multistring(strings)
... | """Populates this object from the given xml string"""
# TODO: Make more robust
def ispluralgroup(node):
"""determines whether the xml node refers to a getttext plural"""
return node.get("restype") == "x-gettext-plurals"
def isnonpluralunit(node):
"""determin... | identifier_body | |
poxliff.py | self._rich_target = None
self._state_n = 0
self.units = []
if empty:
return
if not hasplurals(source):
super().__init__(source)
return
self.xmlelement = etree.Element(self.namespaced("group"))
self.xmlelement.set("restype", "... |
if not super().__eq__(other):
return False
for i in range(len(self.units) - 1):
if not self.units[i + 1] == other.units[i + 1]:
return False
return True
if len(self.units) <= 1:
if isinstance(other, lisa.LISAuni... | return False | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.