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 |
|---|---|---|---|---|
corehq/messaging/smsbackends/start_enterprise/migrations/0001_initial.py | dimagilg/commcare-hq | 471 | 12705617 | # Generated by Django 1.10.8 on 2017-10-12 10:35
from django.db import migrations, models
import jsonfield.fields
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='StartEnterpriseDeliveryReceipt',
f... |
rojak-analyzer/show_word_frequency.py | pyk/rojak | 107 | 12705621 | import csv
from bs4 import BeautifulSoup
from collections import Counter
import re
csv_file = open('data_detikcom_740.csv')
csv_reader = csv.DictReader(csv_file)
words = []
for row in csv_reader:
title = row['title'].strip().lower()
raw_content = row['raw_content']
clean_content = BeautifulSoup(raw_conten... |
src/embedding/recognition.py | mykiscool/DeepCamera | 914 | 12705673 | # coding=utf-8
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os, json, time, sys
import shutil
import time
import os.path
import requests
from uuid import uuid1
import numpy as np
from utilslib.save2gst import generate_protocol_string
import class... |
Master Script/manual db updater.py | avinashkranjan/PraticalPythonProjects | 930 | 12705696 | from optparse import OptionParser
import json
import sys
import os
usage = """
<Script> [Options]
[Options]
-h, --help Show this help message and exit.
-a, --add Goes straight to the add script phase
"""
# Load args
parser = OptionParser()
parser.add_option("-a", "--add", action="store_true", d... |
templates/powershell/ps_system_time.py | ohoph/Ebowla | 738 | 12705710 | buildcode="""
function Get-SystemTime(){
$time_mask = @()
$the_time = Get-Date
$time_mask += [string]$the_time.Year + "0000"
$time_mask += [string]$the_time.Year + [string]$the_time.Month + "00"
$time_mask += [string]$the_time.Year + [string]$the_time.Month + [string]$the_time.Day
return $time_mask
}
"""
callco... |
examples/generate_embeddings.py | JackHopkins/onnxt5 | 197 | 12705718 | <gh_stars>100-1000
from onnxruntime import InferenceSession
from transformers import T5Tokenizer
from onnxt5.api import get_encoder_decoder_tokenizer, run_embeddings_text, get_sess
# The easiest way is to use the onnxt5 api and load the default pre-trained version of t5
decoder_sess, encoder_sess, tokenizer = get_enco... |
raspberryio/project/admin.py | cvautounix/raspberryio | 113 | 12705727 | <gh_stars>100-1000
try:
from PIL import Image
except ImportError:
import Image
from django import forms
from django.contrib import admin
from raspberryio.project.models import (FeaturedProject, Project, ProjectStep,
ProjectCategory)
class FeaturedProjectAdminForm(forms.ModelForm):
class Meta:
... |
synapse/lib/queue.py | ackroute/synapse | 216 | 12705731 | import asyncio
import collections
import synapse.exc as s_exc
import synapse.common as s_common
import synapse.lib.base as s_base
class AQueue(s_base.Base):
'''
An async queue with chunk optimized sync compatible consumer.
'''
async def __anit__(self):
await s_base.Base.__anit__(self)
... |
tests/plugins/test_lyx_filters.py | dsoto/dexy | 136 | 12705739 | from tests.utils import assert_output
def test_lyx():
assert_output("lyxjinja",
"dexy:foo.py|idio:multiply",
"<< d['foo.py|idio']['multiply'] >>",
".tex")
|
data/operator/bbox/spatial/vectorized/torch/utility/normalize.py | zhangzhengde0225/SwinTrack | 143 | 12705764 | <reponame>zhangzhengde0225/SwinTrack
import torch
class BoundingBoxNormalizationHelper:
def __init__(self, interval, range_):
assert interval in ('[)', '[]')
self.right_open = (interval == '[)')
assert range_[1] > range_[0]
self.scale = range_[1] - range_[0]
self.offset = r... |
video_funnel/server.py | fakegit/video-funnel | 113 | 12705771 | import asyncio
from pathlib import Path
import aiohttp
from aiohttp import web
from .funnel import Funnel
from .utils import (
HttpRange,
RangeNotSupportedError,
convert_unit,
load_browser_cookies,
retry,
)
async def make_response(request, url, block_size, piece_size, cookies_from,
... |
tests/api/test_docker.py | peddamat/home-assistant-supervisor-test | 597 | 12705772 | """Test Docker API."""
import pytest
@pytest.mark.asyncio
async def test_api_docker_info(api_client):
"""Test docker info api."""
resp = await api_client.get("/docker/info")
result = await resp.json()
assert result["data"]["logging"] == "journald"
assert result["data"]["storage"] == "overlay2"
... |
setup.py | bingqingsuimeng/ctypesgen | 200 | 12705778 | #!/usr/bin/env python3
"""Examples:
setup.py sdist
setup.py bdist_wininst
"""
from setuptools import setup
if __name__ == "__main__":
setup()
|
k8s_handle/__init__.py | jetbrains-infra/k8s-handle | 152 | 12705781 | <reponame>jetbrains-infra/k8s-handle
import argparse
import logging
import os
import sys
from kubernetes import client
from kubernetes.config import list_kube_config_contexts, load_kube_config
from k8s_handle import config
from k8s_handle import settings
from k8s_handle import templating
from k8s_handle.exceptions im... |
examples/mark_safe_secure.py | mikelolasagasti/bandit | 4,016 | 12705785 | <gh_stars>1000+
import os
from django.utils import safestring
safestring.mark_safe('<b>secure</b>')
safestring.SafeText('<b>secure</b>')
safestring.SafeUnicode('<b>secure</b>')
safestring.SafeString('<b>secure</b>')
safestring.SafeBytes('<b>secure</b>')
my_secure_str = '<b>Hello World</b>'
safestring.mark_safe(my_sec... |
hypernets/core/callbacks.py | Enpen/Hypernets | 1,080 | 12705790 | # -*- coding:utf-8 -*-
"""
"""
import datetime
import json
import os
import time
import numpy as np
import pandas as pd
from IPython.display import display, update_display, display_markdown
from tqdm.auto import tqdm
from ..utils import logging, fs, to_repr
logger = logging.get_logger(__name__)
class Callback():
... |
textworld/gym/spaces/text_spaces.py | JohnnySun8/TextWorld | 307 | 12705799 | <reponame>JohnnySun8/TextWorld
import re
import string
import numpy as np
import gym
import gym.spaces
class VocabularyHasDuplicateTokens(ValueError):
pass
class Char(gym.spaces.MultiDiscrete):
""" Character observation/action space
This space consists of a series of `gym.spaces.Discrete` objects all ... |
tis/client.py | Fudan-Autonomous-Driving-Perception/BiSeNet | 966 | 12705819 |
import numpy as np
import cv2
import grpc
from tritonclient.grpc import service_pb2, service_pb2_grpc
import tritonclient.grpc.model_config_pb2 as mc
np.random.seed(123)
palette = np.random.randint(0, 256, (100, 3))
# url = '10.128.61.7:8001'
url = '127.0.0.1:8001'
model_name = 'bisenetv2'
model_version = '1'
... |
ISMLnextGen/TornadoTestAsync2.py | Ravenclaw-OIer/ISML_auto_voter | 128 | 12705821 | # coding: utf-8
from AsyncIteratorWrapper import AsyncIteratorWrapper
import asyncio
import functools
import aiohttp
import tornado.web
from tornado.platform.asyncio import AsyncIOMainLoop
from threading import Thread
headers={
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/we... |
sumatra/dependency_finder/core.py | usnistgov/corr-sumatra | 143 | 12705845 | <gh_stars>100-1000
"""
Functions for finding the version of a dependency.
Classes
-------
BaseDependency - base class for holding information about a program component.
Functions
---------
find_version_from_versioncontrol - determines whether a file is under version
control, and i... |
tests/serializers.py | chachabooboo/king-phisher | 1,143 | 12705873 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# tests/serializers.py
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list o... |
cleo/io/buffered_io.py | Ivoz/cleo | 859 | 12705887 | <reponame>Ivoz/cleo
from typing import Optional
from typing import cast
from .inputs.input import Input
from .io import IO
from .outputs.buffered_output import BufferedOutput
class BufferedIO(IO):
def __init__(
self,
input: Optional[Input] = None,
decorated: bool = False,
supports... |
Python3/988.py | rakhi2001/ecom7 | 854 | 12705902 | <gh_stars>100-1000
__________________________________________________________________________________________________
sample 44 ms submission
class Solution:
def smallestFromLeaf(self, root: TreeNode) -> str:
def convert(num):
return chr(ord('a') + num)
def dfs(node, pval):
... |
atlas/foundations_events/src/test/consumers/jobs/queued/test_creation_time.py | DeepLearnI/atlas | 296 | 12705945 |
import unittest
from mock import Mock
from foundations_events.consumers.jobs.queued.creation_time import CreationTime
class TestCreationTime(unittest.TestCase):
def setUp(self):
self._redis = Mock()
self._consumer = CreationTime(self._redis)
def test_call_saves_creation_time(self):
... |
Split a string into two elements.py | DazEB2/SimplePyScripts | 117 | 12705969 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = 'ipetrash'
def split_by_pair(text):
items = list()
for i in range(0, len(text), 2):
pair = text[i] + text[i + 1]
items.append(pair)
return items
def split_by_pair_1(text):
result = [a + b for a, b in list(zip(text[::2], t... |
venv/lib/python3.8/site-packages/waitress/tests/fixtureapps/runner.py | ayfallen/urler | 978 | 12705976 | def app(): # pragma: no cover
return None
def returns_app(): # pragma: no cover
return app
|
osp/test/common/utils/test_parse_domain.py | davidmcclure/open-syllabus-project | 220 | 12705984 |
import pytest
from osp.common.utils import parse_domain
@pytest.mark.parametrize('url,domain', [
# Unchanged
(
'test.edu',
'test.edu',
),
# Strip protocol
(
'http://test.edu',
'test.edu',
),
(
'https://test.edu',
'test.edu',
),
... |
examples/cicd/sig-mlops-jenkins-classic/models/news_classifier/src/train_model.py | jsreid13/seldon-core | 3,049 | 12706006 | <gh_stars>1000+
from sklearn.datasets import fetch_20newsgroups
from sklearn.pipeline import Pipeline
from sklearn.feature_extraction.text import TfidfTransformer, CountVectorizer
from sklearn.naive_bayes import MultinomialNB
import numpy as np
import joblib
def fetch_data():
categories = ["alt.atheism", "soc.rel... |
hpccm/building_blocks/mkl.py | robertmaynard/hpc-container-maker | 340 | 12706117 | <reponame>robertmaynard/hpc-container-maker
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licen... |
tf3d/losses/box_prediction_losses_test.py | deepneuralmachine/google-research | 23,901 | 12706136 | # coding=utf-8
# Copyright 2021 The Google Research 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 applicab... |
src/python/pants/jvm/util_rules_test.py | rcuza/pants | 1,806 | 12706148 | <reponame>rcuza/pants
# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
import hashlib
import pytest
from pants.engine.fs import EMPTY_FILE_DIGEST, CreateDigest, Digest, FileContent, FileDigest
from p... |
tools/bin/pythonSrc/pychecker-0.8.18/test/test_module.py | YangHao666666/hawq | 450 | 12706153 | <filename>tools/bin/pythonSrc/pychecker-0.8.18/test/test_module.py
# -*- Mode: Python -*-
# vi:si:et:sw=4:sts=4:ts=4
'''
Tests related to modules.
'''
import unittest
import common
class SameModuleNameTestCase(common.TestCase):
'''
Test that modules with the same name do not shadow eachother.
'''
def... |
pdfarchiver.py | jordanwildon/Telepathy | 213 | 12706156 | <gh_stars>100-1000
#!/usr/bin/env python
"""Telepathy file archiver module:
A tool for archiving files in a chat which may contain metadata.
"""
from telethon.sync import TelegramClient
from telethon.tl.functions.messages import GetDialogsRequest
from telethon.errors import SessionPasswordNeededError
from teletho... |
docs/source/tutorials/code/serialization.py | PuzeLiu/mushroom-rl | 344 | 12706208 | from mushroom_rl.core import Serializable
import torch
import numpy as np
from mushroom_rl.utils.parameters import Parameter
class TestClass(Serializable):
def __init__(self, value):
# Create some different types of variables
self._primitive_variable = value # Primitive python variable
... |
example_training(without_GPUTaskScheduler)/main.py | lipikaramaswamy/DoppelGANger | 157 | 12706217 | <reponame>lipikaramaswamy/DoppelGANger<filename>example_training(without_GPUTaskScheduler)/main.py
import sys
sys.path.append("..")
from gan import output
sys.modules["output"] = output
from gan.doppelganger import DoppelGANger
from gan.util import add_gen_flag, normalize_per_sample
from gan.load_data import load_dat... |
src/backend/common/queries/exceptions.py | guineawheek/ftc-data-take-2 | 266 | 12706264 | class DoesNotExistException(Exception):
pass
|
infrabox/test/pyinfraboxutils/test.py | agu3rra/InfraBox | 265 | 12706283 | <gh_stars>100-1000
#! /usr/bin/env python
import unittest
import sys
import xmlrunner
from pyinfraboxutils.coverage import *
class TestCoverageMethods(unittest.TestCase):
def test_jacoco(self):
parser = Parser("data/report_test.xml")
parser.parse(None, create_markup=False)
self.assertTrue... |
sacrebleu/__init__.py | bricksdont/sacreBLEU | 373 | 12706302 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright 2017--2018 Amazon.com, Inc. or its affiliates. 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. A copy of the License
# is located at
#
# http://aws.... |
cmd/gencudnn/parse.py | xkey-/cu | 275 | 12706314 | from bs4 import BeautifulSoup
import requests
import re
import sys
import os
inputs ={}
outputs = {}
ios = {}
docs = {}
def get():
if os.path.isfile("cache/docs.html"):
with open("cache/docs.html", 'r') as f:
print("Using cache", file=sys.stderr)
return f.read()
r = requests.get("https://docs.nvidia.com/dee... |
module/Probe_Packet.py | Yiidiir/SniffAir | 1,173 | 12706349 | #!/usr/bin/python
import sys
import signal
import argparse
import logging
logging.getLogger ( "scapy.runtime" ).setLevel ( logging.CRITICAL )
from scapy.all import *
# Setup signal handler to catch CTRL-C
def signal_handler(signal, frame):
sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)
# Get arguments
... |
DQM/Physics/test/qcdPhotonsDQM_cfg.py | ckamtsikis/cmssw | 852 | 12706354 | import FWCore.ParameterSet.Config as cms
process = cms.Process("QcdPhotonsDQM")
process.load("DQM.Physics.qcdPhotonsDQM_cfi")
process.load("DQMServices.Core.DQM_cfg")
process.load("DQMServices.Components.DQMEnvironment_cfi")
process.DQM.collectorHost = ''
process.dqmSaver.workflow = cms.untracked.string('/My/Test/Da... |
galaxy/api/fields.py | bmclaughlin/galaxy | 904 | 12706369 | <reponame>bmclaughlin/galaxy<gh_stars>100-1000
# (c) 2012-2019, Ansible by Red Hat
#
# This file is part of Ansible Galaxy
#
# Ansible Galaxy is free software: you can redistribute it and/or modify
# it under the terms of the Apache License as published by
# the Apache Software Foundation, either version 2 of the Licen... |
webwaybooks/utils/meta.py | bysorry/telegram_media_downloader | 401 | 12706374 | <gh_stars>100-1000
"""Utility module to manage meta info."""
import platform
from . import __version__, __copyright__, __license__
APP_VERSION = f"Telegram Media Downloader {__version__}"
DEVICE_MODEL = (
f"{platform.python_implementation()} {platform.python_version()}"
)
SYSTEM_VERSION = f"{platform.system()} {p... |
circus/commands/dstats.py | BradleyKirton/circus | 820 | 12706385 | <filename>circus/commands/dstats.py
from circus.exc import ArgumentError
from circus.commands.base import Command
from circus.util import get_info
_INFOLINE = ("%(pid)s %(cmdline)s %(username)s %(nice)s %(mem_info1)s "
"%(mem_info2)s %(cpu)s %(mem)s %(ctime)s")
class Daemontats(Command):
"""\
... |
car/scripts/lidarEvasion.py | GNSS523/Cherry-Autonomous-Racecar | 330 | 12706396 | #!/usr/bin/env python
"""
Copyright (c) 2017 <NAME>, <NAME>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge... |
testing/buildbot/scripts/upload_test_result_artifacts_unittest.py | zealoussnow/chromium | 14,668 | 12706415 | <reponame>zealoussnow/chromium
# Copyright 2017 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Tests for upload_test_result_artifacts."""
from __future__ import print_function
import json
import mock
import os
import ... |
applications/cli/commands/workflow/tests/test_cancel.py | nparkstar/nauta | 390 | 12706428 | <filename>applications/cli/commands/workflow/tests/test_cancel.py
#
# 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/licen... |
examples/docs_snippets_crag/docs_snippets_crag/concepts/configuration/configured_named_op_example.py | dagster-io/dagster | 4,606 | 12706436 | from dagster import Field, In, Int, List, configured, job, op
# start_configured_named
@op(
config_schema={
"is_sample": Field(bool, is_required=False, default_value=False),
},
ins={"xs": In(List[Int])},
)
def get_dataset(context, xs):
if context.op_config["is_sample"]:
return xs[:5]
... |
test/test_format_utils.py | toskachin/athenacli | 175 | 12706441 | # -*- coding: utf-8 -*-
from collections import namedtuple
from athenacli.packages.format_utils import format_status, humanize_size
def test_format_status_plural():
assert format_status(rows_length=1) == "1 row in set"
assert format_status(rows_length=2) == "2 rows in set"
def test_format_status_no_results... |
kafkashell/__init__.py | amzyang/kafka-shell | 109 | 12706472 | # -*- coding: utf-8 -*-
#
# Copyright 2019 <NAME>. 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. A copy of
# the License is located at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# or in the "li... |
738 Monotone Increasing Digits.py | krishna13052001/LeetCode | 872 | 12706485 | <gh_stars>100-1000
#!/usr/bin/python3
"""
Given a non-negative integer N, find the largest number that is less than or
equal to N with monotone increasing digits.
(Recall that an integer has monotone increasing digits if and only if each pair
of adjacent digits x and y satisfy x <= y.)
Example 1:
Input: N = 10
Output... |
exec.py | fredcallaway/SendCode | 177 | 12706495 | import sublime_plugin
class SendCodeExecCommand(sublime_plugin.WindowCommand):
def run(self, code=None, prog=None):
self.window.active_view().run_command(
"send_code",
{"code": code, "prog": prog}
)
# backward compatibility
class SendCodeBuildCommand(SendCodeExecCommand)... |
Chapter09/list_comp_read_file.py | 4n3i5v74/Python-3-Object-Oriented-Programming-Third-Edition | 393 | 12706531 | <filename>Chapter09/list_comp_read_file.py
import sys
filename = sys.argv[1]
with open(filename) as file:
header = file.readline().strip().split("\t")
contacts = [
dict(zip(header, line.strip().split("\t"))) for line in file
]
for contact in contacts:
print("email: {email} -- {last}, {first}"... |
Validation/RecoEgamma/python/egammaPostValidationMiniAOD_cff.py | ckamtsikis/cmssw | 852 | 12706559 | import FWCore.ParameterSet.Config as cms
from Validation.RecoEgamma.electronPostValidationSequenceMiniAOD_cff import *
egammaPostValidationMiniAOD = cms.Sequence( electronPostValidationSequenceMiniAOD )
|
nets/helloworld.py | postBG/netadapt | 158 | 12706576 | import torch
import torch.nn as nn
__all__ = ['HelloWorld', 'helloworld']
class HelloWorld(nn.Module):
def __init__(self, num_classes=10):
super(HelloWorld, self).__init__()
self.features = nn.Sequential(
nn.Conv2d(3, 16, kernel_size=3, stride=1, padding=1, bias=False),
n... |
chaos_genius/utils/datetime_helper.py | rsohlot/chaos_genius | 320 | 12706595 | """Provides helper functions related to datetime operations."""
from datetime import date, datetime, timedelta, timezone
import pandas as pd
import pytz
from chaos_genius.core.utils.constants import SUPPORTED_TIMEZONES
from chaos_genius.settings import TIMEZONE
def get_server_timezone():
"""Get server timezone... |
alipay/aop/api/response/AlipayFundJointaccountFundallocCountQueryResponse.py | antopen/alipay-sdk-python-all | 213 | 12706599 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.response.AlipayResponse import AlipayResponse
class AlipayFundJointaccountFundallocCountQueryResponse(AlipayResponse):
def __init__(self):
super(AlipayFundJointaccountFundallocCountQueryResponse, self).__init__()
self.... |
armada_backend/api_images.py | firesoft/armada | 281 | 12706616 | <reponame>firesoft/armada<filename>armada_backend/api_images.py
from armada_backend import api_base, docker_client
from armada_command.docker_utils.images import LocalArmadaImage
from armada_command.scripts.compat import json
class Images(api_base.ApiCommand):
def on_get(self, req, resp, image_name_or_address, im... |
sonnet/src/conformance/descriptors.py | ScriptBox99/deepmind-sonnet | 10,287 | 12706622 | <reponame>ScriptBox99/deepmind-sonnet
# Copyright 2019 The Sonnet 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... |
pipeline/oia/oiaTimingPlot.py | konradotto/TS | 125 | 12706629 | # /* Copyright (C) 2016 Ion Torrent Systems, Inc. All Rights Reserved */
import pandas as pd
import datetime
import dateutil
import matplotlib.dates as dates
from matplotlib import pyplot as plt
import numpy as np
from time import strptime
import os
# put the date on the same line with the cpu data
os.system("awk 'NR%... |
3-2.Lattice_LSTM/eval.py | techthiyanes/nlp-notebook | 136 | 12706632 | # -*- coding: utf-8 -*-
import torch
from model import LatticeLSTM
from load_data import char2idx, idx2char, label2idx, idx2label, word2idx, data_generator
character_size = len(char2idx)
word_size = len(word2idx)
embed_dim = 300
hidden_dim = 128
TEST_DATA_PATH = "./data/test_data" # 测试数据
device = "cuda" if torch.cuda... |
siphon/tests/test_catalog.py | DanielWatkins/siphon | 164 | 12706640 | <gh_stars>100-1000
# Copyright (c) 2013-2019 Siphon Contributors.
# Distributed under the terms of the BSD 3-Clause License.
# SPDX-License-Identifier: BSD-3-Clause
"""Test the catalog access API."""
from datetime import datetime
import logging
import pytest
from siphon.catalog import get_latest_access_url, TDSCatal... |
challenge_1/python/jcpattison/src/reverse.py | rchicoli/2017-challenges | 271 | 12706642 | <reponame>rchicoli/2017-challenges
a = input("Enter your string to reverse: \n")
print(a[::-1])
|
projects/DensePose/tests/test_video_keyframe_dataset.py | mmabrouk/detectron2 | 21,274 | 12706671 | <gh_stars>1000+
# Copyright (c) Facebook, Inc. and its affiliates.
import contextlib
import os
import random
import tempfile
import unittest
import torch
import torchvision.io as io
from densepose.data.transform import ImageResizeTransform
from densepose.data.video import RandomKFramesSelector, VideoKeyframeDataset
... |
qcengine/procedures/nwchem_opt/__init__.py | MolSSI/dqm_compute | 105 | 12706703 | from typing import Union, Dict, Any
from qcelemental.models import OptimizationInput, AtomicInput, OptimizationResult, Provenance
from qcengine.config import TaskConfig
from qcengine.exceptions import UnknownError, InputError
from qcengine.procedures.nwchem_opt.harvester import harvest_as_atomic_result
from qcengine.... |
examples/render/dimension_linear.py | mozman/ezdxf | 515 | 12706709 | <filename>examples/render/dimension_linear.py
# Purpose: using DIMENSION horizontal, vertical and rotated
# Copyright (c) 2018-2021, <NAME>
# License: MIT License
from typing import TYPE_CHECKING
import sys
import math
import pathlib
import random
import ezdxf
from ezdxf.tools.standards import setup_dimstyle
from ezdxf... |
stable_nalu/network/number_translation.py | wlm2019/Neural-Arithmetic-Units | 147 | 12706716 |
import torch
from ..abstract import ExtendedTorchModule
from ..layer import GeneralizedLayer, GeneralizedCell
class NumberTranslationNetwork(ExtendedTorchModule):
UNIT_NAMES = GeneralizedCell.UNIT_NAMES
def __init__(self, unit_name,
embedding_size=2, # 1 for the number, 1 for the gate ?
... |
sdk/python/pulumi_gcp/monitoring/alert_policy.py | sisisin/pulumi-gcp | 121 | 12706727 | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** 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, overload
from .. import... |
pyltr/metrics/tests/test_roc.py | Haiga/pyltr | 432 | 12706749 | """
Testing for AUC ROC metric.
"""
from . import helpers
import itertools
import numpy as np
import pyltr
import sklearn.metrics
class TestAUCROC(helpers.TestMetric):
def get_metric(self):
return pyltr.metrics.AUCROC()
def get_queries_with_values(self):
for i in range(0, 7):
f... |
beartype/_util/hint/pep/proposal/pep484/utilpep484ref.py | posita/beartype | 1,056 | 12706753 | #!/usr/bin/env python3
# --------------------( LICENSE )--------------------
# Copyright (c) 2014-2021 Beartype authors.
# See "LICENSE" for further details.
'''
Project-wide :pep:`484`-compliant **forward reference type hint utilities**
(i.e., callables specifically applicable to :pep:`484`-... |
precise/stats.py | Tony763/mycroft-precise | 626 | 12706783 | #!/usr/bin/env python3
# Copyright 2019 Mycroft AI 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... |
rex/exploit/cgc/__init__.py | tiedaoxiaotubie/rex | 471 | 12706800 | <filename>rex/exploit/cgc/__init__.py<gh_stars>100-1000
from .cgc_type1_exploit import CGCType1Exploit
from .cgc_type2_exploit import CGCType2Exploit
from .cgc_exploit import CGCExploit
from .type1 import CGCType1RopExploit, CGCType1ShellcodeExploit, CGCType1CircumstantialExploit
from .type2 import CGCType2RopExploit, ... |
models/mli/fairness/reweighing_recipe.py | pragnesh-ai/driverlessai-recipes | 194 | 12706819 | """Debiasing using reweighing"""
"""
This data recipe performs reweighing debiasing using the AIF360 package.
https://github.com/Trusted-AI/AIF360
<NAME>., <NAME>. Data preprocessing techniques for classification without discrimination.
Knowl Inf Syst 33, 1–33 (2012). https://doi.org/10.1007/s10115-011-0463-8
The... |
tests/test_defs.py | jayvdb/ipynb | 208 | 12706839 | import pytest
import importlib
@pytest.fixture(
scope='module',
params=[
'ipynb.fs.defs.pure_ipynb.foo',
'ipynb.fs.defs.mixed_ipynb.foo'
]
)
def foo(request):
return importlib.import_module(request.param)
@pytest.fixture(
scope='module',
params=[
'ipynb.fs.defs.pure_ip... |
mealpy/human_based/CA.py | thieu1995/mealpy | 162 | 12706851 | <filename>mealpy/human_based/CA.py
#!/usr/bin/env python
# ------------------------------------------------------------------------------------------------------%
# Created by "Thieu" at 12:09, 02/03/2021 %
# ... |
davarocr/davarocr/davar_common/core/__init__.py | icedream2/DAVAR-Lab-OCR | 387 | 12706872 | <reponame>icedream2/DAVAR-Lab-OCR<gh_stars>100-1000
"""
##################################################################################################
# Copyright Info : Copyright (c) Davar Lab @ Hikvision Research Institute. All rights reserved.
# Filename : __init__.py
# Abstract :
# Current Ve... |
gui/custom.py | AXeL-dev/Dindo-Bot | 102 | 12706893 | <reponame>AXeL-dev/Dindo-Bot<gh_stars>100-1000
# <NAME>
# Copyright (c) 2018 - 2019 AXeL
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, Gdk, Pango
from lib.tools import fit_position_to_destination
from lib.parser import parse_color
import math
class CustomComboBox(Gtk.ComboBoxText):
def _... |
tools/accuracy_checker/accuracy_checker/annotation_converters/lmdb.py | APrigarina/open_model_zoo | 1,031 | 12706912 | """
Copyright (c) 2018-2021 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in wri... |
setup.py | nigoroll/django-rest-framework-jwt | 165 | 12706918 | <filename>setup.py
"""A setuptools based setup module.
See:
https://packaging.python.org/en/latest/distributing.html
https://github.com/pypa/sampleproject
"""
# Always prefer setuptools over distutils
from setuptools import setup, find_packages
setup(
package_dir={"": "src"},
packages=find_packages(where="sr... |
organize/filters/created.py | tank0226/organize | 1,231 | 12706941 | import sys
from typing import Dict, Optional, SupportsFloat
import pendulum # type: ignore
from pathlib import Path
from organize.utils import DotDict
from .filter import Filter
class Created(Filter):
"""
Matches files by created date
:param int years:
specify number of years
:param int ... |
test/bibliopixel/util/image/extract_gif_lines_test.py | rec/leds | 253 | 12706943 | import unittest
from unittest.mock import patch
from bibliopixel.util.image import extract_gif_lines
class ExtractGifLinesTest(unittest.TestCase):
def test_extract(self):
actual = list(extract_gif_lines._extract(GIF_LINES))
self.assertEqual(actual, EXPECTED1)
def test_extract_gif_lines(self):... |
kitti360scripts/devkits/convertOxtsPose/python/testPoseToOxts.py | carloradice/kitti360Scripts | 214 | 12706958 | <reponame>carloradice/kitti360Scripts<gh_stars>100-1000
# Test script for loading Oxts data and convert to Mercator coordinate
import os
from data import loadPoses
from utils import postprocessPoses
from convertPoseToOxts import convertPoseToOxts
if __name__=="__main__":
# root dir of KITTI-360
if 'KITTI360_DATAS... |
st3/mdpopups/pygments/lexers/agile.py | evandroforks/mdpopups | 109 | 12706992 | <reponame>evandroforks/mdpopups
# -*- coding: utf-8 -*-
"""
pygments.lexers.agile
~~~~~~~~~~~~~~~~~~~~~
Just export lexer classes previously contained in this module.
:copyright: Copyright 2006-2015 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
from .lisp import S... |
models/multi_speech_model.py | gaoyiyeah/KWS-CTC | 340 | 12706997 | from __future__ import division
import tensorflow as tf
import speech_model
class MultiSpeechModel(object):
def __init__(self, num_gpus):
self.num_gpus = num_gpus
self._init_inference = False
self._init_cost = False
self._init_train = False
def init_inference(self, config):
... |
tests/test_simulation.py | SebastianoF/pyro2 | 151 | 12707010 | <filename>tests/test_simulation.py
import simulation_null as sn
from util import runparams
import mesh.patch as patch
import mesh.boundary as bnd
class TestSimulation(object):
@classmethod
def setup_class(cls):
""" this is run once for each class before any tests """
pass
@classmethod
... |
applications/DEMApplication/tests/test_glued_particles.py | lkusch/Kratos | 778 | 12707035 | import os
import KratosMultiphysics as Kratos
from KratosMultiphysics import Logger
Logger.GetDefaultOutput().SetSeverity(Logger.Severity.WARNING)
import KratosMultiphysics.KratosUnittest as KratosUnittest
import KratosMultiphysics.DEMApplication.DEM_analysis_stage as DEM_analysis_stage
import auxiliary_functions_for_... |
Algorithms/Longest_Consecutive_Sequence.py | abdzitter/Daily-Coding-DS-ALGO-Practice | 289 | 12707045 | <gh_stars>100-1000
# lcs = longest_consecutive_series
# ccn = count_of_consecutive_numbers
class Solution(object): #main function
def longestConsecutive(self, values): #sub funcction
lcs = 0 # Initializing
for i in values: # Iteration the given value
if i-1 not in values: # condition check
... |
DaPy/methods/regressors/lr.py | huihui7987/DaPy | 552 | 12707078 | <gh_stars>100-1000
from DaPy.methods.core import BaseLinearModel
class LinearRegressor(BaseLinearModel):
def __init__(self, engine='numpy', learn_rate=0.05, l1_penalty=0, l2_penalty=0, fit_intercept=True):
BaseLinearModel.__init__(self, engine, learn_rate, l1_penalty, l2_penalty, fit_intercept)
def _f... |
owtf/lib/exceptions.py | Udbhavbisarya23/owtf | 1,514 | 12707151 | <gh_stars>1000+
"""
owtf.lib.exceptions
~~~~~~~~~~~~~~~~~~~
Declares the framework exceptions and HTTP errors
"""
try:
from http.client import responses
except ImportError:
from httplib import responses
import tornado.web
class FrameworkException(Exception):
def __init__(self, value):
self.param... |
openmdao/docs/openmdao_book/other/disable_snopt_cells.py | friedenhe/OpenMDAO | 451 | 12707154 | import json
def disable_snopt_cells(fname):
"""
Once the first SNOPT cell is found, delete all code cells.
Parameters
----------
fname : str
Name of the notebook file, from openmdao_book.
"""
fname = f'openmdao_book/{fname}'
with open(fname) as f:
dct = json.load(f)
... |
AutotestWebD/apps/myadmin/service/UserLogService.py | yangjourney/sosotest | 422 | 12707216 | <filename>AutotestWebD/apps/myadmin/service/UserLogService.py
from all_models.models import TbUserLog
class UserLogService(object):
@staticmethod
def updateUserLogService(permissionData):
tbModel = TbUserLog.objects.filter(id=permissionData["id"])
tbModel.update(**permissionData)
|
plenario/apiary/views.py | vforgione/plenario | 109 | 12707224 | <filename>plenario/apiary/views.py<gh_stars>100-1000
from json import dumps, loads
from flask import Blueprint
from redis import Redis
from sqlalchemy import desc, select
from plenario.database import redshift_base as rshift_base
from plenario.models.SensorNetwork import SensorMeta
from plenario.settings import REDIS... |
longclaw/shipping/serializers/rates.py | al-bezd/longclaw | 351 | 12707229 | from rest_framework import serializers
from longclaw.shipping.models.rates import ShippingRate
class ShippingRateSerializer(serializers.ModelSerializer):
class Meta:
model = ShippingRate
fields = "__all__"
|
configs/_base_/schedules/schedule_1x.py | kazakh-shai/kaggle-global-wheat-detection | 136 | 12707257 | # optimizer
optimizer = dict(type="SGD", lr=0.04, momentum=0.9, weight_decay=0.0001)
optimizer_config = dict(grad_clip=None)
# learning policy
lr_config = dict(policy="step", warmup="linear", warmup_iters=100, warmup_ratio=0.001, step=[7, 11])
total_epochs = 12
|
ufora/FORA/Compiler/Compiler_test.py | ufora/ufora | 571 | 12707265 | <gh_stars>100-1000
# 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 applicable... |
tests/test_serialisation.py | gaganchhabra/appkernel | 156 | 12707270 | from .utils import *
def setup_function(function):
""" executed before each method call
"""
print('\n\nSETUP ==> ')
def teardown_function(function):
""" teardown any state that was previously setup with a setup_method
call.
"""
print("\nTEAR DOWN <==")
def test_basic_serialisation():
... |
src/plugins/nat/extras/nat_ses_open.py | yasics/vpp | 751 | 12707271 | from trex_stl_lib.api import *
class STLS1:
def __init__ (self):
self.ip_range = {'local': {'start': "10.0.0.3", 'end': "10.1.255.255"},
'external': {'start': "172.16.1.3", 'end': "172.16.1.3"},
'remote': {'start': "2.2.0.1", 'end': "2.2.0.1"}}
sel... |
src/app/tests/tests_s3_client.py | iNerV/education-backend | 151 | 12707297 | import pytest
from app.integrations.s3 import AppS3
pytestmark = [pytest.mark.django_db]
def test_client_init():
client = AppS3().client
assert 'botocore.client.S3' in str(client.__class__)
|
sublime_jedi/go_to.py | zjzh/SublimeJEDI | 641 | 12707312 | <gh_stars>100-1000
# -*- coding: utf-8 -*-
try:
from typing import Set, List, Tuple, Any
except Exception:
pass
import sublime
import sublime_plugin
from functools import partial
import re
from .utils import to_relative_path, PythonCommandMixin, get_settings, is_python_scope, debounce
from .daemon import ask_... |
grow/extensions/hooks/deployment_register_hook_test.py | tabulon-ext/grow | 335 | 12707320 | <reponame>tabulon-ext/grow<gh_stars>100-1000
"""Tests for deployment destination registration hook."""
import unittest
from grow.extensions.hooks import deployment_register_hook
class DeploymentRegisterHookTestCase(unittest.TestCase):
"""Test the deployment destination registration hook."""
def test_somethi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.