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 |
|---|---|---|---|---|
Alignment/APEEstimation/test/plottingTools/systematicErrors.py | ckamtsikis/cmssw | 852 | 12657552 | import numpy as np
import ROOT
DIR_BOTH = 0
DIR_UP = 1
DIR_DOWN = -1
NUM_SECTORS = 68
NUM_SECTORS_Y = 14
# systematics has:
# a dict with with coordinate names "X", "Y" as keys
# - each value of these keys is a list/an array of systematic errors for each sector
# - so the list ha... |
hwt/serializer/verilog/serializer.py | ufo2011/hwt | 134 | 12657553 | from copy import copy
from typing import Optional, List
from hdlConvertorAst.hdlAst import HdlStmIf, HdlOp, \
HdlOpType, HdlValueId, HdlModuleDec, iHdlStatement
from hdlConvertorAst.hdlAst._defs import HdlIdDef
from hdlConvertorAst.hdlAst._expr import HdlTypeAuto
from hdlConvertorAst.hdlAst._statements import HdlS... |
cwltool/singularity_utils.py | RenskeW/cwltool | 289 | 12657559 | <gh_stars>100-1000
"""Support for executing Docker containers using the Singularity 2.x engine."""
import os
import os.path
from subprocess import DEVNULL, PIPE, Popen, TimeoutExpired # nosec
from typing import Optional
_USERNS = None # type: Optional[bool]
def singularity_supports_userns() -> bool:
"""Confir... |
glance/async_/flows/plugins/__init__.py | daespinel/glance | 309 | 12657563 | # Copyright 2017 Red Hat, 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... |
deps/zxing/zxing.gyp | rwaldron/node-dv | 264 | 12657594 | <reponame>rwaldron/node-dv
{
'includes': [ '../common.gyp' ],
'targets': [
{
'target_name': 'libzxing',
'type': 'static_library',
'include_dirs': [
'core/src',
],
'sources': [
'core/src/bigint/BigInteger.cc',
'core/src/bigint/BigIntegerAlgorithms.cc',
... |
users/urls.py | hrbhat/twissandra | 308 | 12657606 | <filename>users/urls.py
from django.conf.urls.defaults import patterns, url
urlpatterns = patterns('users.views',
url('^login/$', 'login', name='login'),
url('^logout/$', 'logout', name='logout'),
url(r'^find-friends/$', 'find_friends', name='find_friends'),
url(r'^modify-friend/$', 'modify_friend', na... |
pytorch_neat/aggregations.py | GPittia/PyTorch-NEAT | 486 | 12657641 | # Copyright (c) 2018 Uber Technologies, 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 ag... |
Code/Chenglong/utils/xgb_utils.py | ChenglongChen/Kaggle_Homedepot | 465 | 12657671 | <filename>Code/Chenglong/utils/xgb_utils.py
# -*- coding: utf-8 -*-
"""
@author: <NAME> <<EMAIL>>
@brief: utils for XGBoost models
"""
import numpy as np
import matplotlib
matplotlib.use('Agg')
import xgboost as xgb
class XGBRegressor:
def __init__(self, booster='gbtree', base_score=0., colsample_bylevel=1.,
... |
python/kwiver/vital/tests/test_sfm_constraints.py | mwoehlke-kitware/kwiver | 176 | 12657681 | """
ckwg +31
Copyright 2020 by Kitware, Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the ... |
BlenderAddon/data.py | gamekit-developers/gamekit | 241 | 12657687 | <reponame>gamekit-developers/gamekit<filename>BlenderAddon/data.py<gh_stars>100-1000
bl_addon_data =
{
(2,5,3):
{
(0,0,601):
{
'binary_name':'ogrekit',
'api_compatibility':
{
31845:{
(0,0,601):(995,-1)
... |
playx/playlist/youtube.py | Saul-Dickson/playx | 221 | 12657688 | <reponame>Saul-Dickson/playx<filename>playx/playlist/youtube.py
"""Youtube playlist related functions and classes
defined.
"""
import json
import requests
from bs4 import BeautifulSoup
import re
from playx.utility import exe
from playx.playlist.playlistbase import PlaylistBase, SongMetadataBase
from playx.stringutil... |
tests/console/commands/self/utils.py | zEdS15B3GCwq/poetry | 7,258 | 12657689 | from __future__ import annotations
from pathlib import Path
from typing import TYPE_CHECKING
from poetry.factory import Factory
if TYPE_CHECKING:
from tomlkit.container import Table as TOMLTable
def get_self_command_dependencies(locked: bool = True) -> TOMLTable:
from poetry.console.commands.self.self_com... |
gluon/gluoncv2/models/fishnet.py | naviocean/imgclsmob | 2,649 | 12657701 | """
FishNet for ImageNet-1K, implemented in Gluon.
Original paper: 'FishNet: A Versatile Backbone for Image, Region, and Pixel Level Prediction,'
http://papers.nips.cc/paper/7356-fishnet-a-versatile-backbone-for-image-region-and-pixel-level-prediction.pdf.
"""
__all__ = ['FishNet', 'fishnet99', 'fishnet150... |
learning/setup.py | dibakch/differential-privacy | 2,550 | 12657704 | <reponame>dibakch/differential-privacy<gh_stars>1000+
# Copyright 2021 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unle... |
envs/hns/mujoco-worldgen/mujoco_worldgen/objs/material.py | jiayu-ch15/curriculum | 424 | 12657755 | import numpy as np
import hashlib
from collections import OrderedDict
from mujoco_worldgen.objs.obj import Obj
from mujoco_worldgen.util.types import store_args
class Material(Obj):
placeable = False
@store_args
def __init__(self,
random=True,
rgba=None,
... |
insights/parsers/mongod_conf.py | maxamillion/insights-core | 121 | 12657771 | """
MongodbConf - files - Configuration files for MongoDB
=====================================================
This module contains the following files:
``/etc/mongod.conf``,
``/etc/mongodb.conf`` ,
``/etc/opt/rh/rh-mongodb26/mongod.conf``
``/etc/opt/rh/rh-mongodb34/mongod.conf``
They are provided by... |
test/url_test.py | etrepum/py-nanoid | 256 | 12657779 | <filename>test/url_test.py
from unittest import TestCase
from nanoid.resources import alphabet
class TestURL(TestCase):
def test_has_no_duplicates(self):
for i in range(len(alphabet)):
self.assertEqual(alphabet.rindex(alphabet[i]), i)
def test_is_string(self):
self.assertEqual(ty... |
ide/tests/test_source_api.py | Ramonrlb/cloudpebble | 147 | 12657791 | import json
import mock
from django.core.urlresolvers import reverse
from ide.utils.cloudpebble_test import CloudpebbleTestCase
from utils.fakes import FakeS3
__author__ = 'joe'
fake_s3 = FakeS3()
@mock.patch('ide.models.s3file.s3', fake_s3)
class TestSource(CloudpebbleTestCase):
"""Tests for the Tests models"... |
pygame_menu/examples/window_resize.py | ppizarror/pygame-menu | 419 | 12657795 | """
pygame-menu
https://github.com/ppizarror/pygame-menu
EXAMPLE - WINDOW RESIZE
Resize the menu when the window is resized.
License:
-------------------------------------------------------------------------------
The MIT License (MIT)
Copyright 2017-2021 <NAME>. @ppizarror
Permission is hereby granted, free of char... |
tests/test_model_counting.py | dannyrohde/pydbantic | 124 | 12657805 | <gh_stars>100-1000
import pytest
from tests.models import EmployeeInfo
@pytest.mark.asyncio
async def test_model_counting(loaded_database_and_model):
db, Employees = loaded_database_and_model
all_employees = await Employees.all()
employee_count = await Employees.count()
print(f"Number of Employees is... |
api/tests/integration/tests/rpe/rpe.py | tsingdao-Tp/Indigo | 204 | 12657813 | <filename>api/tests/integration/tests/rpe/rpe.py
import os
import sys
sys.path.append('../../common')
from env_indigo import *
from itertools import product
indigo = Indigo()
def getProduct(reaction):
for mol in reaction.iterateProducts():
return mol
return None
def loadSdf(sdf_path):
sdfitera... |
perf/docker/prom_client.py | daixiang0/tools | 264 | 12657834 | # Copyright Istio 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 to in writing, soft... |
ImageArt/ImageColoring.py | shekkizh/TensorflowProjects | 204 | 12657835 | <gh_stars>100-1000
__author__ = 'Charlie'
"""Image coloring by fully convolutional networks - incomplete """
import numpy as np
import tensorflow as tf
import os, sys, inspect
from datetime import datetime
import scipy.misc as misc
lib_path = os.path.realpath(
os.path.abspath(os.path.join(os.path.split(inspect.get... |
rfhub/blueprints/__init__.py | datakurre/robotframework-hub | 156 | 12657867 | <filename>rfhub/blueprints/__init__.py<gh_stars>100-1000
from rfhub.blueprints.api import blueprint as api
from rfhub.blueprints.dashboard import blueprint as dashboard
from rfhub.blueprints.doc import blueprint as doc
|
tests/app/no_metadata.py | sandutsar/voila | 2,977 | 12657870 | import pytest
NOTEBOOK_PATH = 'no_metadata.ipynb'
@pytest.fixture
def non_existing_notebook_metadata(base_url):
return base_url + f'voila/render/{NOTEBOOK_PATH}'
@pytest.fixture
def voila_args(notebook_directory, voila_args_extra):
return ['--VoilaTest.root_dir=%r' % notebook_directory] + voila_args_extra... |
tests/opytimizer/optimizers/science/test_mvo.py | anukaal/opytimizer | 528 | 12657875 | <filename>tests/opytimizer/optimizers/science/test_mvo.py
import numpy as np
from opytimizer.optimizers.science import mvo
from opytimizer.spaces import search
def test_mvo_params():
params = {
'WEP_min': 0.2,
'WEP_max': 1.0,
'p': 0.5
}
new_mvo = mvo.MVO(params=params)
asser... |
dev/examples/snapswig-check.py | Cam2337/snap-python | 242 | 12657904 | #!/usr/bin/python
# test-bfsdfs.py
#
# Author: <NAME>, Spring 2013
# Description:
# - Loads SNAP as a Python module.
# - Performs mini unit tests for the following functions:
# - gviz (graph visualization, using Gnuplot)
# - bfsfdfs (Breadth First Search)
import sys
sys.path.append("../swig-r")
import ... |
data_management/importers/noaa_seals_2019.py | dnarqq/WildHack | 402 | 12657911 | <filename>data_management/importers/noaa_seals_2019.py
#%% Imports and constants
import os
import pandas as pd
from tqdm import tqdm
# from github.com/microsoft/ai4eutils
import url_utils
# from github.com/microsoft/cameratraps
from visualization import visualization_utils
# A list of files in the lilablobssc conta... |
notebook/dir_builtins.py | vhn0912/python-snippets | 174 | 12657912 | import pprint
print(type(dir(__builtins__)))
# <class 'list'>
print(len(dir(__builtins__)))
# 153
pprint.pprint(dir(__builtins__), compact=True)
# ['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException',
# 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning',
# 'ChildProcessError', '... |
misc/config_tools/board_inspector/extractors/helpers.py | donsheng/acrn-hypervisor | 848 | 12658033 | <filename>misc/config_tools/board_inspector/extractors/helpers.py
# Copyright (C) 2021 Intel Corporation. All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
#
import lxml
def add_child(element, tag, text=None, **kwargs):
child = lxml.etree.Element(tag)
child.text = text
for k,v in kwargs.items... |
vulnscan/POC/struts2/struts2_009_poc.py | imfiver/Sec-Tools | 144 | 12658040 | import requests
# url随意
def poc(url):
print('test {} --> struts2_009'.format(url))
url += "/ajax/example5.action"
#执行ls 命令
exp = "?age=12313&name=(%23context[%22xwork.MethodAccessor.denyMethodExecution%22]=+new+java.lang.Boolean(false),+%23_memberAccess[%22allowStaticMethodAccess%22]=true,+%23a=... |
peeringdb_server/client_adaptor/setup.py | CyberFlameGO/peeringdb | 224 | 12658052 | <filename>peeringdb_server/client_adaptor/setup.py
"""
django-peeringdb backend setup (needed for pdb_load_data command)
"""
from django_peeringdb.client_adaptor.setup import configure # noqa
|
rlgraph/components/loss_functions/euclidian_distance_loss.py | RLGraph/RLGraph | 290 | 12658061 | <gh_stars>100-1000
# Copyright 2018/2019 ducandu GmbH, 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 requi... |
recipes/Python/577371_sending_gmail_though_python_code/recipe-577371.py | tdiprima/code | 2,023 | 12658077 | #Sending an email through gmail using Python - <NAME>
import smtplib
fromaddr = '<EMAIL>'
toaddrs = '<EMAIL>'
msg = 'Email message from PYTHON Raghuram app'
#provide gmail user name and password
username = 'gmailUserName'
password = '<PASSWORD>'
# functions to send an email
server = smtplib.SMTP('smtp.gmail.com:587')... |
maro/utils/exception/__init__.py | yangboz/maro | 598 | 12658091 | from .base_exception import MAROException
from .error_code import ERROR_CODE
__all__ = ["ERROR_CODE", "MAROException"]
|
scripts/probitRegDemo.py | vipavlovic/pyprobml | 4,895 | 12658107 | <filename>scripts/probitRegDemo.py<gh_stars>1000+
import superimport
import numpy as np
from scipy.stats import norm
from scipy.optimize import minimize
from matplotlib import pyplot as plt
from cycler import cycler
import jax.numpy as jnp
import jax.scipy.stats.norm as jnorm
from jax import grad
import pyprobml_utils... |
koku/masu/test/processor/azure/test_azure_report_charge_updater.py | rubik-ai/koku | 157 | 12658142 | <reponame>rubik-ai/koku
#
# Copyright 2021 Red Hat Inc.
# SPDX-License-Identifier: Apache-2.0
#
"""Test the AzureCostModelCostUpdater object."""
from masu.database.azure_report_db_accessor import AzureReportDBAccessor
from masu.external.date_accessor import DateAccessor
from masu.processor.azure.azure_cost_model_cost_u... |
Python/hello_waldo.py | saurabhcommand/Hello-world | 1,428 | 12658143 | <gh_stars>1000+
print('Hello Waldo!')
|
etc/converter/convert-to-FfDL.py | adrian555/FfDL | 680 | 12658163 | <filename>etc/converter/convert-to-FfDL.py
#
# Copyright 2017-2018 IBM 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 re... |
OnePy/sys_module/components/market_maker.py | Chandlercjy/OnePyfx | 321 | 12658175 | import arrow
from OnePy.constants import EVENT
from OnePy.sys_module.components.exceptions import (BacktestFinished,
BlowUpError)
from OnePy.sys_module.metabase_env import OnePyEnvBase
from OnePy.sys_module.models.base_bar import BarBase
from OnePy.sys_module.models.... |
wooey/migrations/0014_wooeyjob_uuid_finalise.py | fridmundklaus/wooey | 1,572 | 12658202 | <reponame>fridmundklaus/wooey
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import uuid
class Migration(migrations.Migration):
dependencies = [
('wooey', '0013_wooeyjob_uuid_populate'),
]
operations = [
# Set to unique=True
... |
core/envs/lab.py | R3NI3/pytorch-rl | 851 | 12658283 | <filename>core/envs/lab.py
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from copy import deepcopy
from gym.spaces.box import Box
import inspect
from utils.helpers import Experience # NOTE: here state0 is always "None"
from ut... |
aim/sdk/objects/audio.py | avkudr/aim | 2,195 | 12658293 | import io
import logging
import os.path
from aim.sdk.num_utils import inst_has_typename
from aim.sdk.objects.io import wavfile
from aim.storage.object import CustomObject
from aim.storage.types import BLOB
logger = logging.getLogger(__name__)
@CustomObject.alias('aim.audio')
class Audio(CustomObject):
"""Audio ... |
appendix/check_diff_upresnet10.py | ly17java8-yangsen/waifu2x-caffe | 7,366 | 12658318 | <reponame>ly17java8-yangsen/waifu2x-caffe
import os
import os.path as osp
import sys
import google.protobuf as pb
from argparse import ArgumentParser
import numpy as np
import shutil
import caffe
from caffe.proto import caffe_pb2
sys.path.append('waifu2x-chainer')
from lib import srcnn
import chainer
def main():
... |
resources/utility_scripts/process_subjects.py | inaccel/TractSeg | 148 | 12658342 | <reponame>inaccel/TractSeg
"""
Random code for testing purposes
"""
from pathlib import Path
import subprocess as sp
from p_tqdm import p_map
import numpy as np
def run_tractseg(subject_id):
# dir = base / subject_id
dir = base / subject_id / "session_1"
# sp.call(f"TractSeg -i {dir}/peaks.nii.gz --previe... |
flask_security/models/__init__.py | briancappello/flask-security | 317 | 12658351 | <gh_stars>100-1000
""""
Copyright 2019 by <NAME> (jwag). All rights reserved.
:license: MIT, see LICENSE for more details.
This packages contains OPTIONAL models for various ORMs/databases that can be used
to quickly get the required DB models setup.
These models have the fields for ALL features. This makes it easy f... |
lib/cheroot/__init__.py | 0x20Man/Watcher3 | 320 | 12658354 | """Cheroot is the high-performance, pure-Python HTTP server used by CherryPy."""
try:
import pkg_resources
except ImportError:
pass
try:
__version__ = pkg_resources.get_distribution('cheroot').version
except Exception:
__version__ = 'unknown'
|
stocklook/apis/yahoo_db/database.py | zbarge/stocklook | 149 | 12658357 | import datetime
import logging
import os
import pandas as pd
from sqlalchemy import create_engine, and_
from sqlalchemy.orm import sessionmaker
from yahoo_finance import Share, YQLResponseMalformedError
from stocklook.utils.formatters import get_stock_data, field_map, get_stock_data_historical
from .tables import Quo... |
shorttext/metrics/embedfuzzy/jaccard.py | vishalbelsare/PyShortTextCategorization | 481 | 12658413 |
from itertools import product
import numpy as np
from scipy.spatial.distance import cosine
from shorttext.utils import tokenize
def jaccardscore_sents(sent1, sent2, wvmodel, sim_words=lambda vec1, vec2: 1-cosine(vec1, vec2)):
""" Compute the Jaccard score between sentences based on their word similarities.
... |
Chapter12/sample_http_server.py | JTamarit/Tkinter_libro | 173 | 12658422 | from http.server import HTTPServer, BaseHTTPRequestHandler
class TestHandler(BaseHTTPRequestHandler):
def _print_request_data(self):
content_length = self.headers['Content-Length']
print("Content-length: {}".format(content_length))
data = self.rfile.read(int(content_length))
print... |
brownie/network/middlewares/geth_poa.py | ActorForth/brownie | 1,595 | 12658431 | from typing import Callable, Dict, List, Optional
from web3 import Web3
from web3.exceptions import ExtraDataLengthError
from web3.middleware import geth_poa_middleware
from brownie.network.middlewares import BrownieMiddlewareABC
class GethPOAMiddleware(BrownieMiddlewareABC):
@classmethod
def get_layer(cls,... |
tests/jit/__init__.py | ldelebec/asteroid | 722 | 12658505 | <reponame>ldelebec/asteroid
import pytest
ignored_warnings = [
"ignore:torch.tensor results are registered as constants in the trace.",
"ignore:Converting a tensor to a Python boolean might cause the trace to be incorrect.",
"ignore:Converting a tensor to a Python float might cause the trace to be incorrec... |
modelchimp/views/api/experiment_metric.py | samzer/modelchimp-server | 134 | 12658511 | from rest_framework import status, viewsets
from rest_framework.response import Response
from rest_framework import mixins
from modelchimp.models.experiment import Experiment
from modelchimp.api_permissions import HasProjectMembership
from rest_framework.permissions import IsAuthenticated
class ExperimentMetricAPI(... |
problems/building-h2o/building_h2o.py | jianpingbadao/leetcode | 198 | 12658537 | <filename>problems/building-h2o/building_h2o.py<gh_stars>100-1000
#!/usr/bin/env python
class H2O:
def __init__(self):
pass
def hydrogen(self, releaseHydrogen: 'Callable[[], None]') -> None:
# releaseHydrogen() outputs "H". Do not change or remove this line.
releaseHydrogen()... |
xclim/testing/tests/test_utils.py | ECCC-CCCS/xclim | 169 | 12658539 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Test for utils
from inspect import signature
import numpy as np
import xarray as xr
from xclim.core.indicator import Daily
from xclim.core.utils import (
ensure_chunk_size,
nan_calc_percentiles,
walk_map,
wrapped_partial,
)
def test_walk_map():
d =... |
CommonTools/ParticleFlow/python/Isolation/pfIsolatedMuons_cfi.py | ckamtsikis/cmssw | 852 | 12658557 | <filename>CommonTools/ParticleFlow/python/Isolation/pfIsolatedMuons_cfi.py
import FWCore.ParameterSet.Config as cms
pfIsolatedMuons = cms.EDFilter(
"PFCandidateFwdPtrCollectionStringFilter",
src = cms.InputTag("pfMuonsFromVertex"),
cut = cms.string("pt > 5 & muonRef.isAvailable() & "\
... |
pywemo/ouimeaux_device/outdoor_plug.py | sullivanmj/pywemo | 102 | 12658583 | <filename>pywemo/ouimeaux_device/outdoor_plug.py
"""Representation of a WeMo OutdoorPlug device."""
from .switch import Switch
class OutdoorPlug(Switch):
"""Representation of a WeMo Motion device."""
|
rpython/jit/metainterp/optimizeopt/test/test_guard.py | nanjekyejoannah/pypy | 333 | 12658588 | <reponame>nanjekyejoannah/pypy
from rpython.jit.metainterp import compile
from rpython.jit.metainterp.history import Const
from rpython.jit.metainterp.optimizeopt.dependency import (
DependencyGraph, IndexVar)
from rpython.jit.metainterp.optimizeopt.guard import (GuardStrengthenOpt,
Guard)
from rpython.jit.... |
tests/components/nina/__init__.py | MrDelik/core | 30,023 | 12658609 | """Tests for the Nina integration."""
import json
from typing import Any
from tests.common import load_fixture
def mocked_request_function(url: str) -> dict[str, Any]:
"""Mock of the request function."""
dummy_response: dict[str, Any] = json.loads(
load_fixture("sample_warnings.json", "nina")
)
... |
chapter8_PyTorch项目实战/text_classification/model.py | Tisword/pytorch-in-action | 164 | 12658629 | <reponame>Tisword/pytorch-in-action
import torch
import torch.nn as nn
import torch.nn.functional as F
class CNN_Text(nn.Module):
def __init__(self, args):
super(CNN_Text, self).__init__()
self.args = args
embed_num = args.embed_num
embed_dim = args.embed_dim
class_num = a... |
webhook/views/views.py | nobgr/xray | 7,086 | 12658636 | import datetime
from datetime import datetime
from executor.executor import dispatch_web_vuln, dispatch_service_vuln, dispatch_statistics
from model.vuln import Statistics, WebVuln, WebParam, WebParamPosition, WebRequest, WebResponse, ServiceVuln
def process_web_vuln(instance, data):
"""将 web 漏洞 json 转换为相关 model... |
seahub/api2/endpoints/admin/file_audit.py | MJochim/seahub | 420 | 12658665 | # Copyright (c) 2012-2016 Seafile Ltd.
import logging
from rest_framework.authentication import SessionAuthentication
from rest_framework.permissions import IsAdminUser
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework import status
from seaserv import seafile_a... |
sample.py | vzkqwvku/kglab | 388 | 12658669 | <filename>sample.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import kglab
# create a KnowledgeGraph object
kg = kglab.KnowledgeGraph()
# load RDF from a URL
kg.load_rdf("https://storage.googleapis.com/kglab-tutorial/foaf.rdf", format="xml")
# measure the graph
measure = kglab.Measure()
measure.measure_graph(kg... |
packages/pyright-internal/src/tests/samples/genericTypes29.py | sasano8/pyright | 241 | 12658670 | <gh_stars>100-1000
# This sample tests bidirectional inference when the
# type derives from the expected type and both are
# generic.
from typing import Mapping, Optional, Union
v0: Optional[Mapping[str, Union[int, str]]] = dict([("test1", 1), ("test2", 2)])
v1: Optional[Mapping[str, float]] = dict([("test1", 1), ("... |
bin/keygen.py | 641i130/keygen | 114 | 12658701 | #!/usr/bin/env python3
import argparse
import os
import string
import sys
import subprocess
parser = argparse.ArgumentParser(description='Generates keys.', epilog='All remaining arguments are passed to OpenSCAD.')
parser.add_argument("filename",
help="OpenSCAD source file for the key")
parser.add_... |
.workshop/jupyterhub_config.py | blues-man/lab-tekton-pipelines | 109 | 12658702 | os.environ["OPENSHIFT_PROJECT"] = "{username}" |
test/hlt/pytest/python/com/huawei/iotplatform/client/dto/BatchTaskCreateOutDTO.py | yuanyi-thu/AIOT- | 128 | 12658781 | class BatchTaskCreateOutDTO(object):
def __init__(self):
self.taskID = None
def getTaskID(self):
return self.taskID
def setTaskID(self, taskID):
self.taskID = taskID
|
desktop_local_tests/windows/test_windows_packet_capture_disrupt_enable_new_adapter.py | UAEKondaya1/expressvpn_leak_testing | 219 | 12658792 | <reponame>UAEKondaya1/expressvpn_leak_testing
from desktop_local_tests.local_packet_capture_test_case_with_disrupter import LocalPacketCaptureTestCaseWithDisrupter
from desktop_local_tests.windows.windows_enable_new_adapter_disrupter import WindowsEnableNewAdapterDisrupter
class TestWindowsPacketCaptureDisruptEnableNe... |
tests/utils.py | mariot/djangorestframework-api-key | 462 | 12658793 | import typing
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import BasePermission
from rest_framework.response import Response
def create_view_with_permissions(
*classes: typing.Type[BasePermission],
) -> typing.Callable:
@api_view()
@permission_classe... |
paper/check-genome-true-positives.py | zihhuafang/slivar_vep105 | 162 | 12658796 | <gh_stars>100-1000
import toolshed
import collections
import hashlib
slivar_found = collections.defaultdict(list)
# first file is tsv from slivar
for d in toolshed.reader(1):
slivar_found[d["sample_id"]].append(d["chr:pos:ref:alt"])
shared_affected = 0
shared_affected_solved = 0
exact_match = 0
sv_del = 0
oocyt... |
robogym/mujoco/warning_buffer.py | 0xflotus/robogym | 288 | 12658817 | <reponame>0xflotus/robogym
import collections
import logging
import mujoco_py.cymj as cymj
logger = logging.getLogger(__name__)
class MujocoErrorException(Exception):
""" Exception raised when mujoco error is called. """
pass
def error_callback(message):
""" Mujoco error callback """
message = me... |
configs/linear/cifar10_res18.py | xyupeng/ContrastiveCrop | 148 | 12658829 | <reponame>xyupeng/ContrastiveCrop<filename>configs/linear/cifar10_res18.py<gh_stars>100-1000
# model
model = dict(type='ResNet', depth=18, num_classes=10, maxpool=False)
loss = dict(type='CrossEntropyLoss')
# dataset
root = '/path/to/your/dataset'
mean = (0.4914, 0.4822, 0.4465)
std = (0.2023, 0.1994, 0.2010)
batch_si... |
chapter2_training/model_db/src/db/schemas.py | sudabon/ml-system-in-actions | 133 | 12658865 | import datetime
from typing import Dict, Optional
from pydantic import BaseModel
class ProjectBase(BaseModel):
project_name: str
description: Optional[str]
class ProjectCreate(ProjectBase):
pass
class Project(ProjectBase):
project_id: int
created_datetime: datetime.datetime
class Config:... |
polymetis/polymetis/python/polymetis/_version.py | ali-senguel/fairo | 669 | 12658903 | import os
import json
import polymetis
__version__ = ""
# Conda installed: Get version of conda pkg (assigned $GIT_DESCRIBE_NUMBER during build)
if "CONDA_PREFIX" in os.environ and os.environ["CONDA_PREFIX"] in polymetis.__file__:
# Search conda pkgs for polymetis & extract version number
stream = os.popen("... |
linked_list_cycle_ii/solution.py | mahimadubey/leetcode-python | 528 | 12658915 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @param head, a ListNode
# @return a list node
def detectCycle(self, head):
if head is None or head.next is None:
return None
sl... |
examples/sharepoint/pages/create_modern_page.py | theodoriss/Office365-REST-Python-Client | 544 | 12658945 | <reponame>theodoriss/Office365-REST-Python-Client<filename>examples/sharepoint/pages/create_modern_page.py
from office365.sharepoint.client_context import ClientContext
from office365.sharepoint.publishing.site_page import SitePage
from tests import test_client_credentials, test_team_site_url
ctx = ClientContext(test_... |
grow/deployments/destinations/local_test.py | denmojo/pygrow | 335 | 12658957 | <reponame>denmojo/pygrow
from . import local
import unittest
class LocalDestinationTestCase(unittest.TestCase):
def test_out_dir(self):
config = local.Config(out_dir='~/test/')
destination = local.LocalDestination(config)
# Weakly verify out_dir is expanded.
self.assertNotIn('~', ... |
starcluster/sc_pysph.py | nauaneed/pysph | 293 | 12658974 | from starcluster.clustersetup import DefaultClusterSetup
from starcluster.logger import log
class PySPHInstallerBase(DefaultClusterSetup):
PYSPH_PROFILE = "/etc/profile.d/pysph.sh"
PYSPH_HOSTS = "/home/pysph/PYSPH_HOSTS"
PYSPH_USER = "pysph"
def _create_env(self, master):
master.ssh.execute(
... |
endtoend_tests/forseti/explain/why_denied_test.py | aarontp/forseti-security | 921 | 12658976 | <filename>endtoend_tests/forseti/explain/why_denied_test.py
# Copyright 2020 The Forseti Security 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://w... |
setup.py | nessessence/dropblock | 556 | 12658999 | <filename>setup.py
from setuptools import setup, find_packages
with open('requirements.txt', encoding='utf-8') as f:
required = f.read().splitlines()
with open('README.md', encoding='utf-8') as f:
long_description = f.read()
setup(
name='dropblock',
version='0.3.0',
packages=find_packages(),
... |
tests/test_additional_commands.py | ils-nsolanki/dev-buildpack | 133 | 12659009 | <reponame>ils-nsolanki/dev-buildpack
from build_pack_utils import utils
extn = utils.load_extension('lib/additional_commands')
class TestAdditionalCommandsExtension(object):
def test_no_additional_commands(self):
ctx = {}
tmp = extn.preprocess_commands(ctx)
assert tmp == []
def test... |
tests/unit/test_cli.py | ClementPruvot/slo-generator | 243 | 12659017 | <gh_stars>100-1000
# Copyright 2019 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law... |
tests/unit/containers/test_envvarcollector.py | senstb/aws-elastic-beanstalk-cli | 110 | 12659029 | <gh_stars>100-1000
# Copyright 2017 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.amazon.com/apache2.0/
#
# or in the 'li... |
fsf-server/modules/EXTRACT_CAB.py | akniffe1/fsf | 259 | 12659037 | <gh_stars>100-1000
#!/usr/bin/env python
#
# Author: <NAME>
# Description: Unpack CAB using cabextract as a helper.
# Basically returns a stream of all the uncompressed contents,
# multiple files are lumped together for displacement by other modules.
# Date: 12/02/2015
# Reference: http://download.microsoft.com/downloa... |
note8/code/infer.py | fluffyrita/LearnPaddle | 367 | 12659047 | <reponame>fluffyrita/LearnPaddle<filename>note8/code/infer.py<gh_stars>100-1000
# coding=utf-8
import gzip
import paddle.v2 as paddle
from network_conf import Model
from reader import DataGenerator
from decoder import ctc_greedy_decoder
from utils import get_file_list, load_dict, load_reverse_dict
def infer_batch(i... |
tools/contributors.py | WarrDaddy/owasp-mstg | 9,156 | 12659079 | import json
import requests
url = 'https://api.github.com/repos/OWASP/owasp-mstg/stats/contributors'
headers = {'Accept' : 'application/vnd.github.v3+json'}
r = requests.get(url, headers=headers)
data = r.json()
coAuthor = "Author/Co-Authors: "
topContributors = "Top Contributors: "
contributors = "Contributors: "
... |
seq2seq_construction/__init__.py | HKUNLP/UnifiedSKG | 191 | 12659097 | <filename>seq2seq_construction/__init__.py
#
# class TrainDataset(Dataset):
#
# def __init__(self, args, raw_datasets):
# # This tab processor is for table truncation and linearize.
# self.raw_datasets = raw_datasets
#
# def __getitem__(self, index) -> T_co:
# raw_data = self.raw_dataset... |
test/python/tests/ana_client/test_ana_client.py | reitermarkus/mayastor | 236 | 12659116 | import pytest
from common.mayastor import container_mod, mayastor_mod
from common.nvme import (
nvme_connect,
nvme_disconnect,
nvme_disconnect_all,
nvme_list_subsystems,
identify_namespace,
)
import uuid
import mayastor_pb2 as pb
import os
POOL_NAME = "pool1"
NEXUS_GUID = "afebdeb9-ff44-1111-2222-... |
ast/testdata/func_defaults.py | MaxTurchin/pycopy-lib | 126 | 12659154 | <filename>ast/testdata/func_defaults.py
def foo(a, b=1, c=3):
pass
|
corehq/apps/linked_domain/dbaccessors.py | andyasne/commcare-hq | 471 | 12659184 | from django.db.models.expressions import RawSQL
from corehq import toggles
from corehq.apps.accounting.utils import domain_has_privilege
from corehq.apps.domain.models import Domain
from corehq.apps.linked_domain.models import DomainLink, DomainLinkHistory
from corehq.apps.linked_domain.util import (
is_available_... |
python/ql/test/library-tests/exprs/compare/compare.py | vadi2/codeql | 4,036 | 12659192 |
a < b < c
x in y
x not in y
x is y
x is not y
x < y
x > y
x >= y
x <= y
x == y
x != y
|
gossip/util/message_code.py | Gokul1077/PytGossip | 122 | 12659199 | <reponame>Gokul1077/PytGossip<filename>gossip/util/message_code.py
# Copyright 2016 <NAME>, <NAME>, <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/licens... |
PIXOR/utils_func.py | mileyan/mileyan | 152 | 12659213 | import torch
import losswise
class AverageMeter(object):
"""Computes and stores the average and current value"""
def __init__(self):
self.reset()
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def update(self, val, n=1):
self.v... |
tests/notifier/test_grafana_notifier.py | Connor-Knabe/chiadog | 503 | 12659218 | <reponame>Connor-Knabe/chiadog<gh_stars>100-1000
# std
import os
import unittest
# project
from src.notifier.grafana_notifier import GrafanaNotifier
from .dummy_events import DummyEvents
class TestGrafanaNotifier(unittest.TestCase):
def setUp(self) -> None:
base_url = os.getenv("GRAFANA_BASE_URL")
... |
sahara/service/validations/edp/data_source.py | ksshanam/sahara | 161 | 12659238 | <gh_stars>100-1000
# Copyright (c) 2013 Mirantis 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... |
tests/test_provider_Ouest_France_ldap.py | mjuenema/python-terrascript | 507 | 12659291 | <filename>tests/test_provider_Ouest_France_ldap.py
# tests/test_provider_Ouest-France_ldap.py
# Automatically generated by tools/makecode.py (24-Sep-2021 15:20:59 UTC)
def test_provider_import():
import terrascript.provider.Ouest_France.ldap
def test_resource_import():
from terrascript.resource.Ouest_France... |
recipes/Python/577929_PythMultidimensional_List_Searcher_/recipe-577929.py | tdiprima/code | 2,023 | 12659312 | <filename>recipes/Python/577929_PythMultidimensional_List_Searcher_/recipe-577929.py
def find(searchList, elem):
endList = []
for indElem in range(0,len(elem)):
resultList = []
for ind in range(0, len(searchList)):
if searchList[ind] == elem[indElem]:
... |
params.py | dalab/hyperbolic_cones | 103 | 12659327 | from collections import OrderedDict
threads = 24
default_params = OrderedDict([
############ Common params:
('wn', 'noun'), # mammal or noun
('print_every', 20),
('save', False), # Whether to save the model in the folder saved_models/
('num_negative', 10), # Number of negative samples to use
... |
afew/files.py | naegling/afew | 159 | 12659345 | <reponame>naegling/afew<gh_stars>100-1000
# SPDX-License-Identifier: ISC
# Copyright (c) <NAME> <<EMAIL>>
import os
import re
import stat
import logging
import platform
import queue
import threading
import notmuch
import pyinotify
import ctypes
import contextlib
if platform.system() != 'Linux':
raise ImportError(... |
api/app/search/views.py | phuonglvh/DataEngineeringProject | 417 | 12659349 | <gh_stars>100-1000
from django_elasticsearch_dsl_drf.viewsets import DocumentViewSet
from django_elasticsearch_dsl_drf.filter_backends import (
FilteringFilterBackend,
CompoundSearchFilterBackend,
DefaultOrderingFilterBackend,
OrderingFilterBackend
)
from search.documents import NewsDocument
from sea... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.