content stringlengths 27 928k | path stringlengths 4 230 | size int64 27 928k | nl_text stringlengths 21 396k | nl_size int64 21 396k | nl_language stringlengths 2 3 | nl_language_score float64 0.04 1 |
|---|---|---|---|---|---|---|
from abaqusConstants import *
from .AnalysisStep import AnalysisStep
from ..Adaptivity.AdaptiveMeshConstraintState import AdaptiveMeshConstraintState
from ..Adaptivity.AdaptiveMeshDomain import AdaptiveMeshDomain
from ..BoundaryCondition.BoundaryConditionState import BoundaryConditionState
from ..Load.LoadCase import L... | src/abaqus/Step/AnnealStep.py | 10,587 | The AnnealStep object anneals a structure by setting the velocities and all appropriate
state variables to zero.
The AnnealStep object is derived from the AnalysisStep object.
Attributes
----------
name: str
A String specifying the repository key.
refTemp: float
A Float specifying the post-anneal reference t... | 7,139 | en | 0.561797 |
import numpy as np
import pickle as pkl
import networkx as nx
import scipy.sparse as sp
from scipy.sparse.linalg.eigen.arpack import eigsh
def sample_mask(idx, l):
"""Create mask."""
mask = np.zeros(l)
mask[idx] = 1
return np.array(mask, dtype=np.bool)
def load_data(cell_line, cross_cell_line, label... | utils.py | 6,506 | Calculate Chebyshev polynomials up to order k. Return a list of sparse matrices (tuple representation).
Construct feed dictionary.
Load input data from data/cell_line directory.
| x_20.index | the indices (IDs) of labeled train instances as list object (for label_rate = 20%) |
| ux_20.index | the indices (IDs) of u... | 1,660 | en | 0.764393 |
class FittingAngleUsage(Enum, IComparable, IFormattable, IConvertible):
"""
An enumerated type representing the options for how to limit the angle values applicable to fitting content.
enum FittingAngleUsage,values: UseAnAngleIncrement (1),UseAnyAngle (0),UseSpecificAngles (2)
"""
def __eq__(se... | release/stubs.min/Autodesk/Revit/DB/__init___parts/FittingAngleUsage.py | 1,260 | An enumerated type representing the options for how to limit the angle values applicable to fitting content.
enum FittingAngleUsage,values: UseAnAngleIncrement (1),UseAnyAngle (0),UseSpecificAngles (2)
x.__eq__(y) <==> x==yx.__eq__(y) <==> x==yx.__eq__(y) <==> x==y
__format__(formattable: IFormattable,format: str) ... | 532 | en | 0.391853 |
# Copyright 2013-2018 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class PerlFileListing(PerlPackage):
"""Parse directory listing"""
homepage = "http://search... | var/spack/repos/builtin/packages/perl-file-listing/package.py | 580 | Parse directory listing
Copyright 2013-2018 Lawrence Livermore National Security, LLC and other Spack Project Developers. See the top-level COPYRIGHT file for details. SPDX-License-Identifier: (Apache-2.0 OR MIT) | 214 | en | 0.643363 |
"""
This plugin is for recording test results in the Testcase Database.
"""
import getpass
import time
import uuid
from nose.plugins import Plugin
from nose.exc import SkipTest
from seleniumbase.core.application_manager import ApplicationManager
from seleniumbase.core.testcase_manager import ExecutionQueryPayload
from... | seleniumbase/plugins/db_reporting_plugin.py | 6,841 | This plugin records test results in the Testcase Database.
After each test error, record testcase run information.
(Test errors should be treated the same as test failures.)
After each test failure, record testcase run information.
After each test success, record testcase run information.
At the start of the run, we wa... | 813 | en | 0.83674 |
# -*- encoding: utf-8 -*-
from django.utils.translation import ugettext_lazy as _
from grappelli.dashboard import modules, Dashboard
from grappelli.dashboard.utils import get_admin_site_name
class DjangoPagesDashboard(Dashboard):
"""
Custom index dashboard for Django-pages
"""
def init_with_context... | django_pages/dashboard.py | 2,529 | Custom index dashboard for Django-pages
-*- encoding: utf-8 -*- | 65 | en | 0.547252 |
import h5py
import numpy as np
import os
from plyfile import PlyData, PlyElement
HDF5_DATA = 'hdf5_data'
print('Generating .h5 files...', '\n')
if not os.path.exists(HDF5_DATA):
os.mkdir(HDF5_DATA)
filenames_training = [line.rstrip() for line in open("filelist_training.txt", 'r')]
filenames_testing = [line.rstr... | data/make_hdf5_files.py | 3,299 | ====== GENERATING TRAINING FILES ============================================== labeldata = [line.rstrip() for line in open("./label_dir/" + filenames_training[i] + ".seg", 'r')] a_label_training[i, j] = labeldata[j] ====== GENERATING TRAINING FILES ============================================== ====== GENERATING TESTI... | 590 | en | 0.451641 |
#!/usr/bin/env python
"""
Object-oriented implementation of backup reporting code.
Defines a class called 'Backup' that records all backups of a device
"""
import os, sys, argparse
import glob
from configparser import ConfigParser
from atlassian import Confluence
class Backup:
def __init__(sel... | python/atlassian/config-report.py | 2,382 | Object-oriented implementation of backup reporting code.
Defines a class called 'Backup' that records all backups of a device
!/usr/bin/env python Remove the full pathname, we only want the directory and the filename Read in all the devices from the nominated filepprint(result) | 279 | en | 0.866185 |
# Copyright 2013-2018 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class RMatrixstats(RPackage):
"""High-performing functions operating on rows and columns of matr... | var/spack/repos/builtin/packages/r-matrixstats/package.py | 944 | High-performing functions operating on rows and columns of matrices,
e.g. col / rowMedians(), col / rowRanks(), and col / rowSds(). Functions
optimized per data type and for subsetted calculations such that both
memory usage and processing time is minimized. There are also optimized
vector-based methods, e.g. binMeans(... | 545 | en | 0.776768 |
import pandas as pd
import re
import nltk
from nltk.corpus import stopwords
from nltk.stem.wordnet import WordNetLemmatizer
from nltk.tokenize import word_tokenize
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
from sklearn.metrics.pairwise import line... | model/recommendation_functions.py | 12,791 | INPUT:
df - pandas dataframe with article_id, title, user_id columns
OUTPUT:
user_item - user item matrix
Description:
Return a matrix with user ids as rows and article ids on the columns with 1 values where a user interacted with
an article and a 0 otherwise
OUTPUT:
similar_users - (list) an ordered list where the... | 4,760 | en | 0.833564 |
#!/usr/bin/env python
import rospy
import math
from std_msgs.msg import Float64
from geometry_msgs.msg import Twist
class SimpleRoverController:
def __init__(self):
self.namespace = rospy.get_param("name_space", "scout_1")
self.w_s = rospy.get_param("wheel_separation", 1.7680) #... | src/csi_rover_controls/deprecated/simple_rover_controller.py | 4,207 | !/usr/bin/env python wheel seperation wheel radisu 10hz check to see if there's an explicit yaw command lock all steering joints to be zero else use crab steering move all of the steering joints to a position. the parameter is an angle value in radians Determine steering angle Set linear_vel as magnitude Range -pi/2 to... | 689 | en | 0.562433 |
"""
Copyright (c) 2018 Intel Corporation
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 wri... | model-optimizer/extensions/middle/UselessMerge.py | 1,507 | Copyright (c) 2018 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, soft... | 562 | en | 0.864985 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
sys.dont_write_bytecode=True
from distutils.core import setup
from pyxsltp import __version__
setup(
name = "pyxsltp",
version = __version__,
py_modules = ['pyxsltp'],
scripts = ['pyxsltp'],
)
| setup.py | 265 | !/usr/bin/python -*- coding: utf-8 -*- | 38 | en | 0.437977 |
# Generated by Django 2.0.6 on 2018-07-05 16:13
from django.db import migrations, models
import posts.models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Post',
fields=[
('id', ... | posts/migrations/0001_initial.py | 1,158 | Generated by Django 2.0.6 on 2018-07-05 16:13 | 45 | en | 0.496208 |
# (C) Datadog, Inc. 2019-present
# All rights reserved
# Licensed under a 3-clause BSD style license (see LICENSE)
__version__ = '2.3.0'
| presto/datadog_checks/presto/__about__.py | 137 | (C) Datadog, Inc. 2019-present All rights reserved Licensed under a 3-clause BSD style license (see LICENSE) | 108 | en | 0.81047 |
from enum import IntEnum
from typing import Dict, Union, Callable, List, Optional
from cereal import log, car
import cereal.messaging as messaging
from common.realtime import DT_CTRL
from selfdrive.config import Conversions as CV
from selfdrive.locationd.calibrationd import MIN_SPEED_FILTER
AlertSize = log.ControlsSt... | selfdrive/controls/lib/events.py | 30,954 | Alert priorities Event types get event name from enum less harsh version of SoftDisable, where the condition is user-triggered ********** helper functions ********** ********** alert callback functions **********if soft_disable_time < int(0.5 / DT_CTRL): return ImmediateDisableAlert(alert_text_2)if soft_disable_time <... | 4,792 | en | 0.918436 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import simplejson as json
from alipay.aop.api.response.AlipayResponse import AlipayResponse
class SsdataDataserviceDtevalIdentitycheckQueryResponse(AlipayResponse):
def __init__(self):
super(SsdataDataserviceDtevalIdentitycheckQueryResponse, self).__init__()... | alipay/aop/api/response/SsdataDataserviceDtevalIdentitycheckQueryResponse.py | 2,093 | !/usr/bin/env python -*- coding: utf-8 -*- | 42 | en | 0.34282 |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# -----------------------------------------------------------------... | venv/lib/python3.8/site-packages/vsts/build/v4_1/models/source_provider_attributes.py | 1,634 | SourceProviderAttributes.
:param name: The name of the source provider.
:type name: str
:param supported_capabilities: The capabilities supported by this source provider.
:type supported_capabilities: dict
:param supported_triggers: The types of triggers supported by this source provider.
:type supported_triggers: lis... | 929 | en | 0.534629 |
""" Tests the creation of tables, and the methods of the sql class
"""
from pyrate.repositories.sql import Table
from utilities import setup_database
class TestSql:
""" Tests the Sql class
"""
def test_get_list_of_columns(self, setup_database):
db = setup_database
rows = [{'unit': 'days',
... | tests/test_sql.py | 1,664 | Tests the Sql class
Tests the creation of tables, and the methods of the sql class | 87 | en | 0.796186 |
# --------------------------------------------------------
# Fast R-CNN
# Copyright (c) 2015 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# Written by Ross Girshick
# --------------------------------------------------------
# pylint: disable-all
# flake8: noqa
"""Factory method for easily getti... | lib/datasets/factory.py | 2,880 | Get an imdb (image database) by name.
List all registered imdbs.
Factory method for easily getting imdbs by name.
-------------------------------------------------------- Fast R-CNN Copyright (c) 2015 Microsoft Licensed under The MIT License [see LICENSE for details] Written by Ross Girshick -------------------------... | 771 | en | 0.513835 |
import math
def is_prime(num):
if num < 2:
return False
for i in range(num):
if i < 2:
continue
if num % i == 0:
return False
return True
def get_nth_prime(n):
cnt = 0
i = 0
while cnt < n:
i += 1
if is_prime(i):
cnt += 1
return i
if __name__ == '__main__':
#pr... | problems/007/run.v1.py | 371 | print get_nth_prime(6) | 22 | ja | 0.056703 |
# coding: utf-8
import pprint
import re
import six
from huaweicloudsdkcore.sdk_response import SdkResponse
class CreateConfigurationResponse(SdkResponse):
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_ma... | huaweicloud-sdk-rds/huaweicloudsdkrds/v3/model/create_configuration_response.py | 3,079 | Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
Returns true if both objects are equal
CreateConfigurationResponse - a model defined i... | 847 | en | 0.673042 |
from tkinter import *
from tkinter import ttk
import time
import time
window = Tk()
mygreen = "lightblue"
myred = "blue"
style = ttk.Style()
style.theme_create( "dedoff", parent="alt", settings={
"TNotebook": {"configure": {"tabmargins": [2, 5, 2, 0] } },
"TNotebook.Tab": {
"configure": ... | edu54book/edu54bookSizeAuto.py | 22,153 | панелиОГО ВТОРООООООООООЙ ТААААААААААААААААААБ Практикум 2_поезд | 64 | lv | 0.744733 |
import unittest
from facial_recog.app import *
from .test_config import test_run_count, seed, success_perc
from .test_util import *
class TestFR(unittest.TestCase):
subject_names = dict()
subject_classes = dict()
def setUp(self):
random.seed(seed)
create_app_dirs()
setup_logger(... | facial_recog/tests/test_app.py | 1,821 | only for super strict testing clear_fdb() | 41 | en | 0.529469 |
# Copyright 2003-2008 by Leighton Pritchard. All rights reserved.
# Revisions copyright 2008-2009 by Peter Cock.
# This code is part of the Biopython distribution and governed by its
# license. Please see the LICENSE file that should have been included
# as part of this package.
#
# Contact: Leighton Pritchard,... | bin/last_wrapper/Bio/Graphics/GenomeDiagram/_CircularDrawer.py | 51,202 | CircularDrawer(AbstractDrawer)
Inherits from:
o AbstractDrawer
Provides:
Methods:
o __init__(self, parent=None, pagesize='A3', orientation='landscape',
x=0.05, y=0.05, xl=None, xr=None, yt=None, yb=None,
start=None, end=None, tracklines=0, track_size=0.75,
circular=1) Called on instantia... | 18,317 | en | 0.783473 |
import plotly.graph_objects as go
import pandas as pd
from .Colors import COLOR_DISCRETE_MAP
from Classification import CATEGORIES
def all_categories_grouping(row: pd.Series) -> str:
"""
Merge Category, Fuel and segment to a single string for unique categorization
"""
if row['Fuel'] == 'Battery Elect... | Graphing/MeanActivityHorizontalBarChart.py | 4,224 | Horizontal bar chart representing mean activity and other activities per unique categorization
:param stock_and_mileage_df: Dataframe of the vehicles registration list
:param output_folder: output folder name where to store resulting chart
:return: an html file containing the horizontal bar chart of the mean activity... | 712 | en | 0.790518 |
class Pessoa:
def __init__(self,nome,idade,cpf,salario):
self.nome = nome
self.idade = idade
self.cpf = cpf
self.salario = salario
def Aumento(self):
return self.salario *0.05
class Gerente(Pessoa):
def __init__(self,nome,idade,cpf,salario,senha):
... | Python_OO/Exercicio.py | 1,236 | def Comportamento(self):return False | 36 | pt | 0.178826 |
import os
import re
import wx
import wx.grid
from . import dialog_base
def pop_error(msg):
wx.MessageBox(msg, 'Error', wx.OK | wx.ICON_ERROR)
class SettingsDialog(dialog_base.SettingsDialogBase):
def __init__(self, extra_data_func, extra_data_wildcard, config_save_func,
file_name_format_h... | InteractiveHtmlBom/dialog/settings_dialog.py | 14,769 | hack for some gtk themes that incorrectly calculate best size hack for new wxFormBuilder generating code incompatible with old wxPython noinspection PyMethodOverriding wxPython 4 wxPython 3 Implementing settings_dialog Implementing HtmlSettingsPanelBase Handlers for HtmlSettingsPanelBase events. Implementing GeneralSet... | 635 | en | 0.657373 |
from __future__ import unicode_literals, print_function
from libraries.lambda_handlers.register_module_handler import RegisterModuleHandler
def handle(event, context):
"""
Called by a module when it is deployed to register it
:param dict event:
:param context:
:return dict:
"""
return Regi... | functions/register_module/main.py | 363 | Called by a module when it is deployed to register it
:param dict event:
:param context:
:return dict: | 102 | en | 0.931528 |
"""
Problem Statement:
Let the function f(s) be the frequency of the lexicographically smallest character in a non-empty string s. For example, if s = "dcce" then f(s) = 2 because the lexicographically smallest character is 'c', which has a frequency of 2.
You are given an array of strings words and another array of q... | Arrays/python/compareStringByFrequencyOfSmallestCharacter.py | 2,164 | Problem Statement:
Let the function f(s) be the frequency of the lexicographically smallest character in a non-empty string s. For example, if s = "dcce" then f(s) = 2 because the lexicographically smallest character is 'c', which has a frequency of 2.
You are given an array of strings words and another array of query ... | 1,153 | en | 0.872966 |
class MetricHandler:
"""
Object meant to be used in the training loop to handle metrics logs
"""
def __init__(self):
pass
def add(self, outputs, targets):
"""
Adding metric for each batch
:param outputs: outputs of the model
:param targets: targets of the m... | facade_project/utils/ml_utils.py | 2,763 | An object which is used to print information about training without spamming the console. (WIP)
Object meant to be used in the training loop to handle metrics logs
Adding metric for each batch
:param outputs: outputs of the model
:param targets: targets of the model
Aggregate accumulated metrics over batches at the en... | 704 | en | 0.768563 |
"""
Optimizers
----------
.. autosummary::
:template: template.rst
:toctree:
Solver
ScipySolver
CandidateSolver
GridSolver
"""
from .solver import Solver
from .scipy import ScipySolver
from .candidate import CandidateSolver, GridSolver, FiniteDomainSolver
| hdbo/febo/solvers/__init__.py | 279 | Optimizers
----------
.. autosummary::
:template: template.rst
:toctree:
Solver
ScipySolver
CandidateSolver
GridSolver | 138 | en | 0.66435 |
import grpc
from functools import wraps
class WalletEncryptedError(Exception):
def __init__(self, message=None):
message = message or 'Wallet is encrypted. Please unlock or set ' \
'password if this is the first time starting lnd. '
super().__init__(message)
def han... | lndgrpc/errors.py | 2,145 | Decorator to add more context to RPC errors
lnd might be active, but not possible to contact using RPC if the wallet is encrypted. If we get an rpc error code Unimplemented, it means that lnd is running, but the RPC server is not active yet (only WalletUnlocker server active) and most likely this is because of an enc... | 371 | en | 0.86211 |
# Copyright (c) OpenMMLab. All rights reserved.
import copy
import torch
import torch.nn as nn
from mmcls.models.builder import BACKBONES
from mmcv.cnn import build_activation_layer, build_norm_layer
from ...utils import Placeholder
class FactorizedReduce(nn.Module):
"""Reduce feature map size by factorized poi... | mmcls/models/architectures/components/backbones/darts_backbone.py | 9,630 | Auxiliary head in 2/3 place of network to let the gradient flow well.
Reduce feature map size by factorized pointwise (stride=2).
Standard conv: ReLU - Conv - BN
Copyright (c) OpenMMLab. All rights reserved. If previous cell is reduction cell, current input size does not match with output size of cell[k-2]. So the ou... | 691 | en | 0.892811 |
"""Project signals"""
import logging
import django.dispatch
from django.contrib import messages
from django.dispatch import receiver
from django.utils.translation import ugettext_lazy as _
from readthedocs.oauth.services import registry
before_vcs = django.dispatch.Signal(providing_args=["version"])
after_vcs = dj... | readthedocs/projects/signals.py | 1,186 | Add post-commit hook on project import
Project signals | 54 | en | 0.570502 |
#Author: Sepehr Roudini.
#Date: 02/05/2018.
#University of Iowa.
#Department of Chemical Engineering.
#Purpose: Calculating mean and Std
#--------------------------------------------------------------------------------------------#
#Defining function and importing necessary libraries.
#----------------------... | Mean_Std_Calculation.py | 1,795 | Author: Sepehr Roudini.Date: 02/05/2018.University of Iowa.Department of Chemical Engineering.Purpose: Calculating mean and Std--------------------------------------------------------------------------------------------Defining function and importing necessary libraries.-------------------------------------------------... | 1,167 | en | 0.294317 |
"""Users serializers"""
# Django
from django.conf import settings
from django.contrib.auth import password_validation, authenticate
from django.core.validators import RegexValidator
# Serializers
from cride.users.serializers.profiles import ProfileModelSerializer
# Django REST Framework
from rest_framework import se... | cride/users/serializers/users.py | 4,371 | Account verification serializer
Meta class.
User Login serializer
Handle the login request data.
User model serializer
User sign up serializer.
Handle sign up data validation and user/profile creation.
Handle user and profile creation.
Generate or retrieve new token
Update user's verified status
Verify passwords match.... | 470 | en | 0.613533 |
import pyomo.environ as pe
import romodel as ro
feeds = range(5)
products = range(4)
pools = range(2)
qualities = range(4)
con_feed_pool = [(0, 0), (1, 0), (2, 0), (3, 1), (4, 1)]
con_pool_prod = [(0, 0), (0, 1), (0, 2), (0, 3), (1, 0), (1, 1), (1, 2), (1, 3)]
con_feed_prod = []
price_product = [16, 25, 15, 10]
pric... | examples/pooling.py | 4,233 | Feed availability Pool capacity Product demand Simplex Product quality | 70 | en | 0.815036 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from . import __version__ as app_version
app_name = "custom_scripts"
app_title = "Custom Scripts"
app_publisher = "C.R.I.O"
app_description = "For custom scripts"
app_icon = "octicon octicon-file-directory"
app_color = "grey"
app_email = "criogroups@gmail... | custom_scripts/hooks.py | 4,188 | -*- coding: utf-8 -*- Includes in <head> ------------------ include js, css files in header of desk.html app_include_css = "/assets/custom_scripts/css/custom_scripts.css" app_include_js = "/assets/custom_scripts/js/custom_scripts.js" include js, css files in header of web template web_include_css = "/assets/custom_scri... | 3,096 | en | 0.583827 |
# Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | base2designs/utils/np_box_list_ops_test.py | 17,894 | Tests for object_detection.utils.np_box_list_ops.
Copyright 2017 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICE... | 719 | en | 0.821082 |
# Generated by Django 3.1.7 on 2021-03-10 03:37
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('Admins', '0036_auto_20210310_0337'),
]
operations = [
migrations.AlterField(
model_name='createpractioner',
name='id... | Admins/migrations/0037_auto_20210310_0337.py | 459 | Generated by Django 3.1.7 on 2021-03-10 03:37 | 45 | en | 0.655498 |
import random
def HiringProblem(score, n):
sample_size = int(round(n / e))
print(f"\nRejecting first {sample_size} candidates as sample")
#finding best candidate in the sample set for benchmark
best_candidate = 0;
for i in range(1, sample_size):
if (score[i] > score[bes... | Semester I/Design and Analysis of Algorithm/Practical 04- Hiring Problem/HiringProblem.py | 1,205 | finding best candidate in the sample set for benchmarkfinding the first best candidate outside the sample set Driver codetotal number of candidate populating the list | 166 | en | 0.872793 |
#
# The Template-Python distribution is Copyright (C) Sean McAfee 2007-2008,
# derived from the Perl Template Toolkit Copyright (C) 1996-2007 Andy
# Wardley. All Rights Reserved.
#
# The file "LICENSE" at the top level of this source distribution describes
# the terms under which this file may be distributed.
#
... | template/parser.py | 35,017 | A trivial local exception class.
This module implements a LALR(1) parser and assocated support
methods to parse template documents into the appropriate "compiled"
format.
Tokenizes a comment.
Tokenizes a filename.
Tokenizes an identifier.
Tokenizes a number.
Parses the list of input tokens passed by reference and retur... | 3,855 | en | 0.812422 |
#!/usr/bin/env python2
# Copyright (c) 2015-2016 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
import hashlib
import sys
import os
from random import SystemRandom
import base64
import hmac
if len(s... | share/rpcuser/rpcuser.py | 1,115 | !/usr/bin/env python2 Copyright (c) 2015-2016 The Bitcoin Core developers Distributed under the MIT software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php.This uses os.urandom() underneathCreate 16 byte hex saltCreate 32 byte b64 password | 291 | en | 0.366729 |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import os
import cv2
import tensorflow as tf
# In[2]:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
# In[3]:
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow import keras
from ten... | train_valid_split.py | 2,189 | !/usr/bin/env python coding: utf-8 In[1]: In[2]: In[3]: Load the Training Data In[4]: curwd = str(os.getcwd()) targetwd = '\\data\\train' path_train = curwd + targetwd In[6]: In[7]: In[8]: Train-Validation Split In[9]: find unique categories of whales in our dataframe map the images to categories perform manual train... | 561 | en | 0.629704 |
# -*- coding: utf-8 -*-
from odoo import fields
from odoo.tests.common import Form, SavepointCase
from odoo.tests import tagged
from contextlib import contextmanager
from unittest.mock import patch
import datetime
@tagged('post_install', '-at_install')
class AccountTestInvoicingCommon(SavepointCase):
@classmet... | odoo/base-addons/account/tests/account_test_savepoint.py | 18,071 | Helper to make easily a python "with statement" mocking the "today" date.
:param forced_today: The expected "today" date as a str or Date object.
:return: An object to be used like 'with self.mocked_today(<today>):'.
Create a new company having the name passed as parameter.
A chart of accounts will be... | 1,047 | en | 0.860917 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#############
## Imports ##
#############
import os
import sys ; sys.path.append("/home/developer/workspace/rklearn-lib")
import tensorflow as tf
from rklearn.tfoo_v1 import BaseModel
#################
## CIFAR10CNN ##
#################
class CIFAR10CNN(BaseModel):
... | rklearn/tests/it/cifar10_cnn.py | 5,623 | Build the custom CNN for the CIFAR-10 dataset.
!/usr/bin/env python -*- coding: utf-8 -*- Imports CIFAR10CNN __init__() these parameters are sent to the trainer through the model because it is easier build_model() The input data holders (cf. shapes after prepa) ex. (50000, 32, 32, 3) ex. (50000, 10) The CNN ar... | 584 | en | 0.61569 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2017/7/25 0025 上午 10:14
# @Author : Exchris Tsai
# @Site :
# @File : example52.py
# @Software: PyCharm
"""
题目:学习使用按位或 | 。
程序分析:0|0=0; 0|1=1; 1|0=1; 1|1=1
"""
__author__ = 'Exchris Tsai'
if __name__ == '__main__':
a = 0o77
b = a | 3
print(... | Old/exercise/example52.py | 412 | 题目:学习使用按位或 | 。
程序分析:0|0=0; 0|1=1; 1|0=1; 1|1=1
!/usr/bin/env python -*- coding: utf-8 -*- @Time : 2017/7/25 0025 上午 10:14 @Author : Exchris Tsai @Site : @File : example52.py @Software: PyCharm | 204 | zh | 0.574206 |
#!/usr/bin/env python
#############################################################################
##
## Copyright (C) 2015 Riverbank Computing Limited.
## Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
## All rights reserved.
##
## This file is part of the examples of PyQt.
##
## $QT_BEGIN_LICENS... | PyQt5_gpl-5.8/examples/opengl/grabber.py | 14,067 | !/usr/bin/env python Copyright (C) 2015 Riverbank Computing Limited. Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). All rights reserved. This file is part of the examples of PyQt. $QT_BEGIN_LICENSE:BSD$ You may use this file under the terms of the BSD license as follows: "Redistribution and use in so... | 1,785 | en | 0.886627 |
"""
Data processing routines
Deepak Baby, UGent, June 2018
deepak.baby@ugent.be
"""
import numpy as np
def reconstruct_wav(wavmat, stride_factor=0.5):
"""
Reconstructs the audiofile from sliced matrix wavmat
"""
window_length = wavmat.shape[1]
window_stride = int(stride_factor * window_length)
wav_length ... | data_ops.py | 1,919 | Apply de_emphasis on test data: works only on 1d data
Apply pre_emph on 2d data (batch_size x window_length)
Reconstructs the audiofile from sliced matrix wavmat
Data processing routines
Deepak Baby, UGent, June 2018
deepak.baby@ugent.be
print ("wav recon shape " + str(wav_recon.shape)) now compute the scaling factor ... | 460 | en | 0.724207 |
from django.views.generic import TemplateView, CreateView, UpdateView
from django.urls import reverse_lazy
from home_app import forms
from django.contrib.auth.mixins import LoginRequiredMixin
from account_app.models import CustomUser
# Create your views here.
class IndexView(TemplateView):
template_name = 'home_... | home_app/views.py | 894 | Create your views here. | 23 | en | 0.928092 |
# Generated by Django 3.2 on 2021-09-07 12:46
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('payment', '0002_alter_invoice_address'),
('item', '0002_alter_item_upc'),
('accounts', '00... | cart/migrations/0001_initial.py | 2,766 | Generated by Django 3.2 on 2021-09-07 12:46 | 43 | en | 0.781417 |
# -*- coding: utf-8 -*-
from unittest import mock
from vispy.scene.visuals import Image
from vispy.testing import (requires_application, TestingCanvas,
run_tests_if_main)
from vispy.testing.image_tester import assert_image_approved, downsample
import numpy as np
import pytest
@requires_ap... | vispy/visuals/tests/test_image.py | 6,614 | Test image visual
Test image visual with clims and gamma on shader.
Test image visual coordinates are only built when needed.
-*- coding: utf-8 -*- RGBA - make alpha fully opaque assert not allclose 16-bit integers and above seem to have precision loss when scaled on the CPU default is RGBA, anything except auto requ... | 537 | en | 0.82938 |
# -*- coding: utf-8 -*-
#
# Copyright 2017 Ricequant, Inc
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable ... | rqalpha/mod/rqalpha_mod_sys_accounts/position_model/future_position.py | 17,514 | [float] 买方向持仓均价
[int] 买方向挂单量
[float] 当日买方向盈亏
[float] 买方向当日持仓盈亏
[float] 买方向持仓保证金
[int] 买方向昨仓
[int] 买方向挂单量
[float] 买方向累计盈亏
[int] 买方向持仓
[float] 买方向平仓盈亏
[int] 买方向今仓
[float] 可平买方向持仓
[float] 可平卖方向持仓
[float] 当日盈亏
[float] 当日持仓盈亏
[float] 保证金
[float] 累计盈亏
[float] 当日平仓盈亏
[float] 卖方向持仓均价
[int] 卖方向挂单量
[float] 当日卖方向盈亏
[float] 卖方向当日持... | 1,112 | en | 0.414527 |
import asyncio
import functools
import logging
from types import FunctionType, ModuleType
from typing import Type
from prometheus_client import Histogram, Counter
logger = logging.getLogger(__name__)
H = Histogram(f"management_layer_call_duration_seconds", "API call duration (s)",
["call"])
def _prom... | management_layer/metrics.py | 4,436 | A Prometheus decorator adding timing metrics to a function in a class.
This decorator will work on both asynchronous and synchronous functions.
Note, however, that this function will turn synchronous functions into
asynchronous ones when used as a decorator.
:param f: The function for which to capture metrics
A Prometh... | 1,505 | en | 0.781973 |
from typing import Callable
import numpy as np
from manimlib.utils.bezier import bezier
def linear(t: float) -> float:
return t
def smooth(t: float) -> float:
# Zero first and second derivatives at t=0 and t=1.
# Equivalent to bezier([0, 0, 0, 1, 1, 1])
s = 1 - t
return (t**3) * (10 * s * s + ... | manimlib/utils/rate_functions.py | 2,453 | Zero first and second derivatives at t=0 and t=1. Equivalent to bezier([0, 0, 0, 1, 1, 1]) Stylistically, should this take parameters (with default values)? Ultimately, the functionality is entirely subsumed by squish_rate_func, but it may be useful to have a nice name for with nice default params for "lingering", diff... | 442 | en | 0.823491 |
from typing import Tuple, FrozenSet
from pysmt.environment import Environment as PysmtEnv
from pysmt.fnode import FNode
import pysmt.typing as types
from utils import symb_to_next
from hint import Hint, Location
def transition_system(env: PysmtEnv) -> Tuple[FrozenSet[FNode], FNode, FNode,
... | benchmarks/software_nontermination/f3_hints/C_Integer/Stroeder_15/Urban-WST2013-Fig1_false-termination.py | 2,581 | pc = 0 & (x <= 10) -> pc' = 1 pc = 0 & !(x <= 10) -> pc' = -1 pc = 1 & (x > 6) -> pc' = 2 pc = 1 & !(x > 6) -> pc' = 0 pc = 2 -> pc' = 0 pc = -1 -> pc' = -1 pc = 0 -> same pc = 1 -> same pc = 2 -> x' = x + 2 pc = end -> same | 224 | en | 0.808315 |
"""
The MIT License (MIT)
Copyright (c) 2015-present Rapptz
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, merg... | discord/message.py | 73,893 | Represents an attachment from Discord.
.. container:: operations
.. describe:: str(x)
Returns the URL of the attachment.
.. describe:: x == y
Checks if the attachment is equal to another attachment.
.. describe:: x != y
Checks if the attachment is not equal to another attachme... | 15,628 | en | 0.747377 |
# -*- coding: utf-8 -*-
"""Utilities for calculation job resources."""
__all__ = (
'get_default_options',
'seconds_to_timelimit',
)
def get_default_options(max_num_machines: int = 1, max_wallclock_seconds: int = 1800, with_mpi: bool = False) -> dict:
"""Return an instance of the options dictionary with t... | aiida_abinit/utils/resources.py | 1,411 | Return an instance of the options dictionary with the minimally required parameters for a `CalcJob`.
:param max_num_machines: set the number of nodes, default=1
:param max_wallclock_seconds: set the maximum number of wallclock seconds, default=1800
:param with_mpi: whether to run the calculation with MPI enabled
Conve... | 561 | en | 0.529731 |
"""On-premise Gitlab clients
"""
# from .v4 import *
| tapis_cli/clients/services/gitlab/__init__.py | 53 | On-premise Gitlab clients
from .v4 import * | 45 | en | 0.522795 |
import json
import re
class FieldValidationException(Exception):
pass
class Field(object):
"""
This is the base class that should be used to create field validators. Sub-class this and override to_python if you
need custom validation.
"""
DATA_TYPE_STRING = 'string'
DATA_TYPE_NUMBER = '... | splunk_eventgen/splunk_app/lib/mod_input/fields.py | 12,593 | The duration field represents a duration as represented by a string such as 1d for a 24 hour period.
The string is converted to an integer indicating the number of seconds.
This is the base class that should be used to create field validators. Sub-class this and override to_python if you
need custom validation.
Class ... | 2,490 | en | 0.733836 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2012 Homer Strong, Radim Rehurek
# Licensed under the GNU LGPL v2.1 - http://www.gnu.org/licenses/lgpl.html
"""This module implements the "hashing trick" [1]_ -- a mapping between words and their integer ids
using a fixed and static mapping.
Notes
-----... | gensim/gensim/corpora/hashdictionary.py | 13,162 | Encapsulates the mapping between normalized words and their integer ids.
Notes
-----
Unlike :class:`~gensim.corpora.dictionary.Dictionary`,
building a :class:`~gensim.corpora.hashdictionary.HashDictionary` before using it **isn't a necessary step**.
The documents can be computed immediately, from an uninitialized
:cla... | 7,492 | en | 0.699109 |
import configparser
import logging
def dict_url(conf):
"""Add all url from file url.ini with
key = name of the parking end value is
the url.
:returns: dictionnary with all parking and url
:rtype: dict
"""
url = configparser.ConfigParser()
logging.debug("initializing the variable url")... | backend/function_park/dict_url.py | 724 | Add all url from file url.ini with
key = name of the parking end value is
the url.
:returns: dictionnary with all parking and url
:rtype: dict | 143 | en | 0.869082 |
from __future__ import absolute_import, print_function, unicode_literals
from builtins import dict, str
from indra.sources.tas.api import _load_data, process_csv
def test_load_data():
data = _load_data()
assert len(data) > 100, len(data)
def test_processor():
tp = process_csv(affinity_class_limit=10)
... | indra/tests/test_tas.py | 625 | This is the total number of statements about human genes | 56 | en | 0.877267 |
from typing import Callable, Iterable, Sequence
import numpy as np
from dpipe.im.axes import AxesLike, AxesParams
from dpipe.itertools import lmap, squeeze_first
from dpipe.im import pad_to_shape
def pad_batch_equal(batch, padding_values: AxesParams = 0, ratio: AxesParams = 0.5):
"""
Pad each element of ``b... | dpipe/batch_iter/utils.py | 4,026 | Returns a function that takes an iterable and applies ``func`` to the values at the corresponding ``index``.
``args`` and ``kwargs`` are passed to ``func`` as additional arguments.
Examples
--------
>>> first_sqr = apply_at(0, np.square)
>>> first_sqr([3, 2, 1])
>>> (9, 2, 1)
Returns a function that takes an iterable... | 1,634 | en | 0.645214 |
# -*- coding: utf-8 -*-
###########################################################################
# Copyright (c), The AiiDA team. All rights reserved. #
# This file is part of the AiiDA code. #
# ... | aiida/cmdline/params/types/plugin.py | 9,286 | AiiDA Plugin name parameter type.
:param group: string or tuple of strings, where each is a valid entry point group. Adding the `aiida.`
prefix is optional. If it is not detected it will be prepended internally.
:param load: when set to True, convert will not return the entry point, but the loaded entry point
Usa... | 3,089 | en | 0.786626 |
from BoundingBox import *
from eval_utils import *
class BoundingBoxes:
def __init__(self):
self._boundingBoxes = []
def addBoundingBox(self, bb):
self._boundingBoxes.append(bb)
def removeBoundingBox(self, _boundingBox):
for d in self._boundingBoxes:
if BoundingBox.co... | ssd_mobilenetv2/BoundingBoxes.py | 2,653 | get only specified bounding box type get only specified bb type get only specified bb type Return all bounding boxes get only specified bb type if ground truth green if detection red def drawAllBoundingBoxes(self, image): for gt in self.getBoundingBoxesByType(BBType.GroundTruth): image = add_bb_into_image(i... | 487 | en | 0.338807 |
#!/usr/bin/env python
#============================================================================
# Copyright (C) Microsoft Corporation, All rights reserved.
#============================================================================
import os
import imp
import re
import codecs
protocol = imp.load_source('protoco... | Providers/Scripts/2.4x-2.5x/Scripts/nxOMSPerfCounter.py | 11,843 | !/usr/bin/env python============================================================================ Copyright (C) Microsoft Corporation, All rights reserved.============================================================================ backwards compatibility with pre-multi-homing bundles | 284 | en | 0.49184 |
"""Parses the arguments passed to the bash script and returns them back to the bash script."""
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
import argparse
import re
import sys
# Technique for printing custom error and help
# Source: https://sta... | binauthz-attestation/parse_arguments.py | 4,687 | Parses the arguments passed to the bash script and returns them back to the bash script.
Technique for printing custom error and help Source: https://stackoverflow.com/a/4042861/862857 By default, arguments with "--" are optional, so we have to make our own argument group so they are required If the user is using KMS... | 476 | en | 0.744523 |
#
# This source file is part of the EdgeDB open source project.
#
# Copyright 2016-present MagicStack Inc. and the EdgeDB authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http... | edgedb/transaction.py | 14,321 | Exit the transaction or savepoint block and commit changes.
Exit the transaction or savepoint block and rollback changes.
Enter the transaction or savepoint block.
This source file is part of the EdgeDB open source project. Copyright 2016-present MagicStack Inc. and the EdgeDB authors. Licensed under the Apache Licen... | 846 | en | 0.848688 |
import os
import datetime
import logging
import sqlite3
import pytest
from utils import setup_mdb_dir, all_book_info, load_db_from_sql_file, TESTS_DIR
from manga_db.manga_db import MangaDB
from manga_db.manga import Book
from manga_db.ext_info import ExternalInfo
from manga_db.constants import LANG_IDS
@pytest.mark.p... | tests/test_book.py | 23,697 | update_assoc_columns/get_assoc_cols pass last_change kwarg so it doesnt get auto set and counts as change upd changes changes should be reset upd changes changes should be reset not testing change_str added removed _add/_remove assoc col _add_associated_column_values doesnt commit static db methods before is last arg s... | 1,637 | en | 0.836662 |
from datetime import timedelta
import json
from os import listdir
from os.path import isfile, join
import pr0gramm
import logging
__author__ = "Peter Wolf"
__mail__ = "pwolf2310@gmail.com"
__date__ = "2016-12-26"
LOG = logging.getLogger(__name__)
class DataSources:
IMAGE, THUMBNAIL, FULL_SIZE = range(3)
class... | src/data_collection/data_collector.py | 6,376 | Read the current annotation file write every item as a line with the following structure: ID;IMAGE_PATH;AMOUNT_OF_TAGS;...TAG_TEXT;TAG_CONFIDENCE;... Check if the item already has an entry in the annotation file and replace it. If no entry already exists, add a new line for the item Write the new content to the file. r... | 543 | en | 0.857904 |
#!/usr/bin/env python3
# Copyright (c) 2014-2019 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test the REST API."""
import binascii
from decimal import Decimal
from enum import Enum
from io import... | test/functional/interface_rest.py | 14,958 | Test the REST API.
!/usr/bin/env python3 Copyright (c) 2014-2019 The Bitcoin Core developers Distributed under the MIT software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php. Random address so node1's balance doesn't increase Check hex format response get the vin to l... | 1,887 | en | 0.860252 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
MAPPING = {
"dynamic": False,
"properties": {
"classification_type": {"type": "keyword"},
"date": {"type": "date", "format": "strict_date_optional_time||epoch_millis"},
"global_metrics": {
"dynamic": False,
"propertie... | tests/testing_samples/mapping_example.py | 6,699 | !/usr/bin/env python -*- coding: utf-8 -*- subfield | 51 | en | 0.3221 |
from tensorflow.keras.layers import Dense, Flatten
from tensorflow.keras.models import Model
from tensorflow.keras.applications.vgg19 import VGG19
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.callbacks import ModelCheckpoint
from datetime import datetime
import numpy as np
i... | training.py | 7,902 | accuracies loss predict logging the unsuccessful Training | 57 | en | 0.943697 |
#
# example from CHiLL manual page 14
#
# permute 3 loops
#
from chill import *
source('permute123456.c')
destination('permute1modified.c')
procedure('mm')
loop(0)
known('ambn > 0')
known('an > 0')
known('bm > 0')
permute([3,1,2])
| chill/examples/chill/testcases/permute1.script.py | 247 | example from CHiLL manual page 14 permute 3 loops | 50 | en | 0.552572 |
# -------------------------------------------------------------------------------
# Copyright IBM Corp. 2017
#
# 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/licens... | pixiedust/display/chart/renderers/commonOptions.py | 6,347 | ------------------------------------------------------------------------------- Copyright IBM Corp. 2017 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 ... | 705 | en | 0.735537 |
import asyncio
import io
from PIL import Image
from PIL import ImageDraw
from discord import Colour
import datetime
import urllib
import urllib.request
import aiohttp
import re
from datetime import datetime, date, timedelta
from calendar import timegm
import time
from utils.database import userDataba... | NabBot-master/utils/tibia.py | 43,555 | Returns an achievement (dictionary), a list of possible matches or none
Returns a dictionary with a player's info
The dictionary contains the following keys: name, deleted, level, vocation, world, residence,
married, gender, guild, last,login, chars*.
*chars is list that contains other characters in the same accou... | 5,712 | en | 0.837665 |
from __future__ import division
import argparse
import os
import torch
from mmcv import Config
from mmdet import __version__
from mmdet.apis import (get_root_logger, init_dist, set_random_seed,
train_detector)
from mmdet.datasets import build_dataset
from mmdet.models import build_detector
d... | tools/train.py | 3,378 | set cudnn_benchmark update configs according to CLI args apply the linear scaling rule (https://arxiv.org/abs/1706.02677) init distributed env first, since logger depends on the dist info. init logger before other steps set random seeds save mmdet version, config file content and class names in checkpoints as meta data... | 367 | en | 0.694573 |
"""An example of jinja2 templating"""
from bareasgi import Application, HttpRequest, HttpResponse
import jinja2
import pkg_resources
import uvicorn
from bareasgi_jinja2 import Jinja2TemplateProvider, add_jinja2
async def http_request_handler(request: HttpRequest) -> HttpResponse:
"""Handle the request"""
r... | examples/example1.py | 1,175 | An example of jinja2 templating | 31 | en | 0.236713 |
from __future__ import print_function
import pprint
import os
import time
import msgpackrpc
import math
import msgpackrpc #install as admin: pip install msgpack-rpc-python
import msgpack
import sys
import inspect
import types
import re
import shutil
import numpy as np #pip install numpy
#==========================... | run_demo.py | 20,375 | Read a pfm file
Wait for a key press on the console and return it.
Write a pfm file
image must be numpy array H X W X channels
install as admin: pip install msgpack-rpc-pythonpip install numpy============================================================================== Class... | 2,914 | en | 0.540771 |
#!/usr/bin/env python
# coding: utf-8
import logging.config
import os
# Конфигурация базы данных
DB_CONFIG = {
'username': 'root',
'password': os.environ.get('MYSQL_TRADING_PASS'),
'host': '127.0.0.1',
'dbname': 'trading_db',
}
# Конфигурация журналирования
LOGGING = {
'version': 1,
'format... | request_handler/appconfig.py | 3,134 | !/usr/bin/env python coding: utf-8 Конфигурация базы данных Конфигурация журналирования Форматирование сообщения Обработчикаи сообщений Логгеры Базовая конфигурация Конфигурация выпуска Конфигурация разработки Конфигурация тестирования Текущая конфигурация -------------------------------------------------- ------------... | 400 | ru | 0.955374 |
#!/usr/bin/env python3
import random
import sys
"""
Markov chains name generator in Python
From http://roguebasin.roguelikedevelopment.org/index.php?title=Markov_chains_name_generator_in_Python .
"""
# from http://www.geocities.com/anvrill/names/cc_goth.html
PLACES = ['Adara', 'Adena', 'Adrianne', 'Alarice', 'Alvita... | lib/markov_usernames.py | 3,086 | A name from a Markov chain
New name from the Markov chain
Building the dictionary
!/usr/bin/env python3 from http://www.geocities.com/anvrill/names/cc_goth.html Markov Name model A random name generator, by Peter Corbett http://www.pick.ucam.org/~ptc24/mchain.html This script is hereby entered into the public domain | 318 | en | 0.710686 |
#!/usr/bin/python
#By Sun Jinyuan and Cui Yinglu, 2021
foldx_exe = "/user/sunjinyuan/soft/foldx"
def getparser():
parser = argparse.ArgumentParser(description=
'To run Foldx PositionScan with multiple threads, make sure' +
' that you have... | RFACA/foldx/foldx_scan.py | 3,503 | !/usr/bin/pythonBy Sun Jinyuan and Cui Yinglu, 2021os.system("/data/home/jsun/mhetase/FoldX/foldx5 --command=SequenceOnly --pdb=" + pdbname) indi_lst_name = "individual_list_"+str(n)+"_.txt" KA12Greadablefile.write(str(x) + " " + mut[0] + " " + mut[2:-1] + " " + mut[-1] + "\n")print(foldx_exe) | 296 | en | 0.457959 |
#
# -------------------------------------------------------------------------
# Copyright (c) 2015-2017 AT&T Intellectual Property
#
# 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
#
# ... | conductor/conductor/solver/optimizer/optimizer.py | 12,731 | ------------------------------------------------------------------------- Copyright (c) 2015-2017 AT&T Intellectual Property 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.a... | 2,494 | en | 0.831059 |
#
# Copyright 2020 by 0x7c2, Simon Brecht.
# All rights reserved.
# This file is part of the Report/Analytic Tool - CPme,
# and is released under the "Apache License 2.0". Please see the LICENSE
# file that should have been included as part of this package.
#
from templates import check
import func
class check_perfor... | performance.py | 3,889 | Copyright 2020 by 0x7c2, Simon Brecht. All rights reserved. This file is part of the Report/Analytic Tool - CPme, and is released under the "Apache License 2.0". Please see the LICENSE file that should have been included as part of this package. | 245 | en | 0.966441 |
# encoding: utf-8
# module renderdoc
# from P:\1-Scripts\_Python\Py-Autocomplete\renderdoc.pyd
# by generator 1.146
# no doc
# imports
import enum as __enum
from .SwigPyObject import SwigPyObject
class BlendStats(SwigPyObject):
""" Contains the statistics for blend state binds in a frame. """
def __eq__(sel... | _pycharm_skeletons/renderdoc/BlendStats.py | 2,222 | Contains the statistics for blend state binds in a frame.
Return self==value.
Return self>=value.
Return self>value.
Return hash(self).
Return self<=value.
Return self<value.
Return self!=value.
Create and return a new object. See help(type) for accurate signature.
encoding: utf-8 module renderdoc from P:\1... | 698 | en | 0.527344 |
from __future__ import division
from __future__ import print_function
from models.pytorch.pna.layer import PNALayer
from multitask_benchmark.util.train import execute_train, build_arg_parser
# Training settings
parser = build_arg_parser()
parser.add_argument('--self_loop', action='store_true', default=False, help='Wh... | multitask_benchmark/train/mpnn.py | 3,036 | Training settings The MPNNs can be considered a particular case of PNA networks with a single aggregator and no scalers (identity) | 130 | en | 0.871023 |
import pytest
from spacy import displacy
from spacy.displacy.render import DependencyRenderer, EntityRenderer
from spacy.lang.fa import Persian
from spacy.tokens import Span, Doc
def test_displacy_parse_ents(en_vocab):
"""Test that named entities on a Doc are converted into displaCy's format."""
doc = Doc(en... | spacy/tests/test_displacy.py | 5,520 | Test that deps and tags on a Doc are converted into displaCy's format.
Test that named entities on a Doc are converted into displaCy's format.
Test that named entities with kb_id on a Doc are converted into displaCy's format.
Test that displaCy accepts custom rendering wrapper.
Test that displaCy can render Spans.
So... | 461 | en | 0.844372 |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... | azure-mgmt-network/azure/mgmt/network/models/security_rule.py | 5,419 | Network security rule.
:param id: Resource Id
:type id: str
:param description: Gets or sets a description for this rule. Restricted
to 140 chars.
:type description: str
:param protocol: Gets or sets Network protocol this rule applies to. Can
be Tcp, Udp or All(*). Possible values include: 'Tcp', 'Udp', '*'
:type pr... | 3,073 | en | 0.668274 |
# Copyright 2018, The TensorFlow Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... | tensorflow_privacy/privacy/dp_query/gaussian_query.py | 4,855 | Implements DPQuery interface for Gaussian average queries.
Accumulates clipped vectors, adds Gaussian noise, and normalizes.
Note that we use "fixed-denominator" estimation: the denominator should be
specified as the expected number of records per sample. Accumulating the
denominator separately would also be possible... | 2,017 | en | 0.823089 |
class NumArray:
# O(n) time | O(n) space - where n is the length of the input list
def __init__(self, nums: List[int]):
self.nums = []
currentSum = 0
for num in nums:
currentSum += num
self.nums.append(currentSum)
# O(1) time to look up the nums list
def s... | dynamicProgramming/303_range_sum_query_immutable.py | 493 | O(n) time | O(n) space - where n is the length of the input list O(1) time to look up the nums list | 99 | en | 0.691362 |
# uncompyle6 version 3.2.0
# Python bytecode 2.4 (62061)
# Decompiled from: Python 2.7.14 (v2.7.14:84471935ed, Sep 16 2017, 20:19:30) [MSC v.1500 32 bit (Intel)]
# Embedded file name: otp.launcher.DownloadWatcher
from direct.task import Task
from otp.otpbase import OTPLocalizer
from direct.gui.DirectGui import *
from p... | otp/launcher/DownloadWatcher.py | 4,283 | uncompyle6 version 3.2.0 Python bytecode 2.4 (62061) Decompiled from: Python 2.7.14 (v2.7.14:84471935ed, Sep 16 2017, 20:19:30) [MSC v.1500 32 bit (Intel)] Embedded file name: otp.launcher.DownloadWatcher | 204 | en | 0.614599 |
from conans import ConanFile, CMake
class LibB(ConanFile):
name = "libB"
version = "0.0"
settings = "os", "arch", "compiler", "build_type"
options = {"shared": [True, False]}
default_options = {"shared": False}
generators = "cmake"
scm = {"type": "git",
"url": "auto",
... | conanfile.py | 788 | to avoid build info bug | 23 | en | 0.612715 |
# Copyright 2018 The Oppia Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable ... | core/domain/suggestion_registry_test.py | 141,288 | Tests for the BaseSuggestion class.
Tests for the BaseVoiceoverApplication class.
Tests for the CommunityContributionStats class.
Tests for the ExplorationVoiceoverApplication class.
Tests for the ReviewableSuggestionEmailInfo class.
Tests for the SuggestionAddQuestion class.
Tests for the SuggestionEditStateContent cl... | 1,467 | en | 0.817353 |
'''
Given a string, write a function that uses recursion to output a
list of all the possible permutations of that string.
For example, given s='abc' the function should return ['abc', 'acb', 'bac', 'bca', 'cab', 'cba']
Note: If a character is repeated, treat each occurence as distinct,
for example an input of 'xxx' ... | udemy-data-structures-and-algorithms/15-recursion/15.8_string_permutation.py | 1,127 | Given a string, write a function that uses recursion to output a
list of all the possible permutations of that string.
For example, given s='abc' the function should return ['abc', 'acb', 'bac', 'bca', 'cab', 'cba']
Note: If a character is repeated, treat each occurence as distinct,
for example an input of 'xxx' woul... | 454 | en | 0.781589 |
#!/usr/bin/env python3
# Copyright (c) 2020 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test generate RPC."""
from test_framework.test_framework import MAGATestFramework
from test_framework.util ... | test/functional/rpc_generate.py | 1,182 | Test generate RPC.
!/usr/bin/env python3 Copyright (c) 2020 The Bitcoin Core developers Distributed under the MIT software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php. | 221 | en | 0.512774 |
# Copyright 2021 Tomoki Hayashi
# Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
"""GAN-based TTS ESPnet model."""
from contextlib import contextmanager
from distutils.version import LooseVersion
from typing import Any
from typing import Dict
from typing import Optional
import torch
from typeguard import... | espnet2/gan_tts/espnet_model.py | 5,163 | GAN-based TTS ESPnet model.
Initialize ESPnetGANTTSModel module.
Calculate features and return them as a dict.
Args:
text (Tensor): Text index tensor (B, T_text).
text_lengths (Tensor): Text length tensor (B,).
speech (Tensor): Speech waveform tensor (B, T_wav).
speech_lengths (Tensor): Speech length t... | 1,595 | en | 0.553821 |
import time
import pytest
from celery.result import GroupResult
from celery.schedules import crontab
from kombu.exceptions import EncodeError
from director import build_celery_schedule
from director.exceptions import WorkflowSyntaxError
from director.models.tasks import Task
from director.models.workflows import Work... | tests/test_workflows.py | 14,451 | Canvas has been built Tasks added in DB Tasks executed in Celery DB rows status updated Canvas has been built Tasks added in DB Tasks executed in Celery DB rows status updated Canvas has been built Tasks added in DB Tasks executed in Celery DB rows status updated Canvas has been built Tasks added in DB Tasks executed i... | 665 | en | 0.958352 |
import logging
import time
from abc import abstractmethod
from enum import Enum
from typing import Dict, Callable, Any, List
from schema import Schema
import sqlalchemy
from sqlalchemy.engine import ResultProxy
from sqlalchemy.orm import Query
from sqlalchemy.schema import Table
from sqlalchemy.engine.base import Eng... | flask_app/utilities/DataInterfaces/SqlInterface.py | 6,994 | SQL methods to tack onto SQL based librarians
Function signatures for factory method
Postgres: (dialect: SqlDialects, host: str, port: int, username: str, password: str,
database_name: str, timeout: int = None)
TODO: Connection Factory 'timeout': int , SqlDialects.sqlite: SqliteConnectionOptions.factory SQLAlchemy i... | 335 | en | 0.519816 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.