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 |
|---|---|---|---|---|
openspeech/modules/add_normalization.py | CanYouImagine/openspeech | 207 | 12778839 | <filename>openspeech/modules/add_normalization.py
# MIT License
#
# Copyright (c) 2021 <NAME> and <NAME> and <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, incl... |
external/iotivity/iotivity_1.2-rel/build_common/iotivityconfig/compiler/default_configuration.py | SenthilKumarGS/TizenRT | 1,433 | 12778905 | # ------------------------------------------------------------------------
# Copyright 2015 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/li... |
tests/test_util.py | magicalyak/blinkpy | 272 | 12778913 | <gh_stars>100-1000
"""Test various api functions."""
import unittest
from unittest import mock
import time
from blinkpy.helpers.util import json_load, Throttle, time_to_seconds, gen_uid
class TestUtil(unittest.TestCase):
"""Test the helpers/util module."""
def setUp(self):
"""Initialize the blink mo... |
Packs/Imperva_WAF/Integrations/ImpervaWAF/ImpervaWAF.py | diCagri/content | 799 | 12778944 | import demistomock as demisto
from CommonServerPython import *
from CommonServerUserPython import *
''' IMPORTS '''
import json
import requests
import traceback
# Disable insecure warnings
requests.packages.urllib3.disable_warnings()
''' CONSTANTS '''
INTEGRATION_CONTEXT_NAME = 'ImpervaWAF'
class Client(BaseClient... |
example/trade/post_batch_create_order.py | bailzx5522/huobi_Python | 611 | 12778947 | <gh_stars>100-1000
import time
from huobi.client.trade import TradeClient
from huobi.constant import *
from huobi.utils import *
trade_client = TradeClient(api_key=g_api_key, secret_key=g_secret_key)
client_order_id_header = str(int(time.time()))
symbol_eosusdt = "eosusdt"
client_order_id_eos_01 = client_order_id_... |
evosax/experimental/decodings/random.py | RobertTLange/evosax | 102 | 12778956 | import jax
import chex
from typing import Union, Optional
from .decoder import Decoder
from ...utils import ParameterReshaper
class RandomDecoder(Decoder):
def __init__(
self,
num_encoding_dims: int,
placeholder_params: Union[chex.ArrayTree, chex.Array],
rng: chex.PRNGKey = jax.ran... |
splashgen/components/CTAButton.py | ndejong/splashgen | 246 | 12778993 | from splashgen import Component
class CTAButton(Component):
def __init__(self, link: str, text: str) -> None:
self.link = link
self.text = text
def render(self) -> str:
return f'<a href="{self.link}" class="btn btn-primary btn-lg px-4">{self.text}</a>'
|
myia/operations/macro_embed.py | strint/myia | 222 | 12779031 | """Implementation of the 'embed' operation."""
from ..lib import Constant, SymbolicKeyInstance, macro, sensitivity_transform
@macro
async def embed(info, x):
"""Return a constant that embeds the identity of the input node."""
typ = sensitivity_transform(await x.get())
key = SymbolicKeyInstance(x.node, ty... |
scripts/tldr_analyze_nuggets.py | allenai/scitldr | 628 | 12779035 | """
Some analysis of informational content of TLDR-Auth and TLDR-PR
"""
import os
import csv
from collections import Counter, defaultdict
INFILE = 'tldr_analyze_nuggets/tldr_auth_pr_gold_nuggets_2020-03-31.csv'
# Q1: How many nuggets do TLDRs contain?
# A: Interesting, both author and PR have nearly identical di... |
SubredditBirthdays/sb.py | voussoir/redd | 444 | 12779036 | import argparse
import bot3
import datetime
import praw3 as praw
import random
import sqlite3
import string
import subprocess
import sys
import time
import tkinter
import traceback
import types
from voussoirkit import betterhelp
from voussoirkit import mutables
from voussoirkit import operatornotify
from voussoirkit i... |
src/promnesia/__init__.py | halhenke/promnesia | 1,327 | 12779090 | from pathlib import Path
from .common import PathIsh, Visit, Source, last, Loc, Results, DbVisit, Context, Res
# add deprecation warning so eventually this may converted to a namespace package?
import warnings
warnings.warn("DEPRECATED! Please import directly from 'promnesia.common', e.g. 'from promnesia.common import... |
examples/fantom/rename.py | pkuksa/FILER_giggle | 210 | 12779108 | import sys
if len(sys.argv) != 4:
sys.stderr.write('usage:\t' + \
sys.argv[0] + \
' <name2library file>' + \
' <expression count matrix file>' + \
' <out dir>\n')
sys.exit(1)
name2library_file=sys.argv[1]
expression_count_matr... |
plots/lasium_paper/plot_accuracy_based_on_gan.py | siavash-khodadadeh/MetaLearning-TF2.0 | 102 | 12779122 | <gh_stars>100-1000
import cv2
import matplotlib.pyplot as plt
from matplotlib.offsetbox import OffsetImage, AnnotationBbox
import numpy as np
def plot_img(img_name, location, index, zoom=0.1):
plt.scatter(index, accs[epochs.index(index)] + 1, color='#0D7377', linewidths=0.5, marker='v')
plt.plot((index, locat... |
WebMirror/management/rss_parser_funcs/feed_parse_extractKitchennovelCom.py | fake-name/ReadableWebProxy | 193 | 12779136 | def extractKitchennovelCom(item):
'''
Parser for 'kitchennovel.com'
'''
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or "preview" in item['title'].lower():
return None
tagmap = [
('Strange World Alchemist Chef', 'Strange World Alchemist Chef'... |
week7/lecture13/test2.py | nobodysshadow/edX_MITx_6.00.1x | 622 | 12779153 | <filename>week7/lecture13/test2.py
# -*- coding: utf-8 -*-
"""
Created on Sun Jun 12 07:17:17 2016
@author: ericgrimson
"""
#import numpy as np
import pylab as plt
mySamples = []
myLinear = []
myQuadratic = []
myCubic = []
myExponential = []
for i in range(0, 30):
mySamples.append(i)
myLinear.append(i)
... |
atx/record/scene_detector.py | jamjven/ATX | 1,132 | 12779179 | #-*- encoding: utf-8 -*-
import os
import cv2
import yaml
import numpy as np
from collections import defaultdict
def find_match(img, tmpl, rect=None, mask=None):
if rect is not None:
h, w = img.shape[:2]
x, y, x1, y1 = rect
if x1 > w or y1 > h:
return 0, None
... |
Giveme5W1H/extractor/extractors/action_extractor.py | bkrrr/Giveme5W | 410 | 12779214 | <reponame>bkrrr/Giveme5W
import re
from nltk.tree import ParentedTree
from Giveme5W1H.extractor.candidate import Candidate
from Giveme5W1H.extractor.extractors.abs_extractor import AbsExtractor
class ActionExtractor(AbsExtractor):
"""
The ActionExtractor tries to extract the main actor and his action.
... |
src/mcedit2/util/settings.py | elcarrion06/mcedit2 | 673 | 12779215 | <gh_stars>100-1000
"""
settings
"""
from __future__ import absolute_import, division, print_function, unicode_literals
import json
import os
from PySide import QtCore
import logging
from mcedit2.util import directories
log = logging.getLogger(__name__)
_settings = None
def Settings():
global _settings
i... |
scanners/zap-advanced/scanner/tests/test_zap_spider_http.py | kevin-yen/secureCodeBox | 488 | 12779241 | #!/usr/bin/env python
# SPDX-FileCopyrightText: 2021 iteratec GmbH
#
# SPDX-License-Identifier: Apache-2.0
# -*- coding: utf-8 -*-
import pytest
from unittest.mock import MagicMock, Mock
from unittest import TestCase
from zapclient.configuration import ZapConfiguration
class ZapSpiderHttpTests(TestCase):
@py... |
asv_oggm_plugin.py | skachuck/oggm | 156 | 12779262 | <reponame>skachuck/oggm
import subprocess
import requests
import tempfile
import os
import logging
from asv.plugins.conda import _find_conda, Conda
from asv.console import log
from asv import util
logging.getLogger("requests").setLevel(logging.WARNING)
OGGM_CONDA_ENV_URL = ("https://raw.githubusercontent.com/OGGM/"
... |
dockerfiles/examples/read-bytes-seed/scale-job.py | kaydoh/scale | 121 | 12779313 | <gh_stars>100-1000
import argparse
import datetime
import json
import logging
import sys
import os
logging.basicConfig(format='%(asctime)s - %(levelname)s - %(message)s',
level=logging.DEBUG, stream=sys.stdout)
def run_algorithm(bytes_total, input_file, out_dir):
"""Read the indicated number ... |
examples/notebooks/test_notebooks.py | mjc87/SHTOOLS | 251 | 12779326 | #!/usr/bin/env python3
"""
This script will run all jupyter notebooks in order to test for errors.
"""
import sys
import os
import nbformat
from nbconvert.preprocessors import ExecutePreprocessor
if os.path.dirname(sys.argv[0]) != '':
os.chdir(os.path.dirname(sys.argv[0]))
notebooks = ('grids-and-coefficients.ipy... |
networking-calico/networking_calico/timestamp.py | mikestephen/calico | 3,973 | 12779383 | # -*- coding: utf-8 -*-
# Copyright (c) 2018 Tigera, 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 re... |
PseudoGenerator.py | yxn-coder/Inf-Net | 273 | 12779427 | # -*- coding: utf-8 -*-
"""Preview
Code for 'Inf-Net: Automatic COVID-19 Lung Infection Segmentation from CT Scans'
submit to Transactions on Medical Imaging, 2020.
First Version: Created on 2020-05-13 (@author: <NAME>)
"""
# ---- base lib -----
import os
import argparse
from datetime import datetime
import cv2
impo... |
tests/wrappers.py | blacksph3re/garage | 1,500 | 12779452 | """Test environment wrapper."""
import gym
class AutoStopEnv(gym.Wrapper):
"""Environment wrapper that stops episode at step max_episode_length."""
def __init__(self, env=None, env_name='', max_episode_length=100):
"""Create an AutoStepEnv.
Args:
env (gym.Env): Environment to be... |
kmip/tests/integration/conftest.py | ondrap/PyKMIP | 179 | 12779471 | <reponame>ondrap/PyKMIP<filename>kmip/tests/integration/conftest.py<gh_stars>100-1000
# Copyright (c) 2015 The Johns Hopkins University/Applied Physics Laboratory
# 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.... |
libtrellis/examples/graph.py | Keno/prjtrellis | 256 | 12779485 | #!/usr/bin/env python3
"""
Testing the routing graph generator
"""
import pytrellis
import sys
pytrellis.load_database("../../database")
chip = pytrellis.Chip("LFE5U-45F")
rg = chip.get_routing_graph()
tile = rg.tiles[pytrellis.Location(9, 71)]
for wire in tile.wires:
print("Wire {}:".format(rg.to_str(wire.key()))... |
python/ql/test/query-tests/Summary/my_file.py | timoles/codeql | 4,036 | 12779507 | """
module level docstring
is not included
"""
# this line is not code
# `tty` was chosen for stability over python versions (so we don't get diffrent results
# on different computers, that has different versions of Python).
#
# According to https://github.com/python/cpython/tree/master/Lib (at 2021-04-23) `tty`
# wa... |
semseg/models/modules/common.py | Genevievekim/semantic-segmentation-1 | 196 | 12779536 | <reponame>Genevievekim/semantic-segmentation-1<filename>semseg/models/modules/common.py
import torch
from torch import nn, Tensor
class ConvModule(nn.Sequential):
def __init__(self, c1, c2, k, s=1, p=0, d=1, g=1):
super().__init__(
nn.Conv2d(c1, c2, k, s, p, d, g, bias=False),
nn.B... |
src/main/resources/resource/AndroidSpeechRecognition/AndroidSpeechRecognition.py | holgerfriedrich/myrobotlab | 179 | 12779544 | #########################################
# AndroidSpeechRecognition.py
# more info @: http://myrobotlab.org/service/AndroidSpeechRecognition
#########################################
# start the service
androidspeechrecognition = Runtime.start("androidspeechrecognition","AndroidSpeechRecognition")
# start mouth
mary... |
src/garage/torch/modules/cnn_module.py | blacksph3re/garage | 1,500 | 12779546 | """CNN Module."""
import warnings
import akro
import numpy as np
import torch
from torch import nn
from garage import InOutSpec
from garage.torch import (expand_var, NonLinearity, output_height_2d,
output_width_2d)
# pytorch v1.6 issue, see https://github.com/pytorch/pytorch/issues/42305
#... |
tensornetwork/backends/tensorflow/tensorflow_tensornetwork_test.py | khanhgithead/TensorNetwork | 1,681 | 12779575 | """Tests for graphmode_tensornetwork."""
import numpy as np
import tensorflow as tf
from tensornetwork import (contract, connect, flatten_edges_between,
contract_between, Node)
import pytest
class GraphmodeTensorNetworkTest(tf.test.TestCase):
def test_basic_graphmode(self):
# pylint:... |
runtests.py | prohfesor/tapiriik | 1,445 | 12779581 | <reponame>prohfesor/tapiriik
import tapiriik.database
tapiriik.database.db = tapiriik.database._connection["tapiriik_test"]
tapiriik.database.cachedb = tapiriik.database._connection["tapiriik_cache_test"]
from tapiriik.testing import *
import unittest
unittest.main()
tapiriik.database._connection.drop_database("tapir... |
koku/providers/azure/client.py | rubik-ai/koku | 157 | 12779586 | #
# Copyright 2021 Red Hat Inc.
# SPDX-License-Identifier: Apache-2.0
#
"""Azure Client Configuration."""
from azure.common.credentials import ServicePrincipalCredentials
from azure.mgmt.costmanagement import CostManagementClient
from azure.mgmt.resource import ResourceManagementClient
from azure.mgmt.storage import St... |
high-availability-endpoint/python/region_lookup.py | fortunecookiezen/aws-health-tools | 825 | 12779599 | <filename>high-availability-endpoint/python/region_lookup.py
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
import dns.resolver
class RegionLookupError(Exception):
"""Rasied when there was a problem when looking up the active region"""
pass
def activ... |
Z - Tool Box/x2john/ccache2john.py | dfirpaul/Active-Directory-Exploitation-Cheat-Sheet-1 | 1,290 | 12779605 | #!/usr/bin/env python2
"""
This script extracts crackable hashes from krb5's credential cache files (e.g.
/tmp/krb5cc_1000).
NOTE: This attack technique only works against MS Active Directory servers.
This was tested with CentOS 7.4 client running krb5-1.15.1 software against a
Windows 2012 R2 Active Directory serve... |
dual_encoder/keras_layers_test.py | garyxcheng/federated | 330 | 12779623 | # 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
#
# Unless required by applicable law or agreed to in writing... |
pcbmode/utils/footprint.py | Hylian/pcbmode | 370 | 12779628 | #!/usr/bin/python
import os
import re
import json
from lxml import etree as et
import pcbmode.config as config
from . import messages as msg
# pcbmode modules
from . import svg
from . import utils
from . import place
import copy
from .style import Style
from .point import Point
from .shape import Shape
class Fo... |
tests/test_examples.py | banesullivan/localtileserver | 105 | 12779642 | from localtileserver import examples
def test_get_blue_marble():
client = examples.get_blue_marble()
assert client.metadata()
def test_get_virtual_earth():
client = examples.get_virtual_earth()
assert client.metadata()
def test_get_arcgis():
client = examples.get_arcgis()
assert client.met... |
tools/clang/scripts/generate_compdb.py | zipated/src | 2,151 | 12779656 | #!/usr/bin/env python
# Copyright 2014 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.
"""
Helper for generating compile DBs for clang tooling. On non-Windows platforms,
this is pretty straightforward. On Windows, the tool... |
utility_scripts/configureCMK.py | jjk-dev/aws-qnabot | 197 | 12779704 | <reponame>jjk-dev/aws-qnabot
import boto3
from botocore.config import Config
import argparse
import json
import base64
import sys
parser = argparse.ArgumentParser(description='Uses a specified CMK to encrypt QnABot Lambdas and Parameter Store settings')
parser.add_argument("region", help="AWS Region")
parser.add_argu... |
baiduocr.py | wangtonghe/hq-answer-assist | 119 | 12779725 | # coding=utf-8
from aip import AipOcr
import re
opt_aux_word = ['《', '》']
def get_file_content(file):
with open(file, 'rb') as fp:
return fp.read()
def image_to_str(name, client):
image = get_file_content(name)
text_result = client.basicGeneral(image)
print(text_result)
result = get_que... |
src/gat.py | simoneazeglio/DeepInf | 258 | 12779735 | <reponame>simoneazeglio/DeepInf
#!/usr/bin/env python
# encoding: utf-8
# File Name: gat.py
# Author: <NAME>
# Create Time: 2017/12/18 21:40
# TODO:
from __future__ import absolute_import
from __future__ import unicode_literals
from __future__ import division
from __future__ import print_function
import torch
import ... |
models/pose/loss/pose_modules.py | raviv/torchcv | 308 | 12779791 | <reponame>raviv/torchcv
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: <NAME>(<EMAIL>)
# Loss function for Pose Estimation.
import torch
import torch.nn as nn
from torch.autograd import Variable
class OPMseLoss(nn.Module):
def __init__(self, configer):
super(OPMseLoss, self).__init__()
s... |
tools/tensorflow/cnn/alexnet/unpickle.py | feifeibear/dlbench | 181 | 12779820 | <gh_stars>100-1000
import cPickle
import numpy as np
import tensorflow as tf
PATH = './cifar-10-batches-py'
TARGETPATH = '/home/comp/csshshi/tensorflow/cifar-10-batches-py'
TEST_FILES = ['test_batch']
FILES = ['data_batch_1', 'data_batch_2', 'data_batch_3', 'data_batch_4', 'data_batch_5']
TRAIN_COUNT = 50000
EVAL_COU... |
workshop_sections/extras/lstm_text_classification/trainer/task.py | CharleyGuo/tensorflow-workshop | 691 | 12779822 | import model
import tensorflow as tf
import utils
def train(target,
num_param_servers,
is_chief,
lstm_size=64,
input_filenames=None,
sentence_length=128,
vocab_size=2**15,
learning_rate=0.01,
output_dir=None,
batch_size=1024,
... |
extractor/open163.py | pwh19920920/spiders | 390 | 12779839 | <filename>extractor/open163.py
# pylint: disable=W0123
import re
import requests
def get(url: str) -> dict:
"""
videos
"""
data = {}
data["videos"] = []
headers = {
"User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36"... |
examples/apps/kinesis-analytics-process-kpl-record/aws_kinesis_agg/__init__.py | eugeniosu/serverless-application-model | 326 | 12779877 | #Kinesis Aggregation/Deaggregation Libraries for Python
#
#Copyright 2014, Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
#Licensed under the Amazon Software License (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... |
geocoder/geolytica.py | termim/geocoder | 1,506 | 12779894 | #!/usr/bin/python
# coding: utf8
from __future__ import absolute_import
import logging
from geocoder.base import OneResult, MultipleResultsQuery
class GeolyticaResult(OneResult):
def __init__(self, json_content):
# create safe shortcuts
self._standard = json_content.get('standard', {})
... |
lib/python/frugal/tests/transport/test_http_transport.py | ariasheets-wk/frugal | 144 | 12779997 | <gh_stars>100-1000
# Copyright 2017 Workiva
# 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 ... |
alipay/aop/api/domain/InsCoverage.py | snowxmas/alipay-sdk-python-all | 213 | 12780018 | <filename>alipay/aop/api/domain/InsCoverage.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class InsCoverage(object):
def __init__(self):
self._coverage_name = None
self._coverage_no = None
self._effect_end_time = None
... |
python/searching/interpolation.py | nikitanamdev/AlgoBook | 191 | 12780063 | <gh_stars>100-1000
#Interpolation search is an improved version of binary search.
#Its time complexity is O(log(log n)) as compared to log(n) of binary search.
#following is the code of interpolation search:
# Python program to implement interpolation search
#Variable naming:
"""
1) lys - our input array
2) val - the... |
Drake-Z/0015/0015.py | saurabh896/python-1 | 3,976 | 12780086 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''第 0015 题: 纯文本文件 city.txt为城市信息, 里面的内容(包括花括号)如下所示:
{
"1" : "上海",
"2" : "北京",
"3" : "成都"
}
请将上述内容写到 city.xls 文件中。'''
__author__ = 'Drake-Z'
import json
from collections import OrderedDict
from openpyxl import Workbook
def txt_to_xlsx(filename):
file = o... |
veles/ocl_blas.py | AkshayJainG/veles | 1,007 | 12780102 | # -*- coding: utf-8 -*-
"""
.. invisible:
_ _ _____ _ _____ _____
| | | | ___| | | ___/ ___|
| | | | |__ | | | |__ \ `--.
| | | | __|| | | __| `--. \
\ \_/ / |___| |___| |___/\__/ /
\___/\____/\_____|____/\____/
Created on Apr 13, 2015
BLAS class to use with ocl backend.
██... |
codigo_das_aulas/aula_17/exemplo_09.py | VeirichR/curso-python-selenium | 234 | 12780107 | <gh_stars>100-1000
from selene.support.shared import browser
from selene.support.conditions import be
from selene.support.conditions import have
browser.open('http://google.com')
browser.element(
'input[name="q"]'
).should(be.blank).type('Envydust').press_enter()
|
tests/test_pycuda.py | karthik20122001/docker-python | 2,030 | 12780109 | <gh_stars>1000+
"""Tests for general GPU support"""
import unittest
from common import gpu_test
class TestPycuda(unittest.TestCase):
@gpu_test
def test_pycuda(self):
import pycuda.driver
pycuda.driver.init()
gpu_name = pycuda.driver.Device(0).name()
self.assertNotEqua... |
pymatgen/io/cube.py | Crivella/pymatgen | 921 | 12780119 | <gh_stars>100-1000
"""
Module for reading Gaussian cube files, which have become one of the standard file formats
for volumetric data in quantum chemistry and solid state physics software packages
(VASP being an exception).
Some basic info about cube files
(abridged info from http://paulbourke.net/dataformats/cube/ by... |
Python/SinglyLinkedList.py | Nikhil-Sharma-1/DS-Algo-Point | 1,148 | 12780138 | class Node:
def __init__(self, data):
self.data = data
self.next = None
class SinglyLinkedList:
def __init__(self):
self.head = None
self.pos = None
def insert(self, data):
newNode = Node(data)
if self.head == None:
self.head = newNode
... |
Python/ds/Firstfit.py | Khushboo85277/NeoAlgo | 897 | 12780139 | """
First fit is the simplest of all the storage allocation strategies.
Here the list of storages is searched and as soon as a free storage block of size >= N is found ,
the pointer of that block is sent to the calling program after retaining the residue space.Thus, for example,
for a block of size 5k , 2k memory will ... |
Python/test/currencies.py | yrtf/QuantLib-SWIG | 231 | 12780165 | """
Copyright (C) 2021 <NAME>
This file is part of QuantLib, a free-software/open-source library
for financial quantitative analysts and developers - http://quantlib.org/
QuantLib is free software: you can redistribute it and/or modify it
under the terms of the QuantLib license. You should have received a
copy... |
smt/SMT.py | jeanqasaur/jeeves | 253 | 12780201 | '''
Translate expressions to SMT import format.
'''
from Z3 import Z3
class UnsatisfiableException(Exception):
pass
# NOTE(JY): Think about if the solver needs to know about everything for
# negative constraints. I don't think so because enough things should be
# concrete that this doesn't matter.
def solve(const... |
watchmen/pipeline/core/context/unit_context.py | Insurance-Metrics-Measure-Advisory/watchman-data-connector | 125 | 12780202 | <reponame>Insurance-Metrics-Measure-Advisory/watchman-data-connector
from model.model.pipeline.pipeline import ProcessUnit
from watchmen.monitor.model.pipeline_monitor import UnitRunStatus
from watchmen.pipeline.core.context.stage_context import StageContext
class UnitContext:
stageContext: StageContext
unit... |
tensorflow/python/distribute/distribute_coordinator_context.py | EricRemmerswaal/tensorflow | 190,993 | 12780203 | <filename>tensorflow/python/distribute/distribute_coordinator_context.py<gh_stars>1000+
# Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the Lice... |
plugins/quetz_content_trust/quetz_content_trust/repo_signer.py | maresb/quetz | 108 | 12780213 | import os
import shutil
from pathlib import Path
import conda_content_trust.signing as cct_signing
class RepoSigner:
def sign_repodata(self, repodata_fn, pkg_mgr_key):
final_fn = self.in_folder / "repodata_signed.json"
print("copy", repodata_fn, final_fn)
shutil.copyfile(repodata_fn, fina... |
machine/storage/backends/base.py | drdarina/slack-machine | 111 | 12780217 | <reponame>drdarina/slack-machine<filename>machine/storage/backends/base.py
class MachineBaseStorage:
"""Base class for storage backends
Extending classes should implement the five methods in this base class. Slack Machine takes
care of a lot of details regarding the persistent storage of data. So storage b... |
tools/etnaviv/mmt.py | ilbers/etna_viv | 121 | 12780222 | import struct
from collections import namedtuple
def read_1(f):
return f.read(1)[0]
def read_2(f):
return struct.unpack('<H', f.read(2))[0]
def read_4(f):
return struct.unpack('<I', f.read(4))[0]
def read_8(f):
return struct.unpack('<Q', f.read(8))[0]
def read_buffer(f):
length = read_4(f)
retu... |
segmenters/nlp/JiebaSegmenter/tests/test_jiebasegmenter.py | saoc90/jina-hub | 106 | 12780230 | <reponame>saoc90/jina-hub
import os
import numpy as np
import pytest
from .. import JiebaSegmenter
cur_dir = os.path.dirname(os.path.abspath(__file__))
path_dict_file = os.path.join(cur_dir, 'dict.txt')
def test_jieba_segmenter():
segmenter = JiebaSegmenter(mode='accurate')
text = '今天是个大晴天!安迪回来以后,我们准备去动物园。... |
data/transcoder_evaluation_gfg/python/MINIMUM_PERIMETER_N_BLOCKS.py | mxl1n/CodeGen | 241 | 12780252 | <filename>data/transcoder_evaluation_gfg/python/MINIMUM_PERIMETER_N_BLOCKS.py
# Copyright (c) 2019-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
import math
def f_gold ( n ) :
l = math.sqrt ... |
aa1_data_util/1_process_zhihu.py | sunshinenum/text_classification | 7,723 | 12780308 | # -*- coding: utf-8 -*-
import sys
#reload(sys)
#sys.setdefaultencoding('utf8')
#1.将问题ID和TOPIC对应关系保持到字典里:process question_topic_train_set.txt
#from:question_id,topics(topic_id1,topic_id2,topic_id3,topic_id4,topic_id5)
# to:(question_id,topic_id1)
# (question_id,topic_id2)
#read question_topic_train_set.txt
import ... |
torchbenchmark/models/fastNLP/reproduction/Star_transformer/util.py | Chillee/benchmark | 2,693 | 12780328 | import fastNLP as FN
import argparse
import os
import random
import numpy
import torch
def get_argparser():
parser = argparse.ArgumentParser()
parser.add_argument('--lr', type=float, required=True)
parser.add_argument('--w_decay', type=float, required=True)
parser.add_argument('--lr_decay', type=float... |
contrib/frontends/django/nntpchan/nntpchan/frontend/templatetags/chanup.py | majestrate/nntpchan | 233 | 12780360 | <gh_stars>100-1000
from django import template
from django.template.defaultfilters import stringfilter
from django.utils.html import conditional_escape
from django.utils.safestring import mark_safe
from nntpchan.frontend.models import Newsgroup, Post
import re
from urllib.parse import urlparse
from html import unes... |
examples/affect/affect_mfm.py | kapikantzari/MultiBench | 148 | 12780388 | import torch
import sys
import os
sys.path.append(os.getcwd())
sys.path.append(os.path.dirname(os.path.dirname(os.getcwd())))
from unimodals.MVAE import TSEncoder, TSDecoder # noqa
from utils.helper_modules import Sequential2 # noqa
from objective_functions.objectives_for_supervised_learning import MFM_objective # no... |
clinicadl/tests/test_classify.py | yogeshmj/AD-DL | 112 | 12780391 | <gh_stars>100-1000
# coding: utf8
import pytest
import os
from os.path import join, exists
@pytest.fixture(params=[
'classify_image',
'classify_slice',
'classify_patch'
])
def classify_commands(request):
out_filename = 'fold-0/cnn_classification/best_balanced_accuracy/DB-TEST_image_level_prediction.... |
configs/universenet/ablation/universenet50_2008_nosepc_fp16_4x4_mstrain_480_960_1x_coco.py | Jack-Hu-2001/UniverseNet | 314 | 12780397 | <gh_stars>100-1000
_base_ = [
'../../universenet/models/universenet50_2008.py',
'../../_base_/datasets/coco_detection_mstrain_480_960.py',
'../../_base_/schedules/schedule_1x.py', '../../_base_/default_runtime.py'
]
model = dict(
neck=dict(
_delete_=True,
type='FPN',
in_channels... |
tools/train_w2v.py | sketscripter/emotional-chatbot-cakechat | 1,608 | 12780402 | <reponame>sketscripter/emotional-chatbot-cakechat
import os
import sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from cakechat.utils.text_processing import get_processed_corpus_path, load_processed_dialogs_from_json, \
FileTextLinesIterator, get_dialog_lines_and_conditions, Proc... |
gubernator/pb_glance.py | Noahhoetger2001/test-infra | 3,390 | 12780412 | <gh_stars>1000+
#!/usr/bin/env python
# Copyright 2016 The Kubernetes 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 re... |
exercises/en/exc_02_02_02.py | Jette16/spacy-course | 2,085 | 12780420 | <filename>exercises/en/exc_02_02_02.py
from spacy.lang.en import English
nlp = English()
doc = nlp("<NAME> is a PERSON")
# Look up the hash for the string label "PERSON"
person_hash = ____.____.____[____]
print(person_hash)
# Look up the person_hash to get the string
person_string = ____.____.____[____]
print(person... |
utils/tool.py | Gagarinwjj/Coeus | 139 | 12780482 | <filename>utils/tool.py
# coding: utf-8
__author__ = 'deff'
import re
class Tools:
@staticmethod
def xml_assent(word):
symbola = re.compile('>')
word = symbola.sub('<', word)
symbolb = re.compile('<')
word = symbolb.sub('>', word)
symbolc = re.compile('&')
... |
test/test_pulljson.py | Teradata/PyTd | 133 | 12780510 | <filename>test/test_pulljson.py
# The MIT License (MIT)
#
# Copyright (c) 2015 by Teradata
#
# 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 ... |
src/blockdiag/imagedraw/__init__.py | flying-foozy/blockdiag | 155 | 12780514 | <filename>src/blockdiag/imagedraw/__init__.py<gh_stars>100-1000
# -*- coding: utf-8 -*-
# Copyright 2011 <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.... |
myia/abstract/__init__.py | strint/myia | 222 | 12780538 | <reponame>strint/myia
"""Abstract data and type/shape inference."""
from .aliasing import *
from .amerge import *
from .data import *
from .infer import *
from .loop import *
from .macro import *
from .ref import *
from .to_abstract import *
from .utils import *
|
Chapter09/c9_52_impact_of_correlation_on_efficient_frontier_notWorking.py | John-ye666/Python-for-Finance-Second-Edition | 236 | 12780545 | <filename>Chapter09/c9_52_impact_of_correlation_on_efficient_frontier_notWorking.py
"""
Name : c9_52_impacto_of_correlation_on_efficient_frontier.py
Book : Python for Finance (2nd ed.)
Publisher: Packt Publishing Ltd.
Author : <NAME>
Date : 6/6/2017
email : <EMAIL>
<EMAIL>
"""... |
tests/core/test_oauth2/test_rfc7591.py | YPCrumble/authlib | 3,172 | 12780555 | from unittest import TestCase
from authlib.oauth2.rfc7591 import ClientMetadataClaims
from authlib.jose.errors import InvalidClaimError
class ClientMetadataClaimsTest(TestCase):
def test_validate_redirect_uris(self):
claims = ClientMetadataClaims({'redirect_uris': ['foo']}, {})
self.assertRaises(I... |
backprop/models/st_model/model.py | lucky7323/backprop | 200 | 12780625 | from typing import Dict, List
import torch
from functools import partial
from backprop.models import PathModel
from torch.optim.adamw import AdamW
from sentence_transformers import SentenceTransformer
class STModel(PathModel):
"""
Class for models which are initialised from Sentence Transformers
Attribut... |
table_border_syntax.py | akrabat/SublimeTableEditor | 313 | 12780627 | <gh_stars>100-1000
# table_border_syntax.py - Base classes for table with borders: Pandoc,
# Emacs Org mode, Simple, reStrucutredText
# Copyright (C) 2012 Free Software Foundation, Inc.
# Author: <NAME>
# Package: SublimeTableEditor
# Homepage: https://github.com/vkocubinsky/SublimeTableEditor
# This file is part o... |
runtime/python/Lib/asyncio/format_helpers.py | hwaipy/InteractionFreeNode | 207 | 12780646 | <filename>runtime/python/Lib/asyncio/format_helpers.py<gh_stars>100-1000
import functools
import inspect
import reprlib
import sys
import traceback
from . import constants
def _get_function_source(func):
func = inspect.unwrap(func)
if inspect.isfunction(func):
code = func.__code__
... |
bazel/aprutil.bzl | arunvc/incubator-pagespeed-mod | 535 | 12780647 | aprutil_build_rule = """
cc_library(
name = "aprutil",
srcs = [
"@mod_pagespeed//third_party/aprutil:aprutil_pagespeed_memcache_c",
'buckets/apr_brigade.c',
'buckets/apr_buckets.c',
'buckets/apr_buckets_alloc.c',
'buckets/apr_buckets_eos.c',
'buckets/apr_buckets_... |
backpack/extensions/firstorder/batch_grad/batch_grad_base.py | jabader97/backpack | 395 | 12780666 | """Calculates the batch_grad derivative."""
from __future__ import annotations
from typing import TYPE_CHECKING, Callable, List, Tuple
from torch import Tensor
from torch.nn import Module
from backpack.core.derivatives.basederivatives import BaseParameterDerivatives
from backpack.extensions.firstorder.base import Fi... |
chinese-poem/probability.py | MashiMaroLjc/ML-and-DM-in-action | 370 | 12780669 | # coding:utf-8
#
def two(words):
"""
:param words:
:return:
"""
new = []
s = len(words)
for index in range(s):
w = words[index]
for next_index in range(index + 1, s):
next_w = words[next_index]
new.append(frozenset([w, next_w]))
return new
poe... |
chapter4/pizza.py | sharad16j/Expert-Python-Programming-Third-Edition | 112 | 12780687 | <filename>chapter4/pizza.py
class Pizza:
def __init__(self, toppings):
self.toppings = toppings
def __repr__(self):
return "Pizza with " + " and ".join(self.toppings)
@classmethod
def recommend(cls):
"""Recommend some pizza with arbitrary toppings,"""
return cls(['spam'... |
moya/context/sortmodifiers.py | moyaproject/moya | 129 | 12780710 | <reponame>moyaproject/moya
"""Hacked up script to sort modifiers"""
# Couldn't find a tool for this
"""
import io
with io.open('modifiers.py', 'rt') as f:
iter_lines = iter(f)
while 1:
line = next(iter_lines, None)
if line.startswith('class ExpressionModifiers('):
break
defs ... |
example_evaluate_with_diff.py | ducha-aiki/manifold-diffusion | 118 | 12780739 | <gh_stars>100-1000
# EXAMPLE_EVALUATE Code to evaluate example results on ROxford and RParis datasets.
# Revisited protocol has 3 difficulty setups: Easy (E), Medium (M), and Hard (H),
# and evaluates the performance using mean average precision (mAP), as well as mean precision @ k (mP@k)
#
# More details about the r... |
users/factories.py | bllli/Django-China-API | 187 | 12780785 | # factories that automatically create user data
import factory
from users.models import User
class UserFactory(factory.DjangoModelFactory):
class Meta:
model = User
username = factory.Sequence(lambda n: 'user%s' % n)
email = factory.LazyAttribute(lambda o: <EMAIL>' % o.username)
password = '... |
xv_leak_tools/test_device/linux_device.py | UAEKondaya1/expressvpn_leak_testing | 219 | 12780862 | <filename>xv_leak_tools/test_device/linux_device.py
import platform
import signal
from xv_leak_tools.exception import XVEx
from xv_leak_tools.helpers import unused
from xv_leak_tools.log import L
from xv_leak_tools.test_device.desktop_device import DesktopDevice
from xv_leak_tools.test_device.connector_helper import C... |
Chapter24/apple_factory.py | DeeMATT/AdvancedPythonProgramming | 278 | 12780886 |
MINI14 = '1.4GHz Mac mini'
class AppleFactory:
class MacMini14:
def __init__(self):
self.memory = 4 # in gigabytes
self.hdd = 500 # in gigabytes
self.gpu = 'Intel HD Graphics 5000'
def __str__(self):
info = (f'Model: {MINI14}',
f... |
run-addon.py | chinedufn/landon | 117 | 12780904 | <reponame>chinedufn/landon
# A script to temporarily install and run the addon. Useful for running
# blender-mesh-to-json via blender CLI where you might be in a
# continuous integration environment that doesn't have the addon
# installed
#
# blender file.blend --python $(mesh2json)
# -> becomes ->
# blender file.b... |
tests/data/aws/securityhub.py | ramonpetgrave64/cartography | 2,322 | 12780949 | GET_HUB = {
'HubArn': 'arn:aws:securityhub:us-east-1:000000000000:hub/default',
'SubscribedAt': '2020-12-03T11:05:17.571Z',
'AutoEnableControls': True,
}
|
lib/python/treadmill/tests/syscall/__init__.py | vrautela/treadmill | 133 | 12780960 | <reponame>vrautela/treadmill
"""Tests for treadmill's linux direct system call interface."""
|
migrations/20211128_01_Mn7Ng-create-holdem-game-record-table.py | zw-g/Funny-Nation | 126 | 12780971 | """
Create holdem game record table
"""
from yoyo import step
__depends__ = {'20211109_01_xKblp-change-comments-on-black-jack-record'}
steps = [
step("CREATE TABLE `holdemGameRecord` ( `userID` BIGINT NOT NULL , `moneyInvested` BIGINT NOT NULL , `status` INT NOT NULL COMMENT '0 represent in progress; 1 represent... |
chariot/transformer/text/lower_normalizer.py | Y-Kuro-u/chariot | 134 | 12781046 | <reponame>Y-Kuro-u/chariot<gh_stars>100-1000
from chariot.transformer.text.base import TextNormalizer
class LowerNormalizer(TextNormalizer):
def __init__(self, copy=True):
super().__init__(copy)
def apply(self, text):
return text.lower()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.