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 |
|---|---|---|---|---|
plane.rs | ----------+
// | Copyright 2016 Matthew D. Steele <mdsteele@alum.mit.edu> |
// | |
// | This file is part of System Syzygy. |
// | ... |
}
(Direction::North, Direction::East) => 4,
(Direction::North, Direction::West) => 7,
(Direction::South, Direction::East) => 5,
(Direction::South, Direction::West) => 6,
(Direction::North, _) | (Dire... | {
8
} | conditional_block |
plane.rs | ----------+
// | Copyright 2016 Matthew D. Steele <mdsteele@alum.mit.edu> |
// | |
// | This file is part of System Syzygy. |
// | ... |
pub fn cancel_drag_and_clear_changes(&mut self) {
self.drag_from = None;
self.changes.clear();
}
pub fn cancel_drag_and_undo_changes(&mut self, grid: &mut PlaneGrid) {
self.drag_from = None;
for &(coords1, coords2) in self.changes.iter().rev() {
grid.toggle_pip... | {
PlaneGridView {
left,
top,
obj_sprites: resources.get_sprites("plane/objects"),
pipe_sprites: resources.get_sprites("plane/pipes"),
drag_from: None,
changes: Vec::new(),
font: resources.get_font("roman"),
letters: ... | identifier_body |
plane.rs | --------------------------------------------------------------------------+
// | Copyright 2016 Matthew D. Steele <mdsteele@alum.mit.edu> |
// | |
// | This file is part of System Syzygy. |
// |... | (Direction::North, Direction::West) => 7,
(Direction::South, Direction::East) => 5,
(Direction::South, Direction::West) => 6,
(Direction::North, _) | (Direction::South, _) => 9,
};
let sprite = &self.pipe_spr... | random_line_split | |
JobSubmit.py | #!/usr/bin/env ganga
import getpass
from distutils.util import strtobool
polarity='MagDown'
datatype='MC'
substitution='None'
channel='11164031'
b=Job()
b.application=DaVinci(version="v36r5")
if datatype=='MC':
b.application.optsfile='NTupleMaker_{0}.py'.format(polarity)
if datatype=='Data':
if substitution... |
b.outputfiles=[DiracFile('Output.root')]
b.inputdata = b.application.readInputData('{0}_12_{1}_{2}.py'.format(datatype,channel,polarity))
if substitution=='None':
b.comment='{0}_12_{1}_{2}'.format(datatype,polarity,channel)
if substitution=='PimforKm':
b.comment='{0}_12_{1}_{2}_{3}'.format(datatype,polarity,ch... | b.application.optsfile='DNTupleMaker_PimforKm.py' | conditional_block |
JobSubmit.py | #!/usr/bin/env ganga
import getpass
from distutils.util import strtobool
polarity='MagDown'
datatype='MC'
substitution='None'
channel='11164031'
b=Job()
b.application=DaVinci(version="v36r5")
if datatype=='MC':
b.application.optsfile='NTupleMaker_{0}.py'.format(polarity)
if datatype=='Data':
if substitution... | if datatype=='MC':
b2.application.optsfile='NTupleMaker_{0}.py'.format(polarity)
if datatype=='Data':
if substitution=='None':
b2.application.optsfile='DNTupleMaker.py'
if substitution=='PimforKm':
b2.application.optsfile='DNTupleMaker_PimforKm.py'
b2.outputfiles=[DiracFile('Output.root')]
b... | random_line_split | |
test-trac-0218.py | # -*- coding: utf-8 -*-
import logging
if __name__ == '__main__':
logging.basicConfig()
_log = logging.getLogger(__name__)
import pyxb.binding.generate
import pyxb.utils.domutils
from xml.dom import Node
import os.path
xst = '''<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:ele... | (self):
instance = topLevel()
self.assertTrue(instance.item is not None)
self.assertFalse(instance.item is None)
self.assertTrue(instance.item != None)
self.assertTrue(None != instance.item)
self.assertFalse(instance.item)
instance.item.extend([1,2,3,4])
... | testBasic | identifier_name |
test-trac-0218.py | # -*- coding: utf-8 -*-
import logging
if __name__ == '__main__':
logging.basicConfig()
_log = logging.getLogger(__name__)
import pyxb.binding.generate
import pyxb.utils.domutils
from xml.dom import Node
import os.path
xst = '''<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:ele... |
if __name__ == '__main__':
unittest.main()
| def testBasic (self):
instance = topLevel()
self.assertTrue(instance.item is not None)
self.assertFalse(instance.item is None)
self.assertTrue(instance.item != None)
self.assertTrue(None != instance.item)
self.assertFalse(instance.item)
instance.item.extend([1,2,3... | identifier_body |
test-trac-0218.py | # -*- coding: utf-8 -*-
import logging
if __name__ == '__main__':
logging.basicConfig()
_log = logging.getLogger(__name__)
import pyxb.binding.generate
import pyxb.utils.domutils
from xml.dom import Node
import os.path
xst = '''<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:ele... | instance = topLevel()
self.assertTrue(instance.item is not None)
self.assertFalse(instance.item is None)
self.assertTrue(instance.item != None)
self.assertTrue(None != instance.item)
self.assertFalse(instance.item)
instance.item.extend([1,2,3,4])
self.asse... | import unittest
class TestTrac0218 (unittest.TestCase):
def testBasic (self): | random_line_split |
test-trac-0218.py | # -*- coding: utf-8 -*-
import logging
if __name__ == '__main__':
|
_log = logging.getLogger(__name__)
import pyxb.binding.generate
import pyxb.utils.domutils
from xml.dom import Node
import os.path
xst = '''<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="topLevel">
<xs:complexType>
<xs:sequence>
<xs:element name="it... | logging.basicConfig() | conditional_block |
interfaces.ts | /**
* 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... | */
export type CommitQuery = Partial<
Pick<Commit, 'customerId' | 'listingId' | 'commitStatus'>
>;
/**
* Commit Interface that contains the fields of a Commit.
*/
export interface Commit extends CommitPayload, CommitPaymentPayload {
id: number;
createdAt: Date;
commitStatus: CommitStatus;
}
/**
* GroupedC... | * CommitQuery Interface that contains the fields of the query that
* would be sent to the server to query for commits. | random_line_split |
livecd.py | post-installation filesystem changes. This may take several minutes."))
# resize rootfs first, since it is 100% full due to genMinInstDelta
self._resizeRootfs(anaconda, wait)
# remount filesystems
anaconda.id.storage.mountFilesystems()
# restore the label of / to what we thi... | packageExists | identifier_name | |
livecd.py | if symlinks and os.path.islink(srcname):
linkto = os.readlink(srcname)
os.symlink(linkto, dstname)
if preserveSelinux:
trySetfilecon(srcname, dstname)
elif os.path.isdir(srcname):
copytree(srcname, dstname, symlinks, preser... |
self.rootFsType = isys.readFSType(self.osimg)
def _getLiveBlockDevice(self):
return os.path.normpath(self.osimg)
def _getLiveSize(self):
def parseField(output, field):
for line in output.split("\n"):
if line.startswith(field + ":"):
retu... | anaconda.intf.messageWindow(_("Unable to find image"),
_("The given location isn't a valid %s "
"live CD to use as an installation source.")
%(productName,), type = "custom",
custom_icon="error"... | conditional_block |
livecd.py | if symlinks and os.path.islink(srcname):
linkto = os.readlink(srcname)
os.symlink(linkto, dstname)
if preserveSelinux:
trySetfilecon(srcname, dstname)
elif os.path.isdir(srcname):
copytree(srcname, dstname, symlinks, preser... |
def doPreInstall(self, anaconda):
if anaconda.dir == DISPATCH_BACK:
self._unmountNonFstabDirs(anaconda)
return
anaconda.id.storage.umountFilesystems(swapoff = False)
def doInstall(self, anaconda):
log.info("Preparing to install packages")
progress = a... | self._unmountNonFstabDirs(anaconda)
try:
anaconda.id.storage.umountFilesystems(swapoff = False)
os.rmdir(anaconda.rootPath)
except Exception, e:
log.error("Unable to unmount filesystems: %s" % e) | identifier_body |
livecd.py | try:
if symlinks and os.path.islink(srcname):
linkto = os.readlink(srcname)
os.symlink(linkto, dstname)
if preserveSelinux:
trySetfilecon(srcname, dstname)
elif os.path.isdir(srcname):
copytree(srcname, d... | for name in names:
srcname = os.path.join(src, name)
dstname = os.path.join(dst, name) | random_line_split | |
lib.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... | (&self, row: &Row, col: &Col) -> Option<&Val> {
self.map.get(row).and_then(|r| r.get(col))
}
/// Remove value from specific cell
///
/// It will remove the row if it's the last value in it
pub fn remove(&mut self, row: &Row, col: &Col) -> Option<Val> {
let (val, is_empty) = {
let row_map = self.map.get_mut... | get | identifier_name |
lib.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... |
/// Get immutable reference for single row in this Table
pub fn row(&self, row: &Row) -> Option<&HashMap<Col, Val>> {
self.map.get(row)
}
/// Get element in cell described by `(row, col)`
pub fn get(&self, row: &Row, col: &Col) -> Option<&Val> {
self.map.get(row).and_then(|r| r.get(col))
}
/// Remove val... | {
self.map.contains_key(row)
} | identifier_body |
lib.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... | // then
assert!(!table.has_row(&1));
assert_eq!(table.len(), 1);
}
} | table.clear_if_empty(&1);
| random_line_split |
lib.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... |
val
}
/// Remove given row from Table if there are no values defined in it
///
/// When using `#row_mut` it may happen that all values from some row are drained.
/// Table however will not be aware that row is empty.
/// You can use this method to explicitly remove row entry from the Table.
pub fn clear_if_e... | {
self.map.remove(row);
} | conditional_block |
keyids.py | 1,
"KEY_D": 32,
"KEY_F": 33,
"KEY_G": 34,
"KEY_H": 35,
"KEY_J": 36,
"KEY_K": 37,
"KEY_L": 38,
"KEY_SEMICOLON": 39,
"KEY_APOSTROPHE": 40,
"KEY_GRAVE": 41,
"KEY_LEFTSHIFT": 42,
"KEY_BACKSLASH": 43,
"KEY_Z": 44,
"KEY_X": 45,
"KEY_C": 46,
"KEY_V": 47,
"KEY_B": 48,
"KEY_N": 49,
"KEY_M": 50,
"KEY_COMMA": 51,
"KEY_DOT": 52,
"... | "KEY_CUT": 137,
"KEY_HELP": 138,
"KEY_MENU": 139,
"KEY_CALC": 140,
"KEY_SETUP": 141,
"KEY_SLEEP": 142,
"KEY_WAKEUP": 143,
"KEY_FILE": 144,
"KEY_SENDFILE": 145,
"KEY_DELETEFILE": 146,
"KEY_XFER": 147,
"KEY_PROG1": 148,
"KEY_PROG2": 149,
"KEY_WWW": 150,
"KEY_MSDOS": 151,
"KEY_COFFEE": 152,
"KEY_DIRECTION": 153,
"KEY_CYCL... | "KEY_FIND": 136, | random_line_split |
orthog.py | """
Copyright 2013 Steven Diamond
This file is part of CVXPY.
CVXPY 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.
CVXPY is distributed i... |
# Constrain all entries to be the value in the matrix.
def _restrict(self, matrix):
return [self == matrix]
def relax(self):
"""Relaxation [I X; X^T I] is PSD.
"""
rows, cols = self.shape
constr = super(Orthog, self).relax()
mat = cp.bmat([[np.eye(rows), se... | """All singular values except k-largest (by magnitude) set to zero.
"""
U, s, V = np.linalg.svd(matrix)
s[:] = 1
return U.dot(np.diag(s)).dot(V) | identifier_body |
orthog.py | """
Copyright 2013 Steven Diamond
This file is part of CVXPY.
CVXPY 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.
CVXPY is distributed i... | (self, random):
"""Initializes the value of the replicant variable.
"""
self.z.value = np.zeros(self.shape)
def _project(self, matrix):
"""All singular values except k-largest (by magnitude) set to zero.
"""
U, s, V = np.linalg.svd(matrix)
s[:] = 1
re... | init_z | identifier_name |
orthog.py | """
Copyright 2013 Steven Diamond
This file is part of CVXPY.
CVXPY 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.
CVXPY is distributed i... | """ A variable satisfying X^TX = I. """
def __init__(self, size, *args, **kwargs):
super().__init__(shape=(size, size), *args, **kwargs)
def init_z(self, random):
"""Initializes the value of the replicant variable.
"""
self.z.value = np.zeros(self.shape)
def _project(s... | class Orthog(NonCvxVariable): | random_line_split |
karma.conf.js | // Karma configuration
// Generated on Thu Oct 01 2015 17:56:10 GMT+0900 (JST)
module.exports = function(config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/k... | // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// start these browsers
// available browser launch... | // enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging | random_line_split |
replication_lib.py | """An implementation of the ReplicationConfig proto interface."""
from __future__ import print_function
import json
import os
import shutil
import sys
from chromite.api.gen.config import replication_config_pb2
from chromite.lib import constants
from chromite.lib import cros_logging as logging
from chromite.lib impo... | # -*- coding: utf-8 -*-
# Copyright 2019 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
| random_line_split | |
replication_lib.py | # -*- coding: utf-8 -*-
# Copyright 2019 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""An implementation of the ReplicationConfig proto interface."""
from __future__ import print_function
import json
import os
im... |
if rule.replication_type == replication_config_pb2.REPLICATION_TYPE_COPY:
if rule.destination_fields.paths:
raise ValueError(
'Rule with REPLICATION_TYPE_COPY cannot use destination_fields.')
elif rule.replication_type == replication_config_pb2.REPLICATION_TYPE_FILTER:
if not rule.destinati... | """Raises an error if a FileReplicationRule is invalid.
For example, checks that if REPLICATION_TYPE_FILTER, destination_fields
are specified.
Args:
rule: (FileReplicationRule) The rule to validate.
"""
if rule.file_type == replication_config_pb2.FILE_TYPE_JSON:
if rule.replication_type != replicati... | identifier_body |
replication_lib.py | # -*- coding: utf-8 -*-
# Copyright 2019 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""An implementation of the ReplicationConfig proto interface."""
from __future__ import print_function
import json
import os
im... | destination_json = {'chromeos': {'configs': destination_device_configs}}
logging.info('Writing filtered JSON source to %s', dst)
with open(dst, 'w') as f:
# Use the print function, so the file ends in a newline.
print(
json.dumps(
destination_json,
... | assert (rule.replication_type ==
replication_config_pb2.REPLICATION_TYPE_FILTER)
assert rule.destination_fields.paths
with open(src, 'r') as f:
source_json = json.load(f)
try:
source_device_configs = source_json['chromeos']['configs']
except KeyError:
rais... | conditional_block |
replication_lib.py | # -*- coding: utf-8 -*-
# Copyright 2019 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""An implementation of the ReplicationConfig proto interface."""
from __future__ import print_function
import json
import os
im... | (replication_config):
"""Run the replication described in replication_config.
Args:
replication_config: (ReplicationConfig) Describes the replication to run.
"""
# Validate all rules before any of them are run, to decrease chance of ending
# with a partial replication.
for rule in replication_config.fi... | Replicate | identifier_name |
account.service.ts | import { HttpClient, HttpErrorResponse, HttpHeaders } from "@angular/common/http";
import { Account } from "../models/account.model"
import { Injectable } from '@angular/core';
import { Observable } from "rxjs/Observable";
import { WIMM_API_URL } from "../../wimm-constants";
@Injectable()
export class AccountService ... | (): Observable<Account[]> {
let url = WIMM_API_URL + "accounts";
return this.http.get<Account[]>(
url, {
headers: new HttpHeaders().set('Authorization', 'token 0123456789abcdef')
}
)
// return this.http.get(API_URL + "accounts").subscribe(
// result => { return result as Acc... | getAccounts | identifier_name |
account.service.ts | import { HttpClient, HttpErrorResponse, HttpHeaders } from "@angular/common/http";
import { Account } from "../models/account.model"
import { Injectable } from '@angular/core';
import { Observable } from "rxjs/Observable";
import { WIMM_API_URL } from "../../wimm-constants";
@Injectable()
export class AccountService ... |
// return this.http.get(API_URL + "accounts").subscribe(
// result => { return result as Account },
// error => { },
// () => { }
// );
}
getAccount(id: number): Promise<Account> {
return Promise.resolve(new Account(id, "short name", "fully callified name", null, null));
}
} | url, {
headers: new HttpHeaders().set('Authorization', 'token 0123456789abcdef')
}
) | random_line_split |
pymatrix.py | import math
import copy
def print_matrix(matrix):
"""
This function prettyprints a matrix
:param matrix: The matrix to prettyprint
"""
for i in range(len(matrix)):
print(matrix[i])
def transpose(matrix):
"""
This function transposes a matrix
:param matrix: The matrix to trans... |
if denom == 0:
raise ValueError("The determinant is 0. Can't invert matrix")
cofactors = [] # the matrix of cofactors, transposed
for i in range(dim):
cofactor_row = []
for j in range(dim):
m_copy = copy.deepcopy(matrix)
minor = minor_matrix(m_copy, j+1, i+... | dim = num_rows
denom = determinant(matrix) | random_line_split |
pymatrix.py | import math
import copy
def print_matrix(matrix):
"""
This function prettyprints a matrix
:param matrix: The matrix to prettyprint
"""
for i in range(len(matrix)):
print(matrix[i])
def transpose(matrix):
"""
This function transposes a matrix
:param matrix: The matrix to trans... |
# remove the specified column
for row in minor:
row.pop(col_index - 1)
return minor
def determinant(matrix):
"""
This function calculates the determinant of a square matrix.
:param m_copy: The matrix to find the determinant
:return: The determinant of the matrix
"""
num_... | """
This function calculates the minor of a matrix for a given row and column
index. The matrix should be a square matrix, and the row and column
should be positive and smaller than the width and height of the matrix.
:param matrix: The matrix to calculate the minor
:param row_index: The row index o... | identifier_body |
pymatrix.py | import math
import copy
def print_matrix(matrix):
"""
This function prettyprints a matrix
:param matrix: The matrix to prettyprint
"""
for i in range(len(matrix)):
print(matrix[i])
def transpose(matrix):
"""
This function transposes a matrix
:param matrix: The matrix to trans... |
return matrix
def multiply(matrix1, matrix2):
"""
This function multiplies two matrices. In order to multiply, it makes sure
the width of matrix1 is the same as the height of matrix2
:param matrix1: Left matrix
:param matrix2: Right matrix
:return: The product matrix of the multiplicatio... | for j in range(len(matrix[0])):
matrix[i][j] *= const | conditional_block |
pymatrix.py | import math
import copy
def print_matrix(matrix):
"""
This function prettyprints a matrix
:param matrix: The matrix to prettyprint
"""
for i in range(len(matrix)):
print(matrix[i])
def | (matrix):
"""
This function transposes a matrix
:param matrix: The matrix to transpose
:return: The transposed matrix
"""
num_cols = len(matrix[0])
trans = []
for i in range(num_cols):
temp = []
for row in matrix:
temp.append(row[i])
trans.append(temp... | transpose | identifier_name |
_FormWidget.js | Index: "0",
// disabled: Boolean
// Should this widget respond to user input?
// In markup, this is specified as "disabled='disabled'", or just "disabled".
disabled: false,
// intermediateChanges: Boolean | // Fires onChange for each value change or only on demand
intermediateChanges: false,
// scrollOnFocus: Boolean
// On focus, should this widget scroll into view?
scrollOnFocus: true,
// These mixins assume that the focus node is an INPUT, as many but not all _FormWidgets are.
attributeMap: dojo.delegate(diji... | random_line_split | |
__init__.py | #!/usr/bin/env python
# Copyright (c) 2013, Carnegie Mellon University
# All rights reserved.
# Authors: Michael Koval <mkoval@cs.cmu.edu>
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# - Redistributions of sourc... | #
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
# LIABLE F... | # software without specific prior written permission. | random_line_split |
paged_results.rs | use super::{ControlParser, MakeCritical, RawControl};
use bytes::BytesMut;
use lber::common::TagClass;
use lber::IResult;
use lber::parse::{parse_uint, parse_tag};
use lber::structures::{ASNTag, Integer, OctetString, Sequence, Tag};
use lber::universal::Types;
use lber::write;
/// Paged Results control ([RFC 2696](h... | val: Some(Vec::from(&buf[..])),
}
}
}
impl ControlParser for PagedResults {
fn parse(val: &[u8]) -> PagedResults {
let mut pr_comps = match parse_tag(val) {
IResult::Done(_, tag) => tag,
_ => panic!("failed to parse paged results value components"),
... | {
let cookie_len = pr.cookie.len();
let cval = Tag::Sequence(Sequence {
inner: vec -> RawControl {
let cookie_len = pr.cookie.len();
let cval = Tag::Sequence(Sequence {
inner: vec
class PluginAuthenticationPolicy(object):
def __init__(self, default, routes=None):
self._default = default
if routes is None:
routes = {}
self._routes = routes
def add_plugin(self, route, policy):
self._routes[route] = policy
def match(self, r... | )
class PluginPolicySelected(object):
def __init__(self, request, policy):
self.request = request | random_line_split |
auth.py | #!/usr/bin/env python
# -*- coding: utf-8; tab-width: 4; indent-tabs-mode: t -*-
#
# NetProfile: Authentication routines
# © Copyright 2013-2014 Alex 'Unik' Unigovsky
#
# This file is part of NetProfile.
# NetProfile is free software: you can redistribute it and/or
# modify it under the terms of the GNU Affero General ... |
@implementer(IAuthenticationPolicy)
class DigestAuthenticationPolicy(object):
def __init__(self, secret, callback, realm='Realm'):
self.secret = secret
self.callback = callback
self.realm = realm
def authenticated_userid(self, request):
params = _parse_authorization(request, self.secret, self.realm)
if pa... | uthz = request.authorization
if (not authz) or (len(authz) != 2) or (authz[0] != 'Digest'):
_add_www_authenticate(request, secret, realm)
return None
params = authz[1]
if 'algorithm' not in params:
params['algorithm'] = 'MD5'
for required in ('username', 'realm', 'nonce', 'uri', 'response', 'cnonce', 'nc', 'o... | identifier_body |
auth.py | #!/usr/bin/env python
# -*- coding: utf-8; tab-width: 4; indent-tabs-mode: t -*-
#
# NetProfile: Authentication routines
# © Copyright 2013-2014 Alex 'Unik' Unigovsky
#
# This file is part of NetProfile.
# NetProfile is free software: you can redistribute it and/or
# modify it under the terms of the GNU Affero General ... | if not _is_valid_nonce(params['nonce'], self.secret):
_add_www_authenticate(request, self.secret, self.realm)
return None
return 'u:%s' % params['username']
def effective_principals(self, request):
creds = [Everyone]
params = _parse_authorization(request, self.secret, self.realm)
if params is None:
... | eturn None
| conditional_block |
auth.py | #!/usr/bin/env python
# -*- coding: utf-8; tab-width: 4; indent-tabs-mode: t -*-
#
# NetProfile: Authentication routines
# © Copyright 2013-2014 Alex 'Unik' Unigovsky
#
# This file is part of NetProfile.
# NetProfile is free software: you can redistribute it and/or
# modify it under the terms of the GNU Affero General ... | object):
def __init__(self, default, routes=None):
self._default = default
if routes is None:
routes = {}
self._routes = routes
def add_plugin(self, route, policy):
self._routes[route] = policy
def match(self, request):
if hasattr(request, 'auth_policy'):
return request.auth_policy
cur = None
c... | luginAuthenticationPolicy( | identifier_name |
index.js |
//Modules
var async = require('async');
var tools = require('./tools.js');
var fs = require('fs');
var pathMod = require('path');
var Handlebars = require('handlebars');
var vCard = require('vcards-js');
var vcardparser = require('vcardparser');
var _ = require('lodash')... |
});
};
module.exports = Sync | {
callback( null, res );
} | conditional_block |
index.js | //Modules
var async = require('async');
var tools = require('./tools.js');
var fs = require('fs');
var pathMod = require('path');
var Handlebars = require('handlebars');
var vCard = require('vcards-js');
var vcardparser = require('vcardparser');
var _ = require('lodash');... | if( err ){
return callback( err );
}
callback(null, _.deepGet(data, 'response[0].propstat[0].prop[0].addressbook-home-set[0].href[0]'));
});
});
};
Sync.prototype.getContacts = function ( filter, path, callback ) {
filter = filter || {};
var body = templates['getContacts'](filter);
... | random_line_split | |
stages_mergesort.js | // Test query stage merge sorting.
t = db.stages_mergesort;
t.drop();
var collname = "stages_mergesort";
var N = 10;
for (var i = 0; i < N; ++i) {
t.insert({foo: 1, bar: N - i - 1});
t.insert({baz: 1, bar: i});
}
t.ensureIndex({foo: 1, bar: 1});
t.ensureIndex({baz: 1, bar: 1});
// foo == 1
// We would (inter... | }
};
mergesort = {
mergeSort: {args: {nodes: [ixscan1, ixscan2], pattern: {bar: 1}}}
};
res = db.runCommand({stageDebug: {plan: mergesort, collection: collname}});
assert.eq(res.ok, 1);
assert.eq(res.results.length, 2 * N);
assert.eq(res.results[0].bar, 0);
assert.eq(res.results[2 * N - 1].bar, N - 1); | random_line_split | |
stages_mergesort.js | // Test query stage merge sorting.
t = db.stages_mergesort;
t.drop();
var collname = "stages_mergesort";
var N = 10;
for (var i = 0; i < N; ++i) |
t.ensureIndex({foo: 1, bar: 1});
t.ensureIndex({baz: 1, bar: 1});
// foo == 1
// We would (internally) use "": MinKey and "": MaxKey for the bar index bounds.
ixscan1 = {
ixscan: {
args: {
keyPattern: {foo: 1, bar: 1},
startKey: {foo: 1, bar: 0},
endKey: {foo: 1, bar: ... | {
t.insert({foo: 1, bar: N - i - 1});
t.insert({baz: 1, bar: i});
} | conditional_block |
bandcamp.py | ://beets.radbox.org/'.format(beets.__version__)
BANDCAMP_SEARCH = 'http://bandcamp.com/search?q={query}&page={page}'
BANDCAMP_ALBUM = 'album'
BANDCAMP_ARTIST = 'band'
BANDCAMP_TRACK = 'track'
ARTIST_TITLE_DELIMITER = ' - '
class BandcampPlugin(plugins.BeetsPlugin):
def __init__(self):
super(BandcampPlugi... | def _search(self, query, search_type=BANDCAMP_ALBUM, page=1):
"""Returns a list of bandcamp urls for items of type search_type
matching the query.
"""
if search_type not in [BANDCAMP_ARTIST, BANDCAMP_ALBUM, BANDCAMP_TRACK]:
self._log.debug('Invalid type for search: {0}'.f... | random_line_split | |
bandcamp.py | _source == 'bandcamp':
dist.add('source', self.config['source_weight'].as_number())
return dist
def candidates(self, items, artist, album, va_likely, extra_tags=None):
"""Returns a list of AlbumInfo objects for bandcamp search results
matching an album and artist (if not various... | _split_artist_title | identifier_name | |
bandcamp.py | = [BandcampAlbumArt(plugin._log, self.config)] + plugin.sources
fetchart.ART_SOURCES['bandcamp'] = BandcampAlbumArt
fetchart.SOURCE_NAMES[BandcampAlbumArt] = 'bandcamp'
break
def album_distance(self, items, album_info, mapping):
"""Returns the al... | raise BandcampException('No track url (id) for track {0} - {1}'.format(track_num, title)) | conditional_block | |
bandcamp.py | items, album_info, mapping):
"""Returns the album distance.
"""
dist = Distance()
if hasattr(album_info, 'data_source') and album_info.data_source == 'bandcamp':
dist.add('source', self.config['source_weight'].as_number())
return dist
def candidates(self, items,... | """Returns a TrackInfo derived from the html describing a track in a
bandcamp album page.
"""
track_num = track_html['rel'].split('=')[1]
track_num = int(track_num)
title_html = track_html.find(attrs={'class': 'title-col'})
title = title_html.find(attrs={'itemprop': 'nam... | identifier_body | |
state.ts | import textCursor from "./textCursor"
import view from "./view"
import intents from "./intents"
import actions from "./actions"
const state: any = {}
export default state
state.representation = (model: any) => {
// compute "view model" for state representation: a flat array of sprites
const orderedSprites = mode... | }
if (model.selectedSpriteId === id) {
sprite.isSelected = true
}
if (model.sizeInfo.isSizing && model.sizeInfo.id === id) {
sprite.isGripping = model.sizeInfo.corner
}
return sprite
})
view.display(view.main(orderedSprites))
}
state.nextAction = (model: any) => {
// render b... | if (model.highlightedSpriteId === id) {
sprite.isHighlighted = true | random_line_split |
state.ts | import textCursor from "./textCursor"
import view from "./view"
import intents from "./intents"
import actions from "./actions"
const state: any = {}
export default state
state.representation = (model: any) => {
// compute "view model" for state representation: a flat array of sprites
const orderedSprites = mode... |
if (model.selectedSpriteId === id) {
sprite.isSelected = true
}
if (model.sizeInfo.isSizing && model.sizeInfo.id === id) {
sprite.isGripping = model.sizeInfo.corner
}
return sprite
})
view.display(view.main(orderedSprites))
}
state.nextAction = (model: any) => {
// render blasts... | {
sprite.isHighlighted = true
} | conditional_block |
mvcarray-utils.ts | import { fromEventPattern, Observable } from 'rxjs';
export function createMVCEventObservable<T>(array: google.maps.MVCArray<T>): Observable<MVCEvent<T>>{
const eventNames = ['insert_at', 'remove_at', 'set_at'];
return fromEventPattern(
handler => eventNames.map(eventName => array.addListener(eventName,
... |
}
getArray(): T[] {
return [...this.vals];
}
getAt(i: number): T {
return this.vals[i];
}
getLength(): number {
return this.vals.length;
}
insertAt(i: number, elem: T): void {
this.vals.splice(i, 0, elem);
this.listeners.insert_at.forEach(listener => listener(i));
}
pop(): T {
... | {
this.removeAt(i);
} | conditional_block |
mvcarray-utils.ts | import { fromEventPattern, Observable } from 'rxjs';
export function createMVCEventObservable<T>(array: google.maps.MVCArray<T>): Observable<MVCEvent<T>>{
const eventNames = ['insert_at', 'remove_at', 'set_at'];
return fromEventPattern(
handler => eventNames.map(eventName => array.addListener(eventName,
... |
pop(): T {
const deleted = this.vals.pop();
this.listeners.remove_at.forEach(listener => listener(this.vals.length, deleted));
return deleted;
}
push(elem: T): number {
this.vals.push(elem);
this.listeners.insert_at.forEach(listener => listener(this.vals.length - 1));
return this.vals.len... | {
this.vals.splice(i, 0, elem);
this.listeners.insert_at.forEach(listener => listener(i));
} | identifier_body |
mvcarray-utils.ts | import { fromEventPattern, Observable } from 'rxjs';
export function createMVCEventObservable<T>(array: google.maps.MVCArray<T>): Observable<MVCEvent<T>>{
const eventNames = ['insert_at', 'remove_at', 'set_at'];
return fromEventPattern(
handler => eventNames.map(eventName => array.addListener(eventName,
... | (): never { throw new Error('Not implemented'); }
changed(): never { throw new Error('Not implemented'); }
get(): never { throw new Error('Not implemented'); }
notify(): never { throw new Error('Not implemented'); }
set(): never { throw new Error('Not implemented'); }
setValues(): never { throw new Error('Not... | bindTo | identifier_name |
mvcarray-utils.ts | import { fromEventPattern, Observable } from 'rxjs';
export function createMVCEventObservable<T>(array: google.maps.MVCArray<T>): Observable<MVCEvent<T>>{
const eventNames = ['insert_at', 'remove_at', 'set_at'];
return fromEventPattern(
handler => eventNames.map(eventName => array.addListener(eventName,
... | }
export class MvcArrayMock<T> implements google.maps.MVCArray<T> {
private vals: T[] = [];
private listeners: {
'remove_at': ((i: number, r: T) => void)[];
'insert_at': ((i: number) => void)[];
'set_at': ((i: number, val: T) => void)[];
} = {
remove_at: [],
insert_at: [],
set_at: [],
}... | newArr: T[];
eventName: MvcEventType;
index: number;
previous?: T; | random_line_split |
__openerp__.py | # -*- encoding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# This module copyright (C) cgstudiomap <cgstudiomap@gmail.com> | # published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE... | #
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as | random_line_split |
history.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use abomonation_derive::Abomonation;
use anyhow::Error;
use filenodes::{FilenodeInfo, FilenodeInfoCached};
#[derive(Abomonation, Clone)]
... | let history = filenodes.into_iter().map(|f| f.into()).collect::<Vec<_>>();
Self { history }
}
} | pub fn from_filenodes(filenodes: Vec<FilenodeInfo>) -> Self { | random_line_split |
history.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use abomonation_derive::Abomonation;
use anyhow::Error;
use filenodes::{FilenodeInfo, FilenodeInfoCached};
#[derive(Abomonation, Clone)]
... | (self) -> Result<Vec<FilenodeInfo>, Error> {
self.history.into_iter().map(|c| c.try_into()).collect()
}
pub fn from_filenodes(filenodes: Vec<FilenodeInfo>) -> Self {
let history = filenodes.into_iter().map(|f| f.into()).collect::<Vec<_>>();
Self { history }
}
}
| into_filenode_info | identifier_name |
read_all.rs | use std::borrow::Cow;
use std::convert::TryInto;
use raw::client_messages;
use raw::client_messages::mod_ReadAllEventsCompleted::ReadAllResult;
use LogPosition;
/// Successful response to `Message::ReadAllEvents`.
#[derive(Debug, Clone, PartialEq)]
pub struct ReadAllCompleted<'a> {
/// Position of the commit of t... | impl<'a> From<client_messages::ResolvedEvent<'a>> for ResolvedEvent<'a> {
fn from(e: client_messages::ResolvedEvent<'a>) -> ResolvedEvent<'a> {
ResolvedEvent {
event: e.event.into(),
link: e.link.into(),
commit_position: e.commit_position.try_into().unwrap(),
... | /// Position where this event is stored
pub prepare_position: LogPosition,
}
| random_line_split |
read_all.rs | use std::borrow::Cow;
use std::convert::TryInto;
use raw::client_messages;
use raw::client_messages::mod_ReadAllEventsCompleted::ReadAllResult;
use LogPosition;
/// Successful response to `Message::ReadAllEvents`.
#[derive(Debug, Clone, PartialEq)]
pub struct ReadAllCompleted<'a> {
/// Position of the commit of t... | <'a> {
/// Unknown when this happens,
NotModified,
/// Other error
Error(Option<Cow<'a, str>>),
/// Access was denied (no credentials provided or insufficient permissions)
AccessDenied
}
impl<'a> From<(ReadAllResult, Option<Cow<'a, str>>)> for ReadAllError<'a> {
fn from((r, msg): (ReadAllRe... | ReadAllError | identifier_name |
getUserID.js | "use strict";
var utils = require("../utils");
var log = require("npmlog");
function | (data) {
return {
userID: utils.formatID(data.uid.toString()),
photoUrl: data.photo,
indexRank: data.index_rank,
name: data.text,
isVerified: data.is_verified,
profileUrl: data.path,
category: data.category,
score: data.score,
};
}
module.exports = function(defaultFuncs, api, ctx) {... | formatData | identifier_name |
getUserID.js | "use strict";
var utils = require("../utils");
var log = require("npmlog");
function formatData(data) |
module.exports = function(defaultFuncs, api, ctx) {
return function getUserID(name, callback) {
if(!callback) {
throw {error: "getUserID: need callback"};
}
var form = {
'value' : name.toLowerCase(),
'viewer' : ctx.userID,
'rsp' : "search",
'context' : "search",
'pat... | {
return {
userID: utils.formatID(data.uid.toString()),
photoUrl: data.photo,
indexRank: data.index_rank,
name: data.text,
isVerified: data.is_verified,
profileUrl: data.path,
category: data.category,
score: data.score,
};
} | identifier_body |
getUserID.js | "use strict";
var utils = require("../utils");
var log = require("npmlog");
function formatData(data) {
return {
userID: utils.formatID(data.uid.toString()),
photoUrl: data.photo,
indexRank: data.index_rank,
name: data.text,
isVerified: data.is_verified,
profileUrl: data.path,
category: ... | .then(function(resData) {
if (resData.error) {
throw resData;
}
var data = resData.payload.entries;
if(data[0].type !== "user") {
throw {error: "Couldn't find a user with name " + name + ". Bes match: " + data[0].path};
}
callback(null, data.m... | .then(utils.parseAndCheckLogin(ctx, defaultFuncs)) | random_line_split |
getUserID.js | "use strict";
var utils = require("../utils");
var log = require("npmlog");
function formatData(data) {
return {
userID: utils.formatID(data.uid.toString()),
photoUrl: data.photo,
indexRank: data.index_rank,
name: data.text,
isVerified: data.is_verified,
profileUrl: data.path,
category: ... |
var data = resData.payload.entries;
if(data[0].type !== "user") {
throw {error: "Couldn't find a user with name " + name + ". Bes match: " + data[0].path};
}
callback(null, data.map(formatData));
})
.catch(function(err) {
log.error("getUserID", err);
... | {
throw resData;
} | conditional_block |
IsoTriangleFactory.js | /**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2019 Photon Storm Ltd.
* @license {@link https://opensource.org/licenses/MIT|MIT License}
*/
var GameObjectFactory = require('../../GameObjectFactory');
var IsoTriangle = require('./IsoTriangle');
/**
* Creates a new IsoTriangle Shape ... | * treat it like any other Game Object in your game, such as tweening it, scaling it, or enabling
* it for input or physics. It provides a quick and easy way for you to render this shape in your
* game without using a texture, while still taking advantage of being fully batched in WebGL.
*
* This shape supports on... | random_line_split | |
equipos.js | /**
* @author David Yzaguirre <dvdyzag@gmail.com>
*
* @copyright Copyright (c) 2016, David Yzaguirre, Aníbal Rodríguez
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free So... | }
return reply({statusCode: 200});
});
}
exports.delete = function(request, reply){
db.Equipo.remove({_id:request.params.idEquipo}, function(err){
if (err) {
console.log("ATLETAS_DELETE err="+JSON.stringify(err));
return reply({statusCode:600});
}
return reply({statusCode: 200});
}... | if (err) {
console.log("EQUIPOS_SAVE err="+JSON.stringify(err));
return reply({statusCode:600}); | random_line_split |
equipos.js | /**
* @author David Yzaguirre <dvdyzag@gmail.com>
*
* @copyright Copyright (c) 2016, David Yzaguirre, Aníbal Rodríguez
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free So... | return reply({statusCode: 200});
});
}
| console.log("ATLETAS_DELETE err="+JSON.stringify(err));
return reply({statusCode:600});
}
| conditional_block |
stage_2.py | #!/usr/bin/env python
# File written by pyctools-editor. Do not edit.
import argparse
import logging
from pyctools.core.compound import Compound
import pyctools.components.arithmetic
import pyctools.components.qt.qtdisplay
import pyctools.components.zone.zoneplategenerator
class Network(object):
components = \
{ ... |
if __name__ == '__main__':
from PyQt5 import QtCore, QtWidgets
QtWidgets.QApplication.setAttribute(QtCore.Qt.AA_X11InitThreads)
app = QtWidgets.QApplication([])
comp = Network().make()
cnf = comp.get_config()
parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsH... | comps = {}
for name, component in self.components.items():
comps[name] = eval(component['class'])(config=eval(component['config']))
return Compound(linkages=self.linkages, **comps) | identifier_body |
stage_2.py | #!/usr/bin/env python
# File written by pyctools-editor. Do not edit.
import argparse
import logging
from pyctools.core.compound import Compound
import pyctools.components.arithmetic
import pyctools.components.qt.qtdisplay
import pyctools.components.zone.zoneplategenerator
class Network(object):
components = \
{ ... | 'config': "{'kx': 0.04, 'kt': -0.34, 'xlen': 600, 'ylen': "
"400, 'zlen': 1000, 'looping': 'repeat'}",
'pos': (70.0, 200.0)},
'zpg2': { 'class': 'pyctools.components.zone.zoneplategenerator.ZonePlateGenerator',
'config': "{'kx': 0.002, 'kt': -... | random_line_split | |
stage_2.py | #!/usr/bin/env python
# File written by pyctools-editor. Do not edit.
import argparse
import logging
from pyctools.core.compound import Compound
import pyctools.components.arithmetic
import pyctools.components.qt.qtdisplay
import pyctools.components.zone.zoneplategenerator
class Network(object):
components = \
{ ... |
return Compound(linkages=self.linkages, **comps)
if __name__ == '__main__':
from PyQt5 import QtCore, QtWidgets
QtWidgets.QApplication.setAttribute(QtCore.Qt.AA_X11InitThreads)
app = QtWidgets.QApplication([])
comp = Network().make()
cnf = comp.get_config()
parser = argparse.ArgumentP... | comps[name] = eval(component['class'])(config=eval(component['config'])) | conditional_block |
stage_2.py | #!/usr/bin/env python
# File written by pyctools-editor. Do not edit.
import argparse
import logging
from pyctools.core.compound import Compound
import pyctools.components.arithmetic
import pyctools.components.qt.qtdisplay
import pyctools.components.zone.zoneplategenerator
class Network(object):
components = \
{ ... | (self):
comps = {}
for name, component in self.components.items():
comps[name] = eval(component['class'])(config=eval(component['config']))
return Compound(linkages=self.linkages, **comps)
if __name__ == '__main__':
from PyQt5 import QtCore, QtWidgets
QtWidgets.QApplication.... | make | identifier_name |
__init__.py | #
# Copyright 2011-2013 Blender Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in... |
def __del__(self):
engine.free(self)
# final render
def update(self, data, scene):
if not self.session:
if self.is_preview:
cscene = bpy.context.scene.cycles
use_osl = cscene.shading_system and cscene.device == 'CPU'
engine.crea... | self.session = None | identifier_body |
__init__.py | #
# Copyright 2011-2013 Blender Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in... | engine.init()
properties.register()
ui.register()
presets.register()
bpy.utils.register_module(__name__)
bpy.app.handlers.version_update.append(version_update.do_versions)
def unregister():
from . import ui
from . import properties
from . import presets
import atexit
bpy... |
# Make sure we only registered the callback once.
atexit.unregister(engine_exit)
atexit.register(engine_exit)
| random_line_split |
__init__.py | #
# Copyright 2011-2013 Blender Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in... | ():
from . import ui
from . import properties
from . import presets
import atexit
bpy.app.handlers.version_update.remove(version_update.do_versions)
ui.unregister()
properties.unregister()
presets.unregister()
bpy.utils.unregister_module(__name__)
| unregister | identifier_name |
__init__.py | #
# Copyright 2011-2013 Blender Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in... |
def engine_exit():
engine.exit()
def register():
from . import ui
from . import properties
from . import presets
import atexit
# Make sure we only registered the callback once.
atexit.unregister(engine_exit)
atexit.register(engine_exit)
engine.init()
properties.register()... | self.report({'ERROR'}, "OSL support disabled in this build.") | conditional_block |
browser-files.js | 'use strict'
var EventManager = require('ethereum-remix').lib.EventManager
function Files (storage) {
var event = new EventManager()
this.event = event
var readonly = {}
this.type = 'browser'
this.exists = function (path) {
var unprefixedpath = this.removePrefix(path)
// NOTE: ignore the config fil... |
var tree = {}
var self = this
// This does not include '.remix.config', because it is filtered
// inside list().
Object.keys(this.list()).forEach(function (path) {
hashmapize(tree, path, {
'/readonly': self.isReadOnly(path),
'/content': self.get(path)
})
})
ret... | {
var nodes = path.split('/')
var i = 0
for (; i < nodes.length - 1; i++) {
var node = nodes[i]
if (obj[node] === undefined) {
obj[node] = {}
}
obj = obj[node]
}
obj[nodes[i]] = val
} | identifier_body |
browser-files.js | 'use strict'
var EventManager = require('ethereum-remix').lib.EventManager
function Files (storage) {
var event = new EventManager()
this.event = event
var readonly = {}
this.type = 'browser'
this.exists = function (path) {
var unprefixedpath = this.removePrefix(path)
// NOTE: ignore the config fil... | this.removePrefix = function (path) {
return path.indexOf(this.type + '/') === 0 ? path.replace(this.type + '/', '') : path
}
//
// Tree model for files
// {
// 'a': { }, // empty directory 'a'
// 'b': {
// 'c': {}, // empty directory 'b/c'
// 'd': { '/readonly': true, '/content': 'He... | random_line_split | |
browser-files.js | 'use strict'
var EventManager = require('ethereum-remix').lib.EventManager
function Files (storage) {
var event = new EventManager()
this.event = event
var readonly = {}
this.type = 'browser'
this.exists = function (path) {
var unprefixedpath = this.removePrefix(path)
// NOTE: ignore the config fil... |
event.trigger('fileRenamed', [this.type + '/' + unprefixedoldPath, this.type + '/' + unprefixednewPath, isFolder])
return true
}
return false
}
this.list = function () {
var files = {}
// add r/w files to the list
storage.keys().forEach((path) => {
// NOTE: as a temporary me... | {
return false
} | conditional_block |
browser-files.js | 'use strict'
var EventManager = require('ethereum-remix').lib.EventManager
function Files (storage) {
var event = new EventManager()
this.event = event
var readonly = {}
this.type = 'browser'
this.exists = function (path) {
var unprefixedpath = this.removePrefix(path)
// NOTE: ignore the config fil... | (obj, path, val) {
var nodes = path.split('/')
var i = 0
for (; i < nodes.length - 1; i++) {
var node = nodes[i]
if (obj[node] === undefined) {
obj[node] = {}
}
obj = obj[node]
}
obj[nodes[i]] = val
}
var tree = {}
var self = this
... | hashmapize | identifier_name |
hintrc.js | {
// environment
"browser": true,
"node": true,
"globals": {
"L": true,
"define": true,
"map":true,
"jQuery":true
// "drawnItems":true
},
"strict": false,
// code style
"bitwise": true,
"camelcase": true,
"curly": true,
"eqeqeq": true,
"forin": false,
"immed": true,
"latedef": true,
"newcap": t... | // "maxparams": 4,
// "maxdepth": 4
} |
// code simplicity - not enforced but nice to check from time to time
// "maxstatements": 20,
// "maxcomplexity": 5 | random_line_split |
movie-score.component.ts | import {Component, OnInit, OnChanges, SimpleChange, Input, Output, EventEmitter, ChangeDetectionStrategy} from '@angular/core';
import {Observable} from 'rxjs/Rx';
@Component({
selector: 'movie-score',
templateUrl: 'app/components/movie-score/movie-score.component.html',
changeDetection: ChangeDetec... |
upVoteThisRecord() {
this.scoringOutput.emit('upvote');
}
downVoteThisRecord() {
this.scoringOutput.emit('downvote');
}
recalculateVoteStatusBar() {
let totalVotes = this.upVotes + this.downVotes;
if (this.upVotes > 0) {
this.upVoteWidth... |
}
| identifier_body |
movie-score.component.ts | import {Component, OnInit, OnChanges, SimpleChange, Input, Output, EventEmitter, ChangeDetectionStrategy} from '@angular/core';
import {Observable} from 'rxjs/Rx';
@Component({
selector: 'movie-score',
templateUrl: 'app/components/movie-score/movie-score.component.html',
changeDetection: ChangeDetec... | {
}
upVoteThisRecord() {
this.scoringOutput.emit('upvote');
}
downVoteThisRecord() {
this.scoringOutput.emit('downvote');
}
recalculateVoteStatusBar() {
let totalVotes = this.upVotes + this.downVotes;
if (this.upVotes > 0) {
this.... | nstructor() | identifier_name |
movie-score.component.ts | import {Component, OnInit, OnChanges, SimpleChange, Input, Output, EventEmitter, ChangeDetectionStrategy} from '@angular/core';
import {Observable} from 'rxjs/Rx';
@Component({
selector: 'movie-score',
templateUrl: 'app/components/movie-score/movie-score.component.html',
changeDetection: ChangeDetec... | }
ngOnChanges(changes: { [propName: string]: SimpleChange }) {
this.recalculateVoteStatusBar();
}
ngOnInit() {
}
} |
this.downVoteWidth = ((this.downVotes / totalVotes) * 100) + "%";
}
| conditional_block |
movie-score.component.ts | import {Component, OnInit, OnChanges, SimpleChange, Input, Output, EventEmitter, ChangeDetectionStrategy} from '@angular/core';
import {Observable} from 'rxjs/Rx';
@Component({
selector: 'movie-score',
templateUrl: 'app/components/movie-score/movie-score.component.html',
changeDetection: ChangeDetec... | @Output() public scoringOutput: EventEmitter<any> = new EventEmitter();
constructor() {
}
upVoteThisRecord() {
this.scoringOutput.emit('upvote');
}
downVoteThisRecord() {
this.scoringOutput.emit('downvote');
}
recalculateVoteStatusBar() {
let tot... | upVoteWidth: string = "0%";
downVoteWidth: string = "0%";
@Input() upVotes: number;
@Input() downVotes: number;
| random_line_split |
RichEditor.tsx | import * as React from 'react';
import { useAppDispatch, useAppSelector } from '~/hooks';
import * as editor from '~/core/editor';
import * as entities from '~/core/entities';
import { fluent } from '~/core/utils';
import RichTranslationForm from './RichTranslationForm';
type Props = {
ftlSwitch: React.ReactNode;
... | const dispatch = useAppDispatch();
const sendTranslation = editor.useSendTranslation();
const updateTranslation = editor.useUpdateTranslation();
const translation = useAppSelector((state) => state.editor.translation);
const entity = useAppSelector((state) =>
entities.selectors.getSelectedEntity(state),
... | * overwritten, to handle the conversion from AST to string and back.
*/
export default function RichEditor(props: Props): React.ReactElement<any> { | random_line_split |
RichEditor.tsx | import * as React from 'react';
import { useAppDispatch, useAppSelector } from '~/hooks';
import * as editor from '~/core/editor';
import * as entities from '~/core/entities';
import { fluent } from '~/core/utils';
import RichTranslationForm from './RichTranslationForm';
type Props = {
ftlSwitch: React.ReactNode;
... |
}
function copyOriginalIntoEditor() {
if (entity) {
const origMsg = fluent.parser.parseEntry(entity.original);
updateTranslation(fluent.flattenMessage(origMsg));
}
}
function sendFluentTranslation(ignoreWarnings?: boolean) {
const fluentString = fluent.serializer.serializeEntry(transl... | {
updateTranslation(
fluent.getEmptyMessage(
fluent.parser.parseEntry(entity.original),
locale,
),
);
} | conditional_block |
RichEditor.tsx | import * as React from 'react';
import { useAppDispatch, useAppSelector } from '~/hooks';
import * as editor from '~/core/editor';
import * as entities from '~/core/entities';
import { fluent } from '~/core/utils';
import RichTranslationForm from './RichTranslationForm';
type Props = {
ftlSwitch: React.ReactNode;
... |
function copyOriginalIntoEditor() {
if (entity) {
const origMsg = fluent.parser.parseEntry(entity.original);
updateTranslation(fluent.flattenMessage(origMsg));
}
}
function sendFluentTranslation(ignoreWarnings?: boolean) {
const fluentString = fluent.serializer.serializeEntry(translatio... | {
if (entity) {
updateTranslation(
fluent.getEmptyMessage(
fluent.parser.parseEntry(entity.original),
locale,
),
);
}
} | identifier_body |
RichEditor.tsx | import * as React from 'react';
import { useAppDispatch, useAppSelector } from '~/hooks';
import * as editor from '~/core/editor';
import * as entities from '~/core/entities';
import { fluent } from '~/core/utils';
import RichTranslationForm from './RichTranslationForm';
type Props = {
ftlSwitch: React.ReactNode;
... | () {
if (entity) {
updateTranslation(
fluent.getEmptyMessage(
fluent.parser.parseEntry(entity.original),
locale,
),
);
}
}
function copyOriginalIntoEditor() {
if (entity) {
const origMsg = fluent.parser.parseEntry(entity.original);
updateTrans... | clearEditor | identifier_name |
all_4.js | var searchData=
[
['detailcontroller',['DetailController',['../classDetailController.html',1,'']]],
['detailcontroller_2ephp',['detailController.php',['../detailController_8php.html',1,'']]],
['detailmodel_2ephp',['detailModel.php',['../detailModel_8php.html',1,'']]],
['detailsitemodel_2ephp',['DetailSiteModel.... | ]; | ['displaystatsview',['DisplayStatsView',['../classStats.html#a8283b7e12c9c60c298a4407212204494',1,'Stats']]] | random_line_split |
editableFieldDirective.js | /* Copyright 2013-2016 Extended Mind Technologies Oy
*
* 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 applicab... | ($parse, $rootScope, $timeout, packaging) {
return {
require: '^?editableFieldContainer',
restrict: 'A',
link: function(scope, element, attrs, editableFieldContainerController) {
var editableFieldType;
if (attrs.editableField.length > 0){
editableFieldType = $parse(attrs.editableField... | editableFieldDirective | identifier_name |
editableFieldDirective.js | /* Copyright 2013-2016 Extended Mind Technologies Oy
*
* 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 applicab... |
var editableFieldType;
if (attrs.editableField.length > 0){
editableFieldType = $parse(attrs.editableField)(scope);
}
if (attrs.editableFieldRegisterCallbacks){
var registerCallbacksFn = $parse(attrs.editableFieldRegisterCallbacks);
registerCallbacksFn(scope, {focus: fo... | require: '^?editableFieldContainer',
restrict: 'A',
link: function(scope, element, attrs, editableFieldContainerController) { | random_line_split |
editableFieldDirective.js | /* Copyright 2013-2016 Extended Mind Technologies Oy
*
* 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 applicab... |
if (document.activeElement === element[0]){
unfocusInProgress = true;
if ($rootScope.$$phase || scope.$$phase){
// It seems $timeout can not be avoided here:
// https://github.com/angular/angular.js/issues/1250
// "In the future, this will (hopefully) be... | {
element[0].blur();
if (deactivateAfterBlur && editableFieldContainerController)
editableFieldContainerController.deactivateContainer();
} | identifier_body |
editableFieldDirective.js | /* Copyright 2013-2016 Extended Mind Technologies Oy
*
* 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 applicab... |
}
}
var unfocusInProgress = false;
function blurElement(deactivateAfterBlur) {
function doBlurElement(){
element[0].blur();
if (deactivateAfterBlur && editableFieldContainerController)
editableFieldContainerController.deactivateContainer();
}
... | {
doFocusElement();
} | conditional_block |
tex2.rs |
use std::io::{self, Write};
use image;
use image::GenericImage;
use nom::{le_u8, le_u32};
use byteorder::{LittleEndian, WriteBytesExt};
named!(pub tex2_header<(u32, u32, u8)>,
do_parse!(
tag!("\x11\x40") >> //.@, the magic number for the format
height: le_u32 >>
width: le_u32 >>
m... | (&self, x: u32, y: u32) -> usize {
(calc_offset(self.height, self.width, (self.mipmap_current) as u32)
+ ((self.cur_width()*y) + x)) as usize
}
pub fn pixel(&self, x: u32, y: u32) -> (u8, u8, u8, u8) {
match self.pixels.get(self.pos(x, y)) {
Some(p) => *p,
Non... | pos | identifier_name |
tex2.rs |
use std::io::{self, Write};
use image;
use image::GenericImage;
use nom::{le_u8, le_u32};
use byteorder::{LittleEndian, WriteBytesExt};
named!(pub tex2_header<(u32, u32, u8)>,
do_parse!(
tag!("\x11\x40") >> //.@, the magic number for the format
height: le_u32 >>
width: le_u32 >>
m... |
fn blend_pixel(&mut self, x: u32, y: u32, pixel: Self::Pixel) {
unimplemented!()
}
}
//12:36:48 AM <ubsan> zekesonxx: lemme think about it
//12:36:51 AM <ubsan> I have an idea
//12:37:24 AM <zekesonxx> ubsan: shoot
//12:37:42 AM <ubsan> zekesonxx: alright, so the function definition would be somethi... | {
let pos = self.pos(x, y);
self.pixels[pos] = (pixel[0], pixel[1], pixel[2], pixel[3]);
} | identifier_body |
tex2.rs | use std::io::{self, Write};
use image;
use image::GenericImage;
use nom::{le_u8, le_u32};
use byteorder::{LittleEndian, WriteBytesExt};
named!(pub tex2_header<(u32, u32, u8)>,
do_parse!(
tag!("\x11\x40") >> //.@, the magic number for the format
height: le_u32 >>
width: le_u32 >>
mi... | }
fn get_pixel(&self, x: u32, y: u32) -> Self::Pixel {
let p = self.pixel(x, y);
image::Rgba([p.0, p.1, p.2, p.3])
}
fn get_pixel_mut(&mut self, x: u32, y: u32) -> &mut Self::Pixel {
unimplemented!()
}
fn put_pixel(&mut self, x: u32, y: u32, pixel: Self::Pixel) {
... | (self.cur_width(), self.cur_height())
}
fn bounds(&self) -> (u32, u32, u32, u32) {
(0, 0, self.cur_width(), self.cur_height()) | random_line_split |
vi.js | /*
Copyright (c) 2003-2014, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'link', 'vi', {
acccessKey: 'Phím hỗ trợ truy cập',
advanced: 'Mở rộng',
advisoryContentType: 'Nội dung hướng dẫn',
advisoryTitle: 'Nhan đề hướng d... | targetFrame: '<khung>',
targetFrameName: 'Tên khung đích',
targetPopup: '<cửa sổ popup>',
targetPopupName: 'Tên cửa sổ Popup',
title: 'Liên kết',
toAnchor: 'Neo trong trang này',
toEmail: 'Thư điện tử',
toUrl: 'URL',
toolbar: 'Chèn/Sửa liên kết',
type: 'Kiểu liên kết',
unlink: 'Xoá liên kết',
upload: 'Tải l... | tabIndex: 'Chỉ số của Tab',
target: 'Đích', | random_line_split |
shipping_container.py | # -*- coding: utf-8 -*-
# © 2016 Comunitea - Kiko Sanchez <kiko@comunitea.com>
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.
from odoo import api, fields, models, _
import odoo.addons.decimal_precision as dp
class ShippingContainerType(models.Model):
_ |
class ShippingContainer(models.Model):
_name = "shipping.container"
@api.one
def _get_moves(self):
self.move_ids_count = len(self.move_ids)
@api.one
def _get_partners(self):
self.partner_ids = self.picking_ids.partner_id
@api.multi
def _available_volume(self):
f... | name = "shipping.container.type"
name = fields.Char("Container type", required=True)
volume = fields.Float("Volumen", help="Container volume (m3)", required=True)
length = fields.Float("Length", help="Length(m)")
height = fields.Float("Height", help="Height(m)")
width = fields.Float("Width", help="... | identifier_body |
shipping_container.py | # -*- coding: utf-8 -*-
# © 2016 Comunitea - Kiko Sanchez <kiko@comunitea.com>
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.
from odoo import api, fields, models, _
import odoo.addons.decimal_precision as dp
class ShippingContainerType(models.Model):
_name = "shipping.container.type"
name = fi... | for move in container.move_ids:
volume -= move.product_id.volume * move.product_uom_qty
weight += move.product_id.weight * move.product_uom_qty
container.available_volume = volume
container.weight = weight
name = fields.Char("Container Ref.", requ... | for container in self:
volume = container.shipping_container_type_id.volume
weight = 0.00 | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.