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
""" Copyright 2019 by Adam Lewicki This file is part of the Game Theory library, and is released under the "MIT License Agreement". Please see the LICENSE file that should have been included as part of this package. """ import json # ====================================================================================...
gametree_lite.py
10,501
GameTree class used to represent game tree: Attributes ---------- nodes : dict dictionary of nodes; groups : dict dictionary of groups leafs : list list of leafs, calculated on demand players_list: list list of players names, indicating which game income from list is connected to which player return tr...
3,611
en
0.753896
# 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 # distributed under the Li...
tests/unit/malware/checks/setup_patterns/test_check.py
33,263
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 distributed under the License is distrib...
705
en
0.828017
# Copyright 2013-2022 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.package import * class RNanotime(RPackage): """Nanosecond-Resolution Time Support for R. Full 64-bit...
var/spack/repos/builtin/packages/r-nanotime/package.py
1,557
Nanosecond-Resolution Time Support for R. Full 64-bit resolution date and time functionality with; nanosecond granularity is provided, with easy transition to and from; the standard 'POSIXct' type. Three additional classes offer interval,; period and duration functionality for nanosecond-resolution timestamps. Copyr...
503
en
0.812746
#!/usr/bin/env python """This is the GRR frontend HTTP Server.""" import BaseHTTPServer import cgi import cStringIO from multiprocessing import freeze_support from multiprocessing import Process import pdb import socket import SocketServer import threading import ipaddr import logging # pylint: disable=unused-i...
tools/http_server.py
7,731
!/usr/bin/env python pylint: disable=unused-import,g-bad-import-order pylint: enable=g-bad-import-order pylint: disable=g-bad-name During our tests we have encountered some issue with the socket library that would stall for a long time when calling socket.recv(n) with a large n. rfile.read() passes the length down to s...
860
en
0.900069
import re from typing import Set, Any, List from sequal.amino_acid import AminoAcid from sequal.modification import Modification, ModificationMap from copy import deepcopy import itertools from json import dumps mod_pattern = re.compile(r"[\(|\[]+([^\)]+)[\)|\]]+") mod_enclosure_start = {"(", "[", "{"} mod_enclosure_e...
sequal/sequence.py
13,992
:param mod_position Indicate the position of the modifications relative to the base block it is supposed to modify :type mod_position: str :param mods Dictionary whose keys are the positions within the sequence and values are array of modifications at those positions :type mods: dict :param encoder Class for encoding o...
2,576
en
0.721979
# -*- coding: utf-8 -*- """ Created on Tue Dec 5 17:37:31 2017 @author: Flame """ from TuringMachine import Rule, Q, Move, TuringMachine, Tape from TuringMachine import EMTY_SYMBOL as empty def check(input_str): rules= \ [ Rule(Q(1),'1',Q(1),'1', Move.Right),# приводим к первоначальному виду ...
main.py
1,808
Created on Tue Dec 5 17:37:31 2017 @author: Flame -*- coding: utf-8 -*- приводим к первоначальному виду операции со строкамивстретили единичку, значит вычитаем еёвстретили нолик, значит добавляем единичку и идём вычитать единичку у след порядка идём вправо, чтобы найти разделитель идём вправо, чтобы найти единичку ...
371
ru
0.986119
# 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-keyvault/azure/keyvault/v2016_10_01/models/secret_bundle.py
2,384
A secret consisting of a value, id and its attributes. Variables are only populated by the server, and will be ignored when sending a request. :param value: The secret value. :type value: str :param id: The secret id. :type id: str :param content_type: The content type of the secret. :type content_type: str :param at...
1,306
en
0.612623
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import os import traceback from flask import current_app, render_template from flask import make_response from flask.json import jsonify from ooniapi.auth import auth_b...
newapi/ooniapi/views.py
3,254
Log a traceback and return code 500 with a simple JSON The CORS header is set as usual. Without this, an error could lead to browsers caching a response without the correct CORS header. def render_problem_exception(exception): response = exception.to_problem() return FlaskApi.get_response(response) def render_ge...
1,334
en
0.401046
import os import sys import subprocess CondylesFeaturesExtractor = "/Users/prisgdd/Documents/Projects/CNN/CondylesFeaturesExtractor-build/src/bin/condylesfeaturesextractor" parser = argparse.ArgumentParser() parser.add_argument('-meshDir', action='store', dest='meshDir', help='Input file to classify', ...
src/runCondylesFeaturesExtractor.py
1,576
Verify directory integrity
26
en
0.44122
import torch import torch.nn as nn from .mol_tree import Vocab, MolTree from .nnutils import create_var from .jtnn_enc import JTNNEncoder from .jtnn_dec import JTNNDecoder from .mpn import MPN, mol2graph from .jtmpn import JTMPN from .chemutils import enum_assemble, set_atommap, copy_edit_mol, attach_mols, atom_equal,...
jtnn/jtnn_vae.py
14,096
node.wid = vocab.get_index(node.smiles)root_batch = [mol_tree.nodes[0] for mol_tree in mol_batch]tree_mess,tree_vec = self.jtnn(root_batch)return tree_mess, tree_vec, mol_vec_, tree_vec, mol_vec = self.encode(mol_batch)tree_mean = self.T_mean(tree_vec)return torch.cat([tree_mean,mol_mean], dim=1)Following Mueller et al...
685
en
0.585031
# This code is heavily inspired from https://github.com/fangwei123456/PixelUnshuffle-pytorch import torch import torch.nn as nn import torch.nn.functional as F def pixel_unshuffle(input, downscale_factor): ''' input: batchSize * c * k*w * k*h downscale_factor: k batchSize * c * k*w * k*h -> batchSize ...
src/model/PixelUnShuffle.py
1,197
input: batchSize * c * k*w * k*h downscale_factor: k batchSize * c * k*w * k*h -> batchSize * k*k*c * w * h input: batchSize * c * k*w * k*h downscale_factor: k batchSize * c * k*w * k*h -> batchSize * k*k*c * w * h This code is heavily inspired from https://github.com/fangwei123456/PixelUnshuffle-pytorch
308
en
0.502909
import itertools import logging import os.path as osp import tempfile import mmcv import numpy as np from mmcv.utils import print_log from pycocotools.coco import COCO from pycocotools.cocoeval import COCOeval from terminaltables import AsciiTable from mmdet.core import eval_recalls from .builder import DATASETS from...
mmdet/datasets/coco_car.py
21,440
Convert detection results to COCO json style. Filter images too small or without ground truths. Parse bbox and mask annotation. Args: ann_info (list[dict]): Annotation info of an image. with_mask (bool): Whether to parse mask annotations. Returns: dict: A dict containing the following keys: bboxes, bboxes_i...
4,587
en
0.63998
from IMDB_task4 import scrape_movie_details from pprint import pprint import os,requests,json,time,random from IMDB_task1 import scrape_top_list # task13 # this task for the make a json file ini our directory def save_data(): movies_data = scrape_top_list() for one_movie in movies_data : id_movie = (one_movie['urls...
IMDB_task8.py
1,056
task13 this task for the make a json file ini our directory task_no. 9
70
id
0.147679
# # Copyright (c) 2015-2016 Wind River Systems, Inc. # # SPDX-License-Identifier: Apache-2.0 # import six from nfv_common.helpers import Constant from nfv_common.helpers import Constants from nfv_common.helpers import Singleton @six.add_metaclass(Singleton) class NfviErrorCodes(Constants): """ NFVI - Error C...
nfv/nfv-vim/nfv_vim/nfvi/_nfvi_defs.py
488
NFVI - Error Code Constants Copyright (c) 2015-2016 Wind River Systems, Inc. SPDX-License-Identifier: Apache-2.0 Constant Instantiation
137
en
0.432332
# -*- coding: utf-8 -*- # Generated by Django 1.10.8 on 2018-06-17 14:10 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('book', '0001_initial'), ] operations = [ migrations.AddField( m...
apps/book/migrations/0002_auto_20180617_2210.py
1,135
-*- coding: utf-8 -*- Generated by Django 1.10.8 on 2018-06-17 14:10
68
en
0.55406
from django.db import models from django.utils.translation import ugettext_lazy as _ from filer.models.imagemodels import Image from fractions import Fraction import exifread class ExifData(models.Model): class Meta: verbose_name = _('EXIF Data') verbose_name_plural = _('EXIF data') image = m...
image_exif/models.py
3,126
Gets element with "key" from dict "tags". Converts this data with convertfunc and inserts it into the formatstring "format". If "format" is None, the data is returned without formatting, conversion is done. It the key is not in the dict, the empty string is returned. read tags get necessary tags format exposure tim...
341
en
0.794176
from decimal import Decimal import logging from django.core.exceptions import ImproperlyConfigured from suds import WebFault from suds.transport import TransportError import vatnumber import stdnum from plans.taxation import TaxationPolicy logger = logging.getLogger('plans.taxation.eu.vies') class EUTaxationPolicy(T...
plans/taxation/eu.py
4,727
This taxation policy should be correct for all EU countries. It uses following rules: * if issuer country is not in EU - assert error, * for buyer of the same country as issuer - return issuer tax, * for company buyer from EU (with VIES) returns VAT n/a reverse charge, * for non-company buyer from EU re...
1,383
en
0.900532
#! /usr/bin/python3 # -*- coding: utf-8 -*- ############################################################################## # Copyright 2020 AlexPDev # # 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 Lice...
tests/test_checktab.py
5,636
Shave some data off the end of file. Test checker procedure. Test checker procedure again. Test checker procedure. Test checker procedure. Check tree item counting functionality. Test checker logTextEdit widget function. Test Fixtures. Test missing files checker proceduire. Test missing files checker proceduire. Test t...
992
en
0.758809
"""Internal Exception classes used by package These classes subclass the base Exception class Classes _______ MissingPortException(Exception) SerialReadException(Exception) UnknownConfirmationCodeException(Exception) """ class MissingPortException(Exception): """ Exception raised when the port param is mis...
adafruit_fingerprint/exceptions.py
618
Exception raised when the port param is missing when instantiating the AdafruitFingerprin class Exception raised when no data is read from the serial port Exception raised when package content is an invalid response Internal Exception classes used by package These classes subclass the base Exception class Classes ___...
431
en
0.628591
"""Python Compatibility Utilities.""" from __future__ import annotations import numbers import sys from contextlib import contextmanager from functools import wraps try: from importlib import metadata as importlib_metadata except ImportError: # TODO: Remove this when we drop support for Python 3.7 import...
kombu/utils/compat.py
3,416
Decorator to mark generator as co-routine. Detect the current environment: default, eventlet, or gevent. Return setuptools entrypoints for namespace. Get fileno from file-like object. Get object fileno, or :const:`None` if not defined. Nest context managers. Python Compatibility Utilities. TODO: Remove this when we d...
553
en
0.786832
# -*- coding: utf-8 -*- # """*********************************************************************************************""" # FileName [ model.py ] # Synopsis [ the 1-hidden model ] # Author [ S3PRL ] # Copyright [ Copyleft(c), Speech Lab, NTU, Taiwan ] """************************************...
downstream/libri_phone/model.py
2,193
********************************************************************************************* -*- coding: utf-8 -*- FileName [ model.py ] Synopsis [ the 1-hidden model ] Author [ S3PRL ] Copyright [ Copyleft(c), Speech Lab, NTU, Taiwan ] conv bank init attributes
291
en
0.465102
# Copyright 2013-2022 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 PyBiopandas(PythonPackage): """Working with molecular structures in pandas DataFrames""" ...
var/spack/repos/builtin/packages/py-biopandas/package.py
875
Working with molecular structures in pandas DataFrames Copyright 2013-2022 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) Note that the source package on PyPi is broken as it is missing the requir...
365
en
0.85067
import argparse import shutil import sys import time from datetime import timedelta from pathlib import Path import torch from openunreid.apis import BaseRunner, test_reid from openunreid.core.solvers import build_lr_scheduler, build_optimizer from openunreid.data import build_test_dataloader, build_train_dataloader ...
tools/UDA_TP/main.py
4,033
init distributed training init logging file build train loader build model build optimizer build lr_scheduler build loss functions build runner resume start training load the best model final testing print time
210
en
0.808318
# 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...
tensorflow/contrib/framework/python/ops/sort_ops_test.py
4,657
Tests for the sort wrapper. 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 require...
954
en
0.875403
from typing import List import argparse import chart_studio.plotly as py import plotly.express as px import pandas as pd class TokyoCovid19Stat: """Holds Tokyo Covid-19 stat data.""" def __init__(self, csv_file_path: str = None): self.csv_file_path = csv_file_path self._df = None self....
stat_by_area.py
2,777
Holds Tokyo Covid-19 stat data. Unpivot the given DataFrame to be used with Plotly. title = 'Tokyo Covid-19 New Cases By Area' fig = px.area(cases_by_area, x='Date', y='Cases', color='Area', title=title) py.plot(fig, filename=title, auto_open=False)
251
en
0.572961
import os import librosa.display as lbd import matplotlib.pyplot as plt import sounddevice import soundfile import torch from InferenceInterfaces.InferenceArchitectures.InferenceHiFiGAN import HiFiGANGenerator from InferenceInterfaces.InferenceArchitectures.InferenceTacotron2 import Tacotron2 from Preprocessing.TextF...
InferenceInterfaces/Nancy_Tacotron2.py
3,897
:param silent: Whether to be verbose about the process :param text_list: A list of strings to be read :param file_location: The path and name of the file it should be saved to
175
en
0.849681
# -*- coding: UTF-8 -*- # Copyright 2002-2019 Rumma & Ko Ltd # License: BSD (see file COPYING for details) """ See :ref:`lino` for non-technical documentation. The :mod:`lino` package itself is the first plugin for all Lino applications, added automatically to your :setting:`INSTALLED_APPS`. It defines no models, but...
lino/__init__.py
4,056
This is the only :class:`django.apps.AppConfig` object used by Lino. Lino applications use the :class:`lino.core.plugins.Plugin` because it has some additional functionality. Start up Django and Lino. Optional `settings_module` is the name of a Django settings module. If this is specified, set the :env...
1,891
en
0.611552
import decimal from threading import local from django.db import DEFAULT_DB_ALIAS from django.db.backends import util from django.utils import datetime_safe from django.utils.importlib import import_module class BaseDatabaseWrapper(local): """ Represents a database connection. """ ops = None def ...
django/db/backends/__init__.py
20,776
This class encapsulates all backend-specific methods for opening a client shell. This class encapsulates all backend-specific introspection utilities This class encapsulates all backend-specific differences, such as the way a backend performs ordering or calculates the ID of a recently-inserted row. This class encapsua...
8,803
en
0.814057
# 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-cognitiveservices-search-visualsearch/azure/cognitiveservices/search/visualsearch/models/creative_work_py3.py
4,181
The most generic kind of creative work, including books, movies, photographs, software programs, etc. You probably want to use the sub-classes and not this class directly. Known sub-classes are: Action, MediaObject, Recipe Variables are only populated by the server, and will be ignored when sending a request. All re...
2,156
en
0.699642
#!/usr/bin/env python # -*- coding: utf-8 -*- # # This is very different to AboutModules in Ruby Koans # Our AboutMultipleInheritance class is a little more comparable # from runner.koan import * # # Package hierarchy of Python Koans project: # # contemplate_koans.py # koans/ # __init__.py # about_asserts.py...
python2/koans/about_packages.py
2,204
!/usr/bin/env python -*- coding: utf-8 -*- This is very different to AboutModules in Ruby Koans Our AboutMultipleInheritance class is a little more comparable Package hierarchy of Python Koans project: contemplate_koans.py koans/ __init__.py about_asserts.py about_attribute_access.py about_class_attribu...
1,021
en
0.607809
""" python site scraping tool """ import xml.etree.ElementTree as ET from StringIO import StringIO import unicodedata import re import requests from BuildItParser import BuildItParser def http_get(url): """ simple wrapper around http get """ try: request = requests.get(url) # not concerned wi...
scraper.py
4,868
not concerned with returning nice utf-8, as only the urls count simplify all other errors as 500's need to strip namespaces print "Processing paths..." print "sitemap: {}".format(sitemap_url) print "Processing paths..." print "page: {}".format(page_url) no new paths added
272
en
0.836466
from django.contrib.auth.decorators import permission_required from django.conf import settings from django.http import HttpResponse, HttpResponseRedirect, JsonResponse from catalog import models as cmod from django_mako_plus import view_function, jscontext import requests import json # @permission_required('manager') ...
catalog/views/search.py
1,225
@permission_required('manager')
31
ja
0.142022
import os import scipy.misc as misc import shutil import cv2 import Constants import numpy as np from skimage import morphology def extract_each_layer(image, threshold): """ This image processing funtion is designed for the OCT image post processing. It can remove the small regions and find the OCT layer...
image_utils.py
1,951
This image processing funtion is designed for the OCT image post processing. It can remove the small regions and find the OCT layer boundary under the specified threshold. :param image: :param threshold: :return: convert the output to the binary image remove the small object print(location_point)
299
en
0.752442
# qubit number=3 # total number=31 import numpy as np from qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ from qiskit.visualization import plot_histogram from typing import * from pprint import pprint from math import log2 from collections import Counter from...
data/p3BR/R2/benchmark/startQiskit166.py
5,998
011 . x + 1 000 . x + 0 111 . x + 1 qubit number=3 total number=31 implement the oracle O_f NOTE: use multi_control_toffoli_gate ('noancilla' mode) https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-...
1,306
en
0.408073
# -*- coding: utf-8 -*- # 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 json import os from urlparse import parse_qsl, urlparse from django.conf import settings...
bedrock/firefox/tests/test_base.py
41,020
SSL-enabled links should always be used except Windows stub installers. The buttons should ignore an invalid lang. The buttons should use the lang from the query parameter. Home page must accept post for newsletter signup. Home page must accept post for newsletter signup. Currently released firefoxen should not redirec...
4,656
en
0.802373
from tkinter import * # import math # https://www.youtube.com/watch?v=r5EQCSW_rLQ pyramid math formulas TIME=3:55 class Pyramid: # contants BLOCK_HEIGHT = 1.5 # meters BLOCK_WIDTH = 2 # meters BLOCK_LENGTH = 2.5 # meters BLOCK_WEIGHT = 15000 # kg # __init__ is Python's constructor method ...
assignments/assignment-2-pyramid-builder-gui.py
8,472
import math https://www.youtube.com/watch?v=r5EQCSW_rLQ pyramid math formulas TIME=3:55 contants meters meters meters kg __init__ is Python's constructor method processing this type of function might not be suitable for inside a class, but going with it for now create superscript for displaying exponents storing funct...
1,799
en
0.741144
# This file is dual licensed under the terms of the Apache License, Version # 2.0, and the BSD License. See the LICENSE file in the root of this repository # for complete details. import typing from cryptography import x509 from cryptography.hazmat.primitives import serialization from cryptography.hazmat.primitives.a...
venv/Lib/site-packages/cryptography/hazmat/primitives/serialization/pkcs12.py
6,481
This file is dual licensed under the terms of the Apache License, Version 2.0, and the BSD License. See the LICENSE file in the root of this repository for complete details.
173
en
0.894731
"""Classification Report""" # Authors: Jeffrey Wang # License: BSD 3 clause import numpy as np from sleepens.analysis import multiconfusion_matrix def calculate_statistics(Y_hat, Y, beta=1, average=None): """ Calculate the precisions, recalls, F-beta scores, and supports for each class in `targets`. ...
sleepens/analysis/_report.py
4,968
Calculate the precisions, recalls, F-beta scores, and supports for each class in `targets`. Parameters ---------- Y_hat : array-like, shape=(n_samples,) List of data labels. Y : array-like, shape=(n_samples,) List of target truth labels. beta : float, default=1 Strength of recall relative to ...
2,855
en
0.678719
import numpy as np try: from cs231n.im2col_cython import col2im_cython, im2col_cython from cs231n.im2col_cython import col2im_6d_cython except ImportError: print ('run the following from the cs231n directory and try again:') print ('python setup.py build_ext --inplace') print ('You may also need to restart yo...
2016winter/assignment2/cs231n/fast_layers.py
9,294
A fast implementation of the backward pass for a convolutional layer based on im2col and col2im. A fast implementation of the forward pass for a convolutional layer based on im2col and col2im. A fast implementation of the backward pass for a max pooling layer. This switches between the reshape method an the im2col met...
2,494
en
0.893951
#----------------------------------------------------------------------------- # Copyright (c) 2014, Ryan Volz # All rights reserved. # # Distributed under the terms of the BSD 3-Clause ("BSD New") license. # # The full license is in the LICENSE file, distributed with this software. #-----------------------------------...
echolect/jicamarca/read_raw.py
8,787
----------------------------------------------------------------------------- Copyright (c) 2014, Ryan Volz All rights reserved. Distributed under the terms of the BSD 3-Clause ("BSD New") license. The full license is in the LICENSE file, distributed with this software.--------------------------------------------------...
1,560
en
0.791981
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Mar 23 18:18:48 2020 @author: tsuyogbasnet """ import os import sys import pickle from tqdm import tqdm from scipy.io import wavfile from python_speech_features import mfcc from keras.models import load_model import pandas as pd from sklearn.metrics im...
predict.py
2,646
Created on Mon Mar 23 18:18:48 2020 @author: tsuyogbasnet !/usr/bin/env python3 -*- coding: utf-8 -*-
103
en
0.480212
# Copyright (c) 2009-2018 Stefan Marr <http://www.stefan-marr.de/> # # 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, cop...
rebench/model/experiment.py
5,249
Copyright (c) 2009-2018 Stefan Marr <http://www.stefan-marr.de/> 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, m...
1,184
en
0.858172
#!/usr/bin/env python3 """ Copyright 2020 The Magma Authors. This source code is licensed under the BSD-style license found in the LICENSE file in the root directory of this source tree. Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BAS...
lte/gateway/python/scripts/state_cli.py
6,243
CLI for debugging current Magma services state and displaying it in readable manner. Helper function to deserialize dictionaries or list with nested json strings :param element Helper function to deserialize sessiond:sessions hash list values :param serialized_json_str Mostly used for debugging, purposely corrupts stat...
1,320
en
0.795429
''' Created on May 11, 2017 @author: optas ''' import numpy as np import tensorflow as tf from tflearn.layers.normalization import batch_normalization from tflearn.layers.core import fully_connected, dropout from . encoders_decoders import encoder_with_convs_and_symmetry, decoder_with_fc_only from . tf_utils import ...
src/generators_discriminators.py
4,160
Used in ICML submission. Used in ICML submission. used in nips submission. used in nips submission. Created on May 11, 2017 @author: optas
159
en
0.895282
''' 07 - March 29, throughout a decade Daylight Saving rules are complicated: they're different in different places, they change over time, and they usually start on a Sunday (and so they move around the calendar). For example, in the United Kingdom, as of the time this lesson was written, Daylight Saving begins o...
18_Working with Dates and Times in Python/03_Time Zones and Daylight Saving/07_March 29, throughout a decade.py
1,520
07 - March 29, throughout a decade Daylight Saving rules are complicated: they're different in different places, they change over time, and they usually start on a Sunday (and so they move around the calendar). For example, in the United Kingdom, as of the time this lesson was written, Daylight Saving begins on th...
761
en
0.900447
# Definition for a binary tree node. class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def maxDepth(self, root: TreeNode) -> int: if root is None: return 0 return 1 + max(self...
python/maximum_depth_of_binary_tree.py
369
Definition for a binary tree node.
34
en
0.719194
"""Add genres back Revision ID: 1d393bb338a4 Revises: 126ecfb9a15e Create Date: 2020-08-23 12:21:59.354200 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '1d393bb338a4' down_revision = '126ecfb9a15e' branch_labels = None depends_on = None def upgrade(): ...
migrations/versions/1d393bb338a4_add_genres_back.py
674
Add genres back Revision ID: 1d393bb338a4 Revises: 126ecfb9a15e Create Date: 2020-08-23 12:21:59.354200 revision identifiers, used by Alembic. commands auto generated by Alembic - please adjust! end Alembic commands commands auto generated by Alembic - please adjust! end Alembic commands
298
en
0.639434
import decimal from graphene.types import Scalar from graphql.language import ast # See: https://github.com/graphql-python/graphene-django/issues/91#issuecomment-305542169 class Decimal(Scalar): """ The `Decimal` scalar type represents a python Decimal. """ @staticmethod def serialize(dec): ...
backend/backend/core/graphql/scalars.py
698
The `Decimal` scalar type represents a python Decimal. See: https://github.com/graphql-python/graphene-django/issues/91issuecomment-305542169
143
en
0.703143
# Generated by Django 2.0.2 on 2018-02-24 04:48 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Food', fields=[ ('ndb_no', models.CharField...
foodviz/search/migrations/0001_initial.py
1,748
Generated by Django 2.0.2 on 2018-02-24 04:48
45
en
0.730574
class Solution: def maxNumber(self, nums1, nums2, k): """ :type nums1: List[int] :type nums2: List[int] :type k: int :rtype: List[int] """ def prep(nums, k): dr = len(nums) - k # 要删除的数目 stay = [] # 保留的list for num in ...
src/321. Create Maximum Number.py
1,191
:type nums1: List[int] :type nums2: List[int] :type k: int :rtype: List[int] 要删除的数目 保留的list 删除的空间 dr 删除的必要 stay[-1] < num 即 堆栈法:上升就替换,下降就保留。 dr = l1 + l2 -k 遍历所有可能并比较大小
170
zh
0.796997
"""Misc. regolith tools. """ import email.utils import os import platform import re import sys import time from copy import deepcopy from calendar import monthrange from datetime import datetime, date, timedelta from regolith.dates import month_to_int, date_to_float, get_dates from regolith.sorters import doc_date_ke...
regolith/tools.py
26,175
Yield all entries in for all collections of a given name in a given database. Make sorted awards grants and honors list. Parameters ---------- p : dict The person entry Converts a date to an RFC 822 formatted string. Gets the database dir name. Gets the database path name. Tool for replacing placeholders for inst...
9,623
en
0.706824
""" This module is for performance testing of EDA module in github action. """ from functools import partial import pandas as pd from typing import Any from ...datasets import load_dataset from ...eda import create_report def report_func(df: pd.DataFrame, **kwargs: Any) -> None: """ Create report function, us...
dataprep/tests/benchmarks/eda.py
585
Create report function, used for performance testing. Performance test of create report on titanic dataset. This module is for performance testing of EDA module in github action.
178
en
0.759343
# Copyright 2019-2021 ETH Zurich and the DaCe authors. All rights reserved. import math import dace import polybench N = dace.symbol('N') #datatypes = [dace.float64, dace.int32, dace.float32] datatype = dace.float64 # Dataset sizes sizes = [{N: 30}, {N: 90}, {N: 250}, {N: 1300}, {N: 2800}] args = [([N, N], datatype...
samples/polybench/gesummv.py
1,458
Copyright 2019-2021 ETH Zurich and the DaCe authors. All rights reserved.datatypes = [dace.float64, dace.int32, dace.float32] Dataset sizes
139
en
0.364997
#! /usr/bin/env python # -*- coding: utf-8 -*- # vim:fenc=utf-8 # # Copyright © 2017 unga <giulioungaretti@me.com> # # Distributed under terms of the MIT license. """ Monitor a set of parameters in a background thread stream output over websocket To start monitor, run this file, or if qcodes is installed as a module: ...
qcodes/monitor/monitor.py
9,410
QCodes Monitor - WebSockets server to monitor qcodes parameters. Monitor qcodes parameters. Args: *parameters: Parameters to monitor. interval: How often one wants to refresh the values. Return a dictionary that contains the parameter metadata grouped by the instrument it belongs to. Return the websockets serv...
2,126
en
0.650479
#!/usr/bin/env python3 # Copyright (c) 2019 The TradePlus_Coin developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # -*- coding: utf-8 -*- from io import BytesIO from struct import pack from random import randint, choice im...
test/functional/fake_stake/base_test.py
20,352
creates a block to spam the network with :param hashPrevBlock: (hex string) hash of previous block stakingPrevOuts: ({COutPoint --> (int, int, int, str)} dictionary) map outpoints (to be used as staking inputs) to amount, block_time, nStakeModifier, hashStake he...
6,283
en
0.738826
import asyncio import sys import pytest from aws_lambda_powertools.event_handler import AppSyncResolver from aws_lambda_powertools.event_handler.appsync import Router from aws_lambda_powertools.utilities.data_classes import AppSyncResolverEvent from aws_lambda_powertools.utilities.typing import LambdaContext from tes...
tests/functional/event_handler/test_appsync.py
5,408
Check whether we can handle an example appsync direct resolver noqa AA03 VNE003 Call the implicit handler Check whether we can handle an example appsync resolver Call the explicit resolve function GIVEN WHEN THEN GIVEN no defined field resolver WHEN THEN GIVEN WHEN THEN GIVEN WHEN THEN GIVEN WHEN THEN Check whether we ...
424
en
0.452923
#-*- coding: utf-8 -*- # Import the extension import isce3.extensions.isceextension as isceextension # Import the wrappers def crossmul(**kwds): """A factory for Crossmul""" from .Crossmul import Crossmul return Crossmul(**kwds) # end of file
python/packages/isce3/signal/__init__.py
259
A factory for Crossmul -*- coding: utf-8 -*- Import the extension Import the wrappers end of file
98
en
0.691
from typing import List, Tuple import pytest from returns.io import IOFailure, IOResult, IOSuccess from returns.pipeline import managed from returns.result import Failure, Result, Success _acquire_success = IOSuccess('acquire success') _acquire_failure = IOFailure('acquire failure') def _use_success(inner_value: s...
tests/test_pipeline/test_managed/test_managed_ioresult.py
3,124
Ensures that managed works as intended. This test is here to be a case for typing. Acquire success: Acquire failure:
118
en
0.980544
# -*- coding: utf-8 -*- # """*********************************************************************************************""" # FileName [ split_long_utter_to_short.py ] # Synopsis [ preprocess long audio / speech to shorter versions ] # Author [ Andy T. Liu (Andi611) ] # Copyright [ Copyleft(c...
s3prl/preprocess/split_long_utter_to_short.py
4,871
********************************************************************************************* -*- coding: utf-8 -*- FileName [ split_long_utter_to_short.py ] Synopsis [ preprocess long audio / speech to shorter versions ] Author [ Andy T. Liu (Andi611) ] Copyright [ Copyleft(c), Speech Lab, ...
758
en
0.564145
#!/usr/bin/env python3 # Copyright (c) 2014-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. """Test the RPC HTTP basics.""" from test_framework.test_framework import BitcoinTestFramework from test_...
test/functional/interface_http.py
4,781
Test the RPC HTTP basics. !/usr/bin/env python3 Copyright (c) 2014-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. lowlevel check for http persistent connection according to http/1.1 connection must st...
1,096
en
0.876142
import time, sys, os from database_check import database_check from link_processor import get_link from link_generator import alphabets_generator, random_address_generator, linear_address_generator, last_link_read_linear_address, mutation_address_generator def program_exit(link, work_mode): if work_mode == '1': ...
telegram_parser_console/main.py
3,616
1 = linear if work_mode == '3': print('Mutation variations of the link ended') work mode with/out delay LINK Checking 1 = linear 2 = random 3 = mutation
156
en
0.614793
# Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """ Test cases for the L{twisted.python.failure} module. """ from __future__ import division, absolute_import import re import sys import traceback import pdb import linecache from twisted.python.compat import _PY3, NativeStringIO from twisted....
fang/Twisted-18.4.0/src/twisted/test/test_failure.py
31,618
A metaclass for an exception type which cannot be presented as a string via C{str}. The aforementioned exception type which cnanot be presented as a string via C{str}. An exception class the instances of which cannot be presented as strings via C{str}. Failure's debug mode should allow jumping into the debugger. Tests ...
10,963
en
0.799211
from sendbee_api.models import Model from sendbee_api.fields import TextField, BooleanField class RateLimitError(Model): """Data model for rate limit error""" _detail = TextField(index='detail', desc='Message detail') _error = BooleanField(index='error', desc='Error or not') _type = TextField(index='...
sendbee_api/rate_limit/models.py
348
Data model for rate limit error
31
en
0.523991
# Generated by Django 3.1 on 2020-10-07 00:22 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('resources', '0016_job_auth_token'), ] operations = [ migrations.AlterField( model_name='report', name='logs', ...
api/resources/migrations/0017_auto_20201007_0022.py
383
Generated by Django 3.1 on 2020-10-07 00:22
43
en
0.815492
"""Module to handle all events within AppDaemon.""" import uuid from copy import deepcopy import traceback import datetime from appdaemon.appdaemon import AppDaemon import appdaemon.utils as utils class Events: """Encapsulate event handling.""" def __init__(self, ad: AppDaemon): """Constructor. ...
appdaemon/events.py
14,324
Encapsulate event handling. Constructor. Args: ad: Reference to the AppDaemon object Module to handle all events within AppDaemon. Events We assume that the event will come back to us via the plugin Just fire the event locally if data["event_type"] == "__AD_ENTITY_REMOVED": print("process event") Kick the sch...
802
en
0.831757
""" Test lldb breakpoint setting by source regular expression. This test just tests the source file & function restrictions. """ from __future__ import print_function import os import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil c...
SymbolExtractorAndRenamer/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/source_regexp/TestSourceRegexBreakpoints.py
3,808
Test that restricting source expressions to files & to functions. Test that restricting source expressions to files & to functions. Test lldb breakpoint setting by source regular expression. This test just tests the source file & function restrictions. Create a target by the debugger. First look just in main: Creat...
426
en
0.877413
import queue from ..workers import Worker from ..codes import WORKER_PROPERTIES class Singleton(type): _instances = {} def __call__(cls, *args, **kwargs): if cls not in cls._instances: cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs) return cls._instances[cls...
gridnetwork/events/socket_handler.py
3,120
Socket Handler is a sigleton class used to handle/manage websocket connections. Number of connections handled by this server. Returns: length: number of connections handled by this server. Retrieve a worker by its UUID string or its socket descriptor. Create a mapping structure to establish a bond between a worke...
1,055
en
0.841297
# <pep8-80 compliant> # ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # ...
engine/2.80/scripts/addons/magic_uv/op/texture_lock.py
15,980
Operation class: Texture Lock (Interactive mode) Operation class: Lock Texture Operation class: Unlock Texture Update UV when vertex coordinates are changed Calculate rest coordinate from other coordinates and angle of end Get initial geometory (Get interior angle of face in vertex/UV space) Get loop linked to vertex G...
1,954
en
0.846276
# Original code from https://github.com/araffin/robotics-rl-srl # Authors: Antonin Raffin, René Traoré, Ashley Hill import argparse import cv2 # pytype: disable=import-error import numpy as np from ae.autoencoder import Autoencoder def create_figure_and_sliders(name, state_dim): """ Creating a window for t...
ae/enjoy_latent.py
2,372
Creating a window for the latent space visualization, and another one for the sliders to control it. :param name: name of model (str) :param state_dim: (int) :return: Original code from https://github.com/araffin/robotics-rl-srl Authors: Antonin Raffin, René Traoré, Ashley Hill pytype: disable=import-error opencv gu...
698
en
0.79604
# Copyright (c) 2020 PaddlePaddle 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 appli...
ppdet/modeling/post_process.py
28,167
Postprocess the model outputs to get final prediction: 1. Do NMS for heatmap to get top `max_per_img` bboxes. 2. Decode bboxes using center offset and box size. 3. Rescale decoded bboxes reference to the origin image shape. Args: max_per_img(int): the maximum number of predicted objects in a image, ...
6,344
en
0.754076
# 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 ...
src/codespaces/azext_codespaces/vendored_sdks/vsonline/models/resource_provider_operation_definition.py
1,200
Describes the Resource Provider Operation. :param name: Resource provider operation name. :type name: str :param display: Resource provider display properties. :type display: ~microsoft.vsonline.models.ResourceProviderOperationDisplay coding=utf-8 ---------------------------------------------------------------------...
690
en
0.512045
JONG_COMP = { 'ㄱ': { 'ㄱ': 'ㄲ', 'ㅅ': 'ㄳ', }, 'ㄴ': { 'ㅈ': 'ㄵ', 'ㅎ': 'ㄶ', }, 'ㄹ': { 'ㄱ': 'ㄺ', 'ㅁ': 'ㄻ', 'ㅂ': 'ㄼ', 'ㅅ': 'ㄽ', 'ㅌ': 'ㄾ', 'ㅍ': 'ㄿ', 'ㅎ': 'ㅀ', } } DEFAULT_COMPOSE_SEPARATOR = u'ᴥ' #################...
hanshift/text.py
2,957
Hangul Automata functions by bluedisk@gmail.com 종성째 출력 방지
57
ko
0.620043
import curses import time # only for debugging stdscr = curses.initscr() class Listdisplay: def __init__(self, lst, start_x, start_y, height, width, headers=None) -> None: """Lst is 2-d. i th list in lst is content of i+1 tab Each string in lst should not be of more length than width sc...
src/client/ui/widget/displaylist.py
2,491
Lst is 2-d. i th list in lst is content of i+1 tab Each string in lst should not be of more length than width scroling is available only in vertical direction only for debugging for debugging
194
en
0.880094
from django.conf.urls import url from django.contrib.auth import login from django.contrib.auth.models import User from django.http import HttpResponse from django.views.decorators.cache import cache_page from django.urls import include, path, re_path from .. import views def repath_view(request): return HttpRes...
tests/contrib/django/django_app/urls.py
1,834
This view can be used to test requests with an authenticated user. Create a user with a default username, save it and then use this user to log in. Always returns a 200.
169
en
0.800411
import requests import csv import sys import os import json from time_converter import date_weather_format, current_day_weather def get_all_json_keys(keys_array, json): for key in json.keys(): if not isinstance(json[key], str): _ = get_all_json_keys(keys_array, json[key][0]) else: ...
data/weather_data.py
3,514
CONSTRUCTS THE API URL RETRIEVES INFORMATION OF ALL FAVORITE SYSTEMS ARRAY TO USE IN CASE PROGRAM FAILS IN THE MIDDLE BC OF LIMITED REQUESTS BASE WEATHER API URL REVERSES THE RESULT TO NEWST RECORDS ON TOP SAVES DATA INTO A FILE REFERING WITH THE SYSTEM ID FLAT THE JSON HEADERS FLAT THE JSON VALUES
299
en
0.738852
# coding=utf-8 # Copyright 2018 The OpenAI Team Authors and HuggingFace Inc. team. # Copyright (c) 2018, NVIDIA CORPORATION. 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...
transformers/modeling_tf_openai.py
30,200
**mc_token_ids**: (`optional`, default to index of the last token of the input) ``Numpy array`` or ``tf.Tensor`` of shape ``(batch_size, num_choices)``: Index of the classification token in each input sequence. Selected in the range ``[0, input_ids.size(-1) - 1[``. Outputs: `Tuple` comprising various e...
8,450
en
0.722596
from singlecellmultiomics.bamProcessing.pileup import pileup_truncated def get_pileup_vect(alignments, contig, pos, ref, alt): """Create feature vector for selected variant Args: alignments(pysam.AlignmentFile) : Handle to alignmentfile contig(str) : contig to perform pileup pos(int) ...
singlecellmultiomics/bamProcessing/bamFeatures.py
2,120
Obtain histogram of mapping qualties, clipped at 60 Args: alignments(pysam.AlignmentFile) : Handle to alignmentfile contig(str) : contig pos(int) : zeros based position of location to check mapping qualties radius(int) : radius to check around selected location Returns: mapping_qualities(list) : ...
943
en
0.671472
#============================================================================= # Copyright 2017 FLIR Integrated Imaging Solutions, Inc. All Rights Reserved. # # This software is the confidential and proprietary information of FLIR # Integrated Imaging Solutions, Inc. ('Confidential Information'). You # shall not d...
PyCapture2-2.13.31/examples/python3/FlyCapture2Test.py
3,616
============================================================================= Copyright 2017 FLIR Integrated Imaging Solutions, Inc. All Rights Reserved. This software is the confidential and proprietary information of FLIR Integrated Imaging Solutions, Inc. ('Confidential Information'). You shall not disclose such Con...
1,129
en
0.801842
# Generated by Django 2.2.7 on 2019-11-21 01:20 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('user', '0004_remove_user_register_time'), ] operations = [ migrations.AlterField( model_name='user', name='username'...
user/migrations/0005_auto_20191121_0120.py
426
Generated by Django 2.2.7 on 2019-11-21 01:20
45
en
0.740107
# Copyright (c) 2022 RWTH Aachen - Werkzeugmaschinenlabor (WZL) # Contact: Simon Cramer, s.cramer@wzl-mq.rwth-aachen.de from sherpa import Client from sherpa.schedulers import Scheduler, _JobStatus import requests import json import logging as logg import numpy as np import socket from time import sleep import os from...
argo_scheduler.py
14,571
Argo Scheduler submit, update, kill jobs and send metrics for sherpa hpo Args: Scheduler (class): shepra.schedulers Set init values Args: default_parameter (dict): Parameter that will be submitted with the argo workflow in a kind of input flags. rebuild_parameter (dict): Parameter that were genereted when...
4,450
en
0.834328
# Generated by Django 2.2.7 on 2020-01-10 19:23 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('chatapp', '0001_initial'), ] operations = [ migrations.RemoveField( ...
ChatProject/chatapp/migrations/0002_auto_20200110_2253.py
1,122
Generated by Django 2.2.7 on 2020-01-10 19:23
45
en
0.684305
# Copyright The PyTorch Lightning team. # # 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 i...
pytorch_lightning/utilities/imports.py
3,880
Compare package version with some requirements >>> _compare_version("torch", operator.ge, "0.1") True Check if a path is available in your environment >>> _module_available('os') True >>> _module_available('bla.bla') False General utilities Copyright The PyTorch Lightning team. Licensed under the Apache License, Ve...
949
en
0.752491
""" Copyright (C) 2018-2020 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 i...
modules/mo_pytorch/mo_extensions/front/pytorch/linear.py
1,217
Copyright (C) 2018-2020 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,...
574
en
0.858332
#@+leo-ver=5-thin #@+node:ekr.20160928073518.1: * @file ../plugins/pyplot_backend.py ''' A helper for the viewrendered plugin. This is *NOT* a real plugin. ''' #@+<< pyplot_backend imports >> #@+node:ekr.20160928074801.1: ** << pyplot_backend imports >> from leo.core import leoGlobals as g from leo.plugins impo...
leo/plugins/pyplot_backend.py
4,779
Public attributes canvas : The FigureCanvas instance num : The Figure number toolbar : The qt.QToolBar window : The qt.QMainWindow (not set) Ctor for the LeoFigureManagerQt class. Return True if the plugin has loaded successfully. Create a new figure manager instance Create a new figure manager i...
1,744
en
0.565615
import sys import os import errno import time import json import glob from base64 import b64decode from watchdog.observers import Observer from watchdog.events import FileSystemEventHandler class Handler(FileSystemEventHandler): def __init__(self, provider): self.provider = provider def on_created(sel...
extractor.py
5,158
Check if it's a JSON file Read JSON file Determine ACME version Find certificates Loop over all certificates Decode private key, certificate and chain Create domain directory if it doesn't exist Write private key, certificate and chain to file Write private key, certificate and chain to flat files Determine path to wat...
525
en
0.851755
#! /usr/bin/env python3 """camera.py - Adding a camera for bigger levels.""" import collections import time import arcade from arcade import key # Constraints SCREEN_WIDTH = 1000 SCREEN_HEIGHT = 650 SCREEN_TITLE = "Platformer" # Scale sprites from original size. 1 is original. CHARACTER_SCALING = 1 TILE_SCALING = 0...
multiple_levels.py
11,747
A class to detect frames per second. Main application class. A class to encapsulate the player sprite. Call the parent class and set up the window. Checks if player at end of level, and if so, load the next level. Ensure the camera is centered on the player. Determine coins remaining. Determine current fps. Display GUI...
2,781
en
0.858775
# -*- coding: utf-8 -*- """ werkzeug.formparser ~~~~~~~~~~~~~~~~~~~ This module implements the form parsing. It supports url-encoded forms as well as non-nested multipart uploads. :copyright: (c) 2011 by the Werkzeug Team, see AUTHORS for more details. :license: BSD, see LICENSE for more deta...
werkzeug/formparser.py
20,612
This class implements parsing of form data for Werkzeug. By itself it can parse multipart and url encoded form data. It can be subclassed and extended but for most mimetypes it is a better idea to use the untouched stream and expose it as separate attributes on a request object. .. versionadded:: 0.8 :param stream_...
7,227
en
0.81013
#!/usr/bin/env python # coding: utf-8 import numpy as np import matplotlib.pyplot as plt import seaborn as sns sns.set_style('whitegrid') import sys import os import pandas as pd from scipy import stats HEADERS = ['device', 'layout', 'enc_type', 'n_states', 'sim_type', 'shots', 'optimizer', 'energy', 'meas_mit'] ...
paper-data/noise/8state_layout_comparison.py
4,121
!/usr/bin/env python coding: utf-8raise ValueErrorlayout = 'None'circ = 'None'colours = {"True" : "tab:blue", "False" : "tab:orange", "None" : "tab:gray"}ax.set_xlim(-3,10)plt.ylim(0,20)plt.xticks(fontsize=16)plt.yticks(fontsize=16)title_string = f"Yorktown, meas_mit={key[1]}"plt.title(title_string, fontsize=20)
313
en
0.158415
""" The file preprocesses the files/train.txt and files/test.txt files. I requires the dependency based embeddings by Levy et al.. Download them from his website and change the embeddingsPath variable in the script to point to the unzipped deps.words file. """ from __future__ import print_function import numpy as np ...
2017-07_Seminar/Session 3 - Relation CNN/code/preprocess.py
6,468
Creates matrices for the events and sentence for the given file Returns from the word2Idex table the word index for a given token The file preprocesses the files/train.txt and files/test.txt files. I requires the dependency based embeddings by Levy et al.. Download them from his website and change the embeddingsPath ...
835
en
0.752085
# vim:ts=4:sw=4:sts=4:et # -*- coding: utf-8 -*- """Classes related to graph clustering. @undocumented: _handle_mark_groups_arg_for_clustering, _prepare_community_comparison""" __license__ = u""" Copyright (C) 2006-2012 Tamás Nepusz <ntamas@gmail.com> Pázmány Péter sétány 1/a, 1117 Budapest, Hungary This program is...
igraph/clustering.py
66,025
Class representing a clustering of an arbitrary ordered set. This is now used as a base for L{VertexClustering}, but it might be useful for other purposes as well. Members of an individual cluster can be accessed by the C{[]} operator: >>> cl = Clustering([0,0,0,0,1,1,1,2,2,2,2]) >>> cl[0] [0, 1, 2, 3] The me...
32,606
en
0.838554
# Copyright 2018 Google LLC. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # #...
third_party/nucleus/io/python/hts_verbose_test.py
2,441
Tests for hts_verbose. Copyright 2018 Google LLC. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following discla...
1,490
en
0.882155
"""Tests for the sensor drivers.""" import pytest import mock from pytest_lazyfixture import lazy_fixture # type: ignore[import] from unittest.mock import patch from mock.mock import AsyncMock from tests.conftest import MockCanMessageNotifier from opentrons_hardware.sensors import fdc1004, hdc2080, mmr920C04, senso...
hardware/tests/opentrons_hardware/sensors/test_sensor_drivers.py
18,584
Fixture for capacitive sensor driver. Fixture for humidity sensor driver. Fixture for pressure sensor driver. Message responder. Message responder. Message responder. Message responder. Message responder. Fixture for temperature sensor driver. Tests for the sensor drivers. type: ignore[import]
296
en
0.549245
""" Common functions for tests """ __author__ = "Dan Gunter <dkgunter@lbl.gov>" __date__ = "10/29/13" # Stdlib import json import logging import os import subprocess import sys import tempfile import traceback import unittest # Third-party from mongomock import MongoClient import pymongo # Package from pymatgen.db.q...
pymatgen/db/tests/common.py
5,095
Mock (fake) QueryEngine, unless a real connection works. You can disable the attempt to do a real connection by setting MP_FAKEMONGO to anything Connect to Mongo DB :return: pymongo Database Determine if MongoDB is up and usable Run the command-line given by the list in `args`, adding the dictionary given by options a...
657
en
0.776966
# ------------------------------------------------------------------------- # Copyright (c) Microsoft. 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.ap...
azure/storage/blob/models.py
26,141
------------------------------------------------------------------------- Copyright (c) Microsoft. 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/licens...
715
en
0.761727
import numpy import matplotlib.pyplot as plt import threading import multiprocessing from scipy import stats class TestHist: def hist(self, parameter_list): x = numpy.random.uniform(0.0, 5.0, 100000) plt.hist(x, 100) plt.show() y = numpy.random.normal(0.0, 5.0, 100000) pl...
helloword/ml.py
1,616
input, slope, intercept numpy.random.seed(12345678) x = numpy.random.random(10) y = 1.6*x + numpy.random.random(10) from scipy import stats x = [5,7,8,7,2,17,2,9,4,11,12,9,6] y = [99,86,87,88,111,86,103,87,94,78,77,85,86] slope, intercept, r, p, std_err = stats.linregress(x, y) def myfunc(x): return slope * x + int...
397
en
0.343033
from rest_framework import permissions from django_otp import user_has_device from .utils import otp_is_verified class IsOtpVerified(permissions.BasePermission): """ If user has verified TOTP device, require TOTP OTP. """ message = "You do not have permission to perform this action until you verify yo...
accounts/permissions.py
545
If user has verified TOTP device, require TOTP OTP.
51
en
0.943975
# a simple python AES decrypter. Do not remember why I needed this, but nice to have. :) pw = [255,155,28,115,214,107,206,49,172,65,62,174,19,27,70,79,88,47,108,226,209,225,243,218,126,141,55,107,38,57,78,91] pw1 = b'' for i in pw: pw1 += i.to_bytes(1, 'little') import sys, hexdump, binascii from Crypto.Cipher im...
htb/remote/decoder.py
780
a simple python AES decrypter. Do not remember why I needed this, but nice to have. :)
86
en
0.750966
# 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 may ...
sdk/compute/azure-mgmt-compute/azure/mgmt/compute/v2019_03_01/aio/operations/_gallery_images_operations.py
22,019
GalleryImagesOperations async operations. You should not instantiate this class directly. Instead, you should create a Client instance that instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. :type models: ~azure.mgmt.compute.v2019_03_01.models :...
2,431
en
0.536312
# Protocol Buffers - Google's data interchange format # Copyright 2008 Google Inc. All rights reserved. # https://developers.google.com/protocol-buffers/ # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # ...
Plugins/UnrealEnginePython/Binaries/Win64/Lib/site-packages/google/protobuf/message.py
14,874
Exception raised when deserializing messages. Exception raised when serializing messages. Base error type for this module. Abstract base class for protocol messages. Protocol message classes are almost always generated by the protocol compiler. These generated types subclass Message and implement the methods shown be...
10,506
en
0.805884
# coding: utf-8 # flake8: noqa """ Design feeds APIs Various design feeds.<BR />[Endpoint] https://api.apitore.com/api/32 # noqa: E501 OpenAPI spec version: 0.0.1 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import # import models into ...
32/swagger_client/models/__init__.py
476
Design feeds APIs Various design feeds.<BR />[Endpoint] https://api.apitore.com/api/32 # noqa: E501 OpenAPI spec version: 0.0.1 Generated by: https://github.com/swagger-api/swagger-codegen.git coding: utf-8 flake8: noqa import models into model package
258
en
0.665961