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 pytorch_lightning as pl
from pytorch_lightning.utilities.parsing import lightning_getattr, lightning_setattr
class MultipleShootingCallback(pl.Callback):
"""This callback increases the length of the training sequences each epoch.
This technique is well known in the SciML community and documented in th... | finite_element_networks/lightning/callbacks.py | 3,133 | This callback increases the length of the training sequences each epoch.
This technique is well known in the SciML community and documented in their tutorials
[1] as a way to avoid falling into local minima when training ODE based models. We can
also see this as an instance of multiple shooting [2, 3] in the data spac... | 1,363 | en | 0.851585 |
import os
import sys
sys.path.append('/trinity/home/m.gasanov/monica/sensitivity/sobol/SALib')
from SALib.analyze import sobol
from SALib.sample import saltelli
from SALib.test_functions import Ishigami
from SALib.util import read_param_file
from numpy import genfromtxt
# Read the parameter range file and generate sa... | Sobol_SA_horizont/CN/sobol.py | 2,006 | Read the parameter range file and generate samplesproblem = read_param_file('../../src/SALib/test_functions/params/Ishigami.txt') Generate samples Run the "model" and save the output in a text file This will happen offline for external modelsY = Ishigami.evaluate(param_values) Perform the sensitivity analysis using the... | 921 | en | 0.574664 |
from .Detector import Detector
import time
import numpy as np
import PyTango
class LC400Buffer(Detector):
"""
Class representing the LC400 piezo machine under the
control of the LC400ScanControl Tango device, used for
reading the flyscan positions.
"""
def __init__(self, name=None, device=No... | contrast/detectors/LC400Buffer.py | 2,979 | Class representing the LC400 piezo machine under the
control of the LC400ScanControl Tango device, used for
reading the flyscan positions.
Placeholder, this detector just reads out whatever buffer is on the
scancontrol device. That device is managed manually from macros.
grab these values in case we have to restart a... | 328 | en | 0.89492 |
# -*- coding: utf-8 -*-
"""OpenCTI valhalla connector core module."""
import os
import yaml
import time
from typing import Any, Dict, Mapping, Optional
from datetime import datetime
from .knowledge import KnowledgeImporter
from .models import Status
from pycti import OpenCTIConnectorHelper, get_config_variable
from... | valhalla/src/valhalla/core.py | 5,966 | OpenCTI valhalla main class
OpenCTI valhalla connector core module.
-*- coding: utf-8 -*- Instantiate the connector helper from config Extra config If we run without API key we can assume all data is TLP:WHITE else we default to TLP:AMBER to be safe. After a successful run pause at least 60sec | 296 | en | 0.725583 |
# Copyright (c) 2017-present, Facebook, 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 o... | lib/datasets/dummy_datasets.py | 2,331 | A dummy COCO dataset that includes only the 'classes' field.
Provide stub objects that can act as stand-in "dummy" datasets for simple use
cases, like getting all classes in a dataset. This exists so that demos can be
run without requiring users to download/install datasets first.
Copyright (c) 2017-present, Facebook... | 848 | en | 0.860986 |
import logging
from django.utils.decorators import method_decorator
from django_filters.rest_framework import DjangoFilterBackend
from drf_yasg.utils import swagger_auto_schema
from rest_condition import Or
from rest_framework import filters, viewsets
from rest_framework.permissions import IsAdminUser, IsAuthenticated... | src/users/views/user.py | 2,515 | An API endpoint for Getting device list
Creating Device
def get_permissions(self): return [permission() for permission in permission_classes] | 147 | en | 0.645327 |
"""
Copyright (c) 2019 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 ... | multi_camera_multi_person_tracking/utils/network_wrappers.py | 3,220 | Wrapper class for detector
Wrapper class for a network returning a vector
Decodes raw SSD output
Performs forward of the underlying network on a given batch
Returns all detections on frames
Copyright (c) 2019 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file exc... | 749 | en | 0.823095 |
import carla
from carla import ColorConverter as cc
from ROAR_Sim.carla_client.util.sensors import IMUSensor
from Bridges.bridge import Bridge
from typing import Union
from ROAR.utilities_module.vehicle_models import (
VehicleControl,
Vehicle,
)
from ROAR.utilities_module.data_structures_models import (
Loc... | Bridges/carla_bridge.py | 6,650 | Convert a CARLA raw image to a BGRA numpy array.
Convert a CARLA raw image to a RGB numpy array.
Convert CARLA raw vehicle control to VehicleControl(throttle,steering).
Convert CARLA raw depth info to
Convert Location data from Carla.location to Agent's lcoation data type
invert the Z axis to make it into right hand c... | 777 | en | 0.653482 |
import importlib
import inspect
import logging
import os
from app.plugin import Hook, Command
PLUGINS_DIR = 'plugins'
def find_plugins():
"""Returns a list of plugin path names."""
for root, dirs, files in os.walk(PLUGINS_DIR):
for file in files:
if file.endswith('.py'):
... | app/processor.py | 1,659 | Returns a list of plugin path names.
Populates the plugin lists. | 64 | en | 0.535551 |
# -*- coding: utf-8 -*-
# TODO: find unused functions and kill them
import logging
import copy
import operator
import utool as ut
import vtool as vt
import numpy as np
import itertools as it
from functools import partial, reduce
from wbia.expt import cfghelpers
from wbia.expt import experiment_helpers
print, rrr, prof... | wbia/expt/test_result.py | 111,317 | CommandLine:
export SMK_PIPE="smk:nwords=[64000],sv=[False]"
wbia TestResult --db PZ_MTEST -a ctrl -p $SMK_PIPE
wbia TestResult --db Oxford -a oxford -p $SMK_PIPE
Example:
>>> # Script
>>> from wbia.init import main_helpers
>>> import utool as ut
>>> ibs, testres = main_helpers.testdata_e... | 31,648 | en | 0.315041 |
from neopixel import NeoPixel
from machine import Pin
from time import sleep
from os import urandom
#pin = Pin(14, Pin.OUT)
np = NeoPixel(Pin(2, Pin.OUT), 8)
pin = Pin(14, Pin.IN)
test = 7/10
while True:
can_win = True
if pin.value() == 0:
can_win = False
for i in range(20):
for i in range(0, 8)... | lessons/MicroPython/forbes.py | 949 | pin = Pin(14, Pin.OUT) | 22 | en | 0.505221 |
#!/usr/bin/env python
"""Tests for `SEIR` package."""
import os
import pytest
from click.testing import CliRunner
from SEIR import cli
@pytest.fixture
def response():
"""Sample pytest fixture.
See more at: http://doc.pytest.org/en/latest/fixture.html
"""
import requests
return requests.get('h... | tests/test_SEIR.py | 1,141 | Sample pytest fixture.
See more at: http://doc.pytest.org/en/latest/fixture.html
Test the CLI.
Sample pytest test function with the pytest fixture as an argument.
Tests for `SEIR` package.
!/usr/bin/env python from bs4 import BeautifulSoup assert 'GitHub' in BeautifulSoup(response.content).title.string result = runne... | 407 | en | 0.514816 |
# -*- coding: utf-8 -*-
import os
print '-------操作文件和目录-------'
# 操作系统名字
print os.name + '\n'
print '\n' + '详细的系统信息'
print os.uname()
print '\n' + '环境变量'
print os.environ
print '\n' + '获取某个环境变量的值'
print os.getenv('PATH')
print '\n'
# 查看当前目录的绝对路径:
print os.path.abspath('.')
selfAbsPath = os.path.abspath('.')
#... | Python/pythonLevel1/python0811_file.py | 1,962 | -*- coding: utf-8 -*- 操作系统名字 查看当前目录的绝对路径: 在某个目录下创建一个新目录, 首先把新目录的完整路径表示出来: '/Users/michael/testdir' 然后创建一个目录: 删掉一个目录: 这样可以正确处理不同操作系统的路径分隔符 对文件重命名: os.rename('test.txt', 'test.py') 删掉文件: os.remove('test.py') shutil模块提供了copyfile()的函数,你还可以在shutil模块中找到很多实用函数,它们可以看做是os模块的补充。 当前目录下的所有目录 当前文件夹下所有python文件 print [x for x in o... | 493 | zh | 0.908339 |
import sys, os, pwd, signal, time
from resource_management import *
from resource_management.core.base import Fail
from resource_management.core.exceptions import ComponentIsNotRunning
from subprocess import call
from impala_base import ImpalaBase
class StateStore(ImpalaBase):
#Call setup.sh to install the service... | ambari-server/src/main/resources/stacks/HDP/2.5/services/IMPALA/package/scripts/impala-state-store.py | 1,812 | Call setup.sh to install the service Install packages listed in metainfo.xmlCall start.sh to start the serviceself.create_hdfs_user(params.flink_user)Called to stop the service using the pidfileCalled to get status of the service using the pidfile | 247 | en | 0.681077 |
from django.conf import settings
from django.conf.urls import patterns, include
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from peekaboo.base.monkeypatches import patch
patch()
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatt... | peekaboo/urls.py | 1,322 | Uncomment the next two lines to enable the admin: In DEBUG mode, serve media files through Django. Remove leading and trailing slashes so the regex matches. | 156 | en | 0.802614 |
# Un meșter trebuie să paveze întreaga pardoseală a unei bucătării cu formă
# dreptunghiulară de dimensiune L_1×L_2 centimetri, cu plăci de gresie
# pătrate, toate cu aceeași dimensiune. Știind că meșterul nu vrea să taie nici o
# placă de gresie și vrea să folosească un număr minim de plăci, să se
# determine dimensiu... | Lab01/lab01_03.py | 773 | Un meșter trebuie să paveze întreaga pardoseală a unei bucătării cu formă dreptunghiulară de dimensiune L_1×L_2 centimetri, cu plăci de gresie pătrate, toate cu aceeași dimensiune. Știind că meșterul nu vrea să taie nici o placă de gresie și vrea să folosească un număr minim de plăci, să se determine dimensiunea plăcil... | 529 | ro | 0.996377 |
# -*- coding: utf-8 -*- {{{
# vim: set fenc=utf-8 ft=python sw=4 ts=4 sts=4 et:
#
# Copyright 2020, Battelle Memorial Institute.
#
# 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... | requirements.py | 4,209 | -*- coding: utf-8 -*- {{{ vim: set fenc=utf-8 ft=python sw=4 ts=4 sts=4 et: Copyright 2020, Battelle Memorial Institute. 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... | 2,567 | en | 0.874905 |
# --------------------------------------------------------
# Fast R-CNN
# Copyright (c) 2015 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# Written by Ross Girshick
# --------------------------------------------------------
import xml.dom.minidom as minidom
import os
import PIL
import numpy as... | faster_rcnn/datasets/pascal_voc2.py | 29,460 | Return the default path where PASCAL VOC is expected to be installed.
Load the indexes listed in this dataset's image set file.
Load image and bounding boxes info from XML file in the PASCAL VOC
format.
Load image and bounding boxes info from txt file in the pascal subcategory exemplar format.
Return the database of gr... | 3,056 | en | 0.82936 |
#!/usr/bin/env python3
# license removed for brevity
#策略 機械手臂 四點來回跑
import rospy
import os
import numpy as np
from std_msgs.msg import String
from ROS_Socket.srv import *
from ROS_Socket.msg import *
import math
import enum
import .ArmCommand.Hiwin_RT605_Arm_Command as ArmTask
##----Arm state-----------
Arm_state_flag ... | src/.history/Test/HiwinRT605_Strategy_test_20190620132725.py | 10,410 | !/usr/bin/env python3 license removed for brevity策略 機械手臂 四點來回跑----Arm state---------------Arm status enum-----------server feedback arm state----------表示手臂忙碌表示手臂準備表示程式中斷rospy.init_node(NAME)server arm staterospy.spin() spin one-----------switch define------------ changed for v1.5, see below------------class-----------... | 950 | en | 0.362008 |
import argparse
import multiprocessing
import os
import threading
import time
from typing import Any, Tuple, Union, Dict, Optional
from .helper import _get_event, ConditionalEvent
from ... import __stop_msg__, __ready_msg__, __default_host__
from ...enums import PeaRoleType, RuntimeBackendType, SocketType
from ...exce... | jina/peapods/peas/__init__.py | 14,814 | :class:`BasePea` is a thread/process- container of :class:`BaseRuntime`. It leverages :class:`threading.Thread`
or :class:`multiprocessing.Process` to manage the lifecycle of a :class:`BaseRuntime` object in a robust way.
A :class:`BasePea` must be equipped with a proper :class:`Runtime` class to work.
Send terminate ... | 3,583 | en | 0.822705 |
from getpass import getuser
from os.path import abspath, join, exists
from uuid import uuid4
from seisflows.tools import unix
from seisflows.tools.config import ParameterError, SeisflowsParameters, SeisflowsPaths, custom_import
PAR = SeisflowsParameters()
PATH = SeisflowsPaths()
class tiger_md(custom_import('syste... | seisflows/system/tiger_md.py | 1,104 | Specially designed system interface for tiger.princeton.edu
See parent class for more information.
Checks parameters and paths
Submits job | 148 | en | 0.720957 |
# discover devices
# by clach04 (https://github.com/clach04)
# found at https://github.com/codetheweb/tuyapi/issues/5#issuecomment-348799963
# tested with Python 3.6.4 on Gentoo Linux
import socket
import struct
host_port = 6666
host_ip = '239.255.255.250'
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, so... | discover_devices.py | 794 | discover devices by clach04 (https://github.com/clach04) found at https://github.com/codetheweb/tuyapi/issues/5issuecomment-348799963 tested with Python 3.6.4 on Gentoo Linux | 175 | en | 0.734741 |
#
# Copyright 2018 Quantopian, 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 wr... | trading_calendars/exchange_calendar_cmes.py | 3,270 | Exchange calendar for the Chicago Mercantile Exchange (CMES).
Open Time: 5:00 PM, America/Chicago
Close Time: 5:00 PM, America/Chicago
Regularly-Observed Holidays:
- New Years Day
- Good Friday
- Christmas
Copyright 2018 Quantopian, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not us... | 1,424 | en | 0.85711 |
# -*- coding: utf-8 -*-
import xlrd
import pandas as pd
import numpy as np
mirna_sim_path = '../data/miRNA_sim.xlsx'
disease_sim_path = '../data/disease_sim.xlsx'
mirna_disease_ass_path = '../data/miRNA_disease.csv'
mirna_data_dict_path = "../data/mirna_data_dict.npy"
disease_data_dict_path = "../data/disease... | code/get_data.py | 1,936 | -*- coding: utf-8 -*- | 21 | en | 0.767281 |
# Copyright 2019 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/python/ops/ragged/ragged_dynamic_partition_op_test.py | 10,544 | Tests for ragged_array_ops.stack_dynamic_partitions.
Copyright 2019 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/L... | 1,360 | en | 0.720576 |
#!/usr/bin/env python3
# Copyright (c) 2015-2016 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test BIP65 (CHECKLOCKTIMEVERIFY).
Test that the CHECKLOCKTIMEVERIFY soft-fork activates at (regtest) b... | test/functional/feature_cltv.py | 9,108 | Modify the scriptPubKey to add an OP_CHECKLOCKTIMEVERIFY, and make
a transaction that spends it.
This transforms the output script to anyone can spend (OP_TRUE) if the
lock time condition is valid.
Default height is -1 which leads CLTV to fail
TODO: test more ways that transactions using CLTV could be invalid (eg
lo... | 1,418 | en | 0.864028 |
"""
Taken from vithursant's repo:
https://github.com/vithursant/MagnetLoss-PyTorch/blob/master/magnet_loss/magnet_loss.py
"""
import numpy as np
import torch
import torch.nn as nn
from torch.autograd import Variable
import torch.nn.functional as F
class MagnetLoss(nn.Module):
"""
Magnet loss technique presen... | losses/magnet_loss.py | 9,465 | Magnet loss technique presented in the paper:
''Metric Learning with Adaptive Density Discrimination'' by Oren Rippel, Manohar Paluri, Piotr Dollar, Lubomir Bourdev in
https://research.fb.com/wp-content/uploads/2016/05/metric-learning-with-adaptive-density-discrimination.pdf?
Args:
r: A batch of features.
clas... | 2,952 | en | 0.662778 |
# Copyright 2013-2020 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 RIca(RPackage):
"""Independent Component Analysis (ICA) using various algorithms: FastICA,... | var/spack/repos/builtin/packages/r-ica/package.py | 921 | Independent Component Analysis (ICA) using various algorithms: FastICA,
Information-Maximization (Infomax), and Joint Approximate Diagonalization
of Eigenmatrices (JADE).
Copyright 2013-2020 Lawrence Livermore National Security, LLC and other Spack Project Developers. See the top-level COPYRIGHT file for details. SPD... | 361 | en | 0.693083 |
import collections
import caffe2.python.hypothesis_test_util as hu
import hypothesis.strategies as st
import numpy as np
from caffe2.python import core, dyndep, workspace
from caffe2.quantization.server.dnnlowp_test_utils import check_quantized_results_close
from hypothesis import given
dyndep.InitOpsL... | venv/Lib/site-packages/caffe2/quantization/server/gather_dnnlowp_op_test.py | 2,871 | FIXME : DNNLOWP Gather doesn't support quantized input and dequantized output | 77 | en | 0.884437 |
# Copyright 2019 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... | setup.py | 4,455 | This class is needed in order to create OS specific wheels.
TensorFlow Addons.
TensorFlow Addons is a repository of contributions that conform to well-
established API patterns, but implement new functionality not available
in core TensorFlow. TensorFlow natively supports a large number of
operators, layers, metrics, ... | 1,302 | en | 0.887655 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import re
import core.pywikibot as pywikibot
from utils import (
SITE_NAMES,
create_links_string,
read_log,
generate_list_page,
)
def main():
site = pywikibot.Site()
for site_name in SITE_NAMES:
page_name, site_regexp, list_page = generate_l... | outdated/site_update.py | 1,485 | !/usr/bin/python -*- coding: utf-8 -*- | 38 | en | 0.437977 |
from fractions import Fraction
def left_rect(f,x,h):
return f(x)
def mid_rect(f,x,h):
return f(x + h/2)
def right_rect(f,x,h):
return f(x+h)
def trapezium(f,x,h):
return (f(x) + f(x+h))/2.0
def simpson(f,x,h):
return (f(x) + 4*f(x + h/2) + f(x+h))/6.0
def cube(x):
return x*x*x
def reciprocal(x):
re... | lang/Python/numerical-integration-1.py | 1,919 | Tests Extra tests (compute intensive) | 37 | en | 0.778764 |
# -*- coding: utf-8 -*-
import json
import os
from collections import ChainMap
from django.contrib.messages import constants as messages
def bool_from_env(var, default: bool=False) -> bool:
"""Helper for converting env string into boolean.
Returns bool True for string values: '1' or 'true', False otherwise.... | src/ralph/settings/base.py | 19,520 | Helper for converting env string into boolean.
Returns bool True for string values: '1' or 'true', False otherwise.
-*- coding: utf-8 -*- as user expect Only for deployment Application definition adapt message's tags to bootstrap noqa noqa possible values: user, person 100 MB noqa noqa REDIS_SENTINEL_HOSTS env varia... | 2,649 | en | 0.697061 |
# -*- coding: utf-8 -*-
'''
Encapsulate the different transports available to Salt. Currently this is only ZeroMQ.
'''
import salt.payload
import salt.auth
class Channel(object):
@staticmethod
def factory(opts, **kwargs):
# Default to ZeroMQ for now
ttype = 'zeromq'
if 'transport_ty... | salt/transport/__init__.py | 3,245 | Encapsulate sending routines to ZeroMQ.
ZMQ Channels default to 'crypt=aes'
In case of authentication errors, try to renegotiate authentication
and retry the method.
Indeed, we can fail too early in case of a master restart during a
minion state execution call
Encapsulate the different transports available to Salt. C... | 682 | en | 0.848412 |
# Copyright 2019 Xilinx 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, ... | models/AI-Model-Zoo/VAI-1.3-Model-Zoo-Code/PyTorch/pt_personreid-res18_market1501_176_80_1.1G_1.3/code/network/__init__.py | 839 | @author: liaoxingyu
@contact: xyliao1993@qq.com
Copyright 2019 Xilinx 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 app... | 619 | en | 0.841326 |
from django.shortcuts import render,redirect
from django.contrib.auth import login, authenticate
from django.contrib.auth.decorators import login_required
from django.urls.base import reverse
import datetime as dt
from .models import Profile,Project,Rating,User
from .forms import *
from .email import send_welcome_email... | main/views.py | 6,341 | Create your views here. | 23 | en | 0.928092 |
from .fsapi_core import *
import time
from xml.dom import minidom
class FSAPI_Node(object):
NAN = -65536
def __init__(self, fsapi_type: str, fsapi_property_alias: str = None, fsapi_set_method_alias: str = None):
self._fsapi_type = fsapi_type
self._fsapi_property_alias = fsap... | fsapi/fsapi_node.py | 10,707 | TODO: Log proper error | 22 | es | 0.438157 |
import logging
from logging import config
from distutils.util import strtobool
from pgopttune.utils.logger import logging_dict
from pgopttune.config.postgres_server_config import PostgresServerConfig
from pgopttune.config.tune_config import TuneConfig
from pgopttune.config.workload_sampling_config import WorkloadSampli... | sampling_workload.py | 1,962 | read setting parameters PostgreSQL Server config Tuning config(only use debug parameter) Workload Sampling Config logging workload sampling | 139 | en | 0.261923 |
from .fhirbase import fhirbase
class ImplementationGuide(fhirbase):
"""
A set of rules of how FHIR is used to solve a particular problem. This
resource is used to gather all the parts of an implementation guide
into a logical whole and to publish a computable definition of all the
parts.
Attr... | cardea/fhir/ImplementationGuide.py | 16,423 | A set of rules of how FHIR is used to solve a particular problem. This
resource is used to gather all the parts of an implementation guide
into a logical whole and to publish a computable definition of all the
parts.
Attributes:
resourceType: This is a ImplementationGuide resource
url: An absolute URI that is ... | 8,573 | en | 0.852449 |
# Copyright 2015-2015 by Eric Rasche. All rights reserved.
#
# This file is part of the Biopython distribution and governed by your
# choice of the "Biopython License Agreement" or the "BSD 3-Clause License".
# Please see the LICENSE file that should have been included as part of this
# package.
"""Bio.AlignIO support... | Bio/AlignIO/MauveIO.py | 12,949 | Mauve xmfa alignment iterator.
Mauve/XMFA alignment writer.
Initialize.
Parse the next alignment from the handle.
Return (name, start, end) string tuple from an identifier (PRIVATE).
Write a single SeqRecord to the file (PRIVATE).
Use this to write (another) single alignment to an open file.
Note that sequences and th... | 4,680 | en | 0.691125 |
import logging
import os
import json
import tensorflow as tf
import pandas as pd
import numpy as np
from tqdm import tqdm
import datetime
from pdb import set_trace
from time import sleep
from openpyxl import load_workbook, Workbook
from openpyxl.worksheet.table import Table
from tensorflow.keras.losses import categoric... | cvnn/montecarlo.py | 52,503 | Inherits from MonteCarlo. Compares a complex model with it's real equivalent.
Example usage:
```
# Assume you already have complex data 'x' with its labels 'y'... and a Cvnn model.
montecarlo = RealVsComplex(complex_model)
montecarlo.run(x, y)
```
Class that allows the statistical comparison of several models on the ... | 17,142 | en | 0.704429 |
# -*- coding: utf-8 -*-
from typing import Text
from zerver.lib.test_classes import WebhookTestCase
class DropboxHookTests(WebhookTestCase):
STREAM_NAME = 'test'
URL_TEMPLATE = "/api/v1/external/dropbox?&api_key={api_key}&stream={stream}"
FIXTURE_DIR_NAME = 'dropbox'
def test_file_updated(self) -> No... | zerver/webhooks/dropbox/tests.py | 1,186 | -*- coding: utf-8 -*- | 21 | en | 0.767281 |
from typing import Dict, Iterator, List, Optional, Tuple, Union
from ..constant.util import Amount, ItemPointer, Number
from .item_wrapper import item_type
from .other_wrapper import *
__all__ = [
'ItemType', 'Item', 'Empty',
'Accessory', 'EnchantedBook', 'ReforgeStone', 'TravelScroll',
'Bow', 'Sword',
... | skyblock/object/object.py | 7,381 | common | uncommon | rare | epic | legendary | mythic | supreme | special | very_special helmet | chestplate | leggings | boots slayer_req: Optional[Tuple[str, int]] = None slayer_req: Optional[Tuple[str, int]] = None | 216 | en | 0.619037 |
# Copyright 2015 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/controllers/collection_viewer.py | 4,157 | Provides the data for a single collection.
Page describing a single collection.
Handles GET requests.
Populates the data on the individual collection page.
Decorator that checks if the user can play the given collection.
Check if the current user can play the collection.
Controllers for the Oppia collection learner vie... | 902 | en | 0.842183 |
"""Tools for converting to other outputs."""
def to_getdist(nested_samples):
"""Convert from anesthetic to getdist samples.
Parameters
----------
nested_samples: MCMCSamples or NestedSamples
anesthetic samples to be converted
Returns
-------
getdist_samples: getdist.mcsamples.MCS... | anesthetic/convert.py | 894 | Convert from anesthetic to getdist samples.
Parameters
----------
nested_samples: MCMCSamples or NestedSamples
anesthetic samples to be converted
Returns
-------
getdist_samples: getdist.mcsamples.MCSamples
getdist equivalent samples
Tools for converting to other outputs. | 282 | en | 0.516571 |
#!/usr/bin/python
from ansible.module_utils.basic import AnsibleModule
def main():
# Define your modules arguments
module_args = dict(
name=dict(type="str", required=True),
new=dict(type="bool", required=False, default=False),
)
# Create an instance of the AnsibleModule class
mo... | bonus2/collateral/modules/library/test_module.py | 611 | !/usr/bin/python Define your modules arguments Create an instance of the AnsibleModule class Define standard results Return items as JSON | 137 | en | 0.338098 |
# -*- coding: utf-8 -*-
# @Time : 2019/7/18 上午9:54
# @Author : Lart Pang
# @FileName: metric.py
# @Project : MINet
# @GitHub : https://github.com/lartpang
import numpy as np
def cal_pr_mae_meanf(prediction, gt):
assert prediction.dtype == np.uint8
assert gt.dtype == np.uint8
assert prediction.shape ... | code/utils/metric.py | 2,605 | -*- coding: utf-8 -*- @Time : 2019/7/18 上午9:54 @Author : Lart Pang @FileName: metric.py @Project : MINet @GitHub : https://github.com/lartpang 确保图片和真值相同 if prediction.shape != gt.shape: prediction = Image.fromarray(prediction).convert('L') gt_temp = Image.fromarray(gt).convert('L') prediction = predic... | 425 | en | 0.279835 |
import os
import logging
from typing import Dict, Union
from datetime import timedelta
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import pandas as pd
import mlflow
import torch
import pytorch_lightning as pl
import pprint
pp = pprint.PrettyPrinter(indent=4)
from arnet i... | arnet/modeling/learner.py | 13,869 | model: torch.nn.Module
cfg: model-agnostic experiment configs
Compute each parameter's gradient's norm and their overall norm.
The overall norm is computed over all gradients together, as if they
were concatenated into a single vector.
Args:
norm_type: The type of the used p-norm, cast to float if necessary.
... | 2,242 | en | 0.627531 |
import sys
import json
import scrapapps
import scrapping
from textrank import TextRankSentences
import preprocessing
import summ
import textrankkeyword
import bss4
url = sys.argv[1]
# url = request.POST.get('web_link', None)
#web_link = scrapapps.scrap_data(url)
web_link = scrapping.scrap_data(url)
#Get Title
judul... | file/py/result_mashara.py | 2,171 | url = request.POST.get('web_link', None)web_link = scrapapps.scrap_data(url)Get Title Preprocessing View Skenario 1 n = 10; if len(stagging) < 10: n = 5 if len(stagging) == 10: n = len(stagging) - 2 if len(stagging) > 30: n = 15 if len(stagging) < 5: n = len(stagging) - 1 if len(stagging) == 1: n = len(stagging) S... | 553 | en | 0.194994 |
import os
import logging, glob
from pathlib import Path
from functools import reduce, partial
from operator import getitem
from datetime import datetime
# from .logger import setup_logging
# import logger.setup_logging
# from . import logger
from .logger import setup_logging
from .util import read_json, write_json
# pr... | code/utils/parse_config.py | 7,179 | Access items like ordinary dict.
class to parse configuration json file. Handles hyperparameters for training, initializations of modules, checkpoint saving
and logging module.
:param config: Dict containing configurations, hyperparameters for training. contents of `config.json` file for example.
:param resume: String,... | 2,278 | en | 0.613527 |
'''
Scenario discovery utilities used by both :mod:`cart` and :mod:`prim`
'''
from __future__ import (absolute_import, print_function, division,
unicode_literals)
import abc
import enum
import itertools
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.patches as patche... | ema_workbench/analysis/scenario_discovery_util.py | 22,617 | Parameters
----------
x : DataFrame
y : np.array
box : DataFrame
Hbox : int
Tbox : int
compare two boxes, for each dimension return True if the
same and false otherwise
determine the number of restriced dimensions of a box given
compared to the inital box that contains all the data
Parameters
----------
box_lims : str... | 5,781 | en | 0.586155 |
import sys
import os
from cx_Freeze import setup, Executable
# because of how namespace packages work, cx-freeze isn't finding zope.interface
# the following will import it, find the path of zope, and add a new empty
# file name _init__.py at the /site-packages/python2.7/zope path.
# this was found here:
# https://bit... | setup.py | 910 | because of how namespace packages work, cx-freeze isn't finding zope.interface the following will import it, find the path of zope, and add a new empty file name _init__.py at the /site-packages/python2.7/zope path. this was found here: https://bitbucket.org/anthony_tuininga/cx_freeze/issues/47/cannot-import-zopeinterf... | 419 | en | 0.793732 |
# -*- coding: utf-8 -*
'''问卷数据分析工具包
Created on Tue Nov 8 20:05:36 2016
@author: JSong
1、针对问卷星数据,编写并封装了很多常用算法
2、利用report工具包,能将数据直接导出为PPTX
该工具包支持一下功能:
1、编码问卷星、问卷网等数据
2、封装描述统计和交叉分析函数
3、支持生成一份整体的报告和相关数据
'''
import os
import re
import sys
import math
import time
import pandas as pd
import numpy as np
import matplo... | reportgen/questionnaire/questionnaire.py | 121,305 | 方差分析
输入
--data: DataFrame格式,包含数值型变量和分类型变量
--formula:变量之间的关系,如:数值型变量~C(分类型变量1)[+C(分类型变量1)[+C(分类型变量1):(分类型变量1)]
返回[方差分析表]
[总体的方差来源于组内方差和组间方差,通过比较组间方差和组内方差的比来推断两者的差异]
--df:自由度
--sum_sq:误差平方和
--mean_sq:误差平方和/对应的自由度
--F:mean_sq之比
--PR(>F):p值,比如<0.05则代表有显著性差异
关联规则分析
df: DataFrame,bool 类型。是一个类似购物篮数据
ftime 是完成问卷的秒数
思路:
1、只... | 11,122 | zh | 0.718491 |
# -*- coding: utf-8 -*-
"""Functions for retrieving raw and processed run data"""
from datetime import datetime
from html_table_parser import HTMLTableParser
from utils import convert_numbers
import commands
import vcf
def laneHTML(run, path):
"""Retrieve data from the lane.html page, the data is the general run... | scripts/upload/data/import_data.py | 14,835 | -*- coding: utf-8 -*- tables[1]==run tables[2]==lane tables[1]==run tables[2]==sample dic_samples[sample name] = [number of variant, Percentage dbSNP variants from total, Percentage PASS variants from total] sample_dup[sample name] = duplication there is a None at the end of each line | 285 | en | 0.762057 |
"""
Consensus Algorithm for 2 Robots using MLP Model
Scene: Robot 1, Robot 3
Inputs: Mx, My
Outputs: Ux, Uy
"""
import torch
import MLP_Model
import math
import numpy as np
import rclpy
from rclpy.node import Node
from tf2_msgs.msg import TFMessage
from std_msgs.msg import Float32
import time
L = 1
d = 0.5
# load... | Real Topology Graph/GNN Model 2/Cyclic Graph/test_n2_robot3.py | 6,982 | Calculate Mx1, My1, ...... Mx6, My6
Consensus Algorithm for 2 Robots using MLP Model
Scene: Robot 1, Robot 3
Inputs: Mx, My
Outputs: Ux, Uy
load model using dict in radiansChange according to topic in child script,String to Float32Change according to topic in child script,String to Float32Change according to topic... | 871 | en | 0.750398 |
# pylint: disable=missing-docstring
# pylint: disable=unbalanced-tuple-unpacking
import os
from resdk.tests.functional.base import BaseResdkFunctionalTest
class TestUpload(BaseResdkFunctionalTest):
def get_samplesheet(self):
"""Return path of an annotation samplesheet."""
files_path = os.path.no... | resdk/tests/functional/data_upload/e2e_upload.py | 19,017 | Return path of an annotation samplesheet.
pylint: disable=missing-docstring pylint: disable=unbalanced-tuple-unpacking Create the collection with named, unannotated samples Two different samples A duplicated sample A sample derived from an alignment file Missing organism Missing source Apply the sample annotations fr... | 4,052 | en | 0.673844 |
from typing import Dict
import pyarrow as pa
import regex as re
from feast import ValueType
def trino_to_feast_value_type(trino_type_as_str: str) -> ValueType:
type_map: Dict[str, ValueType] = {
"tinyint": ValueType.INT32,
"smallint": ValueType.INT32,
"int": ValueType.INT32,
"int... | sdk/python/feast/infra/offline_stores/contrib/trino_offline_store/trino_type_map.py | 3,230 | PyArrow types: https://arrow.apache.org/docs/python/api/datatypes.html Trino type: https://trino.io/docs/current/language/types.html | 132 | en | 0.535711 |
from psutil import virtual_memory, cpu_freq, disk_usage, cpu_percent, cpu_count, swap_memory
from subprocess import check_output
#from termcolor import colored
from colorhex import colorex, BOLD, BLINKING, UNDERLINE, ITALIC
from time import sleep
from sys import exit
from os import system
CPU_MODEL = check_out... | pymn_v6.py | 6,894 | from termcolor import colored | 29 | en | 0.638816 |
import signal
import sys
import logging
import decimal
import datetime
from pymysqlreplication import BinLogStreamReader
from pymysqlreplication.row_event import (
DeleteRowsEvent,
UpdateRowsEvent,
WriteRowsEvent,
)
def mysql_stream(conf, mongo, queue_out):
logger = logging.getLogger(__name__)
#... | mymongolib/mysql.py | 4,127 | server_id is your slave identifier, it should be unique. set blocking to True if you want to block and wait for the next event at the end of the stream mysql 基础配置 只查询当前表的事件 只查询当前的数据库 event_type, vals = None, None 将事件类型和记录数值写入数据库中 将返回的 _id 当做序列号返回 刷新 log 日志的位置 将 _id 作为 seqnum 插入队列中 将非int数据全部转换为 str后续可能在导入的时候转换 则这里就是全部为 ... | 824 | zh | 0.445539 |
#Program to plot a point
from cg_algorithms.circle_algorithms import circle_algorithms
from OpenGL.GL import *
from OpenGL.GLU import *
from OpenGL.GLUT import *
import sys
import math
import time
def init():
glClearColor(0.0, 0.0, 0.0, 0.0)
gluOrtho2D(-250.0, 250.0, -250.0, 250.0)
def plot_points():
g... | tests/test_circle.py | 895 | Program to plot a point | 23 | en | 0.910665 |
from __future__ import absolute_import, division, print_function
import pytest
pytest.importorskip('numpy')
import dask.array as da
from dask.array.utils import assert_eq as _assert_eq
from dask.core import get_deps
from dask.context import set_options
import numpy as np
# temporary until numpy functions migrated
tr... | webpage/lib/python3.5/site-packages/dask/array/tests/test_reductions.py | 13,593 | temporary until numpy functions migrated pragma: no cover Difference in dtype algo Difference in dtype algo Difference in dtype algo Difference in dtype algo chunks are a mix of some/all/no NaNs Poorly conditioned Tree reduction 2D 3D | 234 | en | 0.734738 |
#!/usr/bin/python
import sdk_common
import yaml
import re
import uuid
import random
import os
import time
# Block in charge of running integration tests (using Docker compose)
class SDKIntegrationTestRunner(sdk_common.BuildStepUsingGradle):
def __init__(self, logger=None):
super(SDKIntegrationTestRunner, ... | scripts/sdk_run_integration_tests.py | 6,322 | !/usr/bin/python Block in charge of running integration tests (using Docker compose) self.log_info("Building test server docker image") arguments = ["docker-compose", "build"] return_code = self.call_command(arguments, None, True) if return_code != 0: raise Exception('Error code', return_code) The failure of the co... | 424 | en | 0.5738 |
#!/usr/bin/env python
import numpy as np
import scipy
from shared_utils import ArrayUtils
class SkellamMetrics:
def __init__(self, x_metrics, y_metrics, y_hat, model, l0, l1, training_values):
self._y = y_metrics
self._y_hat = y_hat
self.model = model
self.l0 = ArrayUtils.convert_t... | metrics/__init__.py | 4,777 | Create arrays for our predictions of the two Poisson distributions
Calculate p values for our two sets of coefficients
Calculate robust variance covariance matrices for our two sets of coefficients
Calculate robust standard errors for our two sets of coefficients by taking the square root of ... | 865 | en | 0.808176 |
#!/bin/env python
# -*- coding: utf-8 -*-
"""test Queue
by Valentyn Stadnytskyi
created: August 2, 2019
This is a test library to evaluate the performance of the code.
Queue is an abstract data structure, somewhat similar to Stacks.
Unlike stacks, a queue is open at both its ends.
One ... | circular_buffer_numpy/tests/test_circular_buffer.py | 4,626 | test if the default pointer in the buffer is -1.
test if the default pointer in the buffer is -1.
test Queue
by Valentyn Stadnytskyi
created: August 2, 2019
This is a test library to evaluate the performance of the code.
Queue is an abstract data structure, somewhat similar to Stacks.
Unlike stacks, a queue is open at... | 697 | en | 0.815812 |
from __future__ import absolute_import
from contextlib import contextmanager
from mock import Mock, patch
from celery import states
from celery.exceptions import IncompleteStream, TimeoutError
from celery.five import range
from celery.result import (
AsyncResult,
EagerResult,
TaskSetResult,
result_fro... | p2p/lib/python2.7/site-packages/celery/tests/tasks/test_result.py | 23,342 | has RETRY state has RETRY state | 31 | en | 0.997474 |
from future import standard_library
standard_library.install_aliases()
from builtins import zip
from contextlib import contextmanager
import datetime
import io
import os
import time
import tempfile
import xml.etree.ElementTree as ET
from salesforce_bulk.util import IteratorBytesIO
from sqlalchemy.ext.automap import a... | cumulusci/tasks/bulkdata.py | 32,391 | Initiate a bulk insert and upload batches to run in parallel.
Download the bulk API result file for a single batch
Get data from the local db
Returns the first mapping for a table name
Load data for a single step.
Build a query to retrieve data from the local db.
Includes columns from the mapping
as well as joining t... | 2,859 | en | 0.803144 |
# 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 or ag... | google-cloud-sdk/.install/.backup/lib/googlecloudsdk/core/diagnostics/diagnostic_base.py | 3,354 | Base class for diagnostics.
Attributes:
intro: A message to introduce the objectives and tasks of the diagnostic.
title: The name of the diagnostic.
checklist: An iterator of checkbase.Check objects to be run by the
diagnostic.
Runs one or more checks, tries fixes, and outputs results.
Returns:
True if t... | 1,294 | en | 0.838603 |
# -----------------------------------------------------------------------------
# Copyright (c) 2020 Nicolas P. Rougier. All rights reserved.
# Distributed under the (new) BSD License.
# -----------------------------------------------------------------------------
import numpy as np
import hypyp.ext.mpl3d.glm as glm
fr... | hypyp/ext/mpl3d/camera.py | 4,511 | Interactive trackball camera.
This camera can be used for static or interactive rendering with mouse
controlled movements. In this latter case, it is necessary to connect the
camera to a matplotlib axes using the `connect` method and to provide an
update function that will be called each time an update is necessary
re... | 1,222 | en | 0.734435 |
import numpy as np
import os
import pickle
import pytest
import re
import time
import shutil
from copy import deepcopy
from numpy import allclose, isclose
from flare import struc, env, gp
from flare.parameters import Parameters
from flare.mgp import MappedGaussianProcess
from flare.lammps import lammps_calculator
fro... | tests/test_mgp.py | 12,765 | test the mapping for mc_simple kernel
test the predict for mc_simple kernel
test the init function
test the lammps implementation
test the mapping for mc_simple kernel
test the predict for mc_simple kernel
test the mapping for mc_simple kernel
set up executable for ASE set up input params create ASE calc grid paramet... | 1,084 | en | 0.631007 |
# GENERATED VERSION FILE
# TIME: Fri May 21 12:58:40 2021
__version__ = '0.1.0+62e3868'
short_version = '0.1.0'
version_info = (0, 1, 0)
| qdtrack/version.py | 137 | GENERATED VERSION FILE TIME: Fri May 21 12:58:40 2021 | 53 | en | 0.750826 |
"""
MTGJSON EnumValues Object
"""
import json
import logging
import pathlib
from typing import Any, Dict, List, Union
from ..compiled_classes.mtgjson_all_printings import MtgjsonAllPrintingsObject
from ..consts import OUTPUT_PATH
from ..utils import sort_internal_lists
from .mtgjson_structures import MtgjsonStructures... | mtgjson5/compiled_classes/mtgjson_enum_values.py | 5,527 | MTGJSON EnumValues Object
Initializer to build the internal mapping
Given Decks Path, compile enums based on the types found in the files
:param decks_directory: Path to the decks/ output directory
:return Sorted list of enum options for each key
Given AllPrintings, compile enums based on the types found in the file
:p... | 715 | en | 0.725902 |
#!/usr/bin/env python3
import sys
import chpl_platform, overrides, third_party_utils
from utils import error, memoize, warning
@memoize
def get():
platform_val = chpl_platform.get('target')
linux = platform_val.startswith('linux64')
osx = platform_val.startswith('darwin')
val = overrides.get('CHPL_UN... | util/chplenv/chpl_unwind.py | 2,068 | !/usr/bin/env python3 Mac OS X supports libunwind in the C library it's not actually a special library. Get the link arguments (e.g. -lunwind) Try using pkg-config to get the libraries to link libunwind with. the pkg-config file for libunwind is nice, but as of 1.1 it doesn't include -lzma when it probably should. So t... | 400 | en | 0.849108 |
#!/usr/bin/env python3
# Copyright 2020 The Emscripten Authors. All rights reserved.
# Emscripten is available under two separate licenses, the MIT license and the
# University of Illinois/NCSA Open Source License. Both these licenses can be
# found in the LICENSE file.
import json
import os
import re
import shutil
... | tests/benchmark_sse.py | 11,806 | !/usr/bin/env python3 Copyright 2020 The Emscripten Authors. All rights reserved. Emscripten is available under two separate licenses, the MIT license and the University of Illinois/NCSA Open Source License. Both these licenses can be found in the LICENSE file. System info Native info Emscripten info Run native build... | 514 | en | 0.650492 |
# coding=utf-8
import json
import urllib
import urllib2
from bs4 import BeautifulSoup
def run(bot, chat_id, user, keyConfig='', message='', totalResults=1):
requestText = str(message)
if requestText == '':
totalSteamGames = int(Get_steam_total())
totalGOGGames = int(Get_GOG_total())
... | telegram_commands/getgame.py | 10,840 | coding=utf-8this bypasses the "mature content - continue/cancel" screenthis bypasses the "enter your date of birth" screenif 'links' in data and 'product_card' in data['links']: AllGameDetailsFormatted += data['links']['product_card'] + '\n'if 'release_date' in data: AllGameDetailsFormatted += 'Release Date: ' + ... | 347 | en | 0.561408 |
import logging
from typing import Dict, Sequence
from talon import Context, Module, actions
from .user_settings import get_list_from_csv
mod = Module()
ctx = Context()
mod.list("vocabulary", desc="additional vocabulary words")
# Default words that will need to be capitalized.
# DON'T EDIT THIS. Edit settings/words... | code/vocabulary.py | 6,262 | Utility for replacing phrases by other phrases inside text or word lists.
Replacing longer phrases has priority.
Args:
- phrase_dict: dictionary mapping recognized/spoken forms to written forms
Default words that will need to be capitalized. DON'T EDIT THIS. Edit settings/words_to_replace.csv instead. These defau... | 2,305 | en | 0.90345 |
# coding: utf-8
"""
Decision Lens API
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) # noqa: E501
OpenAPI spec version: 1.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
impor... | python/test/test_project_attachment_removed_message_payload.py | 1,103 | ProjectAttachmentRemovedMessagePayload unit test stubs
Test ProjectAttachmentRemovedMessagePayload
Decision Lens API
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) # noqa: E501
OpenAPI spec version: 1.0
Generated by: https://github.com/swagger-api/swagger-codeg... | 542 | en | 0.592884 |
#!/usr/bin/env python3
import sys
def gen_freq(freq: float, duration: int):
tmp = 0.0
pri = chr(32)
sec = chr(126)
for i in range(duration):
if (tmp >= freq):
tmp -= freq
pri, sec = sec, pri
tmp += 1.0
print(pri, end='')
sys.stdout.flush()
if __name... | .pake/pkgdir/files/opt/nplayer/gen_freq.py | 420 | !/usr/bin/env python3 | 21 | fr | 0.448822 |
# coding=utf-8
# *** WARNING: this file was generated by pulumigen. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union
from ... import _utilities, _tables
from . import outpu... | sdk/python/pulumi_kubernetes/events/v1/outputs.py | 14,627 | Event is a report of an event somewhere in the cluster. It generally denotes some state change in the system. Events have a limited retention time and triggers and messages may evolve with time. Event consumers should not rely on the timing of an event with a given Reason reflecting a consistent underlying trigger, or... | 7,639 | en | 0.893261 |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-03-17 21:35
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('UserManagement', '0028_auto_20170316_1206'),
]
operations = [
migrations.Ad... | UserManagement/migrations/0029_course_institution_abbr.py | 489 | -*- coding: utf-8 -*- Generated by Django 1.10.5 on 2017-03-17 21:35 | 68 | en | 0.655803 |
"""Models for assessing primal feasibility"""
from __future__ import unicode_literals
from .set import ConstraintSet
from ..nomials import Variable, VectorVariable, parse_subs, NomialArray
from ..keydict import KeyDict
from .. import NamedVariables, SignomialsEnabled
class ConstraintsRelaxedEqually(ConstraintSet):
... | gpkit/constraints/relax.py | 6,705 | Relax constants in a constraintset.
Arguments
---------
constraints : iterable
Constraints which will be relaxed (made easier).
include_only : set (optional)
variable names must be in this set to be relaxed
exclude : set (optional)
variable names in this set will never be relaxed
Attributes
----------
... | 2,029 | en | 0.872077 |
from typing import Tuple
import yaml
class World:
world = None
"""
The first index is the Y coordinate, and the second index is the X coordinate
:type world: List[List[int]]
"""
width = None
"""
:type width: int
"""
height = None
"""
:type height: int
"""
d... | src/B2/world.py | 1,339 | Create an empty world If our row is an even row, it is a horizontal row. All the streets have an offset of +1 on a horizontal row | 129 | en | 0.846565 |
import os
import sys
sys.path.append('../')
import speedify
from speedify import State, Priority, SpeedifyError, SpeedifyAPIError
import speedifysettings
import speedifyutil
import logging
import unittest
import time
logging.basicConfig(handlers=[logging.FileHandler('test.log'),logging.StreamHandler(sys.stdout)],forma... | tests/test_speedify.py | 13,727 | Test the speedify library assumes you're logged inNote doesn't test login/logout. but then we have to deal with credentials being stored. to make sure runtime changed, could check stats and look for connectionstats : connections[] : protocollogging.disable(logging.ERROR);logging.disable(logging.NOTSET)pull settings fr... | 1,379 | en | 0.912694 |
"""
Adds the source files to the path for files in any subdirectory
TODO: check that we have not alredy added to our path.
"""
import os
import sys
fileLocation = os.path.dirname(os.path.abspath(__file__))
sourceLocation = os.path.abspath(os.path.join(fileLocation, 'RCWA/source/'))
nkLocation = os.path.abspath(os.path... | context.py | 645 | Adds the source files to the path for files in any subdirectory
TODO: check that we have not alredy added to our path. | 118 | en | 0.858506 |
# -*- coding: utf-8 -*-
from operator import attrgetter
from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType
from pyangbind.lib.yangtypes import RestrictedClassType
from pyangbind.lib.yangtypes import TypedListType
from pyangbind.lib.yangtypes import YANGBool
from pyangbind.lib.yangtypes import YANGListTy... | napalm_yang/models/openconfig/interfaces/interface/subinterfaces/subinterface/ipv4/unnumbered/interface_ref/config/__init__.py | 9,689 | This class was auto-generated by the PythonClass plugin for PYANG
from YANG module openconfig-interfaces - based on the path /interfaces/interface/subinterfaces/subinterface/ipv4/unnumbered/interface-ref/config. Each member element of
the container is represented as a class variable - with a specific
YANG type.
YANG D... | 2,426 | en | 0.593299 |
#
# Copyright 2020 The FATE 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 ... | fate-manager/hyperion/entity/types.py | 5,047 | Copyright 2020 The FATE 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 law or agreed to in ... | 575 | en | 0.869725 |
# testing/assertions.py
# Copyright (C) 2005-2021 the SQLAlchemy authors and contributors
# <see AUTHORS file>
#
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
from __future__ import absolute_import
import contextlib
import re
import sys... | lib/sqlalchemy/testing/assertions.py | 23,007 | assert that any exception we're catching does not have a __context__
without a __cause__, and that __suppress_context__ is never set.
Python 3 will report nested as exceptions as "during the handling of
error X, error Y occurred". That's not what we want to do. we want
these exceptions in a cause chain.
As assert_res... | 3,139 | en | 0.890451 |
import collections
import datetime
from django.utils.translation import gettext_lazy as _
from .base import * # noqa
# Override static and media URL for prefix in WSGI server.
# https://code.djangoproject.com/ticket/25598
STATIC_URL = '/2016/static/'
MEDIA_URL = '/2016/media/'
CONFERENCE_DEFAULT_SLUG = 'pycontw... | src/pycontw2016/settings/production/pycontw2016.py | 655 | noqa Override static and media URL for prefix in WSGI server. https://code.djangoproject.com/ticket/25598 | 105 | en | 0.707523 |
"""llvm
Tool-specific initialization for LLVM
"""
#
# Copyright (c) 2009 VMware, Inc.
#
# 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 ... | scons/llvm.py | 12,980 | llvm
Tool-specific initialization for LLVM
Copyright (c) 2009 VMware, Inc. 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, co... | 2,062 | en | 0.793994 |
#!/usr/bin/env python
# In this example we show the use of the
# vtkBandedPolyDataContourFilter. This filter creates separate,
# constant colored bands for a range of scalar values. Each band is
# bounded by two scalar values, and the cell data lying within the
# value has the same cell scalar value.
import vtk
from... | Examples/VisualizationAlgorithms/Python/BandContourTerrain.py | 4,282 | !/usr/bin/env python In this example we show the use of the vtkBandedPolyDataContourFilter. This filter creates separate, constant colored bands for a range of scalar values. Each band is bounded by two scalar values, and the cell data lying within the value has the same cell scalar value. The lookup table is similar ... | 951 | en | 0.857383 |
# Copyright 2017 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.
#
#... | deeptrio/variant_caller_test.py | 21,412 | A placeholder VariantCaller.
This class provides a get_candidates implementation and so allows
the base class to be instantiated and its methods tested.
Tests that we don't blow up when the coverage gets really high.
Tests for deepvariant .variant_caller.
Copyright 2017 Google LLC. Redistribution and use in source a... | 4,659 | en | 0.845665 |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
import enum
from typing import Dict
@enum.unique
class EmbOptimType(enum.Enum):
SGD =... | fbgemm_gpu/fbgemm_gpu/split_embedding_configs.py | 2,759 | !/usr/bin/env python3 Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. This source code is licensed under the BSD-style license found in the LICENSE file in the root directory of this source tree. uses non-deterministic updates (atomicAdd(..)) with duplicate ids uses deterministic updates (via sort... | 493 | en | 0.779103 |
"""
Builder for web assembly
"""
import subprocess
import sys
from SCons.Script import AlwaysBuild, Default, DefaultEnvironment
try:
subprocess.check_output(["em++", "--version"])
except FileNotFoundError:
print(
"Could not find emscripten. Maybe install it? (e.g. `brew install emscripten` on macO... | builder/main.py | 718 | Builder for web assembly
Target: Build wasm Default targets | 61 | en | 0.588407 |
#!/usr/bin/env python
# coding=utf-8
# Copyright 2020 The HuggingFace Inc. team. 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/LI... | examples/pytorch/text-classification/run_glue.py | 23,860 | Arguments pertaining to what data we are going to input our model for training and eval.
Using `HfArgumentParser` we can turn this class
into argparse arguments to be able to specify them on
the command line.
Arguments pertaining to which model/config/tokenizer we are going to fine-tune from.
Finetuning the library mo... | 4,542 | en | 0.840931 |
from tkinter import *
#Palomo, Nemuel Rico O.
class ButtonLab:
def __init__(self, window):
self.color = Button(window, text='Color', fg='red', bg='blue')
self.button = Button(window, text='<---Click to change the color of the button :)', fg='black', command=self.changeColor)
self... | Lab (The Coders) #5.py | 613 | Palomo, Nemuel Rico O. | 22 | fr | 0.150451 |
# BEGIN GENERATED CONTENT (do not edit below this line)
# This content is generated by ./gengl.py.
# Wrapper for /usr/include/GL/glx.h
from OpenGL import platform, constant
from ctypes import *
c_void = None
# H (/usr/include/GL/glx.h:26)
GLX_VERSION_1_1 = constant.Constant( 'GLX_VERSION_1_1', 1 )
GLX_VERSION_1_2 = ... | PyOpenGL-3.0.2/OpenGL/raw/_GLX.py | 35,907 | BEGIN GENERATED CONTENT (do not edit below this line) This content is generated by ./gengl.py. Wrapper for /usr/include/GL/glx.h H (/usr/include/GL/glx.h:26) /usr/include/GL/glx.h:178 /usr/include/X11/X.h:66 /usr/include/GL/glx.h:179 /usr/include/GL/glx.h:180 /usr/include/GL/glx.h:182 /usr/include/GL/glx.h:183 /usr/inc... | 6,408 | en | 0.151555 |
#!/usr/bin/python3
import gameinstance
from colour import Colour
from constants import Constants
from vec2 import vec2
from misc import Fade
import sdl2
import hud
class Menu(gameinstance.GameInstance):
"""Game menu representation."""
# Variables to control menu background.
backgrounds = []
current_bg = 0
bg_o... | menu.py | 3,426 | Game menu representation.
Process relevant events.
Returns False if GameInstance should be no longer active.
Render scene.
Update game state.
!/usr/bin/python3 Variables to control menu background.250bg_offset_at_start0x880xff0.33 Background stuff. | 249 | en | 0.580765 |
from .config import *
import MySQLdb
class DBReader:
def __init__(self):
self.conn = None
self.db = None
# Initalize the connection
self.db = MySQLdb.connect(user=DB_USER, passwd=DB_PASS, db=DB_NAME, host=DB_HOST,
port=DB_PORT)
if self.db ==... | killerbee/dblog.py | 8,219 | Initalize the connectiondatasource must be provided if DBLogger is desired Initalize the connectionthis backup check may be redundant Set the ds_id attribute to correspond to the requested data source name Use values in 'full' parameter to provide data for undefined other parameters Get the location ID, or create one, ... | 782 | en | 0.666083 |
from keras.preprocessing.image import img_to_array
import imutils
import cv2
from keras.models import load_model
import numpy as np
import geocoder
import streamlink
#import mysql.connector as con
#mydb = con.connect(
# host="localhost",
# user="yourusername",
# passwd="yourpassword",
# database="mydatabase"
#)
#my... | src/ActuarialIntelligence.Infrastructure.PythonScripts/StreamFootageAnalyse.py | 4,041 | import mysql.connector as conmydb = con.connect( host="localhost", user="yourusername", passwd="yourpassword", database="mydatabase")mycursor = mydb.cursor() parameters for loading data and images hyper-parameters for bounding boxes shape loading modelsfeelings_faces = []for index, emotion in enumerate(EMOTIONS): fe... | 1,017 | en | 0.430182 |
from collections import namedtuple
from datetime import datetime
import pprint
import pickle
import json
import sqlite3
BUILDINGS = ['AGNEW', 'LARNA', 'AJ E', 'AJPAV', 'AQUAC', 'AA', 'ADRF', 'ARMRY', 'ART C', 'BEEF', 'BFH', 'BRNCH', 'PRC', 'BURCH', 'BUR', 'CAM', 'CARNA', 'CAM M', 'CAPRI', 'CSB', 'LIBR', 'COL', 'CMMID... | scraper/processor.py | 7,730 | Load buildings and rooms Load classes | 37 | en | 0.92727 |
import glob
import argparse
import os
import shutil
"""
This module helps to filter only the images
that have binary masks within a dataset
"""
if __name__ == '__main__':
# Parse command line arguments
parser = argparse.ArgumentParser(
description='Filter masked data from dataset')
parser.add... | samples/uvas/utils/filter_with_mask.py | 1,112 | Parse command line argumentsCreate paths if not existsOpen the train_masked.txt Copying files | 94 | en | 0.466998 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.