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
import os import layout import callbacks # layout needs to be defined before creating callbacks import routes import appserver server = appserver.app.server if __name__ == "__main__": debug_mode = True if os.getenv("DEBUG", "false") == "true" else False if debug_mode is True: print(f"Initiating server...
src/app.py
548
layout needs to be defined before creating callbacks appserver.app.enable_dev_tools(debug=True)
95
en
0.665986
# Visualizer is for debugging purposes only import logging import math import random import threading import http.server import socketserver import os import re from shapely import wkt import matplotlib.pyplot as plt import mpld3 import screeninfo import tempfile import webbrowser import owlready2 from shapely import ...
auto/auto_visualizer/auto_visualizer.py
41,090
Describes the given traffic entity as an HTML list. :param entity: An object of an owlready2 class. :return: The HTML-representation of entity. Checks if the new rectangle (new_bb) collides with some existing rectangles. Creates an HTML visualization of the given scenario. Starts a simple web server at localhost:8000 (...
1,781
en
0.767776
# coding: utf-8 """ SendinBlue API SendinBlue provide a RESTFul API that can be used with any languages. With this API, you will be able to : - Manage your campaigns and get the statistics - Manage your contacts - Send transactional Emails and SMS - and much more... You can download our wrappers at h...
test/test_get_extended_contact_details_statistics.py
1,842
GetExtendedContactDetailsStatistics unit test stubs Test GetExtendedContactDetailsStatistics SendinBlue API SendinBlue provide a RESTFul API that can be used with any languages. With this API, you will be able to : - Manage your campaigns and get the statistics - Manage your contacts - Send transactional Emails ...
1,269
en
0.631238
# Define here the models for your spider middleware # # See documentation in: # https://docs.scrapy.org/en/latest/topics/spider-middleware.html from scrapy import signals # useful for handling different item types with a single interface from itemadapter import is_item, ItemAdapter class Proj2062SpiderMiddleware: ...
support_files/scraping/entries/proj_2062/proj_2062/middlewares.py
3,652
Define here the models for your spider middleware See documentation in: https://docs.scrapy.org/en/latest/topics/spider-middleware.html useful for handling different item types with a single interface Not all methods need to be defined. If a method is not defined, scrapy acts as if the spider middleware does not modify...
1,963
en
0.869042
import functools as ft import inspect from typing import Any, Callable, Dict, Iterable, List, Optional, Union import pydantic from . import base class PydanticValidator(base.BaseValidator): """ Parameters validator based on `pydantic <https://pydantic-docs.helpmanual.io/>`_ library. Uses python type ann...
xjsonrpc/server/validators/pydantic.py
3,352
Parameters validator based on `pydantic <https://pydantic-docs.helpmanual.io/>`_ library. Uses python type annotations for parameters validation. :param coerce: if ``True`` returns converted (coerced) parameters according to parameter type annotation otherwise returns parameters as is Builds pydantic mo...
844
en
0.466695
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. import pytest import re from urllib.parse import urljoin from requests import get from time import sleep from datetime i...
tests/webview/ui/test_content.py
36,680
This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. FIXME Requires varnish (False, '/content/col23946', 301), FIXME Requires varnish (False, '/content/col23946/1.1', 301), GIVEN s...
7,522
en
0.843556
# # Copyright 2019 Delphix # # 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, so...
sdb/commands/zfs/internal/__init__.py
2,156
return a string which is the short name of the enum value (truncating off the common prefix) Copyright 2019 Delphix 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...
674
en
0.84273
# -*- coding: utf-8 -*- # Copyright (c) 2018-2021, earthobservations developers. # Distributed under the MIT License. See LICENSE for more info. class _GetAttrMeta(type): # https://stackoverflow.com/questions/33727217/subscriptable-objects-in-class def __getitem__(cls, x): return getattr(cls, x) de...
wetterdienst/util/parameter.py
568
Getting subclasses which usually represent resolutions -*- coding: utf-8 -*- Copyright (c) 2018-2021, earthobservations developers. Distributed under the MIT License. See LICENSE for more info. https://stackoverflow.com/questions/33727217/subscriptable-objects-in-class
271
en
0.755687
import os import sys import numpy as np import random import math from PIL import Image, ImageOps, ImageFilter import torch import torch.utils.data as data import torchvision.transforms as transform from .base import BaseDataset class NYUv2Segmentation(BaseDataset): BASE_DIR = 'nyuv2' NUM_CLAS...
cvss/datasets/nyuv2.py
4,776
assert exists and prepare dataset automatically synchrosized transform general resize, normalize and toTensor random mirror random scale (short edge) pad crop random crop crop_size final transform final transform
212
en
0.660784
# This file was scaffold by idol_mar, but it will not be overwritten, so feel free to edit. # This file will be regenerated if you delete it. from ...codegen.all.target.optional_method import ( AllTargetOptionalMethodSchema as OptionalMethodSchemaCodegen, ) class OptionalMethodSchema(OptionalMethodSchemaCodegen):...
test/src/lib/idol/py_mar/all/target/optional_method.py
330
This file was scaffold by idol_mar, but it will not be overwritten, so feel free to edit. This file will be regenerated if you delete it.
137
en
0.978566
# -*- coding: utf-8 -*- import os import sqlite3 import logging logger = logging.getLogger("xtc") class sqlite_handle(object): def __init__(self): self.dbname = "Xsense.db" self.conn = None def db_init(self): # 初始化db task_info、apps、scripts、run_tasks self.db_table_all() conn...
client-autosense/sense/sqlite_syn.py
7,075
-*- coding: utf-8 -*- 初始化db task_info、apps、scripts、run_tasks logger.info(cre) 插入任务信息 for 插入脚本信息 插入任务信息 多项 保存需要运行的任务 有必要么元素为tuple,(205937, 'pyclient-test', 1, 107864, 'http://202.105.193....69910.zip', 20191006000000, 20201231235959, '000000', '235959', 2, 1, 1, 1) 获取未完成的按次任务 不含重复项 新增+启动, exeType=2按次执行 exeType=1按时执行...
851
zh
0.852034
def notas(*n, sit=False): """ Função para analisar notas e situação de varios alunos. :param n: Uma ou mais notas dos alunos (aceita varias) :param sit: Valor opcional, indicando se deve ou não adicionar a situação. :return: Dicionario com varias informações sobre a situação da turma. """ di...
Modulo-03/ex105/ex105.py
713
Função para analisar notas e situação de varios alunos. :param n: Uma ou mais notas dos alunos (aceita varias) :param sit: Valor opcional, indicando se deve ou não adicionar a situação. :return: Dicionario com varias informações sobre a situação da turma.
255
pt
0.996466
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2018, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any...
test/aqua/operators/__init__.py
508
-*- coding: utf-8 -*- This code is part of Qiskit. (C) Copyright IBM 2018, 2019. This code is licensed under the Apache License, Version 2.0. You may obtain a copy of this license in the LICENSE.txt file in the root directory of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. Any modifications or der...
482
en
0.898065
import os import csv import shutil from datetime import datetime from numpy import logspace import torch import torch.nn as nn from torch.optim.lr_scheduler import LambdaLR from torch.utils.data import DataLoader from torch.optim import Adam from dataset.e_piano import create_epiano_datasets, create_pop909_datasets ...
train.py
21,588
---------- Author: Damon Gwinn ---------- Entry point. Trains a model specified by command line arguments ---------- Baseline is an untrained epoch that we evaluate as a baseline loss and accuracy main Output prep Tensorboard Datasets 데이터셋이 바뀌기 때문에 아래와같이 해주어야함 EY critic num_prime = args.num_prime Continuing from p...
819
en
0.807554
# Copyright 2019 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
codelabs/spark-bigquery/backfill.py
4,054
Copyright 2019 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distribut...
2,349
en
0.85888
import random import unittest from domain_tree.tree import DomainTree, DomainNode, NodeNotFoundException from domain_tree.domain import RealDomain, RealInterval class TestDomainTree(unittest.TestCase): @classmethod def setUpClass(cls) -> None: pass @classmethod def tearDownClass...
test/test_tree.py
4,387
self.d0 = {"x0": (0, 1)}d = {"x0": (0, 1), "x1": (2, 3)}tree.print_tree()
73
en
0.332616
# Copyright 2014, Doug Wiegley, A10 Networks. # # 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 ...
octavia/tests/unit/common/test_config.py
1,946
Copyright 2014, Doug Wiegley, A10 Networks. 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 agree...
728
en
0.843139
import getpass, platform, sys, threading from .. util import log from . control import ExtractedControl # See https://stackoverflow.com/questions/42603000 DARWIN_ROOT_WARNING = """ In MacOS, pynput must to be running as root in order to get keystrokes. Try running your program like this: sudo %s <your commands h...
bibliopixel/control/keyboard.py
1,583
See https://stackoverflow.com/questions/42603000 join() on pynput.keyboard.Listener waits on a queue...
103
en
0.704784
# # Autogenerated by Frugal Compiler (3.4.7) # # DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING # from thrift.Thrift import TType, TMessageType, TException, TApplicationException from frugal.util import make_hashable from thrift.transport import TTransport from thrift.protocol import TBinaryProtocol...
test/expected/python.asyncio/actual_base/ttypes.py
5,575
Attributes: - things Attributes: - an_id - a_string Autogenerated by Frugal Compiler (3.4.7) DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
162
en
0.857254
import os import numpy as np import pandas as pd from sklearn.preprocessing import OneHotEncoder,LabelEncoder,StandardScaler from sklearn.decomposition import TruncatedSVD,PCA from sklearn.metrics.pairwise import cosine_similarity,pairwise_distances from sklearn.feature_extraction.text import TfidfVectorizer SEED = 204...
quora/pyfm/generate_interaction.py
1,594
, nrows=5000), nrows=5000)
26
es
0.328432
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import base64 import lzma from ... import TestUnitBase from refinery.units.formats.office.xlxtr import _ref2rc, _rc2ref class TestCellIndexConverter(TestUnitBase): def test_concistency(self): for row in range(1, 12): for col in range(1, 12): ...
test/units/formats/office/test_xlxtr.py
10,276
!/usr/bin/env python3 -*- coding: utf-8 -*-
43
fr
0.304089
from argparse import ArgumentParser from typing import Any from zerver.lib.management import ZulipBaseCommand from zerver.models import Service, UserProfile class Command(ZulipBaseCommand): help = """Given an existing bot, converts it into an outgoing webhook bot.""" def add_arguments(self, parser: Argument...
zerver/management/commands/convert_bot_to_outgoing_webhook.py
2,267
TODO: Add token and interface as arguments once OutgoingWebhookWorker uses these fields on the Service object. TODO: Normalize email?
133
en
0.603571
# -*- coding: utf-8 -*- # Copyright (C) 2014-2016 Andrey Antukh <niwi@niwi.nz> # Copyright (C) 2014-2016 Jesús Espino <jespinog@gmail.com> # Copyright (C) 2014-2016 David Barragán <bameda@dbarragan.com> # Copyright (C) 2014-2016 Alejandro Alonso <alejandro.alonso@kaleidos.net> # Copyright (C) 2014-2016 Anler Hernández ...
docker-images/taigav2/taiga-back/tests/integration/test_stats.py
7,248
-*- coding: utf-8 -*- Copyright (C) 2014-2016 Andrey Antukh <niwi@niwi.nz> Copyright (C) 2014-2016 Jesús Espino <jespinog@gmail.com> Copyright (C) 2014-2016 David Barragán <bameda@dbarragan.com> Copyright (C) 2014-2016 Alejandro Alonso <alejandro.alonso@kaleidos.net> Copyright (C) 2014-2016 Anler Hernández <hello@anler...
987
en
0.79645
import sys import compileall import importlib.util import test.test_importlib.util import os import pathlib import py_compile import shutil import struct import tempfile import time import unittest import io from unittest import mock, skipUnless try: from concurrent.futures import ProcessPoolExecut...
python/Lib/test/test_compileall.py
25,965
Test compileall's CLI. Issue 6716: compileall should escape source code when printing errors to stdout. Check that compileall recreates bytecode when the new metadata is used. Test a change in mtime leads to a new .pyc. Test a change in mtime leads to a new .pyc. Test compiling a single file, and complete directory T...
1,465
en
0.782112
# -*- coding: utf-8 -*- """ Created on Sat Jun 6 22:41:54 2020 @author: mahjaf Automatic sleep scoring implemented for Zmax headband. """ #%% Reading EDF section #####===================== Importiung libraries =========================##### import mne import numpy as np from numpy import loadtxt import h5py impor...
Zmax_autoscoring_controlled_train_test_split.py
10,657
Created on Sat Jun 6 22:41:54 2020 @author: mahjaf Automatic sleep scoring implemented for Zmax headband. -*- coding: utf-8 -*-%% Reading EDF section===================== Importiung libraries ============================================= Defining required paths r============================================ Reading...
3,025
en
0.592874
import warnings from mlprimitives.utils import import_object _RESAMPLE_AGGS = [ 'mean', 'median', 'prod', 'quantile', 'std', 'sum', 'var', ] def resample(df, rule, on=None, groupby=(), aggregation='mean', reset_index=True, time_index=None): """pd.DataFrame.resample adapt...
mlprimitives/adapters/pandas.py
3,458
Join the names of a multi-level index with an underscore. pd.DataFrame.resample adapter. Call the `df.resample` method on the given time_index and afterwards call the indicated aggregation. Optionally group the dataframe by the indicated columns before performing the resampling. If groupby option is used, the result...
1,802
en
0.7267
"""Rectify function""" import torch from torch.autograd import Function from encoding import cpu if torch.cuda.device_count() > 0: from encoding import gpu __all__ = ['rectify'] class _rectify(Function): @staticmethod def forward(ctx, y, x, kernel_size, stride, padding, dilation, average): ctx.s...
encoding/functions/rectify.py
1,377
Rectify function assuming kernel_size is 3
44
en
0.565457
from pyspark.sql import SparkSession def get_spark(): return (SparkSession.builder .appName("simpleapp") .master("local") .getOrCreate()) from pyspark import SparkConf, SparkContext import sys def main(sc, args): print("SimpleApp Arguments") for x in args: ...
src/test/resources/simpleapp.py
773
Configure Spark Execute Main functionality
42
en
0.627353
import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt from itertools import product from sklearn.preprocessing import LabelEncoder # ============================================================================= # The lines where we processed our data # ==============...
preprocessing.py
7,598
============================================================================= The lines where we processed our data ============================================================================= if subtype is nan then type 34 month ============================================================================= correlation...
405
en
0.385731
from nepc import nepc from nepc.util import util import pandas as pd import os import pytest import platform # TODO: remove dependence on csv; put function in scraper that uses built-in # readlines function import csv # TODO: test that all values in [nepc]/tests/data are in the nepc database @pytest.mark.usefix...
tests/test_mysql_build.py
4,509
check that the states table has a species_id column TODO: remove dependence on csv; put function in scraper that uses built-in readlines function TODO: test that all values in [nepc]/tests/data are in the nepc database subtract 1 to account for header assert e_energy == pytest.approx(df['e_energy'].tolist())
317
en
0.611032
#CODE1---For preparing the list of DRUG side-effect relation from SIDER database--- #Python 3.6.5 |Anaconda, Inc. import sys import glob import errno import csv path = '/home/16AT72P01/Excelra/SIDER1/output/adverse_effects.tsv' files = glob.glob(path) unique_sideeffect = set() unique_drug = set() unique_pair = set()...
src/dictionaryCode/other/siderData1.py
741
CODE1---For preparing the list of DRUG side-effect relation from SIDER database---Python 3.6.5 |Anaconda, Inc.
110
en
0.604889
""" ASGI config for apiproject project. It exposes the ASGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/3.2/howto/deployment/asgi/ """ import os from django.core.asgi import get_asgi_application os.environ.setdefault('DJANGO_SE...
apiproject/apiproject/asgi.py
397
ASGI config for apiproject project. It exposes the ASGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/3.2/howto/deployment/asgi/
216
en
0.733707
""" This module provides an interface for reading and writing to a HackPSU RaspberryPi Scanner config file Methods: getProperty(configFile, prop) Get a property from a config file by reading the config file until the desired property is found setProperty(configFile, prop, value) Set a property by updating the co...
HackPSUconfig.py
3,681
dictionary getProperties(str) This funciton reads the entire config file and builds a dictionary from the config file Args: configFile: The configuration file to read from Returns: dictionary: A list of key value pairs from the config file str getProperty(str, str) This function searches a c...
2,486
en
0.718828
from django.test import TestCase from django.contrib.auth import get_user_model from core import models def sample_user(email='rg171195@gmail.com', password='testpass'): '''Creating sample user''' return get_user_model().objects.create_user(email, password) class ModelTests(TestCase): def test_create_u...
app/core/tests/test_models.py
1,622
Creating sample user Test for creating super user Test creating a new user with an email is successful Testing weather email is in normalize form or not
152
en
0.945155
import copy import dask import dask.array as da from dask.distributed import Client import datetime import logging import math from multiprocessing.pool import ThreadPool import numpy as np from pathlib import Path from tqdm.auto import tqdm from typing import Union, TypeVar, Tuple import xarray as xr import shutil imp...
src/qa4sm_preprocessing/nc_image_reader/transpose.py
14,150
Calculates chunk sizes for the given array for the intermediate output files. Parameters ---------- array : xr.DataArray Array to rechunk and transpose chunks : dict or None Chunks passed to write_transposed_dataset, None if none were given. new_last_dim : str Name of the new last dimension, normally "time...
3,677
en
0.792345
import asyncio from pathlib import Path from secrets import token_bytes from typing import Optional import aiosqlite import pytest from clvm_tools import binutils from ceres.types.blockchain_format.coin import Coin from ceres.types.blockchain_format.program import Program, SerializedProgram from ceres.types.blockchai...
tests/pools/test_wallet_pool_store.py
4,789
Idempotent Rebuild cache, no longer present
43
en
0.67074
import time import torch import numpy as np from collections import deque from graphnas.trainer import Trainer class Evolution_Trainer(Trainer): """ This class implements the Asyncronous Aging Evolution, proposed by Real et. al. on: Regularized Evolution for Image Classifier Architecture Search ...
graphnas/evolution_trainer.py
5,889
This class implements the Asyncronous Aging Evolution, proposed by Real et. al. on: Regularized Evolution for Image Classifier Architecture Search available on: https://arxiv.org/abs/1802.01548 train from scratch to get the final score run 10 times to get Mean and Stddev Choose a random position on the individual t...
785
en
0.817421
# Generated by Django 2.1.4 on 2018-12-28 02:51 from django.conf import settings from django.db import migrations, models import django.db.models.deletion import django.utils.timezone class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUT...
mysite/blog/migrations/0001_initial.py
907
Generated by Django 2.1.4 on 2018-12-28 02:51
45
en
0.649989
# Make SweetPea visible regardless of whether it's been installed. import sys sys.path.append("..") from sweetpea.primitives import Factor, DerivedLevel, WithinTrial, Transition from sweetpea.constraints import no_more_than_k_in_a_row from sweetpea import fully_cross_block, synthesize_trials_non_uniform, print_experim...
example_programs/PadmalaPessoa2011.py
3,593
Make SweetPea visible regardless of whether it's been installed. DEFINE REWARD, RESPONSE and CONGRUENCY FACTORS DEFINE CONGRUENCY TRANSITION FACTOR DEFINE RESPONSE TRANSITION FACTOR DEFINE SEQUENCE CONSTRAINTS DEFINE EXPERIMENT SOLVE
233
en
0.822226
# coding: utf-8 import pprint import re import six class KeyStatusInfo: """ 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 j...
huaweicloud-sdk-kms/huaweicloudsdkkms/v1/model/key_status_info.py
3,578
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 KeyStatusInfo - a model defined in huaweicloud ...
1,022
en
0.500621
# -*- encoding: utf-8 -*- """ @Author : zYx.Tom @Contact : 526614962@qq.com @site : https://github.com/zhuyuanxiang/tensorflow_cookbook --------------------------- @Software : PyCharm @Project : TensorFlow_Machine_Learning_Cookbook @File : C0106_operations.py @Version : v0.1...
01_Introduction/C0106_operations.py
3,173
@Author : zYx.Tom @Contact : 526614962@qq.com @site : https://github.com/zhuyuanxiang/tensorflow_cookbook --------------------------- @Software : PyCharm @Project : TensorFlow_Machine_Learning_Cookbook @File : C0106_operations.py @Version : v0.1 @Time : 2019-10-29 14:11 ...
1,235
zh
0.415768
import numpy # FIXME: copy the functions here from sklearn.mixture.gmm import log_multivariate_normal_density, logsumexp def sample_gaussian2(means, cv, size, random_state, mins, maxes): def once(size1): g = random_state.multivariate_normal(means, cv, size1).T g = g.reshape(len(means), -1) ...
bananas/model.py
5,790
Generate random samples from the model. Returns ------- X : array_like, shape (n_samples, n_features) List of samples FIXME: copy the functions here decide which component to use for each sample for each component, generate all needed samples occurrences of current component in X number of those occurrences FIXME...
506
en
0.810332
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import wagtail.wagtailcore.fields import modelcluster.fields class Migration(migrations.Migration): dependencies = [ ('wagtailcore', '0020_add_index_on_page_first_published_at'), ('tests', '0...
wagtail/tests/testapp/migrations/0014_m2m_blog_page.py
2,284
-*- coding: utf-8 -*-
21
en
0.767281
#!/usr/bin/env python # -*- coding: utf-8 -*- import pytest from pytest import raises, approx def test(): import pytq_crawlib pass if __name__ == "__main__": import os basename = os.path.basename(__file__) pytest.main([basename, "-s", "--tb=native"])
tests/test_import.py
277
!/usr/bin/env python -*- coding: utf-8 -*-
42
en
0.34282
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import (print_function, unicode_literals, absolute_import, with_statement) import os import sys if __name__ == '__main__': if __package__ is None: dir_name = os.path.dirname(__file__) sys.path.append( ...
excel2mysql/__main__.py
448
!/usr/bin/env python -*- coding: utf-8 -*-
42
en
0.34282
import biathlonresults as api def test_cups(): res = api.cups(1819) assert isinstance(res, list) assert len(res) == 37 def test_cup_results(): res = api.cup_results("BT1819SWRLCP__SMTS") assert isinstance(res, dict) assert isinstance(res["Rows"], list) assert res["Rows"][0]["Name"] == "B...
tests/test_api.py
2,006
Raphael Poiree Pokljuka 1819 Pokljuka 1819 W PU podiums men stat in case someone breaks Bjoerndalen's record
108
en
0.451887
# Copyright (c) Max-Planck-Institut für Eisenforschung GmbH - Computational Materials Design (CM) Department # Distributed under the terms of "New BSD License", see the LICENSE file. """ Run a job from hdf5. """ from pyiron.base.job.wrapper import job_wrapper_function def register(parser): parser.add_argument( ...
pyiron/cli/wrapper.py
1,139
Run a job from hdf5. Copyright (c) Max-Planck-Institut für Eisenforschung GmbH - Computational Materials Design (CM) Department Distributed under the terms of "New BSD License", see the LICENSE file. TODO: what's that mean?
225
en
0.729952
import numpy as np import wmf import batched_inv import batched_inv_mp import solve_mp import solve_gpu np.random.seed(123) B = np.load("test_matrix.pkl") S = wmf.log_surplus_confidence_matrix(B, alpha=2.0, epsilon=1e-6) num_factors = 40 + 1 num_iterations = 1 batch_size = 1000 solve = batched_inv.solve_sequentia...
test_batched_inv_mp.py
633
solve = solve_mp.solve_mp solve = solve_gpu.solve_gpu
53
en
0.851619
""" ASGI config for cryptocurrency project. It exposes the ASGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/3.0/howto/deployment/asgi/ """ import os from django.core.asgi import get_asgi_application os.environ.setdefault('DJANG...
cryptocurrency/asgi.py
405
ASGI config for cryptocurrency project. It exposes the ASGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/3.0/howto/deployment/asgi/
220
en
0.761994
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
topi/python/topi/cuda/conv2d_nhwc_tensorcore.py
12,782
Compute conv2d with tensorcore for NCHW layout Compute declaration for tensorcore TOPI schedule callback Schedule tensorcore template Tensorcore template for cuda backend Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work ...
1,455
en
0.804194
# Generated by Django 2.1.5 on 2019-05-03 15:45 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('blog', '0035_post_video'), ] operations = [ migrations.AlterField( model_name='post', name='video', fiel...
blog/migrations/0036_auto_20190503_1645.py
402
Generated by Django 2.1.5 on 2019-05-03 15:45
45
en
0.441726
import asyncio import os import warnings from datetime import date from secedgar.cik_lookup import CIKLookup from secedgar.client import NetworkClient from secedgar.core._base import AbstractFiling from secedgar.core.filing_types import FilingType from secedgar.exceptions import FilingTypeError from secedgar.utils imp...
secedgar/core/company.py
8,908
Base class for receiving EDGAR filings. Args: cik_lookup (str): Central Index Key (CIK) for company of interest. filing_type (Union[secedgar.core.filing_types.FilingType, None]): Valid filing type enum. Defaults to None. If None, then all filing types for CIKs will be returned. start_date (Union[st...
3,256
en
0.737018
from __future__ import absolute_import, division, unicode_literals import socket from .base import StatsClientBase, PipelineBase class Pipeline(PipelineBase): def __init__(self, client): super(Pipeline, self).__init__(client) self._maxudpsize = client._maxudpsize def _send(self): d...
statsd/client/udp.py
1,531
A client for statsd. Create a new client. Send data to statsd. Use popleft to preserve the order of the stats. No time for love, Dr. Jones!
141
en
0.676127
"""grpc service. Reliably launch and connect to grpc process. """ import datetime import enum import logging import os import subprocess import sys import tempfile import time from typing import Any, Dict, Optional from typing import TYPE_CHECKING import grpc from wandb.proto import wandb_server_pb2 as spb from wand...
wandb/sdk/service/service.py
4,847
Launch grpc server and return port. grpc service. Reliably launch and connect to grpc process. process finished References for starting processes - https://github.com/wandb/client/blob/archive/old-cli/wandb/__init__.py - https://stackoverflow.com/questions/1196074/how-to-start-a-background-process-in-python Add cove...
375
en
0.776191
import numpy as np from sklearn.metrics import r2_score np.random.seed(42) import matplotlib.pyplot as plt import seaborn as sns import pandas as pd figsize = (8, 4) def show_r2(results): data_size = results["data_size"] test_scores = results["test_scores"] test_scores_exp = results["test_scores_exp"] ...
generator_labeler/paper_results/custom_plots.py
14,825
print(i, " -> min_local_u", min_local_u)print(r)min_cost_id = np.argwhere(IQRs_RMSE == min_cost)ax.plot(np.arange(len(y_pred)), (y_pred_lower[p]+y_pred_upper[p])/2, marker=".", linewidth=0, label="smooth", color="green") ax.ticklabel_format(axis='y', style='sci', scilimits=(0, 3))ax.set_yscale("log")ax.set_ylim((0, 1))...
757
en
0.437238
### # Copyright (c) 2004, Daniel DiPaolo # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, # this list of condition...
plugins/QuoteGrabs/__init__.py
2,652
Quotegrabs are like IRC sound bites. When someone says something funny, incriminating, stupid, outrageous, ... anything that might be worth remembering, you can grab that quote for that person. With this plugin, you can store many quotes per person and display their most recent quote, as well as see who "grabbed" the...
2,255
en
0.899325
#!/usr/bin/python # configure mini-split heat pumps for E files # uses NRCan CSV list converted to TSV # https://oee.nrcan.gc.ca/pml-lmp/index.cfm?language_langue=en&action=app.search-recherche&appliance=ASHP2_GH import math, os, sys import xml.etree.ElementTree as ET if len(sys.argv) < 3: print(sys.argv[0], "E-f...
ghwiz/mshp.py
2,747
!/usr/bin/python configure mini-split heat pumps for E files uses NRCan CSV list converted to TSV https://oee.nrcan.gc.ca/pml-lmp/index.cfm?language_langue=en&action=app.search-recherche&appliance=ASHP2_GH tsv field list: Brand Outside model Inside model Furnace model HSPF (Region IV) Rated heating capacity (Btu/hour)...
1,072
en
0.697795
from __future__ import absolute_import, unicode_literals from django.contrib.auth import authenticate from django.contrib.auth.models import User from django.core.urlresolvers import reverse from tracpro.test.cases import TracProDataTest class ManageUserCreateTest(TracProDataTest): def test_create_as_non_superu...
tracpro/profiles/tests/test_views.py
16,564
Non-superuser cannot use this view Not a superuser Post something that would be an error (empty form) and would be a 200 status if we had access. We get redirected to login An error case submit with no fields entered FIXME: this error makes no sense in this context create non-superuser create superuser Non-superuser ca...
1,883
en
0.923321
# Copyright 2016 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...
tensorflow/contrib/learn/python/learn/monitors.py
44,353
Base class for Monitors. Defines basic interfaces of Monitors. Monitors can either be run on all workers or, more commonly, restricted to run exclusively on the elected chief worker. Captures a variable's values into a collection. This monitor is useful for unit testing. You should exercise caution when using this mo...
18,022
en
0.797643
''' Image ===== The :class:`Image` widget is used to display an image:: Example in python:: wimg = Image(source='mylogo.png') Kv Example:: Image: source: 'mylogo.png' size: self.texture_size Asynchronous Loading -------------------- To load an image asynchronously (for example from an ex...
kivy/uix/image.py
13,148
Asynchronous Image class. See the module documentation for more information. .. note:: The AsyncImage is a specialized form of the Image class. You may want to refer to the :mod:`~kivy.loader` documentation and in particular, the :class:`~kivy.loader.ProxyImage` for more detail on how to handle events...
2,540
en
0.783445
#!/usr/bin/env python # # Copyright 2016 Google Inc. 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 requir...
examples/ad_manager/v201811/activity_service/get_all_activities.py
1,771
!/usr/bin/env python Copyright 2016 Google Inc. 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 law ...
894
en
0.869554
#!/usr/bin/env python from __future__ import print_function import sys from Configuration.PyReleaseValidation.MatrixReader import MatrixReader from Configuration.PyReleaseValidation.MatrixRunner import MatrixRunner from Configuration.PyReleaseValidation.MatrixInjector import MatrixInjector,performInjectionOptionTest ...
Configuration/PyReleaseValidation/scripts/runTheMatrix.py
14,528
!/usr/bin/env python ================================================================================ ================================================================================ test for wrong input workflows ================================================================================this can get out of hereFa...
997
en
0.36078
import re import torch import torch.nn as nn import torch.nn.functional as F from models.networks.sync_batchnorm import SynchronizedBatchNorm2d import torch.nn.utils.spectral_norm as spectral_norm # Returns a function that creates a normalization function # that does not condition on semantic map def get_nonspade_norm...
baselines/scripts/segvae/models/networks/normalization.py
3,467
Returns a function that creates a normalization function that does not condition on semantic map helper function to get output channels of the previous layer this function will be returned remove bias in the previous layer, which is meaningless since it has no effect after normalization The dimension of the intermedia...
492
en
0.825035
import io import copy import uuid import numpy as np try: # pip install pycollada import collada except BaseException: collada = None try: import PIL.Image except ImportError: pass from .. import util from .. import visual from ..constants import log def load_collada(file_obj, resolver=None, ...
trimesh/exchange/dae.py
13,247
Load a texture from a file into a PIL image. Turn a COLLADA effect into a trimesh material. Recursively parse COLLADA scene nodes. Turn a trimesh material into a COLLADA material. Export a mesh or a list of meshes as a COLLADA .dae file. Parameters ----------- mesh: Trimesh object or list of Trimesh objects The me...
1,977
en
0.541639
#!/usr/bin/env python """ Copyright (c) 2006-2019 sqlmap developers (http://sqlmap.org/) See the file 'LICENSE' for copying permission """ import string from lib.core.enums import PRIORITY __priority__ = PRIORITY.NORMAL def tamper(payload, **kwargs): """ Unicode-escapes non-encoded characters in a given pa...
Toolz/sqlmap/tamper/charunicodeescape.py
1,214
Unicode-escapes non-encoded characters in a given payload (not processing already encoded) (e.g. SELECT -> SELECT) Notes: * Useful to bypass weak filtering and/or WAFs in JSON contexes >>> tamper('SELECT FIELD FROM TABLE') '\\u0053\\u0045\\u004C\\u0045\\u0043\\u0054\\u0020\\u0046\\u0049\\u0045\\u004C\\u0044\\u002...
523
en
0.490526
# Copyright 2018 ZTE 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 ...
catalog/packages/serializers/vnf_pkg_software_image_info.py
3,191
Copyright 2018 ZTE 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, software ...
557
en
0.868543
#!/usr/bin/env python import numpy as np import socket, curses, json, traceback, math, argparse, math, sys, os, stat from operator import itemgetter, attrgetter from configutils.dfmux_config_constructor import get_physical_id, sq_phys_id_to_info from configutils.dfmux_config_constructor import uniquifyList, generate_d...
bin/kookaburra.py
24,872
Splits the string into a list where the numbers and the characters between numbers are each element Copied from spt3g_software to fix dependencies (sorry) Compares two strings where numbers are sorted according to value, so Sq12 ends up after Sq8, use in sorted function Copied from spt3g_software to fix dependencies (...
927
en
0.746892
import os from spirl.models.closed_loop_spirl_mdl import GoalClSPiRLMdl from spirl.components.logger import Logger from spirl.utils.general_utils import AttrDict from spirl.configs.default_data_configs.kitchen import data_spec from spirl.components.evaluator import TopOfNSequenceEvaluator from spirl.data.kitchen.src.k...
spirl/configs/few_shot_imitation_learning/kitchen/hierarchical_cl_gc_top_bot_excluded_demo_topknob_bot_hinge_slide_oneshot/conf.py
1,945
Dataset flat last action from seq gets cropped
46
en
0.695533
""" Script for copying back xml junit files from tests """ import argparse # pylint: disable=minimum-python-version import os import subprocess import paramiko import salt.utils.yaml class DownloadArtifacts: def __init__(self, instance, artifacts): self.instance = instance self.artifacts = arti...
tests/support/copyartifacts.py
2,940
Make sure all xml files are readable by the world so that anyone can grab them Script for copying back xml junit files from tests pylint: disable=minimum-python-version pylint: disable=minimum-python-version pylint: enable=minimum-python-version
247
en
0.663011
#!/usr/bin/env python """pattern.py: An example like <Rolling an image> in Pillow document. """ import os.path from PIL import Image def run(filepath): """Create a wallpaper image from a PNG file.""" src = Image.open(filepath) target = swap_quadrants(src) paste_with_alpha(target, src, (0, 0), 0x10) ...
source/_sample/pillow/pattern.py
1,534
An alpha_composite-like operation. Quarter the bounding box of an image. Create a wallpaper image from a PNG file. Quarter the image and swap two diagonal quadrant pairs. pattern.py: An example like <Rolling an image> in Pillow document. !/usr/bin/env python Z
261
en
0.686324
from rest_framework.permissions import BasePermission, SAFE_METHODS class IsOwnerOrReadOnly(BasePermission): message = 'You must be the owner of this object.' def has_object_permission(self, request, view, obj): # member = Membership.objects.get(user=user.request) # member.is_active if...
Book/api/permissions.py
416
member = Membership.objects.get(user=user.request) member.is_active
67
en
0.803435
"""View representations of Product Active docs pages""" from widgetastic_patternfly4 import PatternflyTable from widgetastic.widget import View, Text from testsuite.ui.views.admin.product import BaseProductView from testsuite.ui.widgets.buttons import ThreescaleDeleteButton, ThreescaleEditButton from testsuite.ui.widg...
testsuite/ui/views/admin/product/active_docs.py
3,008
View representation of Active Docs Detail page View representation of Active Docs list page OAS version 2 section OAS version 3 section Navigate to active doc detail/preview page Make request on preview page :param endpoint: string of endpoint which should be tried :return: Make request on preview page :param path stri...
530
en
0.656706
import os import json import logging import serial from serial.tools import list_ports import time CONFIG_FILENAME_DEFAULT = 'olfa_config.json' def get_olfa_config(config_filename=''): """ Find and parse olfactometer configuration JSON. :param config_filename: string with path to configuration. :re...
olfactometry/utils.py
3,766
Return Serial object after making sure that the port is accessible and that the port is expressed as a string. :param port: str or int (ie "COM4" or 4 for Windows). :param baudrate: baudrate. :param timeout: read timeout in seconds, default 1 sec. :param writeTimeout: write timeout in seconds, default 1 sec. :return: ...
1,445
en
0.750846
# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use ...
aria/parser/__init__.py
1,084
Parser package. Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may ...
770
en
0.876814
#!/usr/bin/env python ''' Created on Apr 12, 2017 @author: Brian Jimenez-Garcia @contact: brian.jimenez@bsc.es ''' import sys import os if len(sys.argv[1:]) != 2: raise SystemExit("usage: %s pdb_file1 pdb_file2" % os.path.basename(sys.argv[0])) pdb_file1 = sys.argv[1] pdb_file2 = sys.argv[2] # Panda3D imports...
launch.py
1,183
Created on Apr 12, 2017 @author: Brian Jimenez-Garcia @contact: brian.jimenez@bsc.es !/usr/bin/env python Panda3D imports Change window properties Set up a loading screen Render three frames to avoid black screen Load the game Hide loading
241
en
0.599197
# (c) Copyright [2018-2021] Micro Focus or one of its affiliates. # 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 applicabl...
verticapy/learn/tsa.py
69,298
--------------------------------------------------------------------------- [Beta Version] Creates an SARIMAX object using the Vertica Linear Regression algorithm on the data. Parameters ---------- name: str Name of the the model. The model will be stored in the DB. cursor: DBcursor, optional Vertica database...
10,095
en
0.523928
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Feb 14 08:23:08 2017 Author: Zachary W. Mikus """ #These are testing variables d1 = {1:30, 2:20, 3:30, 5:80} d2 = {1:40, 2:50, 3:60, 4:70} def f(x, y): k = x + y return k def commonKeys(longerList, shorterList): commonKeyList = [] #Va...
dict_interdiff.py
3,543
Created on Tue Feb 14 08:23:08 2017 Author: Zachary W. Mikus !/usr/bin/env python3 -*- coding: utf-8 -*-These are testing variablesVariablesintersectDictionary = The final returned intersect dictionarycommonKeyList = The list of keys that appear in both dictionariesThis function uses similar logic to the commonKeys fu...
1,222
en
0.773525
# Generated by Django 4.0 on 2021-10-12 22:38 import blog.models from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('auth', '0012_alter_user_first_name_max_length'), ] operations = [ migr...
farmblr/blog/migrations/0001_initial.py
1,368
Generated by Django 4.0 on 2021-10-12 22:38
43
en
0.796131
import urllib.parse from datetime import datetime from unittest.mock import patch from django.contrib.auth.models import User from django.test import TestCase from django.utils import timezone from dfirtrack_artifacts.models import ( Artifact, Artifactpriority, Artifactstatus, Artifacttype, ) from dfi...
dfirtrack_config/tests/status/test_status_views.py
12,598
status view tests test status view test status view test status view test status view test status view test status view test status view test status view test status view test status view test status view test status view create user create object create object create object create object create object c...
1,407
en
0.49602
import sys import getopt import os import subprocess import shutil import logging as log def Initialize(platform): print "Initializing Workspace" global workspace workspace = os.environ['WORKSPACE'] if platform == "windows": # Jenkins puts quotes in the path, which is wrong. Remove quotes. ...
src/pal/automation/util.py
2,814
Jenkins puts quotes in the path, which is wrong. Remove quotes. must specify target, project and arch
101
en
0.856487
import robocup import constants import main import math import skills.touch_ball import skills._kick import skills.pass_receive ## AngleReceive accepts a receive_point as a parameter and gets setup there to catch the ball # It transitions to the 'aligned' state once it's there within its error thresholds and is stead...
soccer/gameplay/skills/angle_receive.py
6,233
AngleReceive accepts a receive_point as a parameter and gets setup there to catch the ball It transitions to the 'aligned' state once it's there within its error thresholds and is steady Set its 'ball_kicked' property to True to tell it to dynamically update its position based on where the ball is moving and attempt to...
2,115
en
0.894094
from big_ol_pile_of_manim_imports import * import os import pyclbr class Shapes(Scene): #A few simple shapes #Python 2.7 version runs in Python 3.7 without changes def construct(self): #circle = Circle() #square = Square() line=Line(UP,DOWN) #line2=Line #triangle=P...
examples/tutorial.py
24,971
A few simple shapesPython 2.7 version runs in Python 3.7 without changescircle = Circle()square = Square()line2=Linetriangle=Polygon(np.array([0,0,0]),np.array([1,1,0]),np.array([1,-1,0]))self.play(ShowCreation(circle))self.play(FadeOut(circle))self.play(GrowFromCenter(square))self.play(Transform(square,triangle))A few...
2,025
en
0.760929
#!/usr/bin/env python # Copyright (c) 2014 Wladimir J. van der Laan # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. ''' Run this script from the root of the repository to update all translations from transifex. It will do the follo...
contrib/devtools/update-translations.py
8,149
Find all format specifiers in a string. Remove invalid characters from translation string Sanitize string for printing Split format specifiers between numeric (Qt) and others (strprintf) Run this script from the root of the repository to update all translations from transifex. It will do the following automatically: -...
2,468
en
0.750959
# Copyright 2020 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/wipeout_service_test.py
182,295
Provides testing of the deletion part of wipeout service. Provides testing of the deletion part of wipeout service. Provides testing of the deletion part of wipeout service. Provides testing of the deletion part of wipeout service. Provides testing of the deletion part of wipeout service. Provides testing of the deleti...
5,756
en
0.948945
from unittest.mock import call, PropertyMock, MagicMock import pytest from analytical_validation.exceptions import DataWasNotFitted from src.analytical_validation.validators.linearity_validator import LinearityValidator @pytest.fixture(scope='function') def fitted_result_obj(mocker): mock = mocker.Mock(create=T...
tests/unit/test_validators/test_linearity_validator.py
19,599
Given data When residual_autocorrelation is called Then must create durbin_watson_value Given data, When check_residual is called after fitting the model Should pass creating 0 < durbin_watson_value < 4 Given data, if no regression was calculated Should raise an exception Given analytical data The LinearityValidator Sh...
1,779
en
0.625069
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
superset/dashboards/commands/importers/v0.py
13,991
Import dashboard in JSON format. This is the original unversioned format used to export and import dashboards in Superset. Updates slice_ids in the position json. Sample position_json data: { "DASHBOARD_VERSION_KEY": "v2", "DASHBOARD_ROOT_ID": { "type": "DASHBOARD_ROOT_TYPE", "id": "DASHBOARD_...
3,443
en
0.766774
from datetime import datetime from django.conf import settings from django.contrib.auth import authenticate from django.contrib.auth.backends import RemoteUserBackend from django.contrib.auth.middleware import RemoteUserMiddleware from django.contrib.auth.models import User from django.contrib.auth.tests.utils import ...
django/contrib/auth/tests/test_remote_user.py
9,572
Middleware that overrides custom HTTP auth user header. Tests a custom RemoteUserMiddleware subclass with custom HTTP auth user header. Backend that overrides RemoteUserBackend methods. Tests a custom RemoteUserBackend subclass that overrides the clean_username and configure_user methods. Backend that doesn't create un...
2,198
en
0.874221
import pandas as pd import numpy as np from torch.utils.data import Dataset import os from PIL import Image class CXRDataset(Dataset): def __init__( self, path_to_images, fold, transform=None, sample=0, finding="any",): self.transfo...
nih/loader.py
2,449
can limit to sample, useful for testing if fold == "train" or fold =="val": sample=500 can filter for positive findings of the kind described; useful for evaluation can leave zero if zero, else make one
202
en
0.831188
from job import * class NoncookingJob(Job): def __init__(self, name, prefs, maxMatches): Job.__init__(self, name, prefs, maxMatches) # remove pairs & underclassmen self.prefs = filter(lambda x: x.numPeople != 1 and x.semsCooked < 4, self.prefs) # sort all the people by number of semesters cooked, high to low...
noncookingjob.py
376
remove pairs & underclassmen sort all the people by number of semesters cooked, high to low
91
en
0.81482
import math import pandas as pd import spacy # Requires: python -m spacy download en_core_web_sm from spacy import displacy from nltk import sent_tokenize, word_tokenize, PorterStemmer from nltk.corpus import stopwords from data import load_model import streamlit as st class tf_idf(): nlp = load_model('en_cor...
TextSummarization/TF_IDF.py
5,677
Create sentence word frequency table {s1:{w1:f1, ..., wN:fN}, ..., sN:{w1:f1, ..., wN:fN} }. :rtype: dict Create document word frequency table {w1:f1, ..., wN:fN}. Remove stop words, punct, etc. and lowercase :rtype: dict Requires: python -m spacy download en_core_web_sm here, keys are the same in both the table Scor...
917
en
0.549476
""" ======================================================== Statistic the SV Stat after AGE Process ======================================================== Author: Shujia Huang & Siyang Liu Date : 2014-03-07 0idx:54:15 """ import sys import re import os import string import numpy as np import matplotlib.pyplot as pl...
src/AsmvarVarScore/FeatureToScore2.py
12,476
plt.title(title[i], fontsize=16) Negative Positive Positive->Negative bad goodfig.savefig(figureFile + '.pdf') Negative Positive Positive->Negative bad goodfig.savefig(figureFile + '.pdf') VCF formatif re.search(r'^PASS', col[6]): continueif not re.search(r'_TRAIN_SITE', col[7]): continueif not re.search(r'^PASS', col[...
505
en
0.421564
# coding: utf-8 # Copyright (c) 2016, 2022, Oracle and/or its affiliates. All rights reserved. # This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may c...
src/oci/management_agent/models/work_submission_key.py
2,219
Work Submission Identifier Initializes a new WorkSubmissionKey object with values from keyword arguments. The following keyword arguments are supported (corresponding to the getters/setters of this class): :param work_submission_key: The value to assign to the work_submission_key property of this WorkSubmissionKey...
1,048
en
0.785599
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright (c) 2011 X.commerce, a business unit of eBay Inc. # Copyright 2011 OpenStack LLC. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # ...
debian/python-nova/usr/lib/python2.7/dist-packages/nova/tests/api/openstack/compute/test_extensions.py
90
Provides access to Tweedle Beetles vim: tabstop=4 shiftwidth=4 softtabstop=4 Copyright (c) 2011 X.commerce, a business unit of eBay Inc. Copyright 2011 OpenStack LLC. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the Lice...
1,319
en
0.887135
#!/usr/bin/env python # # Author: Qiming Sun <osirpt.sun@gmail.com> # from pyscf import gto from pyscf import scf from pyscf import mcscf from pyscf.dmrgscf import dmrgci ''' Block code for active space N-particle density matrices. ''' b = 1.2 mol = gto.M( verbose = 4, atom = 'N 0 0 0; N 0 0 %f'%b, basis...
examples/dmrg/03-density_matrix.py
808
!/usr/bin/env python Author: Qiming Sun <osirpt.sun@gmail.com> or computing DMs all together in one DMRG call
109
en
0.471611
import os import re import shutil import sys import urllib.error import urllib.parse import urllib.request from zipfile import ZipFile import helpers.config as config from helpers.logger import Logger class Updater: __instance = None @staticmethod def Get(): if Updater.__instance is None: ...
frontend/update.py
8,093
Unable to connect to the internet Zip is downloaded, now extract Files Old version is deleted Sucessful return: bool Unsuccessful: list[message: str, continue: bool] When working on project and updating locally Sucessful return: list[InstalledVersion: str, CheckedVersion: str] Unsucessful: list[message: str, continue: ...
740
en
0.862953
# -*- coding:utf-8 -*- # # Author : TangHanYi # E-mail : thydeyx@163.com # Create Date : 2016-12-11 09:33:17 AM # Last modified : 2016-12-11 10:48:50 AM # File Name : Super_Pow.py # Desc : class Solution(object): def superPow(self, a, b): if len(b) == 0: return a tmp = a ret = 1...
Super_Pow.py
2,705
-*- coding:utf-8 -*- Author : TangHanYi E-mail : thydeyx@163.com Create Date : 2016-12-11 09:33:17 AM Last modified : 2016-12-11 10:48:50 AM File Name : Super_Pow.py Desc :
201
en
0.302557
""" Création des images pour la tâche de détermination numérique (pour évaluer l'impact de la configuration sur le subitizing) Victor ANTOINE - victor.antoine@ens.fr """ import pygame from random import sample from numpy import random, sort from os import path from itertools import product W, H = 960, 540 pygame...
create_pictures.py
2,966
Création des images pour la tâche de détermination numérique (pour évaluer l'impact de la configuration sur le subitizing) Victor ANTOINE - victor.antoine@ens.fr création des images en disposition aléatoirecréation des images en dispostion configurationnelle
260
fr
0.970843
#!/usr/bin/env python # # Electrum - lightweight Bitcoin client # Copyright (C) 2014 Thomas Voegtlin # # 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...
plugins/cosigner_pool/qt.py
7,739
!/usr/bin/env python Electrum - lightweight Bitcoin client Copyright (C) 2014 Thomas Voegtlin 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 r...
1,136
en
0.860996
"""mgear.core.vector test""" def test_get_distance(run_with_maya_pymel, setup_path): # Maya imports from maya import OpenMaya import pymel.core as pm # mGear imports from mgear.core.vector import get_distance v_1 = [0, 0, 0] v_2 = [1, 0, 0] assert get_distance(v_1, v_2) == 1.0 v_...
tests/test_mgear/test_core/test_vector.py
3,039
mgear.core.vector test Maya imports mGear imports Maya imports mGear imports Maya imports mGear imports Maya imports mGear imports
132
en
0.365017
from sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay from sklearn.metrics import accuracy_score from sklearn.model_selection import TimeSeriesSplit from keras.layers import Dropout from keras.layers import Dense, LSTM from keras.models import Sequential import numpy as np from sklearn.preprocessing impo...
app/src/main/python/KinoCode.py
33,041
pandasのインポート データの読み込みdf = pd.read_csv('finance_dataset.csv') データフレームの表示df '6976'67582021年から今日までの1年間のデータを取得しましょう。期日を決めて行きます。 (2021, 1, 1) 教師データ(今までのデータ)start_train = datetime.date(2022, 1, 1) 教師データ(今までのデータ)dowstart_train = datetime.date(2022, 1, 5)start_train + relativedelta(days=+3) 昨日分(today-1日)まで取得できる(当日分は変動しているた...
4,181
ja
0.99513