max_stars_repo_path stringlengths 4 245 | max_stars_repo_name stringlengths 7 115 | max_stars_count int64 101 368k | id stringlengths 2 8 | content stringlengths 6 1.03M |
|---|---|---|---|---|
genie/2.2.1/example/run_pig_job_2.py | jrobinson17/netflixossgenieapp | 353 | 11030814 | <reponame>jrobinson17/netflixossgenieapp
#!/usr/bin/python2.7
# Copyright 2015 Netflix, 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.... |
scipy/special/basic.py | Ennosigaeon/scipy | 353 | 11030883 | # Deprecated in SciPy 1.4
from ._basic import *
from warnings import warn as _warn
_warn(
'scipy.special.basic is deprecated, '
'import directly from scipy.special instead',
category=DeprecationWarning,
stacklevel=2
)
|
test/run/t333.py | timmartin/skulpt | 2,671 | 11030887 | x = "Please make startswith and endswith work"
if x.startswith("Please") :
print "Starts with Please"
else:
print "Not good"
if x.endswith("work") :
print "Ends with work"
else:
print "Not good"
if x.startswith("please") :
print "Not good"
else:
print "Does not start with please"
if x.endswit... |
test/extensions/filters/network/thrift_proxy/driver/finagle/TFinagleServerProtocol.py | dcillera/envoy | 17,703 | 11030890 | <reponame>dcillera/envoy<filename>test/extensions/filters/network/thrift_proxy/driver/finagle/TFinagleServerProtocol.py
from thrift.protocol import TBinaryProtocol
from gen.twitter.finagle.thrift.ttypes import (RequestHeader, ResponseHeader)
class TFinagleServerProtocolFactory(object):
def getProtocol(self, tran... |
cuegui/tests/CueJobMonitorTree_tests.py | mb0rt/OpenCue | 334 | 11030895 | # Copyright (c) OpenCue Project Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed ... |
httpie/manager/core.py | elliottl/httpie | 24,849 | 11030935 | import argparse
from httpie.context import Environment
from httpie.manager.plugins import PluginInstaller
from httpie.status import ExitStatus
from httpie.manager.cli import missing_subcommand, parser
MSG_COMMAND_CONFUSION = '''\
This command is only for managing HTTPie plugins.
To send a request, please use the http... |
reaver/envs/base/__init__.py | HatsuneMiku4/reaver | 239 | 11030937 | import platform
from .spec import Space, Spec
from .abc import Env
from .shm_multiproc import ShmMultiProcEnv
from .msg_multiproc import MsgMultiProcEnv
MultiProcEnv = ShmMultiProcEnv
if platform.system() == 'Windows':
MultiProcEnv = MsgMultiProcEnv
|
venv/lib/python3.8/site-packages/placebo/__init__.py | ayfallen/urler | 401 | 11030940 | # Copyright (c) 2015-2019 <NAME>
#
# 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 writi... |
recipes/Python/65223_Fetch_diary_entries/recipe-65223.py | tdiprima/code | 2,023 | 11030964 | <filename>recipes/Python/65223_Fetch_diary_entries/recipe-65223.py
#!/usr/bin/env python
import sgmllib, string, urllib
class DiaryParser(sgmllib.SGMLParser):
def __init__(self):
sgmllib.SGMLParser.__init__(self)
self.entries = []
self.dates = []
self.inHtml = 0
self.... |
venv/Lib/site-packages/statsmodels/multivariate/api.py | EkremBayar/bayar | 6,931 | 11030983 | __all__ = [
"PCA", "MANOVA", "Factor", "FactorResults", "CanCorr",
"factor_rotation"
]
from .pca import PCA
from .manova import MANOVA
from .factor import Factor, FactorResults
from .cancorr import CanCorr
from . import factor_rotation
|
mitmproxy/utils/emoji.py | KarlParkinson/mitmproxy | 24,939 | 11030995 | <reponame>KarlParkinson/mitmproxy
#!/usr/bin/env python3
"""
All of the emoji and characters that can be used as flow markers.
"""
# auto-generated. run this file to refresh.
emoji = {
":+1:": "👍",
":-1:": "👎",
":100:": "💯",
":1234:": "🔢",
":1st_place_medal:": "🥇",
":2nd_place_medal:": "�... |
serialtests/runmotors.py | simondlevy/Hackflight | 200 | 11031000 | <gh_stars>100-1000
#!/usr/bin/env python3
from parser import MspParser
from serial import Serial
from time import sleep
PORT = '/dev/ttyS31'
class MyParser(MspParser):
def __init__(self, port):
MspParser.__init__(self)
self.port = port
def handle_ATTITUDE(self, angx, angy, heading):
... |
wannacry/smb_parsepcap.py | sysopfb/Malware_Scripts | 102 | 11031015 | from scapy.all import *
import scapy.layers.smb
import sys
import hashlib
test2 = "\x00\x00\x10N\xffSMB2\x00\x00\x00\x00\x18\x07\xc0\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x08\xff\xfe\x00\x08B"
a = rdpcap(sys.argv[1])
pkts = [x for x in a if hasattr(x, 'dport') and x.dport in [139,445]]
for i in range(... |
python/ray/tune/examples/tf_mnist_example.py | 77loopin/ray | 21,382 | 11031039 | #!/usr/bin/env python
# coding: utf-8
#
# This example showcases how to use TF2.0 APIs with Tune.
# Original code: https://www.tensorflow.org/tutorials/quickstart/advanced
#
# As of 10/12/2019: One caveat of using TF2.0 is that TF AutoGraph
# functionality does not interact nicely with Ray actors. One way to get around... |
natlas-server/app/scope/scope_collection.py | purplesecops/natlas | 500 | 11031051 | from netaddr import IPNetwork, IPSet
class ScopeCollection:
list = []
set = IPSet()
size = 0
def __init__(self, scope_source: callable):
"""
name: A name for this collection of scopes
scope_source: A callable that returns a collection of ScopeItem
"""
s... |
clients/native/examples/python-examples/websocket/textsend.py | tommyv1987/nym | 543 | 11031053 | import asyncio
import json
import websockets
self_address_request = json.dumps({
"type": "selfAddress"
})
async def send_text_without_reply():
message = "Hello Nym!"
uri = "ws://localhost:1977"
async with websockets.connect(uri) as websocket:
await websocket.send(self_address_request)
... |
samples/scripts/download_kittens.py | tomgilbertson/script-server-v1 | 833 | 11031063 | #!/usr/bin/python3
import sys
import tempfile
import time
import requests
# api_key = os.environ.get('KITTENS_API_KEY')
# if not api_key:
# print('Please request api_key from http://requestkittens.com and put it into KITTENS_API_KEY env. variable')
# sys.exit(-1)
for i in range(1, 6):
# response = reques... |
tools/nntool/importer/tflite2/common/__init__.py | 00-01/gap_sdk | 118 | 11031074 | import logging
import uuid
from numbers import Number
from onnx import TensorProto, mapping, helper
LOG = logging.getLogger('nntool.' + __name__)
class TFLiteImportException(Exception):
pass
class NoQuantizationError(Exception):
pass
def check(condition, message):
if not condition:
raise TFLite... |
tests/unit/test_modulegraph/testpkg-regr1/main_script.py | hawkhai/pyinstaller | 9,267 | 11031094 | <reponame>hawkhai/pyinstaller
from pkg import a
|
tracardi/service/wf/domain/debug_info.py | bytepl/tracardi | 153 | 11031100 | <reponame>bytepl/tracardi
from typing import List, Dict, Optional
from pydantic import BaseModel
from time import time
from .debug_call_info import DebugCallInfo, Profiler, DebugInput, DebugOutput
from .entity import Entity
from .error_debug_info import ErrorDebugInfo
from .input_params import InputParams
from ...plugi... |
DataViewer.py | Purkey95/ScraXBRL | 172 | 11031105 | <gh_stars>100-1000
import settings
import os
import sys
import pickle
class DataView:
def __init__(self, symbol, date, ftype):
self.symbol = symbol
self.date = date
self.ftype = ftype
self.data = None
self.load_data()
def load_data(self):
fpath_no_p = "{0}/{1}/{2}/xml/{3}/".format(settings.EXTRACTED_... |
software/contrib/hello_world.py | mjaskula/EuroPi | 104 | 11031109 | <reponame>mjaskula/EuroPi
from time import sleep
from europi import oled, b1, din
from europi_script import EuroPiScript
class HelloWorld(EuroPiScript):
def __init__(self):
super().__init__()
state = self.load_state_json()
self.counter = state.get("counter", 0)
self.enabled = stat... |
src/winforms/setup.py | freespace/toga | 1,261 | 11031110 | <filename>src/winforms/setup.py
#!/usr/bin/env python
import re
from setuptools import setup
# Version handline needs to be programatic because
# we can't import toga_winforms to compute the version;
# and to support versioned subpackage dependencies
with open('toga_winforms/__init__.py', encoding='utf8') as version_... |
utils/coco_tools_test.py | iostermann/deeplab2 | 587 | 11031151 | # coding=utf-8
# Copyright 2021 The Deeplab2 Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law ... |
examples/lm1b/language_model.py | Ezra-H/autodist | 127 | 11031165 | import os
import numpy as np
import tensorflow as tf
from absl import flags
FLAGS = flags.FLAGS
flags.DEFINE_integer('oov_bucket_size', 1, "The number of out-of-vocabulary buckets")
flags.DEFINE_integer('batch_size', 128, 'Batch size')
flags.DEFINE_integer('num_steps', 20, 'Number of steps')
flags.DEFINE_float('learni... |
tests/test_mocks.py | phitranphitranphitran/django-mock-queries | 235 | 11031173 | <reponame>phitranphitranphitran/django-mock-queries
import sys
import django
from django.db import connection
from django.db.utils import NotSupportedError
from django.db.backends.base.creation import BaseDatabaseCreation
try:
from unittest.mock import patch, MagicMock, PropertyMock
except ImportError:
from moc... |
matrix-python-project/cover_generator/typesetting/select_algorithm.py | hokaso/hocassian-media-matrix | 141 | 11031179 | <reponame>hokaso/hocassian-media-matrix
# 在M*N的棋盘上摆放N个元帅(M>=N),棋盘上每个方格有特定的值,每个元帅之间都不能处于同一行和同一列,求所有元帅所在的方格的值相加最小的那种摆法,以及这个最小值为多少。
import copy, random, sys, time
from munkres import Munkres, print_matrix
# 时间复杂度O(n!)
class SelectAlgorithmWithDFS(object):
def __init__(self, _row, _column, _matrix):
# 初始化数... |
third_party/chromite/lib/builder_status_lib_unittest.py | zipated/src | 2,151 | 11031181 | <reponame>zipated/src<gh_stars>1000+
# -*- coding: utf-8 -*-
# Copyright 2017 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Unittests for builder_status_lib."""
from __future__ import print_function
import mock
... |
gabbi/handlers/base.py | scottwallacesh/gabbi | 145 | 11031195 | <reponame>scottwallacesh/gabbi
#
# 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 writin... |
app/factories/urlscan.py | tapsykrett/emailanalyze | 119 | 11031200 | <filename>app/factories/urlscan.py<gh_stars>100-1000
from dataclasses import dataclass
from functools import partial
from typing import List, Optional
import aiometer
from loguru import logger
from app.schemas.verdict import Detail, Verdict
from app.services.urlscan import Urlscan
@dataclass
class UrlscanVerdict:
... |
tests/test_sync.py | RalphWalters/thredo | 340 | 11031214 | <filename>tests/test_sync.py
import thredo
def test_event_wait():
evt = thredo.Event()
result = []
def waiter():
evt.wait()
result.append('waiter')
def main():
t = thredo.spawn(waiter)
result.append('start')
evt.set()
t.join()
thredo... |
alipay/aop/api/domain/AlipayCommerceIotMsgcenterSendModel.py | snowxmas/alipay-sdk-python-all | 213 | 11031227 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class AlipayCommerceIotMsgcenterSendModel(object):
def __init__(self):
self._content = None
self._datetime = None
self._ext_info = None
self._is_support_link = None
... |
Model/structs/PostProcess.py | argusswift/SSD-pytorch | 379 | 11031334 | # -*- coding: utf-8 -*-
# @Author : LG
import torch
import torchvision
from Utils.Boxs_op import center_form_to_corner_form, convert_locations_to_boxes
from .Anchors import priorbox
import torch.nn.functional as F
__all__ = ['postprocessor']
class postprocessor:
def __init__(self, cfg):
super().__init__(... |
bcbio/variation/ploidy.py | a113n/bcbio-nextgen | 418 | 11031346 | <filename>bcbio/variation/ploidy.py
"""Calculate expected ploidy for a genomic regions.
Handles configured ploidy, with custom handling for sex chromosomes and pooled
haploid mitochondrial DNA.
"""
import collections
import io
import toolz as tz
from bcbio import utils
from bcbio.distributed.transaction import file_... |
sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/_shared/credential.py | rsdoherty/azure-sdk-for-python | 2,728 | 11031361 | <filename>sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/_shared/credential.py<gh_stars>1000+
# ------------------------------------
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
# ------------------------------------
try:
from typing import TYPE_CHECKING
except... |
cctbx/eltbx/tests/tst_xray_scattering.py | dperl-sol/cctbx_project | 155 | 11031373 | <reponame>dperl-sol/cctbx_project
from __future__ import absolute_import, division, print_function
from cctbx.eltbx import xray_scattering
from cctbx.array_family import flex
from libtbx.test_utils import Exception_expected, approx_equal
from six.moves import range
from six.moves import zip
try:
from six.moves import... |
metadrive/manager/__init__.py | liuzuxin/metadrive | 125 | 11031378 | """
This package is used to manage all runtime elements, including their moving and interaction
"""
|
python/paddle/fluid/tests/unittests/xpu/test_xpu_place.py | zmxdream/Paddle | 17,085 | 11031384 | # 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 app... |
NLP/UNIMO/src/utils/utils.py | zhangyimi/Research | 1,319 | 11031415 | <gh_stars>1000+
# Copyright (c) 2021 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... |
Scripts/sims4communitylib/debug/traits/_auto_apply_traits.py | ColonolNutty/Sims4CommunityLibrary | 118 | 11031450 | """
The Sims 4 Community Library is licensed under the Creative Commons Attribution 4.0 International public license (CC BY 4.0).
https://creativecommons.org/licenses/by/4.0/
https://creativecommons.org/licenses/by/4.0/legalcode
Copyright (c) COLONOLNUTTY
"""
from sims.sim_info import SimInfo
from sims4communitylib.en... |
paysage/batch/__init__.py | fyumoto/RBMs | 124 | 11031473 | from .in_memory import *
from .hdf import *
from .batch import *
from .shuffle import *
|
tests/linter/test_basic_corner_cases.py | dzil123/godot-gdscript-toolkit | 361 | 11031529 | <gh_stars>100-1000
from gdtoolkit.linter import lint_code
def test_empty_code_linting():
lint_code("")
def test_newlineless_code():
code = """func foo():
pass"""
lint_code(code)
|
tradingbot/components/broker/factories.py | stungkit/TradingBot | 218 | 11031535 | from enum import Enum
from typing import TypeVar, Union
from .. import Configuration
from . import (
AccountInterface,
AVInterface,
IGInterface,
StocksInterface,
YFinanceInterface,
)
AccountInterfaceImpl = TypeVar("AccountInterfaceImpl", bound=AccountInterface)
StocksInterfaceImpl = TypeVar("Stock... |
examples/python/django/app/ride_share/views/scooter/scooter.py | ScriptBox99/pyroscope | 5,751 | 11031569 | <reponame>ScriptBox99/pyroscope
from rest_framework.views import APIView
from rest_framework.response import Response
from ride_share.utility.utility import find_nearest_vehicle
class ScooterView(APIView):
"""
View to order a scooter
"""
def order_scooter(self, search_radius):
find_nearest_veh... |
examples/grid_layout.py | pzahemszky/guizero | 320 | 11031600 | <reponame>pzahemszky/guizero<filename>examples/grid_layout.py
from guizero import App, PushButton, Slider
def print_pos(x, y):
print("{}, {}".format(x, y))
def print_bottom():
print("bottom button")
def hide():
b00.hide()
b01.hide()
b10.hide()
b11.hide()
b_bottom.hide()
def show():
b... |
esprima/jsx_parser.py | SeaHOH/esprima-python | 174 | 11031617 | # -*- coding: utf-8 -*-
# Copyright JS Foundation and other contributors, https://js.foundation/
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright
# ... |
graspologic/cluster/base.py | j1c/graspologic | 110 | 11031633 | # Copyright (c) Microsoft Corporation and contributors.
# Licensed under the MIT License.
from abc import ABC, abstractmethod
from typing import Any, Optional
import numpy as np
from sklearn.base import BaseEstimator, ClusterMixin
from sklearn.metrics import adjusted_rand_score
from sklearn.utils.validation import ch... |
test/unit/agent/collectors/nginx/config.py | dp92987/nginx-amplify-agent | 308 | 11031634 | # -*- coding: utf-8 -*-
from copy import deepcopy
from hamcrest import *
from amplify.agent.common.context import context
from amplify.agent.managers.nginx import NginxManager
from amplify.agent.objects.nginx.config.config import NginxConfig
from test.base import RealNginxTestCase
__author__ = "<NAME>"
__copyright__... |
scripts/get_openimages_dataset.py | automaton123456/darknet_for_colab | 413 | 11031689 | import csv
import os
#select classes you want to download at https://github.com/openimages/dataset/blob/master/dict.csv
CLASS_LIST = ('/m/01g317','/m/04yx4')
img_name = "111111111111"
#download csv from https://storage.googleapis.com/openimages/web/download.html
with open('path\\train-annotations-bbox.csv', newline='... |
gpMgmt/bin/gppylib/recoveryinfo.py | shalamovivan/gpdb | 5,535 | 11031692 | <reponame>shalamovivan/gpdb<gh_stars>1000+
import datetime
#TODO: check if pickle is better
import json
from gppylib import gplog
class RecoveryInfo(object):
"""
This class encapsulates the information needed on a segment host
to run full/incremental recovery for a segment.
Note: we don't have target... |
api/institutions/renderers.py | gaybro8777/osf.io | 628 | 11031741 | <gh_stars>100-1000
from rest_framework_csv.renderers import CSVRenderer
class MetricsCSVRenderer(CSVRenderer):
"""
CSVRenderer with updated render method to export `data` dictionary of API Response to CSV
"""
def render(self, data, media_type=None, renderer_context={}, writer_opts=None):
"""
... |
setup_develop.py | tuan-tl/eosfactory | 255 | 11031748 | <filename>setup_develop.py
import setuptools
import os
import eosfactory.core.config as config
from shutil import rmtree
setuptools_name = config.SETUPTOOLS_NAME
try:
rmtree("build")
except:
pass
try:
rmtree("dist")
except:
pass
try:
rmtree(setuptools_name + ".egg-info")
except:
pass
def read... |
linked_list/split_circular_lists.py | x899/algorithms | 472 | 11031751 | """ Split a Circular Linked List into two halves
If there are odd number of nodes, then first list should contain one extra.
Input: A -> B -> C -> D -> ...
Output: A -> B -> ... and C -> D -> ...
URL: https://www.geeksforgeeks.org/split-a-circular-linked-list-into-two-halves/
"""
class Node:
""" ... |
attic/sequences/bisect_time.py | matteoshen/example-code | 5,651 | 11031780 | <reponame>matteoshen/example-code<filename>attic/sequences/bisect_time.py
"""
bisect_time.py
"""
import timeit
SETUP = '''
SIZE = 10**6
import array
import random
from bisect_find import bisect_find
random.seed(42)
haystack = [random.randrange(SIZE)*2 for i in range(SIZE)]
needles = [random.choice(haystack) + i % 2 f... |
tests/syntax/simple_expression/test_member_in.py | PowerOlive/mindspore | 3,200 | 11031825 | <filename>tests/syntax/simple_expression/test_member_in.py
# Copyright 2021 Huawei Technologies Co., Ltd
#
# 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/LIC... |
ck/repo/module/advice/module.py | krai/ck | 480 | 11031848 | #
# Collective Knowledge (universal advice about experiments, bugs, models,
# features, optimizations, adaptation,
# community remarks ...)
#
# See CK LICENSE.txt for licensing details
# See CK COPYRIGHT.txt for copyright details
#
# Developer: <NAME>, <EMAIL>, http://fursi... |
Algo and DSA/LeetCode-Solutions-master/Python/merge-strings-alternately.py | Sourav692/FAANG-Interview-Preparation | 3,269 | 11031856 | # Time: O(m + n)
# Space: O(1)
class Solution(object):
def mergeAlternately(self, word1, word2):
"""
:type word1: str
:type word2: str
:rtype: str
"""
result = []
i = 0
while i < len(word1) or i < len(word2):
if i < len(word1):
... |
modules/dbnd/src/dbnd/_core/task_build/task_signature.py | busunkim96/dbnd | 224 | 11031874 | import hashlib
import re
import attr
from dbnd._core.utils import json_utils
from dbnd._core.utils.traversing import flatten, traverse_frozen_set
SIGNATURE_ID_TRUNCATE_HASH = 10
TASK_ID_INCLUDE_PARAMS = 3
TASK_ID_TRUNCATE_PARAMS = 16
TASK_ID_INVALID_CHAR_REGEX = re.compile(r"[^A-Za-z0-9_.]")
@attr.s
class Signat... |
tina/mesh/trans.py | xuhao1/taichi_three | 152 | 11031886 | from ..common import *
from .base import MeshEditBase
class MeshTransform(MeshEditBase):
def __init__(self, mesh, trans=None):
super().__init__(mesh)
self.trans = ti.Matrix.field(4, 4, float, ())
self.trans_normal = ti.Matrix.field(3, 3, float, ())
@ti.materialize_callback
... |
eventsourcing/examples/searchabletimestamps/persistence.py | ParikhKadam/eventsourcing | 107 | 11031888 | from abc import abstractmethod
from datetime import datetime
from typing import Optional
from uuid import UUID
from eventsourcing.persistence import ApplicationRecorder
class SearchableTimestampsRecorder(ApplicationRecorder):
@abstractmethod
def get_version_at_timestamp(
self, originator_id: UUID, ti... |
src/tf_transformers/core/chainer.py | legacyai/tf-transformers | 116 | 11031895 | <filename>src/tf_transformers/core/chainer.py
# -*- coding: utf-8 -*-
# mypy: ignore-errors
# coding=utf-8
# Copyright 2021 TF-Transformers Authors and 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 wit... |
validation_tests/analytical_exact/parabolic_basin/plot_results.py | samcom12/anuga_core | 136 | 11031897 | """
Quick plot of the dam break outputs
"""
import numpy
from numpy import zeros
import anuga.utilities.plot_utils as util
import matplotlib
matplotlib.use('Agg')
from matplotlib import pyplot as pyplot
from math import sqrt, pi, cos, sin
from analytical_parabolic_basin import analytic_cannal
# Get the sww file
p... |
env/Lib/site-packages/OpenGL/GLES2/NV/viewport_swizzle.py | 5gconnectedbike/Navio2 | 210 | 11031964 | <reponame>5gconnectedbike/Navio2<filename>env/Lib/site-packages/OpenGL/GLES2/NV/viewport_swizzle.py<gh_stars>100-1000
'''OpenGL extension NV.viewport_swizzle
This module customises the behaviour of the
OpenGL.raw.GLES2.NV.viewport_swizzle to provide a more
Python-friendly API
Overview (from the spec)
This extens... |
Section 5 - Numpy and Pandas/Introduction to Pandas.py | kungfumas/bahasa-alami | 169 | 11032001 | # Natural Language Processing using Python
# Introduction to pandas
# Importing Libraries
import pandas as pd
import numpy as np
# Series
# pd.Series(self, data=None, index=None, dtype=None, name=None, copy=False, fastpath=False)
x = pd.Series([1,2,3,4,5])
x + 100
(x ** 2) + 100
x > 2
# any and all
larger_than_... |
dropbox/oauth.py | ParikhKadam/dropbox-sdk-python | 910 | 11032024 | <reponame>ParikhKadam/dropbox-sdk-python<filename>dropbox/oauth.py
import hashlib
__all__ = [
'BadRequestException',
'BadStateException',
'CsrfException',
'DropboxOAuth2Flow',
'DropboxOAuth2FlowNoRedirect',
'NotApprovedException',
'OAuth2FlowNoRedirectResult',
'OAuth2FlowResult',
'P... |
src/python3/request/item_delta_collection.py | meson800/onedrive-sdk-python | 912 | 11032078 | # -*- coding: utf-8 -*-
'''
# Copyright (c) 2015 Microsoft Corporation
#
# 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 us... |
Image_Lib/image_utils.py | vygasuresh/img | 263 | 11032081 | __author__ = 'Charlie'
import cv2
import numpy as np
def image_resize(image, width=-1, height=-1):
shape = image.shape
if width == -1:
if height == -1:
return image
else:
return cv2.resize(image, (int(height * shape[1] / shape[0]), height))
elif height == -1:
... |
qchem/tests/test_read_structure.py | ryanlevy/pennylane | 712 | 11032083 | <reponame>ryanlevy/pennylane<filename>qchem/tests/test_read_structure.py<gh_stars>100-1000
import pytest
from pennylane import qchem
import numpy as np
import os
import subprocess
ref_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), "test_ref_files")
@pytest.mark.parametrize(
"names",
[
... |
tests/bayesian/test_betabinomial.py | erik-stenberg/confidence | 107 | 11032092 | """Tests for `confidence` categorical variables."""
import pytest
import spotify_confidence
import pandas as pd
import numpy as np
spotify_confidence.options.set_option("randomization_seed", 1)
class TestCategorical(object):
def setup(self):
self.data = pd.DataFrame(
{
"vari... |
gff/Scripts/gff/gff_to_biosql.py | bgruening/bcbb | 339 | 11032133 | <reponame>bgruening/bcbb
#!/usr/bin/env python
"""Load a fasta file of sequences and associated GFF file into BioSQL.
You will need to adjust the database parameters and have a BioSQL database set
up. See:
http://biopython.org/wiki/BioSQL
Depending on the size of the sequences being loaded, you may also get errors o... |
harvesttext/match_patterns.py | awesome-archive/HarvestText | 1,524 | 11032237 | import re
import jieba
import jieba.posseg
from harvesttext import HarvestText
def AllEnglish():
rule = lambda x: bool(re.fullmatch(r"[a-zA-Z]*",x))
return rule
def AllEnglishOrNum():
rule = lambda x: bool(re.fullmatch(r"[a-zA-Z0-9]*",x))
return rule
def UpperFirst():
rule = lambda x: bool(re.ful... |
examples/v4l2-hero9-webcam.py | starlord1980/gopro-py-api | 1,232 | 11032240 | <gh_stars>1000+
import sys
from goprocam import GoProCamera, constants
import ffmpeg
print("Run modprobe v4l2loopback device=1 video_nr=44 card_label=\"GoPro\" exclusive_caps=1")
input("Hit enter when done!")
gopro = GoProCamera.GoPro(ip_address=GoProCamera.GoPro.getWebcamIP(
sys.argv[1]), camera=constants.gpcontr... |
part5/SpaceSciencePython_part5.py | ajpmaclean/SpaceScienceTutorial | 167 | 11032259 | <reponame>ajpmaclean/SpaceScienceTutorial
# Import modules
import datetime
import spiceypy
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
# Load the SPICE kernels via a meta file
spiceypy.furnsh('kernel_meta.txt')
# Create an initial date-time object that is converted to a string
DATETIME... |
examples/exceptions/server.py | lonly7star/Pyro5 | 188 | 11032272 | from Pyro5.api import Daemon, serve
import excep
def my_error_handler(daemon, client_sock, method, vargs, kwargs, exception):
print("\nERROR IN METHOD CALL USER CODE:")
print(" client={} method={} exception={}".format(client_sock, method.__qualname__, repr(exception)))
daemon = Daemon()
daemon.methodcall_er... |
wandb/integration/tensorboard/monkeypatch.py | borisgrafx/client | 3,968 | 11032325 | <gh_stars>1000+
"""
monkeypatch: patch code to add tensorboard hooks
"""
import os
import socket
import re
import wandb
TENSORBOARD_C_MODULE = "tensorflow.python.ops.gen_summary_ops"
TENSORBOARD_X_MODULE = "tensorboardX.writer"
TENSORFLOW_PY_MODULE = "tensorflow.python.summary.writer.writer"
TENSORBOARD_WRITER_MODU... |
tests/facebook/test_message.py | sns-sdks/python-facebook | 181 | 11032330 | """
Tests for message.
"""
import responses
def test_get_info(helpers, fb_api):
msg_id = "m_ToF35NI1OImBjyUIgplSaBMylUFmkYY4bHogy9C1otLISU6SGhccB5NK-THX_W4EdVQiKVv5SgCW9m-_C78mRA"
with responses.RequestsMock() as m:
m.add(
method=responses.GET,
url=f"https://graph.faceboo... |
pkgs/ipywidgets-4.1.1-py27_0/lib/python2.7/site-packages/ipywidgets/widgets/widget_color.py | wangyum/anaconda | 652 | 11032338 | <filename>pkgs/ipywidgets-4.1.1-py27_0/lib/python2.7/site-packages/ipywidgets/widgets/widget_color.py
"""Color class.
Represents an HTML Color .
"""
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
from .widget import DOMWidget, register
from .trait_types import Co... |
visualDet3D/data/pipeline/__init__.py | jovialio/visualDet3D | 250 | 11032349 | from .stereo_augmentator import *
from .augmentation_builder import build_augmentator |
cocos/tests/test_numerics/test_statistics/utilities.py | michaelnowotny/cocos | 101 | 11032367 | import numpy as np
from scipy.stats import kstest
import typing as tp
import cocos.numerics as cn
def perform_ks_test(x: tp.Union[np.ndarray, cn.ndarray],
alpha: float,
distribution,
args: tp.Tuple = None,
verbose: bool = False) -> bool:... |
examples/babbage-lights-n-sounds.py | DT-was-an-ET/explorer-hat | 156 | 11032373 | <reponame>DT-was-an-ET/explorer-hat<filename>examples/babbage-lights-n-sounds.py
#!/usr/bin/env python
import random
import time
from pdtone import PDTone
import explorerhat
print("""
This example tries to re-create the classic pattern copying game Simon.
Press the lights in the sequence given, and try not to make ... |
doc/samples/getargs_group.py | m4ta1l/doit | 1,390 | 11032396 | <reponame>m4ta1l/doit
def task_compute():
def comp(x):
return {'x':x}
yield {'name': '5',
'actions': [ (comp, [5]) ]
}
yield {'name': '7',
'actions': [ (comp, [7]) ]
}
def show_getargs(values):
print(values)
assert sum(v['x'] for v in values.values()) ==... |
tools/pokemon/name.py | stoiandan/OpenPokemonRed | 204 | 11032403 | <filename>tools/pokemon/name.py
names = [
"Bulbasaur",
"Ivysaur",
"Venusaur",
"Charmander",
"Charmeleon",
"Charizard",
"Squirtle",
"Wartortle",
"Blastoise",
"Caterpie",
"Metapod",
"Butterfree",
"Weedle",
"Kakuna",
"Beedrill",
"Pidgey",
"Pidgeotto",
... |
robogym/observation/common.py | 0xflotus/robogym | 288 | 11032420 | <gh_stars>100-1000
import abc
from enum import Enum
from typing import Generic, TypeVar
import numpy as np
class SyncType(Enum):
"""
Enum which determines how frequent sync() will be called for given observation
provider. This can be used to control when given observation will change. There
are 3 dif... |
tests/modules/test_lief.py | neriberto/viper | 1,131 | 11032428 | # -*- coding: utf-8 -*-
# This file is part of Viper - https://github.com/viper-framework/viper
# See the file 'LICENSE' for copying permission.
import os
import re
import pytest
from tests.conftest import FIXTURE_DIR
from viper.common.abstracts import Module
from viper.common.abstracts import ArgumentErrorCallback
... |
liualgotrader/fincalcs/vwap.py | riven314/LiuAlgoTrader | 369 | 11032472 | <reponame>riven314/LiuAlgoTrader
from datetime import datetime
import pandas as pd
from pandas import DataFrame as df
from pandas import Timestamp as ts
from liualgotrader.common import config
from liualgotrader.common.tlog import tlog
def add_daily_vwap(
minute_data: df, debug=False, back_time=None, in_place=T... |
scripts/automation/trex_control_plane/stf/trex_stf_lib/trex_status_e.py | timgates42/trex-core | 956 | 11032484 | #!/router/bin/python
try:
from . import outer_packages
except:
import outer_packages
from simple_enum import SimpleEnum
# define the states in which a TRex can hold during its lifetime
TRexStatus = SimpleEnum('TRexStatus', 'Idle Starting Running')
|
libs/rpy2-2.9.3/rpy/rlike/tests/test_container.py | walbaum1994/python-ml-course | 655 | 11032552 | import unittest
import sys
if sys.version_info[0] == 2:
from itertools import izip as zip
import rpy2.rlike.container as rlc
class OrdDictTestCase(unittest.TestCase):
def testNew(self):
nl = rlc.OrdDict()
x = (('a', 123), ('b', 456), ('c', 789))
nl = rlc.OrdDict(x)
def testLen(se... |
ufora/FORA/python/PurePython/ConstantConverter.py | ufora/ufora | 571 | 11032567 | <reponame>ufora/ufora
# Copyright 2015 Ufora 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 applica... |
script/auto_upgrade_dbt.py | xy00/DreamBox | 153 | 11032592 | <filename>script/auto_upgrade_dbt.py
import os
from shutil import copyfile
import hashlib
from functools import partial
def file_md5(path):
with open(path, mode='rb') as f:
d = hashlib.md5()
for buf in iter(partial(f.read, 128), b''):
d.update(buf)
return d.hexdigest()
def ch... |
scripts/devaccess/helper_scripts/redacted.py | fahlmant/openshift-tools | 164 | 11032603 | <gh_stars>100-1000
#!/usr/bin/env python
"""
This script will dump config files in a clean format for developer access
"""
import os
import pwd
import sys
import yaml
CONFIG_FILE = "/usr/local/bin/redacted.yaml"
def load_config():
'''
Loads the config file for redacted
'''
with open(CONFIG_FILE, "r")... |
dmb/utils/__init__.py | jiaw-z/DenseMatchingBenchmark | 160 | 11032617 | from .dist_utils import all_reduce_grads, DistOptimizerHook, DistApexOptimizerHook
from .collect_env import collect_env_info
from .env import init_dist, set_random_seed, get_root_logger
from .tensorboard_logger import TensorboardLoggerHook
from .text_logger import TextLoggerHook
from .registry import Registry
|
corehq/ex-submodules/casexml/apps/phone/restore_caching.py | dimagilg/commcare-hq | 471 | 11032654 | <filename>corehq/ex-submodules/casexml/apps/phone/restore_caching.py<gh_stars>100-1000
import hashlib
import logging
import datetime
from casexml.apps.phone.const import RESTORE_CACHE_KEY_PREFIX, ASYNC_RESTORE_CACHE_KEY_PREFIX
from corehq.toggles import ENABLE_LOADTEST_USERS
from corehq.util.quickcache import quickcach... |
bindings/python/tests/test_ethash.py | andrei-kondakov/ethash | 631 | 11032662 | # ethash: C/C++ implementation of Ethash, the Ethereum Proof of Work algorithm.
# Copyright 2019 <NAME>.
# Licensed under the Apache License, Version 2.0.
import unittest
import ethash
class TestEthash(unittest.TestCase):
epoch_number = 0
nonce = 0x4242424242424242
header_hash = bytes.fromhex(
'... |
envs/hns/mujoco-worldgen/examples/simple_particle.py | jiayu-ch15/curriculum | 424 | 11032694 | <filename>envs/hns/mujoco-worldgen/examples/simple_particle.py
import numpy as np
from mujoco_worldgen import Env, WorldParams, WorldBuilder, Floor, ObjFromXML
def get_reward(sim):
object_xpos = sim.data.get_site_xpos("object")
target_xpos = sim.data.get_site_xpos("target")
ctrl = np.sum(np.square(sim.dat... |
helper/can_i_use/can_i_use_command.py | exploitmik/JavaScript-Completions | 420 | 11032708 | items_found_can_i_use = None
can_i_use_file = None
can_i_use_popup_is_showing = False
can_i_use_list_from_main_menu = False
path_to_can_i_use_data = os.path.join(H_SETTINGS_FOLDER, "can_i_use", "can_i_use_data.json")
path_to_test_can_i_use_data = os.path.join(H_SETTINGS_FOLDER, "can_i_use", "can_i_use_data2.json")
url_... |
examples/pybullet/examples/forcetorquesensor.py | stolk/bullet3 | 158 | 11032716 | import pybullet as p
p.connect(p.DIRECT)
hinge = p.loadURDF("hinge.urdf")
print("mass of linkA = 1kg, linkB = 1kg, total mass = 2kg")
hingeJointIndex = 0
#by default, joint motors are enabled, maintaining zero velocity
p.setJointMotorControl2(hinge, hingeJointIndex, p.VELOCITY_CONTROL, 0, 0, 0)
p.setGravity(0, 0, -1... |
modules/password-recovery/cewl.py | decidedlygray/ptf | 4,391 | 11032720 | <filename>modules/password-recovery/cewl.py
#!/usr/bin/env python
#####################################
# Installation module for CeWL
#####################################
# AUTHOR OF MODULE NAME
AUTHOR="<NAME>"
# DESCRIPTION OF THE MODULE
DESCRIPTION="This module will install/update CeWL - Custom Word List generato... |
bigbench/benchmark_tasks/simple_arithmetic/test.py | sebschu/BIG-bench | 460 | 11032723 | # Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, so... |
examples/pytorch/ggnn/ggsnn.py | ketyi/dgl | 9,516 | 11032729 | <reponame>ketyi/dgl
"""
Gated Graph Sequence Neural Network for sequence outputs
"""
from dgl.nn.pytorch import GatedGraphConv, GlobalAttentionPooling
import torch
from torch import nn
import torch.nn.functional as F
class GGSNN(nn.Module):
def __init__(self,
annotation_size,
ou... |
tests/testAccount.py | pir2/python-omniture | 105 | 11032747 | <reponame>pir2/python-omniture
#!/usr/bin/python
import unittest
import requests_mock
import omniture
import os
creds = {}
creds['username'] = os.environ['OMNITURE_USERNAME']
creds['secret'] = os.environ['OMNITURE_SECRET']
test_report_suite = "omniture.api-gateway"
class AccountTest(unittest.TestCase):
def setU... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.