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 |
|---|---|---|---|---|
data.py | import itertools
import os
import zipfile
import numpy as np
import requests
import scipy.sparse as sp
def _get_movielens_path():
"""
Get path to the movielens dataset file.
"""
return os.path.join(os.path.dirname(os.path.abspath(__file__)),
'movielens.zip')
def _download... |
def _build_interaction_matrix(rows, cols, data):
"""
Build the training matrix (no_users, no_items),
with ratings >= 4.0 being marked as positive and
the rest as negative.
"""
mat = sp.lil_matrix((rows, cols), dtype=np.int32)
for uid, iid, rating, timestamp in data:
if rating >=... | """
Parse movielens dataset lines.
"""
for line in data:
if not line:
continue
uid, iid, rating, timestamp = [int(x) for x in line.split('\t')]
yield uid, iid, rating, timestamp | identifier_body |
signal.ts | module Retrieve
{
interface SignalCallbackItem {
callback:(...args:any[]) => void;
context?:any;
}
export class Signal {
private callbacks:SignalCallbackItem[];
add(callback:(...args:any[]) => void, context?:any) {
this.callbacks || (this.callbacks = []);
... | }
}
return -1;
}
}
} | for (var i:number = 0; i < this.callbacks.length; i++) {
var item:SignalCallbackItem = this.callbacks[i];
if (item && (!callback || item.callback === callback) && (!context || item.context === context))
return i; | random_line_split |
signal.ts | module Retrieve
{
interface SignalCallbackItem {
callback:(...args:any[]) => void;
context?:any;
}
export class Signal {
private callbacks:SignalCallbackItem[];
add(callback:(...args:any[]) => void, context?:any) {
this.callbacks || (this.callbacks = []);
... |
}
private getCallbackIndex(callback:(...args:any[]) => void, context?:any):number {
if (this.callbacks && (callback || context)) {
for (var i:number = 0; i < this.callbacks.length; i++) {
var item:SignalCallbackItem = this.callbacks[i];
... | {
for (var i:number = 0; i < this.callbacks.length; i++) {
var item:SignalCallbackItem = this.callbacks[i];
if (item && typeof item.callback === "function")
item.callback.apply(item.context || this, args);
}
} | conditional_block |
signal.ts | module Retrieve
{
interface SignalCallbackItem {
callback:(...args:any[]) => void;
context?:any;
}
export class Signal {
private callbacks:SignalCallbackItem[];
add(callback:(...args:any[]) => void, context?:any) {
this.callbacks || (this.callbacks = []);
... | (...args:any[]) {
if (this.callbacks) {
for (var i:number = 0; i < this.callbacks.length; i++) {
var item:SignalCallbackItem = this.callbacks[i];
if (item && typeof item.callback === "function")
item.callback.apply(item.context ... | trigger | identifier_name |
signal.ts | module Retrieve
{
interface SignalCallbackItem {
callback:(...args:any[]) => void;
context?:any;
}
export class Signal {
private callbacks:SignalCallbackItem[];
add(callback:(...args:any[]) => void, context?:any) {
this.callbacks || (this.callbacks = []);
... |
trigger(...args:any[]) {
if (this.callbacks) {
for (var i:number = 0; i < this.callbacks.length; i++) {
var item:SignalCallbackItem = this.callbacks[i];
if (item && typeof item.callback === "function")
item.callback.ap... | {
var index:number = this.getCallbackIndex(callback, context);
if (index >= 0)
this.callbacks.splice(index, 1);
} | identifier_body |
angular-loading-bar.js | 3 Wes Cruver
* License: MIT
*/
(function() {
'use strict';
// Alias the loading bar for various backwards compatibilities since the project has matured:
angular.module('angular-loading-bar', ['cfp.loadingBarInterceptor']);
angular.module('chieffancypants.loadingBar', ['cfp.loadingBarInterceptor']);
/**
* loadi... |
config.cached = cached;
return cached;
}
return {
'request': function(config) {
// Check to make sure this request hasn't already been cached and that
// the requester didn't explicitly ask us to ignore this request:
if (!config.ignoreLoadingBar && !i... | {
return config.cached;
} | conditional_block |
angular-loading-bar.js | 3 Wes Cruver
* License: MIT
*/
(function() {
'use strict';
// Alias the loading bar for various backwards compatibilities since the project has matured:
angular.module('angular-loading-bar', ['cfp.loadingBarInterceptor']);
angular.module('chieffancypants.loadingBar', ['cfp.loadingBarInterceptor']);
/**
* loadi... | () {
$timeout.cancel(startTimeout);
cfpLoadingBar.complete();
reqsCompleted = 0;
reqsTotal = 0;
}
/**
* Determine if the response has already been cached
* @param {Object} config the config option from the request
* @return {Boolean} retrns true if cac... | setComplete | identifier_name |
angular-loading-bar.js | 3 Wes Cruver
* License: MIT
*/
(function() {
'use strict';
// Alias the loading bar for various backwards compatibilities since the project has matured:
angular.module('angular-loading-bar', ['cfp.loadingBarInterceptor']);
angular.module('chieffancypants.loadingBar', ['cfp.loadingBarInterceptor']);
/**
* loadi... | if (includeBar) {
$animate.enter(loadingBarContainer, $parent, angular.element($parent[0].lastChild));
}
if (includeSpinner) {
$animate.enter(spinner, $parent, angular.element($parent[0].lastChild));
}
_set(startSize);
}
/**
* Set the loa... |
$rootScope.$broadcast('cfpLoadingBar:started');
started = true;
| random_line_split |
angular-loading-bar.js | 3 Wes Cruver
* License: MIT
*/
(function() {
'use strict';
// Alias the loading bar for various backwards compatibilities since the project has matured:
angular.module('angular-loading-bar', ['cfp.loadingBarInterceptor']);
angular.module('chieffancypants.loadingBar', ['cfp.loadingBarInterceptor']);
/**
* loadi... | // finally, increment it .5 %
rnd = 0.005;
} else {
// after 99%, don't increment:
rnd = 0;
}
var pct = _status() + rnd;
_set(pct);
}
function _status() {
return status;
}
function _completeAnimation() {
... | {
if (_status() >= 1) {
return;
}
var rnd = 0;
// TODO: do this mathmatically instead of through conditions
var stat = _status();
if (stat >= 0 && stat < 0.25) {
// Start out between 3 - 6% increments
rnd = (Math.random() * (5 - 3 + 1) + 3... | identifier_body |
contents.spec.tsx | import React from 'react';
import {shallow} from 'enzyme';
import toJson from 'enzyme-to-json';
import ShallowDropDownContents, {ShallowDropDownContentsProps} from './contents';
describe('<ShallowDropDownContents/>', () => {
const props: ShallowDropDownContentsProps = {
...ShallowDropDownContents.defaultP... | const wrapper = shallow(<ShallowDropDownContents {...props} isOpen={true} className="fooClassName"/>);
expect(wrapper.prop('className')).toContain('fooClassName');
});
it('should render the themes "dropDown__contents--isOpen" className in case the "isOpen" prop is true.', () => {
const... |
expect(toJson(wrapper)).toBeFalsy();
});
it('should allow the propagation of "className" with the "className" prop.', () => { | random_line_split |
filesystem.d.ts | /// <reference types="node" /> | * Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import { Path, PathFragment } from '@angular-devkit/core';
import { DirEntry, FileEntry } from './interface';
import { VirtualDirEntr... | /**
* @license | random_line_split |
filesystem.d.ts | /// <reference types="node" />
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import { Path, PathFragment } from '@angular-devkit/core';
import { DirEntry, FileEntr... | extends FileSystemTree {
constructor(host: FileSystemTreeHost);
}
| FileSystemCreateTree | identifier_name |
projecteuler6.py | # -*- coding: UTF-8 -*-
#The sum of the squares of the first ten natural numbers is,
#1² + 2² + ... + 10² = 385
#The square of the sum of the first ten natural numbers is,
#(1 + 2 + ... + 10)² = 552 = 3025
#Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum... | sumsquare = sumsquare + i*i
for j in range(1, 101):
sum = sum + j
print(sum)
print(sum*sum)
print(sum*sum - sumsquare) | sumsquare = 0
sum = 0
for i in range(1, 101): | random_line_split |
projecteuler6.py | # -*- coding: UTF-8 -*-
#The sum of the squares of the first ten natural numbers is,
#1² + 2² + ... + 10² = 385
#The square of the sum of the first ten natural numbers is,
#(1 + 2 + ... + 10)² = 552 = 3025
#Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum... | j in range(1, 101):
sum = sum + j
print(sum)
print(sum*sum)
print(sum*sum - sumsquare) | are = sumsquare + i*i
for | conditional_block |
gtest_attribute.rs |
/// given to Gtest. The name of the test function itself does not matter, and need not be unique
/// (it's placed into a unique module based on the Gtest suite + test names.
///
/// The test function must have no arguments. The return value must be either `()` or
/// `std::result::Result<(), E>`. If another return typ... | let test_fn = &input_fn.sig.ident;
// Implements ToTokens to generate a reference to a static-lifetime, null-terminated, C-String
// literal. It is represented as an array of type std::os::raw::c_char which can be either
// signed or unsigned depending on the platform, and it can be passed directly to ... | format_ident!("{}_{}_{}_{}", file_name, test_suite_name, test_name, f.sig.ident)
};
let run_test_fn = format_ident!("run_test_{}", mangled_function_name(&input_fn));
// The identifier of the function which contains the body of the test. | random_line_split |
gtest_attribute.rs |
/// given to Gtest. The name of the test function itself does not matter, and need not be unique
/// (it's placed into a unique module based on the Gtest suite + test names.
///
/// The test function must have no arguments. The return value must be either `()` or
/// `std::result::Result<(), E>`. If another return typ... | {
TestSuite,
TestName,
}
// Returns a string representation of an identifier argument to the attribute. For example, for
// #[gtest(Foo, Bar)], this function would return "Foo" for position 0 and "Bar" for position 1.
// If the argument is not a Rust identifier or not present, it return... | GtestAttributeArgument | identifier_name |
gtest_attribute.rs |
/// given to Gtest. The name of the test function itself does not matter, and need not be unique
/// (it's placed into a unique module based on the Gtest suite + test names.
///
/// The test function must have no arguments. The return value must be either `()` or
/// `std::result::Result<(), E>`. If another return typ... | }
}
}
let args = syn::parse_macro_input!(arg_stream as syn::AttributeArgs);
let input_fn = syn::parse_macro_input!(input as syn::ItemFn);
if let Some(asyncness) = input_fn.sig.asyncness {
// TODO(crbug.com/1288947): We can support async functions once we have block_on() su... | {
let error_stream = match which {
GtestAttributeArgument::TestSuite => {
quote_spanned! {
args[pos].span() =>
compile_error!(
"Expected a test suite name, written as a... | conditional_block |
testutils.py | from __future__ import absolute_import, print_function, division
from pony.py23compat import basestring
from functools import wraps
from contextlib import contextmanager
from pony.orm.core import Database
from pony.utils import import_module
def raises_exception(exc_class, msg=None):
def decorator(func... |
def commit(con):
pass
def rollback(con):
pass
def cursor(con):
return test_cursor
class TestCursor(object):
def __init__(cursor):
cursor.description = []
cursor.rowcount = 0
def execute(cursor, sql, args=None):
pass
def fetchone(cur... | con.database = database
if database and database.provider_name == 'postgres':
con.autocommit = True | identifier_body |
testutils.py | from __future__ import absolute_import, print_function, division
from pony.py23compat import basestring
from functools import wraps
from contextlib import contextmanager
from pony.orm.core import Database
from pony.utils import import_module
def raises_exception(exc_class, msg=None):
def decorator(func... | (object):
def __init__(con, database):
con.database = database
if database and database.provider_name == 'postgres':
con.autocommit = True
def commit(con):
pass
def rollback(con):
pass
def cursor(con):
return test_cursor
class TestCursor(o... | TestConnection | identifier_name |
testutils.py | from __future__ import absolute_import, print_function, division
from pony.py23compat import basestring
from functools import wraps
from contextlib import contextmanager
from pony.orm.core import Database
from pony.utils import import_module
def raises_exception(exc_class, msg=None):
def decorator(func... |
else:
test.assertTrue(str(e).endswith(exc_msg[3:]))
elif exc_msg.endswith('...'):
test.assertTrue(str(e).startswith(exc_msg[:-3]))
else:
test.assertEqual(str(e), exc_msg)
else:
test.assertFalse(cond)
def flatten(x):
result ... | test.assertIn(exc_msg[3:-3], str(e)) | conditional_block |
testutils.py | from __future__ import absolute_import, print_function, division
from pony.py23compat import basestring
from functools import wraps
from contextlib import contextmanager
from pony.orm.core import Database
from pony.utils import import_module
def raises_exception(exc_class, msg=None):
def decorator(func... | def fetchmany(cursor, size):
return []
def fetchall(cursor):
return []
test_cursor = TestCursor()
class TestPool(object):
def __init__(pool, database):
pool.database = database
def connect(pool):
return TestConnection(pool.database)
def release(pool, con... | random_line_split | |
__init__.py | #
# Copyright (C) 2010-2017 Samuel Abels | # Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copi... | # The MIT License (MIT)
# | random_line_split |
directory_watcher.py | """Contains the implementation for the DirectoryWatcher class."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
from tensorflow.python.platform import gfile
from tensorflow.python.platform import logging
class DirectoryWatcher(object):
|
Raises:
ValueError: If directory or loader_factory is None.
"""
if directory is None:
raise ValueError('A directory is required')
if loader_factory is None:
raise ValueError('A loader factory is required')
self._directory = directory
self._loader_factory = loader_factory
s... | """A DirectoryWatcher wraps a loader to load from a directory.
A loader reads a file on disk and produces some kind of values as an
iterator. A DirectoryWatcher takes a directory with one file at a time being
written to and a factory for loaders and watches all the files at once.
This class is *only* valid un... | identifier_body |
directory_watcher.py | """Contains the implementation for the DirectoryWatcher class."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
from tensorflow.python.platform import gfile
from tensorflow.python.platform import logging
class DirectoryWatcher(object):
"""A ... |
self._directory = directory
self._loader_factory = loader_factory
self._loader = None
self._path = None
self._path_filter = path_filter
def Load(self):
"""Loads new values from disk.
The watcher will load from one file at a time; as soon as that file stops
yielding events, it will m... | raise ValueError('A loader factory is required') | conditional_block |
directory_watcher.py | """Contains the implementation for the DirectoryWatcher class."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
from tensorflow.python.platform import gfile
from tensorflow.python.platform import logging
class DirectoryWatcher(object):
"""A ... | (self):
"""Loads new values from disk.
The watcher will load from one file at a time; as soon as that file stops
yielding events, it will move on to the next file. We assume that old files
are never modified after a newer file has been written. As a result, Load()
can be called multiple times in a ... | Load | identifier_name |
directory_watcher.py | """Contains the implementation for the DirectoryWatcher class."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
from tensorflow.python.platform import gfile
from tensorflow.python.platform import logging
class DirectoryWatcher(object):
"""A ... | # written between when we finished reading the current file and when we
# checked for the new one. The sequence of events might look something
# like this:
#
# 1. Event #1 written to file #1.
# 2. We check for events and yield event #1 from file #1
# 3. We check for events and ... | # There's a new file, so check to make sure there weren't any events | random_line_split |
proto.js | var fs = require('fs');
var protobuf = require('protobufjs');
var protoStr = fs.readFileSync(__dirname + '/remotecontrolmessages.proto', 'utf8');
var builder = protobuf.loadProto(protoStr);
var ns = 'pb.remote';
function build(type) {
return builder.build(ns+'.'+type);
}
var proto = {
MsgType: build('MsgType'),
E... | Message: build('Message')
};
var Message = proto.Message;
function getConstName(value, obj) {
for (var name in obj) {
if (obj[name] === value) {
return name;
}
}
return '';
}
proto.getMsgTypeName = function (typeIndex) {
return getConstName(typeIndex, proto.MsgType);
};
proto.getEngineStateName = functio... | RepeatMode: build('RepeatMode'),
ShuffleMode: build('ShuffleMode'),
ReasonDisconnect: build('ReasonDisconnect'),
DownloadItem: build('DownloadItem'), | random_line_split |
proto.js | var fs = require('fs');
var protobuf = require('protobufjs');
var protoStr = fs.readFileSync(__dirname + '/remotecontrolmessages.proto', 'utf8');
var builder = protobuf.loadProto(protoStr);
var ns = 'pb.remote';
function build(type) {
return builder.build(ns+'.'+type);
}
var proto = {
MsgType: build('MsgType'),
E... | (value, obj) {
for (var name in obj) {
if (obj[name] === value) {
return name;
}
}
return '';
}
proto.getMsgTypeName = function (typeIndex) {
return getConstName(typeIndex, proto.MsgType);
};
proto.getEngineStateName = function (stateIndex) {
return getConstName(stateIndex, proto.EngineState);
};
proto.get... | getConstName | identifier_name |
proto.js | var fs = require('fs');
var protobuf = require('protobufjs');
var protoStr = fs.readFileSync(__dirname + '/remotecontrolmessages.proto', 'utf8');
var builder = protobuf.loadProto(protoStr);
var ns = 'pb.remote';
function build(type) {
return builder.build(ns+'.'+type);
}
var proto = {
MsgType: build('MsgType'),
E... |
}
return '';
}
proto.getMsgTypeName = function (typeIndex) {
return getConstName(typeIndex, proto.MsgType);
};
proto.getEngineStateName = function (stateIndex) {
return getConstName(stateIndex, proto.EngineState);
};
proto.getRepeatModeName = function (repeatModeIndex) {
return getConstName(repeatModeIndex, prot... | {
return name;
} | conditional_block |
proto.js | var fs = require('fs');
var protobuf = require('protobufjs');
var protoStr = fs.readFileSync(__dirname + '/remotecontrolmessages.proto', 'utf8');
var builder = protobuf.loadProto(protoStr);
var ns = 'pb.remote';
function build(type) {
return builder.build(ns+'.'+type);
}
var proto = {
MsgType: build('MsgType'),
E... |
proto.getMsgTypeName = function (typeIndex) {
return getConstName(typeIndex, proto.MsgType);
};
proto.getEngineStateName = function (stateIndex) {
return getConstName(stateIndex, proto.EngineState);
};
proto.getRepeatModeName = function (repeatModeIndex) {
return getConstName(repeatModeIndex, proto.RepeatMode);
};... | {
for (var name in obj) {
if (obj[name] === value) {
return name;
}
}
return '';
} | identifier_body |
SsidChartSharp.js | "use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon"));
var _jsxRuntime = require("react/jsx-runtime")... | exports.default = _default; | random_line_split | |
filter.ts | /*-----------------------------------------------------------------------------
| Copyright (c) 2014-2017, PhosphorJS Contributors
|
| Distributed under the terms of the BSD 3-Clause License.
|
| The full license is in the file LICENSE, distributed with this software.
|--------------------------------------------------... |
/**
* Create an independent clone of the iterator.
*
* @returns A new independent clone of the iterator.
*/
clone(): IIterator<T> {
let result = new FilterIterator<T>(this._source.clone(), this._fn);
result._index = this._index;
return result;
}
/**
* Get the next value from the it... | {
return this;
} | identifier_body |
filter.ts | /*-----------------------------------------------------------------------------
| Copyright (c) 2014-2017, PhosphorJS Contributors
|
| Distributed under the terms of the BSD 3-Clause License.
|
| The full license is in the file LICENSE, distributed with this software.
|--------------------------------------------------... |
}
return undefined;
}
private _index = 0;
private _source: IIterator<T>;
private _fn: (value: T, index: number) => boolean;
}
| {
return value;
} | conditional_block |
filter.ts | /*-----------------------------------------------------------------------------
| Copyright (c) 2014-2017, PhosphorJS Contributors
|
| Distributed under the terms of the BSD 3-Clause License.
|
| The full license is in the file LICENSE, distributed with this software.
|--------------------------------------------------... | (): IIterator<T> {
let result = new FilterIterator<T>(this._source.clone(), this._fn);
result._index = this._index;
return result;
}
/**
* Get the next value from the iterator.
*
* @returns The next value from the iterator, or `undefined`.
*/
next(): T | undefined {
let fn = this._fn;... | clone | identifier_name |
filter.ts | /*-----------------------------------------------------------------------------
| Copyright (c) 2014-2017, PhosphorJS Contributors
|
| Distributed under the terms of the BSD 3-Clause License.
|
| The full license is in the file LICENSE, distributed with this software.
|--------------------------------------------------... | return new FilterIterator<T>(iter(object), fn);
}
/**
* An iterator which yields values which pass a test.
*/
export
class FilterIterator<T> implements IIterator<T> {
/**
* Construct a new filter iterator.
*
* @param source - The iterator of values of interest.
*
* @param fn - The predicate funct... | random_line_split | |
interfaces.ts | import type { DataEntity } from './entities/data-entity';
export type {
Omit,
Overwrite,
Override,
Required,
Optional,
Nil,
WithoutNil,
Many,
RecursiveArray,
ListOfRecursiveArraysOrValues,
EmptyObject,
AnyObject,
PartialDeep,
Diff,
Filter,
ValueOf, | FilteredResult,
Unpacked
} from '@terascope/types';
/**
* Used for sending data to particular index/topic/file/table in a storage system.
* This is used by the routed sender in the standard-assets
*/
export interface RouteSenderAPI {
/**
* Sends the records to the respective storage backend
*
... | random_line_split | |
event_dispatcher.ts | import {
RenderViewRef,
RenderEventDispatcher,
} from 'angular2/src/render/api';
import {Serializer} from 'angular2/src/web_workers/shared/serializer';
import {
serializeMouseEvent,
serializeKeyboardEvent,
serializeGenericEvent,
serializeEventWithTarget
} from 'angular2/src/web_workers/ui/event_serializer';... | implements RenderEventDispatcher {
constructor(private _viewRef: RenderViewRef, private _sink: EventEmitter,
private _serializer: Serializer) {}
dispatchRenderEvent(elementIndex: number, eventName: string, locals: Map<string, any>) {
var e = locals.get('$event');
var serializedEvent;
// ... | EventDispatcher | identifier_name |
event_dispatcher.ts | import {
RenderViewRef,
RenderEventDispatcher,
} from 'angular2/src/render/api';
import {Serializer} from 'angular2/src/web_workers/shared/serializer';
import {
serializeMouseEvent,
serializeKeyboardEvent,
serializeGenericEvent,
serializeEventWithTarget
} from 'angular2/src/web_workers/ui/event_serializer';... | serializedEvent = serializeMouseEvent(e);
break;
case "keydown":
case "keypress":
case "keyup":
serializedEvent = serializeKeyboardEvent(e);
break;
case "input":
case "change":
case "blur":
serializedEvent = serializeEventWithTarget(e);
... | case "mouseleave":
case "mousemove":
case "mouseout":
case "mouseover":
case "show": | random_line_split |
event_dispatcher.ts | import {
RenderViewRef,
RenderEventDispatcher,
} from 'angular2/src/render/api';
import {Serializer} from 'angular2/src/web_workers/shared/serializer';
import {
serializeMouseEvent,
serializeKeyboardEvent,
serializeGenericEvent,
serializeEventWithTarget
} from 'angular2/src/web_workers/ui/event_serializer';... |
dispatchRenderEvent(elementIndex: number, eventName: string, locals: Map<string, any>) {
var e = locals.get('$event');
var serializedEvent;
// TODO (jteplitz602): support custom events #3350
switch (e.type) {
case "click":
case "mouseup":
case "mousedown":
case "dblclick":
... | {} | identifier_body |
no_0064_minimum_path_sum.rs | struct Solution;
impl Solution {
pub fn min_path_sum(grid: Vec<Vec<i32>>) -> i32 {
if grid.is_empty() {
return 0;
}
let (m, n) = (grid.len(), grid[0].len());
let mut arr = vec![std::i32::MAX; n];
arr[0] = 0;
for i in 0..m {
for j in 0..n {
... | }
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_min_path_sum() {
let grid = vec![vec![1, 3, 1], vec![1, 5, 1], vec![4, 2, 1]];
assert_eq!(Solution::min_path_sum(grid), 7);
}
} | } | random_line_split |
no_0064_minimum_path_sum.rs | struct Solution;
impl Solution {
pub fn | (grid: Vec<Vec<i32>>) -> i32 {
if grid.is_empty() {
return 0;
}
let (m, n) = (grid.len(), grid[0].len());
let mut arr = vec![std::i32::MAX; n];
arr[0] = 0;
for i in 0..m {
for j in 0..n {
// 选择上面(arr[j])和左面(arr[j-1])最小的那个
... | min_path_sum | identifier_name |
no_0064_minimum_path_sum.rs | struct Solution;
impl Solution {
pub fn min_path_sum(grid: Vec<Vec<i32>>) -> i32 | arr[n - 1]
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_min_path_sum() {
let grid = vec![vec![1, 3, 1], vec![1, 5, 1], vec![4, 2, 1]];
assert_eq!(Solution::min_path_sum(grid), 7);
}
}
| {
if grid.is_empty() {
return 0;
}
let (m, n) = (grid.len(), grid[0].len());
let mut arr = vec![std::i32::MAX; n];
arr[0] = 0;
for i in 0..m {
for j in 0..n {
// 选择上面(arr[j])和左面(arr[j-1])最小的那个
if j == 0 {
... | identifier_body |
no_0064_minimum_path_sum.rs | struct Solution;
impl Solution {
pub fn min_path_sum(grid: Vec<Vec<i32>>) -> i32 {
if grid.is_empty() |
let (m, n) = (grid.len(), grid[0].len());
let mut arr = vec![std::i32::MAX; n];
arr[0] = 0;
for i in 0..m {
for j in 0..n {
// 选择上面(arr[j])和左面(arr[j-1])最小的那个
if j == 0 {
// 左边没有,只有上面的元素
arr[j] = arr[j] +... | {
return 0;
} | conditional_block |
issue-59494.rs | fn | <A, B, C>(f: impl Fn(B) -> C, g: impl Fn(A) -> B) -> impl Fn(A) -> C {
move |a: A| -> C { f(g(a)) }
}
fn t8n<A, B, C>(f: impl Fn(A) -> B, g: impl Fn(A) -> C) -> impl Fn(A) -> (B, C)
where
A: Copy,
{
move |a: A| -> (B, C) {
let b = a;
let fa = f(a);
let ga = g(b);
(fa, ga)
... | t7p | identifier_name |
issue-59494.rs | fn t7p<A, B, C>(f: impl Fn(B) -> C, g: impl Fn(A) -> B) -> impl Fn(A) -> C |
fn t8n<A, B, C>(f: impl Fn(A) -> B, g: impl Fn(A) -> C) -> impl Fn(A) -> (B, C)
where
A: Copy,
{
move |a: A| -> (B, C) {
let b = a;
let fa = f(a);
let ga = g(b);
(fa, ga)
}
}
fn main() {
let f = |(_, _)| {};
let g = |(a, _)| a;
let t7 = |env| |a| |b| t7p(f, g)(... | {
move |a: A| -> C { f(g(a)) }
} | identifier_body |
issue-59494.rs | fn t7p<A, B, C>(f: impl Fn(B) -> C, g: impl Fn(A) -> B) -> impl Fn(A) -> C {
move |a: A| -> C { f(g(a)) }
}
fn t8n<A, B, C>(f: impl Fn(A) -> B, g: impl Fn(A) -> C) -> impl Fn(A) -> (B, C)
where
A: Copy,
{
move |a: A| -> (B, C) {
let b = a;
let fa = f(a);
let ga = g(b);
(fa, ... | let g = |(a, _)| a;
let t7 = |env| |a| |b| t7p(f, g)(((env, a), b));
let t8 = t8n(t7, t7p(f, g));
//~^ ERROR: expected a `Fn<(_,)>` closure, found `impl Fn<(((_, _), _),)>
} | let f = |(_, _)| {}; | random_line_split |
bst.rs | // Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... | let mut x = BinarySearchTree::new();
x.insert(5);
x.insert(6);
assert!(x.contains(&5));
assert!(x.contains(&6));
assert!(!x.contains(&7));
}
#[test]
fn test_structure() {
let mut x = BinarySearchTree::new();
x.insert(10);
x.insert(15);... | fn test_insert_contains() { | random_line_split |
bst.rs | // Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... | <T> {
v: T,
left: NodePtr<T>,
right: NodePtr<T>,
}
type NodePtr<T> = Option<Box<Node<T>>>;
#[derive(Debug)]
pub struct BinarySearchTree<T> {
root: NodePtr<T>,
}
impl<T> Node<T> {
fn new(v: T) -> NodePtr<T> {
Some(Box::new(Self {
v,
left: None,
right: No... | Node | identifier_name |
bst.rs | // Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... |
pub fn insert(&mut self, v: T)
where
T: Ord,
{
let slot = self.find_slot(&v);
if slot.is_none() {
*slot = Node::new(v);
}
}
pub fn contains(&self, v: &T) -> bool
where
T: Ord + std::fmt::Debug,
{
let mut current = &self.root;
... | {
let mut current = &mut self.root;
while current.is_some() {
if ¤t.as_ref().unwrap().v == v {
break;
}
use std::cmp::Ordering;
let inner = current.as_mut().unwrap();
match v.cmp(&inner.v) {
Ordering::Less ... | identifier_body |
ContinuousMonitoringUtils.ts | import tl = require('vsts-task-lib/task');
import { AzureEndpoint } from 'azure-arm-rest/azureModels';
import {AzureAppService } from 'azure-arm-rest/azure-arm-app-service';
import { AzureApplicationInsights } from 'azure-arm-rest/azure-arm-appinsights';
import { Kudu } from 'azure-arm-rest/azure-arm-app-service-kudu'... | catch(error) {
tl.warning(error);
}
try {
tl.debug('add web test for app service - app insights');
var appInsightsWebTestsUtils: AzureApplicationInsightsWebTestsUtils = new AzureApplicationInsightsWebTestsUtils(appInsightsWebTests);
await ... | await appService.patchConfiguration({ "properties" :{"alwaysOn": true}});
} | random_line_split |
ContinuousMonitoringUtils.ts | import tl = require('vsts-task-lib/task');
import { AzureEndpoint } from 'azure-arm-rest/azureModels';
import {AzureAppService } from 'azure-arm-rest/azure-arm-app-service';
import { AzureApplicationInsights } from 'azure-arm-rest/azure-arm-appinsights';
import { Kudu } from 'azure-arm-rest/azure-arm-app-service-kudu'... |
appInsightsResource.tags["hidden-link:" + appDetails.id] = "Resource";
tl.debug('Link app insights with app service via tag');
await appInsights.update(appInsightsResource);
tl.debug('Link app service with app insights via instrumentation key');
await appService.patchApplicatio... | {
var appKuduService: Kudu = await appServiceUtils.getKuduService();
await appKuduService.installSiteExtension(APPLICATION_INSIGHTS_EXTENSION_NAME);
} | conditional_block |
ContinuousMonitoringUtils.ts | import tl = require('vsts-task-lib/task');
import { AzureEndpoint } from 'azure-arm-rest/azureModels';
import {AzureAppService } from 'azure-arm-rest/azure-arm-app-service';
import { AzureApplicationInsights } from 'azure-arm-rest/azure-arm-appinsights';
import { Kudu } from 'azure-arm-rest/azure-arm-app-service-kudu'... | });
try {
tl.debug('Enable alwaysOn property for app service.');
await appService.patchConfiguration({ "properties" :{"alwaysOn": true}});
}
catch(error) {
tl.warning(error);
}
try {
tl.debug('add web test for ... | {
try {
console.log(tl.loc('EnablingContinousMonitoring', appService.getName()));
var appDetails = await appService.get();
var appServiceUtils = new AzureAppServiceUtils(appService);
var appInsightsResource = await appInsights.get();
var appInsightsWebTests = new ApplicationI... | identifier_body |
ContinuousMonitoringUtils.ts | import tl = require('vsts-task-lib/task');
import { AzureEndpoint } from 'azure-arm-rest/azureModels';
import {AzureAppService } from 'azure-arm-rest/azure-arm-app-service';
import { AzureApplicationInsights } from 'azure-arm-rest/azure-arm-appinsights';
import { Kudu } from 'azure-arm-rest/azure-arm-app-service-kudu'... | (endpoint: AzureEndpoint, appService: AzureAppService, appInsights: AzureApplicationInsights) {
try {
console.log(tl.loc('EnablingContinousMonitoring', appService.getName()));
var appDetails = await appService.get();
var appServiceUtils = new AzureAppServiceUtils(appService);
var app... | enableContinuousMonitoring | identifier_name |
setup.py | from setuptools import setup, Extension
with open('README.md') as istream:
long_description = istream.read()
tests_require = ['pytest']
libReQL = Extension(
'libReQL',
include_dirs=['src'],
sources=[
'src/Python/connection.c',
'src/Python/cursor.c',
'src/Python/query.c',
... | 'testing': tests_require
},
ext_modules=[libReQL],
keywords='',
license='Apache',
long_description=long_description,
name='libReQL',
package_data={
},
tests_require=tests_require,
url='https://github.com/grandquista/ReQL-Core',
version='1.0.0',
zip_safe=True
) | },
extras_require={ | random_line_split |
parsertestcase.py | #
# Walldo - A wallpaper downloader
# Copyright (C) 2012 Fernando Castillo
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later v... | current = self.parser.parse(self.lines, '1024x768')
for i in range(len(current)):
self.assertEquals(self.expected[i], current[i], 'Entry incorrect') | identifier_body | |
parsertestcase.py | #
# Walldo - A wallpaper downloader
# Copyright (C) 2012 Fernando Castillo
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,... | # as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of | random_line_split |
parsertestcase.py | #
# Walldo - A wallpaper downloader
# Copyright (C) 2012 Fernando Castillo
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later v... | self.assertEquals(self.expected[i], current[i], 'Entry incorrect') | conditional_block | |
parsertestcase.py | #
# Walldo - A wallpaper downloader
# Copyright (C) 2012 Fernando Castillo
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later v... | (self):
current = self.parser.parse(self.lines, '1024x768')
for i in range(len(current)):
self.assertEquals(self.expected[i], current[i], 'Entry incorrect')
| testParse | identifier_name |
taskbar_ui.js | (function ($) {
/**
* Move a block in the blocks table from one region to another via select list.
*
* This behavior is dependent on the tableDrag behavior, since it uses the
* objects initialized in that behavior to update the row.
*/
Drupal.behaviors.taskbarUIDrag = {
attach: function (context, settings) {
... |
// This region has become empty
if ($(this).next('tr').is(':not(.draggable)') || $(this).next('tr').size() == 0) {
$(this).removeClass('region-populated').addClass('region-empty');
}
// This region has become populated.
else if ($(this).is('.region-empty')) {
... | {
// Prevent a recursion problem when using the keyboard to move rows up.
if ((rowObject.method != 'keyboard' || rowObject.direction == 'down')) {
rowObject.swap('after', this);
}
} | conditional_block |
taskbar_ui.js | (function ($) {
/**
* Move a block in the blocks table from one region to another via select list.
*
* This behavior is dependent on the tableDrag behavior, since it uses the
* objects initialized in that behavior to update the row.
*/
Drupal.behaviors.taskbarUIDrag = {
attach: function (context, settings) {
... |
// Add the behavior to each region select list.
$('select.item-region-select', context).once('item-region-select', function() {
$(this).change(function(event) {
// Make our new row and select field.
var row = $(this).parents('tr:first');
var select = $(this);
tableDrag.row... | }; | random_line_split |
hypothesis_testing_kolmogorov_smirnov_test_example.py | #
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not us... | sc = SparkContext(appName="HypothesisTestingKolmogorovSmirnovTestExample")
# $example on$
parallelData = sc.parallelize([0.1, 0.15, 0.2, 0.3, 0.25])
# run a KS test for the sample versus a standard normal distribution
testResult = Statistics.kolmogorovSmirnovTest(parallelData, "norm", 0, 1)
# summ... | conditional_block | |
hypothesis_testing_kolmogorov_smirnov_test_example.py | #
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not us... | # Note that the Scala functionality of calling Statistics.kolmogorovSmirnovTest with
# a lambda to calculate the CDF is not made available in the Python API
print(testResult)
# $example off$
sc.stop() | # run a KS test for the sample versus a standard normal distribution
testResult = Statistics.kolmogorovSmirnovTest(parallelData, "norm", 0, 1)
# summary of the test including the p-value, test statistic, and null hypothesis
# if our p-value indicates significance, we can reject the null hypothesis | random_line_split |
vote-taker.componet.ts | import {Component} from '@angular/core';
import { HEROES } from './mock-heroes';
@Component({
selector: 'vote-taker',
template: `
<h2>Should mankind colonize the Universe?</h2>
<h3>Agree: {{agreed}}, Disagree: {{disagreed}}</h3>
<my-voter *ngFor="let voter of heroes"
length=5
[na... | greed: boolean) {
agreed ? this.agreed++ : this.disagreed++;
}
}
| Voted(a | identifier_name |
vote-taker.componet.ts | selector: 'vote-taker',
template: `
<h2>Should mankind colonize the Universe?</h2>
<h3>Agree: {{agreed}}, Disagree: {{disagreed}}</h3>
<my-voter *ngFor="let voter of heroes"
length=5
[name]="voter.name"
(onVoted)="onVoted($event)">
</my-voter>
`
})
export class VoteTakerComp... | import {Component} from '@angular/core';
import { HEROES } from './mock-heroes';
@Component({ | random_line_split | |
vote-taker.componet.ts | import {Component} from '@angular/core';
import { HEROES } from './mock-heroes';
@Component({
selector: 'vote-taker',
template: `
<h2>Should mankind colonize the Universe?</h2>
<h3>Agree: {{agreed}}, Disagree: {{disagreed}}</h3>
<my-voter *ngFor="let voter of heroes"
length=5
[na... | agreed ? this.agreed++ : this.disagreed++;
}
} | identifier_body | |
minters.py | # -*- coding: utf-8 -*-
#
# This file is part of CERN Analysis Preservation Framework.
# Copyright (C) 2018 CERN.
#
# CERN Analysis Preservation Framework 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... | object_uuid=record_uuid,
status=PIDStatus.REGISTERED
)
data['_deposit'] = {
'id': pid.pid_value,
'status': 'draft',
}
return pid | pid_value,
object_type='rec', | random_line_split |
minters.py | # -*- coding: utf-8 -*-
#
# This file is part of CERN Analysis Preservation Framework.
# Copyright (C) 2018 CERN.
#
# CERN Analysis Preservation Framework 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... | (record_uuid, data):
"""Mint deposit's identifier."""
try:
pid_value = data['_deposit']['id']
except KeyError:
pid_value = uuid.uuid4().hex
pid = PersistentIdentifier.create(
'depid',
pid_value,
object_type='rec',
object_uuid=record_uuid,
status=P... | cap_deposit_minter | identifier_name |
minters.py | # -*- coding: utf-8 -*-
#
# This file is part of CERN Analysis Preservation Framework.
# Copyright (C) 2018 CERN.
#
# CERN Analysis Preservation Framework 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... | """Mint deposit's identifier."""
try:
pid_value = data['_deposit']['id']
except KeyError:
pid_value = uuid.uuid4().hex
pid = PersistentIdentifier.create(
'depid',
pid_value,
object_type='rec',
object_uuid=record_uuid,
status=PIDStatus.REGISTERED
)... | identifier_body | |
widget_QTableView_edit_print_signal_when_data_changed.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Ref: http://doc.qt.io/qt-5/modelview.html#2-1-a-read-only-table
import sys
from PyQt5.QtCore import Qt, QAbstractTableModel, QVariant
from PyQt5.QtWidgets import QApplication, QTableView
class MyData:
def __init__(self):
self._num_rows = 3
self._nu... | my_model = MyModel(data)
my_model.dataChanged.connect(changedCallback)
my_model.rowsInserted.connect(changedCallback)
my_model.rowsRemoved.connect(changedCallback)
table_view.setModel(my_model)
table_view.show()
# The mainloop of the application. The event handling starts from this point.... | data = MyData()
table_view = QTableView() | random_line_split |
widget_QTableView_edit_print_signal_when_data_changed.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Ref: http://doc.qt.io/qt-5/modelview.html#2-1-a-read-only-table
import sys
from PyQt5.QtCore import Qt, QAbstractTableModel, QVariant
from PyQt5.QtWidgets import QApplication, QTableView
class | :
def __init__(self):
self._num_rows = 3
self._num_columns = 2
self._data = [["hello" for j in range(self._num_columns)] for i in range(self._num_rows)]
def get_num_rows(self):
return self._num_rows
def get_num_columns(self):
return self._num_columns
def get_d... | MyData | identifier_name |
widget_QTableView_edit_print_signal_when_data_changed.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Ref: http://doc.qt.io/qt-5/modelview.html#2-1-a-read-only-table
import sys
from PyQt5.QtCore import Qt, QAbstractTableModel, QVariant
from PyQt5.QtWidgets import QApplication, QTableView
class MyData:
def __init__(self):
self._num_rows = 3
self._nu... | sys.exit(exit_code)
| app = QApplication(sys.argv)
data = MyData()
table_view = QTableView()
my_model = MyModel(data)
my_model.dataChanged.connect(changedCallback)
my_model.rowsInserted.connect(changedCallback)
my_model.rowsRemoved.connect(changedCallback)
table_view.setModel(my_model)
table_view.show()
... | conditional_block |
widget_QTableView_edit_print_signal_when_data_changed.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Ref: http://doc.qt.io/qt-5/modelview.html#2-1-a-read-only-table
import sys
from PyQt5.QtCore import Qt, QAbstractTableModel, QVariant
from PyQt5.QtWidgets import QApplication, QTableView
class MyData:
def __init__(self):
self._num_rows = 3
self._nu... |
def changedCallback():
print("changed")
if __name__ == '__main__':
app = QApplication(sys.argv)
data = MyData()
table_view = QTableView()
my_model = MyModel(data)
my_model.dataChanged.connect(changedCallback)
my_model.rowsInserted.connect(changedCallback)
my_model.rowsRemoved.con... | return Qt.ItemIsSelectable | Qt.ItemIsEditable | Qt.ItemIsEnabled | identifier_body |
dlg_github_login_ui.py | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file '/home/colin/dev/QCrash/forms/dlg_github_login.ui'
#
# Created by: PyQt5 UI code generator 5.5.1
#
# WARNING! All changes made in this file will be lost!
from qcrash.qt import QtCore, QtGui, QtWidgets
class Ui_Dialog(object):
def setupU... |
from . import qcrash_rc | _translate = QtCore.QCoreApplication.translate
Dialog.setWindowTitle(_translate("Dialog", "Sign in to github"))
self.lbl_html.setText(_translate("Dialog", "<html><head/><body><p align=\"center\"><img src=\":/rc/GitHub-Mark.png\"/></p><p align=\"center\">Sign in to GitHub</p></body></html>"))
sel... | identifier_body |
dlg_github_login_ui.py | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file '/home/colin/dev/QCrash/forms/dlg_github_login.ui'
#
# Created by: PyQt5 UI code generator 5.5.1
#
# WARNING! All changes made in this file will be lost!
from qcrash.qt import QtCore, QtGui, QtWidgets
class Ui_Dialog(object):
def | (self, Dialog):
Dialog.setObjectName("Dialog")
Dialog.resize(366, 248)
Dialog.setMinimumSize(QtCore.QSize(350, 0))
self.verticalLayout = QtWidgets.QVBoxLayout(Dialog)
self.verticalLayout.setObjectName("verticalLayout")
self.lbl_html = QtWidgets.QLabel(Dialog)
self... | setupUi | identifier_name |
dlg_github_login_ui.py | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file '/home/colin/dev/QCrash/forms/dlg_github_login.ui'
#
# Created by: PyQt5 UI code generator 5.5.1
#
# WARNING! All changes made in this file will be lost!
| def setupUi(self, Dialog):
Dialog.setObjectName("Dialog")
Dialog.resize(366, 248)
Dialog.setMinimumSize(QtCore.QSize(350, 0))
self.verticalLayout = QtWidgets.QVBoxLayout(Dialog)
self.verticalLayout.setObjectName("verticalLayout")
self.lbl_html = QtWidgets.QLabel(Dialo... | from qcrash.qt import QtCore, QtGui, QtWidgets
class Ui_Dialog(object): | random_line_split |
accounts.py | """
sentry.web.frontend.accounts
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2012 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import
import itertools
from django.contrib import messages
from django.contrib.auth import login as lo... | settings_form = NotificationSettingsForm(request.user, request.POST or None)
# TODO(dcramer): this is an extremely bad pattern and we need a more optimal
# solution for rendering this (that ideally plays well with the org data)
project_list = []
organization_list = Organization.objects.get_for_user... | def notification_settings(request): | random_line_split |
accounts.py | """
sentry.web.frontend.accounts
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2012 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import
import itertools
from django.contrib import messages
from django.contrib.auth import login as lo... |
else:
form = ChangePasswordRecoverForm()
context = {
'form': form,
}
return render_to_response(tpl, context, request)
@csrf_protect
@never_cache
@login_required
@sudo_required
@transaction.atomic
def settings(request):
form = AccountSettingsForm(request.user,... | user.set_password(form.cleaned_data['password'])
user.save()
# Ugly way of doing this, but Django requires the backend be set
user = authenticate(
username=user.username,
password=form.cleaned_data['password'],
)
... | conditional_block |
accounts.py | """
sentry.web.frontend.accounts
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2012 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import
import itertools
from django.contrib import messages
from django.contrib.auth import login as lo... | # Ugly way of doing this, but Django requires the backend be set
user = authenticate(
username=user.username,
password=form.cleaned_data['password'],
)
login_user(request, user)
password_hash.delete... | try:
password_hash = LostPasswordHash.objects.get(user=user_id, hash=hash)
if not password_hash.is_valid():
password_hash.delete()
raise LostPasswordHash.DoesNotExist
user = password_hash.user
except LostPasswordHash.DoesNotExist:
context = {}
tpl = '... | identifier_body |
accounts.py | """
sentry.web.frontend.accounts
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2012 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import
import itertools
from django.contrib import messages
from django.contrib.auth import login as lo... | (request):
login_url = get_login_redirect(request)
return HttpResponseRedirect(login_url)
def recover(request):
form = RecoverPasswordForm(request.POST or None,
captcha=bool(request.session.get('needs_captcha')))
if form.is_valid():
password_hash, created = LostP... | login_redirect | identifier_name |
mod.rs | // This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
mod bindings;
use std::{collections::HashMap, ffi::CString, io};
use log::Record;
use crate::stratis::{StratisErro... |
/// Notify systemd that a daemon has started.
#[allow(clippy::implicit_hasher)]
pub fn notify(unset_variable: bool, key_value_pairs: HashMap<String, String>) -> StratisResult<()> {
let serialized_pairs = serialize_pairs(key_value_pairs);
let cstring = CString::new(serialized_pairs)?;
let ret = unsafe { bi... | {
pairs
.iter()
.map(|(key, value)| format!("{}={}", key, value))
.fold(String::new(), |mut string, key_value_pair| {
string += key_value_pair.as_str();
string += "\n";
string
})
} | identifier_body |
mod.rs | // This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
mod bindings;
use std::{collections::HashMap, ffi::CString, io}; | use log::Record;
use crate::stratis::{StratisError, StratisResult};
fn serialize_pairs(pairs: HashMap<String, String>) -> String {
pairs
.iter()
.map(|(key, value)| format!("{}={}", key, value))
.fold(String::new(), |mut string, key_value_pair| {
string += key_value_pair.as_str... | random_line_split | |
mod.rs | // This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
mod bindings;
use std::{collections::HashMap, ffi::CString, io};
use log::Record;
use crate::stratis::{StratisErro... | (pairs: HashMap<String, String>) -> String {
pairs
.iter()
.map(|(key, value)| format!("{}={}", key, value))
.fold(String::new(), |mut string, key_value_pair| {
string += key_value_pair.as_str();
string += "\n";
string
})
}
/// Notify systemd that... | serialize_pairs | identifier_name |
message.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use {OpaqueStyleAndLayoutData, PendingImage, TrustedNodeAddress};
use app_units::Au;
use euclid::{Point2D, Rect};
... | {
pub id: PipelineId,
pub url: ServoUrl,
pub is_parent: bool,
pub layout_pair: (Sender<Msg>, Receiver<Msg>),
pub pipeline_port: IpcReceiver<LayoutControlMsg>,
pub constellation_chan: IpcSender<ConstellationMsg>,
pub script_chan: IpcSender<ConstellationControlMsg>,
pub image_cache: Arc<I... | NewLayoutThreadInfo | identifier_name |
message.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use {OpaqueStyleAndLayoutData, PendingImage, TrustedNodeAddress};
use app_units::Au;
use euclid::{Point2D, Rect};
... | use script_traits::{ScrollState, UntrustedNodeAddress, WindowSizeData};
use script_traits::Painter;
use servo_arc::Arc as ServoArc;
use servo_atoms::Atom;
use servo_channel::{Receiver, Sender};
use servo_url::ServoUrl;
use std::sync::Arc;
use style::context::QuirksMode;
use style::properties::PropertyId;
use style::sel... | random_line_split | |
message.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use {OpaqueStyleAndLayoutData, PendingImage, TrustedNodeAddress};
use app_units::Au;
use euclid::{Point2D, Rect};
... |
}
/// Information needed for a reflow.
pub struct Reflow {
/// A clipping rectangle for the page, an enlarged rectangle containing the viewport.
pub page_clip_rect: Rect<Au>,
}
/// Information derived from a layout pass that needs to be returned to the script thread.
#[derive(Default)]
pub struct ReflowComp... | {
match *self {
ReflowGoal::Full | ReflowGoal::TickAnimations => true,
ReflowGoal::LayoutQuery(ref querymsg, _) => match querymsg {
&QueryMsg::NodesFromPointQuery(..) |
&QueryMsg::TextIndexQuery(..) |
&QueryMsg::ElementInnerTextQuery(_) => ... | identifier_body |
linkedList.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | <E> {
element: E;
next: Node<E>;
prev: Node<E>;
constructor(element: E) {
this.element = element;
}
}
export class LinkedList<E> {
private _first: Node<E>;
private _last: Node<E>;
isEmpty(): boolean {
return !this._first;
}
clear(): void {
this._first = undefined;
this._last = undefined;
}
uns... | Node | identifier_name |
linkedList.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... |
unshift(element: E) {
return this.insert(element, false);
}
push(element: E) {
return this.insert(element, true);
}
private insert(element: E, atTheEnd: boolean) {
const newNode = new Node(element);
if (!this._first) {
this._first = newNode;
this._last = newNode;
} else if (atTheEnd) {
// p... | {
this._first = undefined;
this._last = undefined;
} | identifier_body |
linkedList.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | }
};
}
iterator(): IIterator<E> {
let _done: boolean;
let _value: E;
let element = {
get done() { return _done; },
get value() { return _value; }
};
let node = this._first;
return {
next(): { done: boolean; value: E } {
if (!node) {
_done = true;
_value = undefined;
} else... | random_line_split | |
linkedList.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... |
return () => {
for (let candidate = this._first; candidate instanceof Node; candidate = candidate.next) {
if (candidate !== newNode) {
continue;
}
if (candidate.prev && candidate.next) {
// middle
let anchor = candidate.prev;
anchor.next = candidate.next;
candidate.next.prev... | {
// unshift
const oldFirst = this._first;
this._first = newNode;
newNode.next = oldFirst;
oldFirst.prev = newNode;
} | conditional_block |
pin_pt.rs | // Zinc, the bare metal stack for rust.
// Copyright 2014 Vladimir "farcaller" Pouzanov <farcaller@gmail.com>
//
// 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.o... | format!("unknown pin function `{}`, allowed functions: {}",
fun, avaliable.join(", ")).as_str());
return;
},
Some(func_idx) => {
format!("AltFunction{}", func_idx)
}
}
}
}
}
};
let fu... | match maybe_func {
None => {
let avaliable: Vec<String> = pin_funcs.keys().map(|k|{k.to_string()}).collect();
cx.parse_sess().span_diagnostic.span_err(
node.get_attr("function").value_span, | random_line_split |
pin_pt.rs | // Zinc, the bare metal stack for rust.
// Copyright 2014 Vladimir "farcaller" Pouzanov <farcaller@gmail.com>
//
// 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.o... | (builder: &mut Builder, _: &mut ExtCtxt, node: Rc<node::Node>) {
node.materializer.set(Some(verify as fn(&mut Builder, &mut ExtCtxt, Rc<node::Node>)));
for port_node in node.subnodes().iter() {
port_node.materializer.set(Some(verify as fn(&mut Builder, &mut ExtCtxt, Rc<node::Node>)));
add_node_dependency(&n... | attach | identifier_name |
pin_pt.rs | // Zinc, the bare metal stack for rust.
// Copyright 2014 Vladimir "farcaller" Pouzanov <farcaller@gmail.com>
//
// 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.o... |
#[test]
fn builds_altfn_gpio() {
with_parsed("
gpio {
0 {
p3@3 { direction = \"out\"; function = \"ad0_6\"; }
}
}", |cx, failed, pt| {
let mut builder = Builder::new(pt.clone(), cx);
super::build_pin(&mut builder, cx, pt.get_by_name("p3").unwrap());
asse... | {
with_parsed("
gpio {
0 {
p2@2 { direction = \"out\"; }
}
}", |cx, failed, pt| {
let mut builder = Builder::new(pt.clone(), cx);
super::build_pin(&mut builder, cx, pt.get_by_name("p2").unwrap());
assert!(unsafe{*failed} == false);
assert!(builder.main_s... | identifier_body |
live.spec.ts | import {TestBed, ComponentFixture, inject} from '@angular/core/testing';
import {Component} from '@angular/core';
import {By} from '@angular/platform-browser';
import {Live, ARIA_LIVE_DELAY} from './live';
function getLiveElement(): HTMLElement {
return document.body.querySelector('#ngb-live') !as HTMLElement;
}
... |
}
| { this.live.say('test'); } | identifier_body |
live.spec.ts | import {TestBed, ComponentFixture, inject} from '@angular/core/testing';
import {Component} from '@angular/core';
import {By} from '@angular/platform-browser';
import {Live, ARIA_LIVE_DELAY} from './live';
function getLiveElement(): HTMLElement {
return document.body.querySelector('#ngb-live') !as HTMLElement;
}
... | {
constructor(public live: Live) {}
say() { this.live.say('test'); }
}
| TestComponent | identifier_name |
live.spec.ts | import {TestBed, ComponentFixture, inject} from '@angular/core/testing';
import {Component} from '@angular/core';
import {By} from '@angular/platform-browser';
import {Live, ARIA_LIVE_DELAY} from './live';
function getLiveElement(): HTMLElement {
return document.body.querySelector('#ngb-live') !as HTMLElement;
}
... |
it('should remove the used element from the DOM on destroy', () => {
say();
live.ngOnDestroy();
expect(getLiveElement()).toBeFalsy();
});
});
});
@Component({template: `<button (click)="say()">say</button>`})
class TestComponent {
constructor(public live: Live) {}
say() { this.live.... | const liveElement = getLiveElement();
expect(liveElement.textContent).toBe('test');
expect(liveElement.id).toBe('ngb-live');
}); | random_line_split |
transaction.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any lat... |
/// Creates new view onto block from rlp.
pub fn new_from_rlp(rlp: Rlp<'a>) -> TransactionView<'a> {
TransactionView {
rlp: rlp
}
}
/// Return reference to underlaying rlp.
pub fn rlp(&self) -> &Rlp<'a> {
&self.rlp
}
/// Get the nonce field of the transaction.
pub fn nonce(&self) -> U256 { self.rlp... | {
TransactionView {
rlp: Rlp::new(bytes)
}
} | identifier_body |
transaction.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any lat... | // GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! View onto transaction rlp
use util::{U256, Bytes, Hashable, H256};
use rlp::{Rlp, View};
/// View onto transaction rlp.
pub struc... | // Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | random_line_split |
transaction.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any lat... | (bytes: &'a [u8]) -> TransactionView<'a> {
TransactionView {
rlp: Rlp::new(bytes)
}
}
/// Creates new view onto block from rlp.
pub fn new_from_rlp(rlp: Rlp<'a>) -> TransactionView<'a> {
TransactionView {
rlp: rlp
}
}
/// Return reference to underlaying rlp.
pub fn rlp(&self) -> &Rlp<'a> {
&self... | new | identifier_name |
luhn_test.rs | // Implements http://rosettacode.org/wiki/Luhn_test_of_credit_card_numbers
struct | {
m: u64
}
impl Iterator for Digits {
type Item = u64;
fn next(&mut self) -> Option<u64> {
match self.m {
0 => None,
n => {
let ret = n % 10;
self.m = n / 10;
Some(ret)
}
}
}
}
#[derive(Copy, Clone)]
enum Lu... | Digits | identifier_name |
luhn_test.rs | // Implements http://rosettacode.org/wiki/Luhn_test_of_credit_card_numbers
struct Digits {
m: u64
}
impl Iterator for Digits {
type Item = u64;
fn next(&mut self) -> Option<u64> {
match self.m {
0 => None,
n => {
let ret = n % 10;
self.m = n / 10... | {
assert!(luhn_test(49927398716));
assert!(!luhn_test(49927398717));
assert!(!luhn_test(1234567812345678));
assert!(luhn_test(1234567812345670));
} | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.