max_stars_repo_path stringlengths 3 269 | max_stars_repo_name stringlengths 4 119 | max_stars_count int64 0 191k | id stringlengths 1 7 | content stringlengths 6 1.05M | score float64 0.23 5.13 | int_score int64 0 5 |
|---|---|---|---|---|---|---|
attack_methods/attack_initializer.py | ASU-Active-Perception-Group/decentralized_attribution_of_generative_models | 3 | 12764851 | from .Crop import Crop
from .Gaussian_blur import Gaussian_blur
from .Gaussian_noise import Gaussian_noise
from .Jpeg_compression import JpegCompression
from .Combination import Combination_attack
import torch
def attack_initializer(attack_method, is_train):
if (attack_method == 'Crop'):
attack = Crop([0.... | 2.484375 | 2 |
results/plot_bulk.py | vincentlui/megae | 82 | 12764852 | <filename>results/plot_bulk.py
import glob
import os
import ast
import numpy as np
from copy import deepcopy
import seaborn as sns; sns.set()
sns.set_style('whitegrid')
from scipy.signal import medfilt
import argparse
import matplotlib
import matplotlib.pyplot as plt
matplotlib.rcParams.update({'font.size': 12})
c... | 2.453125 | 2 |
nmfamv2/UserHandler/__init__.py | gmarupilla/NMRFAMv2 | 0 | 12764853 | import zipfile
import pandas as pd
"""
Lay of the land:
"""
class UserHandler(object):
# This Object is used to access the directory that saves the results
def __init__(self, user_directory_path, pathToMixture):
self.user_directory_path = user_directory_path
self.username = None
sel... | 3.3125 | 3 |
bob/db/swan/test.py | bioidiap/bob.db.swan | 0 | 12764854 | <filename>bob/db/swan/test.py
#!/usr/bin/env python
# vim: set fileencoding=utf-8 :
"""Test Units
"""
import logging
logger = logging.getLogger(__name__)
def _test_numbers(files, n_total_files, n_clients, n_recordings,
n_devices, n_sessions, session_list, sites):
n_clients_ = len(set(f.client... | 2.484375 | 2 |
alloy_related/railMLToAlloy/parserRail/instance.py | pedrordgs/RailML-Utilities | 21 | 12764855 | class Instance:
def __init__ (self, alloyfp):
self.bitwidth = '4'
self.maxseq = '4'
self.mintrace = '-1'
self.maxtrace = '-1'
self.filename = alloyfp
self.tracel = '1'
self.backl = '0'
self.sigs = []
self.fields = []
def add_sig(self, sig... | 2.578125 | 3 |
watcher_metering/store/ceilometer.py | b-com/watcher-metering | 2 | 12764856 | # -*- encoding: utf-8 -*-
# Copyright (c) 2015 b<>com
#
# 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... | 1.6875 | 2 |
Lecture 03 - Simple Algorithms/newton_raphson.py | ag-ds-bubble/MIT6.00.1x | 0 | 12764857 | # Find square root using <NAME>
num = 987
eps = 1e-6
iteration = 0
sroot = num/2
while abs(sroot**2-num)>eps:
iteration+=1
if sroot**2==num:
print(f'At Iteration {iteration} : Found It!, the cube root for {num} is {sroot}')
break
sroot = sroot - (sroot**2-num)/(2*sroot)
print(f'At Itera... | 4 | 4 |
sourceCode/PreProcessing/filterings.py | suryagupta/ProteinAssociationPair | 0 | 12764858 | __author__ = 'surya'
from Analysis import GetAssayCount
def preFiltrationWithHighlyOCcuringProteins(MSFile,uniprotProteinList,out):
assCountList=[]
with open(MSFile) as OpenedMSFile:
next(OpenedMSFile)
for line in OpenedMSFile:
colList=line.split("\t")
assCount = int(c... | 2.734375 | 3 |
Enet_lapa_camvid_pytorch/datasets/lapa_loader.py | TheDetial/Image-Segmentation | 21 | 12764859 | # -*- coding: utf-8 -*-
import os
import random
from torch.utils.data import Dataset
from PIL import Image
import numpy as np
from datasets.data_io import get_transform, read_all_lines
from datasets.data_io import *
import torchvision.transforms as transforms
import torch
import torch.nn as nn
class LapaPngPng(Da... | 2.40625 | 2 |
leetcode/monthly_challenges/2020-06/w1-2_delete_node_linked_list.py | mawillcockson/coding_challenges | 0 | 12764860 | <filename>leetcode/monthly_challenges/2020-06/w1-2_delete_node_linked_list.py
"""
Constraints:
- The linked list will have at least two elements.
- All of the nodes' values will be unique.
- The given node will not be the tail and it will always be a valid node of the linked list.
- Do not return anything from your fu... | 4.0625 | 4 |
sliced/datasets/banknote.py | joshloyal/reduce-learn | 10 | 12764861 | <gh_stars>1-10
import csv
from os.path import dirname
from sliced.datasets.base import load_data
def load_banknote():
"""Load and return the swiss banknote dataset (classification).
Six measurements made on 100 genuine Swiss banknotes and 100 counterfeit
ones.
Features
========
Length:
... | 2.9375 | 3 |
ex14-list_remove_duplicates.py | lew18/practicepython.org-mysolutions | 0 | 12764862 | """
https://www.practicepython.org
Exercise 14: List Remove Duplicates
2 chilis
Write a program (function!) that takes a list and returns a new list that
contains all the elements of the first list minus all the duplicates.
Extras:
- Write two different functions to do this - one using a loop and constructing
a li... | 4.03125 | 4 |
stepRNA/index_bowtie.py | bmm514/Becky_alignment | 0 | 12764863 | <reponame>bmm514/Becky_alignment
from subprocess import run, PIPE
import os
def main(ref):
ref_base = os.path.splitext(ref)[0]
command = ['bowtie2-build', ref, ref_base]
run(command, stdout=PIPE)
return ref_base
if __name__ == "__main__":
description = 'Index a reference sequence for ready for bo... | 2.5 | 2 |
code/doh_data_classifier/classifier_mlp.py | yshao321/doh_website_fingerprinting | 1 | 12764864 | <reponame>yshao321/doh_website_fingerprinting
#!/usr/bin/env python
# coding: utf-8
import sys
import os
import time
import json
import numpy as np
import pandas as pd
import dill
import random
from os.path import join, dirname, abspath, pardir, basename
from sklearn.model_selection import StratifiedKFold
from sklea... | 2.84375 | 3 |
pymtl3/passes/rtlir/util/test_utility.py | kevinyuan/pymtl3 | 152 | 12764865 | <gh_stars>100-1000
#=========================================================================
# test_utility.py
#=========================================================================
# Author : <NAME>
# Date : Feb 21, 2019
"""Test utilities used by RTLIR tests."""
from contextlib import contextmanager
import py... | 2.734375 | 3 |
modelling/model/__init__.py | nulberry/ADaPT-ML | 5 | 12764866 | import os
import logging
import argparse
TMP_ARTIFACTS = '/tmp_artifacts'
X_TRAIN_FILENAME = os.path.join(TMP_ARTIFACTS, 'x_train.npy')
TRAIN_DF_FILENAME = os.path.join(TMP_ARTIFACTS, 'train.pkl')
TRAIN_DF_HTML_FILENAME = os.path.join(TMP_ARTIFACTS, 'train.html')
TEST_PRED_DF_FILENAME = os.path.join(TMP_ARTIFACTS,... | 2.46875 | 2 |
ScriptBox/haddSE.py | kschweiger/ToolBox | 0 | 12764867 | <gh_stars>0
from glob import glob
import sys
import os
import subprocess
#############################################################
############### Configure Logging
import logging
log_format = (
'[%(asctime)s] %(levelname)-8s %(message)s')
logging.basicConfig(
format=log_format,
level=logging.INFO,
)
#... | 2.375 | 2 |
datacube/__init__.py | otto-AMA/datacube-core | 2 | 12764868 | <reponame>otto-AMA/datacube-core<filename>datacube/__init__.py
"""
Datacube
========
Provides access to multi-dimensional data, with a focus on Earth observations data such as LANDSAT.
To use this module, see the `Developer Guide <http://datacube-core.readthedocs.io/en/stable/dev/developer.html>`_.
The main class to... | 2.234375 | 2 |
python/pandemic_simulator/script_helpers/experiments.py | stacyvjong/PandemicSimulator | 0 | 12764869 | # Confidential, Copyright 2020, Sony Corporation of America, All rights reserved.
from typing import List, Optional, Sequence, Union
import numpy as np
from tqdm import trange
from .setup_sim_env import make_gym_env
from ..data.interfaces import ExperimentDataSaver, StageSchedule
from ..environment import PandemicSi... | 2.25 | 2 |
gnn-comparison/models/graph_classifiers/DeepMultisets.py | tech-srl/bottleneck | 56 | 12764870 | import torch
import torch.nn.functional as F
from torch.nn import Linear
from torch_geometric.nn import global_add_pool
class DeepMultisets(torch.nn.Module):
def __init__(self, dim_features, dim_target, config):
super(DeepMultisets, self).__init__()
hidden_units = config['hidden_units']
... | 3.125 | 3 |
src/tests/files/test_observer.py | mhubii/GIFT-Grab | 41 | 12764871 | from pytest import fail, mark, yield_fixture, raises
try:
# in case of PyPI installation, this will work:
from giftgrab.tests.utils import FileChecker
except ImportError:
# in case of installation from source, this will work:
from utils import FileChecker
from time import sleep
from pygiftgrab import Vi... | 1.976563 | 2 |
fhcrc_pathology/OneFieldPerSpecimen.py | LabKey/argos_nlp | 0 | 12764872 | ''' author@esilgard'''
#
# Copyright (c) 2013-2016 <NAME> Cancer Research Center
#
# Licensed under the Apache License, Version 2.0: http://www.apache.org/licenses/LICENSE-2.0
#
import re, os
import global_strings as gb
PATH = os.path.dirname(os.path.realpath(__file__)) + os.path.sep
class OneFieldPerSpecimen(object)... | 2.390625 | 2 |
commandServer.py | LeHuman/PythonSocketTest | 0 | 12764873 | VERSION = "1.0.0"
HOST = "192.168.1.217"
PORT = 4578
CERT = "cert.pem"
KEY = "priv.key"
RESTARTS = 5
TARGET_SERVER = "mc.koolkidz.club"
API_URL = "https://api.mcsrvstat.us/2/" + TARGET_SERVER
print("\n----------------------------------------------")
print("Command SSL Socket Server", VERSION)
print("-------------------... | 2.6875 | 3 |
promoterz/evaluationPool.py | mczero80/japonicus | 229 | 12764874 | <filename>promoterz/evaluationPool.py
#!/bin/python
import time
import random
import itertools
from multiprocessing import Pool, TimeoutError
from multiprocessing.pool import ThreadPool
class EvaluationPool():
def __init__(self,
World,
Urls, poolsize, individual_info):
... | 2.578125 | 3 |
website/website/apps/cognacy/urls.py | SimonGreenhill/Language5 | 1 | 12764875 | <gh_stars>1-10
from django.conf.urls import *
from website.apps.cognacy import views as v
urlpatterns = [
# PUBLIC
# index page -- two names, index/source_index to allow later respecification
url(r'^$', v.CognateSourceIndex.as_view(), name="index"),
url(r'^$', v.CognateSourceIndex.as_view(), name... | 2.03125 | 2 |
target.py | kirtis26/PyMissile | 0 | 12764876 | import numpy as np
from math import *
from interpolation import InterpVec
class Target(object):
@classmethod
def get_simple_target(cls, pos, vel):
velocity_vectors = [[0, np.array(vel)]]
vel_interp = InterpVec(velocity_vectors)
target = cls(vel_interp=vel_interp)
paramet... | 2.671875 | 3 |
tests/test_modules/test_web/test_system_websocket.py | MattTaylorDLS/pymalcolm | 0 | 12764877 | import unittest
import json
from tornado.websocket import websocket_connect
from tornado import gen
from malcolm.core import Process, call_with_params, Queue, Context, \
ResponseError
from malcolm.modules.builtin.blocks import proxy_block
from malcolm.modules.demo.blocks import hello_block, counter_block
from mal... | 2.46875 | 2 |
src/yamagics/yamagicscore.py | addamit/youngatlas | 4 | 12764878 | """
IPYthon Magics Extension to play audio without displaying the audio widget.
"""
from yaserver import QUOTES_LOCATION, YASERVER_URI
import os
import random
import pathlib
import inspect
from typing import Optional
from IPython import get_ipython
from IPython.display import Audio, display
from IPython.core.magic i... | 2.859375 | 3 |
mongoop/default_settings.py | Lujeni/mongoop | 41 | 12764879 | <filename>mongoop/default_settings.py
# -*- coding: utf-8 -*-
"""
mongoop.default_settings
~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2015 by Lujeni.
:license: BSD, see LICENSE for more details.
"""
mongodb_host = 'localhost'
mongodb_port = 27017
mongodb_credentials = None
mongodb_options = None
fre... | 1.007813 | 1 |
LeetCode/160_intersection_of_two_linked_lists/getIntersectionNode.py | harveyc95/ProgrammingProblems | 0 | 12764880 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def getIntersectionNode(self, headA, headB):
a, b = headA, headB
while a != b:
a = a.next if a else headB
b =... | 3.40625 | 3 |
dcgan.py | czhongyu/generative-models | 2 | 12764881 | <filename>dcgan.py<gh_stars>1-10
from __future__ import print_function
import argparse
import os
import random
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.optim as optim
import torch.utils.data
from torchvision import datasets, transforms
from torchvision.utils import save_image
import con... | 2.25 | 2 |
train.py | cwyd0822/cifar10-classification-tensorflow-slim | 2 | 12764882 | import tensorflow as tf
import readcifar10
slim = tf.contrib.slim
import os
import resnet
# 定义网络结构
# image:一张图像
# 返回10维的向量
def model(image, keep_prob=0.8, is_training=True):
batch_norm_params = {
"is_training": is_training,
"epsilon": 1e-5, # 防止除以0
"decay": 0.997, # 衰减系数
'scale':... | 2.5 | 2 |
cat_detector/observer/main.py | axbg/workshop-asmi-2020 | 1 | 12764883 | <filename>cat_detector/observer/main.py
from threading import Thread
from base64 import b64encode, b64decode
from requests.exceptions import ConnectionError
import os
import json
import sys
import cv2
import requests
import config
import numpy as np
def upload_image(url, data):
try:
payload = {"image": d... | 2.5625 | 3 |
app/app.py | hkvh/sonata-archives | 0 | 12764884 | <gh_stars>0
#!/usr/bin/env python
import logging
import os
from flask import Flask, render_template, send_from_directory
from flask_bootstrap import Bootstrap
from psycopg2 import sql
from database_design.sonata_table_specs import Composer, Piece, Sonata, Intro, Expo, Development, \
Recap, Coda, ColumnDisplay
fro... | 2.40625 | 2 |
SAM2017/registration/admin.py | jpavelw/sam-2017 | 1 | 12764885 | from django.contrib import admin
from . import models
class UserFieldFilter(admin.ModelAdmin):
fields = ['role']
admin.site.register(models.User, UserFieldFilter)
admin.site.register(models.Role)
| 1.5 | 2 |
tests/unit/test_non_empty_configs_provider.py | barryib/gitlabform | 299 | 12764886 | import pytest
from gitlabform import EXIT_INVALID_INPUT
from gitlabform.configuration.projects_and_groups import ConfigurationProjectsAndGroups
from gitlabform.filter import NonEmptyConfigsProvider
def test_error_on_missing_key():
config_yaml = """
---
# no key at all
"""
with pytest.raises(Syst... | 2.421875 | 2 |
packages/legacycomponents/mcstas2/python/mcstas2/utils/parsers.old/ShareIncludeParser.py | mcvine/mcvine | 5 | 12764887 | #!/usr/bin/env python
#
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#
# <NAME>
# California Institute of Technology
# (C) 2008 All Rights Reserved
#
# {LicenseText}
#
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~... | 2.109375 | 2 |
question_bank/linked-list-in-binary-tree/linked-list-in-binary-tree.py | yatengLG/leetcode-python | 9 | 12764888 | # -*- coding: utf-8 -*-
# @Author : LG
"""
执行用时:108 ms, 在所有 Python3 提交中击败了96.06% 的用户
内存消耗:15.8 MB, 在所有 Python3 提交中击败了25.37% 的用户
解题思路:
先在树中找到与链表第一个节点相同值的 树节点
然后以这些树中节点为根的子树中寻找是否存在链表
"""
class Solution:
def isSubPath(self, head: ListNode, root: TreeNode) -> bool:
def Sub(root, head): # 递归在子树中判断... | 3.71875 | 4 |
drivers/driver.py | OttrOne/suivi | 0 | 12764889 | <reponame>OttrOne/suivi
class DriverMeta(type):
def __instancecheck__(cls, __instance) -> bool:
return cls.__subclasscheck__(type(__instance))
def __subclasscheck__(cls, __subclass: type) -> bool:
return (
hasattr(__subclass, 'create') and callable(__subclass.create)
... | 2.4375 | 2 |
karapace/protobuf/proto_type.py | instaclustr/karapace | 1 | 12764890 | <gh_stars>1-10
# Ported from square/wire:
# wire-library/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/ProtoType.kt
"""
Names a protocol buffer message, enumerated type, service, map, or a scalar. This class models a
fully-qualified name using the protocol buffer package.
"""
from enum import auto, Enum
fr... | 1.78125 | 2 |
release/cs_submitter/mainform/migrations/0002_auto_20170801_1155.py | kvswim/kv_jhucs_coursesubmit | 0 | 12764891 | <filename>release/cs_submitter/mainform/migrations/0002_auto_20170801_1155.py
# -*- coding: utf-8 -*-
# Generated by Django 1.11.3 on 2017-08-01 15:55
from __future__ import unicode_literals
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies... | 1.625 | 2 |
src/main.py | andrejmiscic/simcls-pytorch | 5 | 12764892 | <reponame>andrejmiscic/simcls-pytorch<filename>src/main.py
import argparse
import os
import torch
from torch.utils.data import DataLoader
from evaluator import Evaluator
from model import CandidateScorer
from trainer import Trainer, TrainConfig
from utils.data_utils import SummarizationDataset, collate_inputs_to_bat... | 2.484375 | 2 |
tests/src/smiley/smiley/commands/show.py | incognitoRepo/hdlogger | 0 | 12764893 | import logging
from cliff import command
from smiley import db
from smiley import output
class Show(command.Command):
"""Show the details of one run.
Includes summaries of the thread resource consumption, when
multiple threads are present.
"""
log = logging.getLogger(__name__)
def get_par... | 2.5625 | 3 |
d2l-zh/recurrent-neural-network/rnn-start.py | hyschn/practice-code | 2 | 12764894 | # encoding:utf-8
"""
@Time : 2020-05-22 21:14
@Author : <EMAIL>
@File : rnn-start.py
@Software: PyCharm
"""
import d2lzh as d2l
import math
from mxnet import autograd, nd
from mxnet.gluon import loss as gloss
import time
def to_onehot(X, size):
return [nd.one_hot(x, size) for x in X.T]
def get_params():
... | 2.40625 | 2 |
python_work/Chapter5/cars.py | Elektra-2/python_crash_course_2nd | 1 | 12764895 | <reponame>Elektra-2/python_crash_course_2nd<gh_stars>1-10
# Simple example using ifs
cars = ['volks', 'ford', 'audi', 'bmw', 'toyota']
for car in cars:
if car == 'bmw':
print(car.upper())
else:
print(car.title())
# Comparing Values
#
# requested_toppings = 'mushrooms'
# if requested_topping... | 3.625 | 4 |
etils/epy/itertools_test.py | google/etils | 13 | 12764896 | <reponame>google/etils<filename>etils/epy/itertools_test.py<gh_stars>10-100
# Copyright 2022 The etils 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/l... | 2.375 | 2 |
models/xsts.py | tefra/xsdata-w3c-tests | 1 | 12764897 | from dataclasses import dataclass, field
from decimal import Decimal
from enum import Enum
from typing import Dict, List, Optional, Union
from xsdata.models.datatype import XmlDate
from models.xlink import TypeType
from models.xml import LangValue
__NAMESPACE__ = "http://www.w3.org/XML/2004/xml-schema-test-suite/"
c... | 2.265625 | 2 |
tddd92-SC2-AI/ArmyHandler/squad.py | AxelGard/university-projects | 2 | 12764898 | class Squad():
def __init__(self, handler, role, hold_point):
self.handler = handler
if len(handler.squads[role]) > 0:
self.id = handler.squads[role][-1].id + 1
else:
self.id = 1
self.units = {
handler.unit.MARINE: [],
handler... | 2.90625 | 3 |
Q049.py | Linchin/python_leetcode_git | 0 | 12764899 | <filename>Q049.py
"""
49
medium
group anagrams
Given an array of strings strs, group the anagrams together.
You can return the answer in any order.
"""
from typing import List
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
hash = {}
for string in strs:
... | 4.125 | 4 |
src/zignalz/core/util.py | rscohn2/sensepy | 0 | 12764900 | <gh_stars>0
# SPDX-FileCopyrightText: 2020 <NAME>
#
# SPDX-License-Identifier: MIT
import logging
from subprocess import Popen, run
logger = logging.getLogger(__name__)
def shell(cmd, dry_run=False, check=True):
logger.info(f'shell: {cmd}')
if dry_run:
return
run(cmd, shell=True, check=check)
... | 2.28125 | 2 |
GeneratorInterface/GenFilters/python/ZgammaFilter_cfi.py | ckamtsikis/cmssw | 852 | 12764901 | <reponame>ckamtsikis/cmssw
import FWCore.ParameterSet.Config as cms
# values tuned also according to slide 3 of :
# https://indico.cern.ch/getFile.py/access?contribId=23&sessionId=2&resId=0&materialId=slides&confId=271548
# selection efficiency of approx 6% for ZMM_8TeV
myZgammaFilter = cms.EDFilter('ZgammaMassFilter... | 1.398438 | 1 |
SublimeText3_3176/Data/Packages/SublimeTextXdebug-master/xdebug/config.py | xiexie1993/Tool_Sublime_Text3_for_Windows | 1 | 12764902 | import sublime
# Settings variables
try:
from . import settings as S
except:
import settings as S
def load_project_values():
try:
settings = sublime.active_window().active_view().settings()
# Use 'xdebug' as key which contains dictionary with project values for package
S.CONFIG_PR... | 2.359375 | 2 |
master_thesis_doc/img/statsWilcoxon_examples.py | nicolai-schwartze/Masterthesis | 1 | 12764903 | <gh_stars>1-10
# -*- coding: utf-8 -*-
"""
Created on Wed Aug 26 15:42:31 2020
@author: Nicolai
"""
import seaborn as sns
import sys
sys.path.append("../../code/post_proc/")
import post_proc as pp
import matplotlib.pyplot as plt
import numpy as np
if __name__ == "__main__":
###############################
... | 2.109375 | 2 |
tests/integration/test_dummy.py | vbpns/fastapi-boilerplate | 0 | 12764904 | <reponame>vbpns/fastapi-boilerplate<filename>tests/integration/test_dummy.py
import unittest
# Arquivo de exemplo para testes de integracao
# Fontes:
# https://realpython.com/python-testing/#writing-your-first-test
class TestDummy2(unittest.TestCase):
def sum(arg):
total = 0
for val in arg:
... | 3.171875 | 3 |
rubra/utils.py | bjpop/rubra | 14 | 12764905 | <reponame>bjpop/rubra
# Various useful utilities for the pipeline.
import sys
import errno
import subprocess
from ruffus.proxy_logger import *
import logging
import imp
import os
import os.path
from shell_command import shellCommand
from cluster_job import PBS_Script
import re
# A simple container object
class Bag:
... | 2.140625 | 2 |
tests/test_github.py | dantin/coral | 0 | 12764906 | <filename>tests/test_github.py<gh_stars>0
# -*- coding: utf-8 -*-
import os
import pytest
from scrapy.http import TextResponse
from coral.spiders.github import parse_release_link, parse_release_links
@pytest.fixture
def landing_page(page_path):
with open(os.path.join(page_path, 'landing_page.html'), 'r') as f:
... | 2.40625 | 2 |
utils/data_cleaning.py | grazimelo/previsao-diabetes | 0 | 12764907 | from pandas import DataFrame
def remover_duplicatas(df: DataFrame, drop_if_found=True) -> tuple:
"""Remove linhas e colunas duplicadas no dataframe.
Args:
df (DataFrame): Um dataframe para ser analisado.
drop_if_found (bool): Flag indicando se é pra devolver o dataframe ou só analisar.
R... | 3.953125 | 4 |
leetcode/binary-tree/unique_BSTs.py | Gaurav-Pande/DataStructures | 5 | 12764908 | <reponame>Gaurav-Pande/DataStructures
# https://leetcode.com/problems/unique-binary-search-trees-ii/
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def generateTrees(self, n):
... | 3.90625 | 4 |
scripts/tools/feature.py | kamigaito/SLAHAN | 15 | 12764909 | import argparse
import codecs
parser = argparse.ArgumentParser(description='Conveter of the Google sentence compression dataset')
parser.add_argument("-s", "--sent-file", dest="file_sent", type=str, help="path to the sentence file")
parser.add_argument("-p", "--pos-file", dest="file_pos", type=str, help="path to the p... | 2.96875 | 3 |
libraries/stats/widgets/spline.py | PiRSquared17/r-orange | 1 | 12764910 | <gh_stars>1-10
"""Spline Fit widget
.. helpdoc::
Generates a spline fit to X, Y data. This can be used for plotting or for interogating the splines.
"""
"""<widgetXML>
<name>Spline Fit</name>
<icon>stats.png</icon>
<screenshots></screenshots>
<summary>Produces a spline fit of X/Y data.<... | 2.921875 | 3 |
scripts/mmarc_reads_aligned.py | lakinsm/meta-marc-publication | 1 | 12764911 | <reponame>lakinsm/meta-marc-publication
#!/usr/bin/env python3
import re
import os.path
import sys
ltrans = {1: 'Class', 2: 'Mechanism', 3: 'Group'}
counts = {1: {}, 2: {}, 3: {}}
reads_mapped = 0
total_reads = 0
def load_mmarc_metadata(infile):
ret = {}
with open(infile, 'r') as f:
data = f.read()... | 2.46875 | 2 |
dzTraficoBackend/dzTrafico/BusinessLayer/SimulationManager.py | DZAymen/dz-Trafico | 0 | 12764912 | <reponame>DZAymen/dz-Trafico<filename>dzTraficoBackend/dzTrafico/BusinessLayer/SimulationManager.py
from dzTrafico.BusinessLayer.SimulationCreation.SimulationCreator import SimulationCreator
from dzTrafico.BusinessEntities.Simulation import Simulation
from dzTrafico.BusinessEntities.Sink import Sink
from dzTrafico.Busi... | 2.3125 | 2 |
sqlhandler/custom/executable.py | matthewgdv/sqlhandler | 0 | 12764913 | <filename>sqlhandler/custom/executable.py
from __future__ import annotations
from typing import Any, TYPE_CHECKING, Optional
from abc import ABC, abstractmethod
from pathmagic import File, PathLike
from miscutils import ParametrizableMixin
from sqlhandler.frame import Frame
if TYPE_CHECKING:
from sqlhandler imp... | 2.734375 | 3 |
audio8/wrd2bpe.py | mead-ml/audio8 | 2 | 12764914 | <reponame>mead-ml/audio8
import logging
import os
from argparse import ArgumentParser
from audio8.text import BPEVectorizer
from eight_mile.utils import revlut
parser = ArgumentParser()
parser.add_argument("--root_dir")
parser.add_argument("--train_dataset", type=str, help='Dataset (by name), e.g. train-clean-360')
pa... | 2.53125 | 3 |
xautodl/spaces/__init__.py | Joey61Liuyi/AutoDL-Projects | 817 | 12764915 | #####################################################
# Copyright (c) <NAME> [GitHub D-X-Y], 2021.01 #
#####################################################
# Define complex searc space for AutoDL #
#####################################################
from .basic_space import Categorical
from .basic_space... | 1.914063 | 2 |
AIO/pairs/pairs.py | eddiegz/Personal-C | 3 | 12764916 | infile=open('pairin.txt','r')
n=int(infile.readline().strip())
dic={}
for i in range(2*n):
sn=int(infile.readline().strip())
if sn not in dic:
dic[sn]=i
else:
dic[sn]-=i
maxkey=min(dic,key=dic.get)
outfile=open('pairout.txt','w')
outfile.write(str(abs(dic[maxkey])))
outfile.close... | 2.9375 | 3 |
feder/domains/__init__.py | efefre/feder | 0 | 12764917 | <gh_stars>0
from django.apps import AppConfig
from django.utils.translation import ugettext_lazy as _
class DomainsConfig(AppConfig):
name = "feder.domains"
verbose_name = _("Domains")
| 1.242188 | 1 |
imagex/upload/views.py | natlungfy/comp3297-imagex | 0 | 12764918 | from django.shortcuts import render
from accounts.models import Member
from search.models import Image, Tag, Category
import datetime
def parse_tags(tag, img):
data = tag.split(',')
for d in data:
num_records = Tag.objects.filter(tag_name__iexact=d).count()
if num_records == 0:
... | 2.234375 | 2 |
stacks_queues/queue_via_stacks.py | UPstartDeveloper/Problem_Solving_Practice | 0 | 12764919 | <reponame>UPstartDeveloper/Problem_Solving_Practice<filename>stacks_queues/queue_via_stacks.py
"""
Queue via Stacks
Implement a MyQueue class which implements a queue using two stacks.
Questions and Assumptions:
Model 1: Back to Back ArrayStacks
MyQ
stack1 stack2
t2 t1
... | 4.1875 | 4 |
src/pascal-ranslate-exp.py | alisure-ml/Semantic-Segmentation-clockwork-fcn | 2 | 12764920 | import os
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
import time
from collections import namedtuple
import caffe
from lib import run_net
from lib import score_util
from datasets.pascal_voc import Pascal
PV = Pascal('C:\\ALISURE\\Data\\voc\\VOCdevkit\\VOC2012')
val_set = PV.get_data_se... | 2.453125 | 2 |
channels/management/commands/backpopulate_channel_fields.py | mitodl/open-discussions | 12 | 12764921 | <filename>channels/management/commands/backpopulate_channel_fields.py
"""Management command to backpopulate channel fields"""
from django.core.management.base import BaseCommand
from channels.tasks import populate_channel_fields
from open_discussions.utils import now_in_utc
class Command(BaseCommand):
"""Backpop... | 2.59375 | 3 |
tests/test_generation.py | createchaos/coop_assembly | 3 | 12764922 | import os
import pytest
from itertools import combinations
from compas.datastructures import Network
from coop_assembly.help_functions import find_point_id
from coop_assembly.help_functions import find_point_id, tet_surface_area, \
tet_volume, distance_point_triangle
from coop_assembly.geometry_generation.tet_seq... | 2.015625 | 2 |
etutils/viz/savefig.py | erdogant/etutils | 0 | 12764923 | """ This function saves figures in PNG format.
from etutils.viz.savefig import savefig
A=savefig(data, <optional>)
INPUT:
data: fig object
OPTIONAL
OUTPUT
BOOLEAN
[0]: If not succesful
[1]: If succesful
DESCRIPTION
This function saves figures in PNG format.
EXAMPLE
from e... | 3.34375 | 3 |
Python/leetcode.260.single-number-iii.py | tedye/leetcode | 4 | 12764924 | <filename>Python/leetcode.260.single-number-iii.py
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
workingset = set()
for n in nums:
if n not in workingset:
workingset.add(n)
... | 3.640625 | 4 |
app/models/old/teams.py | WilliamBesseau/Groot | 0 | 12764925 | from app.models import db
from app.models.projects import Project
class Team(db.Model):
__tablename__ = 'teams'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String)
logo = db.Column(db.String)
tokens = db.Column(db.Integer)
description = db.Column(db.String)
id_assign... | 2.578125 | 3 |
test.py | Chash-dot/Pythin_CI_Example | 0 | 12764926 | <filename>test.py
import unittest
import SimpleRest as app
class TestHello(unittest.TestCase):
def setUp(self):
app.app.testing = True
self.app = app.app.test_client()
def test_hello(self):
rv = self.app.get('/')
self.assertEqual(rv.status, '200 OK')
self.assertEqual(r... | 3.15625 | 3 |
src/data_loading.py | HugoHo0212/Elasticsearch-demo | 0 | 12764927 | <filename>src/data_loading.py<gh_stars>0
from typing import Tuple
import tarfile
import os
from elasticsearch import Elasticsearch
from elasticsearch.client import IndicesClient
from pyquery import PyQuery as pq
def load_data(es: Elasticsearch) -> None:
"""
This function loads data from the tarball "wiki-sm... | 3.296875 | 3 |
ovpn_bypass.py | gaohuazuo/pku-free-ip | 0 | 12764928 | #!/usr/bin/env python3
import os
from fetch import fetch
def main():
ip_list = fetch()
print('# PKU free ip')
for ip, _, netmask in ip_list:
print('route', ip, netmask, 'net_gateway')
if __name__ == '__main__':
main()
| 2.890625 | 3 |
labs-python/tests/test3/exe2.py | xR86/ml-stuff | 3 | 12764929 | <filename>labs-python/tests/test3/exe2.py
import urllib
import re
import json
f = urllib.urlopen("http://localhost:8000/participanti/orar_I3B5.html")
response = f.read()
# print response
"""
<tr>
<td> 12:00</td>
<td> 14:00</td>
<td> Animatie 3D: algoritmi si tehnici fundamentale</td>
<td> Seminar</td... | 3.0625 | 3 |
core/urls.py | adson62/donodotime | 0 | 12764930 | from django.urls import path
from core import views
app_name = 'core'
urlpatterns = [
path('', views.index, name='index'),
path('noticias/', views.noticiaListView.as_view(), name='noticiaListView'),
path('noticias/new/', views.noticiaCadastro, name='noticiaCadastro'),
path('noticias/<int:id>/', views.noticiaDetal... | 1.835938 | 2 |
visualizer/go.py | AndreasMadsen/bachelor-code | 1 | 12764931 |
import os.path as path
import sys
import numpy as np
thisdir = path.dirname(path.realpath(__file__))
sys.path.append(path.join(thisdir, '..'))
import dataset
import model
from graph_server import GraphServer
name = sys.argv[1]
build_dir = path.join(thisdir, '..', 'outputs', 'builds')
clusters = model.load(path.jo... | 2.25 | 2 |
pygmy/rest/wsgi.py | ParikhKadam/pygmy | 571 | 12764932 | #!/usr/bin/env python3
from pygmy.core.initialize import initialize
initialize()
from pygmy.rest.manage import app
if __name__ == '__main__':
app.run()
| 1.273438 | 1 |
adventOfCode/Day3_2.py | oana-cit/Aoc2017 | 0 | 12764933 | '''
Created on Dec 4, 2017
@author: atip
'''
def getAdjSquareSum():
global posX, posY, valMatrix
adjSquareSum = 0
adjSquareSum += valMatrix[maxRange + posX + 1][maxRange + posY]
adjSquareSum += valMatrix[maxRange + posX + 1][maxRange + posY + 1]
adjSquareSum += valMatrix[maxRange + posX][maxRange ... | 2.84375 | 3 |
python/CeaserCipher.py | rishab9750/HacktoberFest_2021 | 33 | 12764934 | def encrypt(text,s):
result = ""
for i in range(len(text)):
char = text[i]
if (char.isupper()):
result += chr((ord(char) + s-65) % 26 + 65)
else:
result += chr((ord(char) + s - 97) % 26 + 97)
return result
text = "ATT<PASSWORD>"
s = 4
print "Text : " + tex... | 3.984375 | 4 |
tests/test_NDList.py | Tyler314/led_matrix | 3 | 12764935 | <gh_stars>1-10
import unittest
from random import random
import led_matrix
class test_NDList(unittest.TestCase):
def test_init_0(self):
ndl = led_matrix.NDList(shape=(0,))
self.assertEqual(ndl, [])
def test_init_1(self):
ndl = led_matrix.NDList(shape=(1,))
self.assertEqual(nd... | 2.859375 | 3 |
models.py | jwadden/invoicinator | 0 | 12764936 | <reponame>jwadden/invoicinator
import sqlalchemy
import sqlalchemy.ext.declarative
import sqlalchemy.orm
engine = None
Session = None
Base = sqlalchemy.ext.declarative.declarative_base()
def init_engine(settings_dict):
global engine
global Session
engine = sqlalchemy.create_engine(settings_dict['db_engin... | 2.265625 | 2 |
Python3/77.combinations.py | 610yilingliu/leetcode | 0 | 12764937 | <reponame>610yilingliu/leetcode<filename>Python3/77.combinations.py<gh_stars>0
#
# @lc app=leetcode id=77 lang=python3
#
# [77] Combinations
#
# @lc code=start
class Solution:
def combine(self, n, k):
self.ans = []
nums = [num for num in range(1, n + 1)]
if n == k:
self.ans.appe... | 3.09375 | 3 |
tuiuiu/tuiuiudocs/__init__.py | caputomarcos/tuiuiu.io | 3 | 12764938 | default_app_config = 'tuiuiu.tuiuiudocs.apps.TuiuiuDocsAppConfig'
| 1.15625 | 1 |
bin/augment_classification.py | VynOpenSource/vyn-augment | 0 | 12764939 | <reponame>VynOpenSource/vyn-augment<gh_stars>0
"""
This file as well as the other examples will store the augmented images in the vyn-augment/images/output_data folder.
On the other hand, the folder notebooks contains the same examples with the images being plotted in the same file
instead of being saved in memory. In ... | 3.046875 | 3 |
assignment26.py | swarnaishu/nlp-peronsal-archive | 0 | 12764940 | <gh_stars>0
import grammar_check
tool=grammar_check.LanguageTool('en-gb')
sentence='he is playing cricket'
matches=tool.check(sentence)
len(matches)
grammar_check.correct(text,matches) | 2.65625 | 3 |
contents_rank_crawling.py | dldldlfma/py_tutorial | 0 | 12764941 | <filename>contents_rank_crawling.py
from selenium import webdriver
from bs4 import BeautifulSoup
from pprint import pprint
def keyword_preprocessing(word):
"""
검색 keyword를 google 검색 URL과 붙이기 위해 적합한 형태로 전환합니다.
띄어쓰기를 +로 바꾸는 정도 입니다.
"""
change_word = list(word)
for i in range(len(change_word)):
... | 3.0625 | 3 |
manage/propget.py | Rome84/AWS | 0 | 12764942 | <reponame>Rome84/AWS
# Copyright (c) 2006-2009 <NAME> http://garnaat.org/
#
# 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... | 2.734375 | 3 |
datachimp/views/api/ml_model.py | ModelChimp/datachimp | 0 | 12764943 | from django.conf import settings
from django.http import HttpResponse
from rest_framework import generics, status
from rest_framework.response import Response
from rest_framework.decorators import api_view, permission_classes
from datachimp.models.machinelearning_model import MachineLearningModel
from datachimp.model... | 2.078125 | 2 |
tests/test_CameraCorrected.py | a1rb4Ck/camera_fusion | 25 | 12764944 | """camera_fusion CameraCorrected class tests."""
import cv2
import os
import sys
import filecmp
import pytest
import numpy as np
import shutil
import time
import unittest.mock as mock
sys.path.insert(
0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
import camera_fusion # noqa
class Vc(object... | 2.59375 | 3 |
tests/__init__.py | dbauducco/DistributedReplays | 69 | 12764945 | from sqlalchemy.engine import create_engine
from sqlalchemy.orm.session import Session
def setup_module():
global transaction, connection, engine
# Connect to the database and create the schema within a transaction
engine = create_engine('postgresql:///yourdb')
connection = engine.connect()
tran... | 3.03125 | 3 |
gmailapi_backend/service.py | innoveit/django-gmailapi-json-backend | 1 | 12764946 | import base64
import json
import logging
import mimetypes
import email.encoders as encoder
import socket
from email.mime.audio import MIMEAudio
from email.mime.base import MIMEBase
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from django.con... | 2.078125 | 2 |
discode/models/message.py | TheFarGG/Discode | 3 | 12764947 | from __future__ import annotations
__all__ = ("Message", "MessageReference")
from typing import Any, Optional, Dict, List, Union, TYPE_CHECKING
from ..app import Button, LinkButton, component_from_dict
from ..utils import UNDEFINED
from .abc import Snowflake
from .channel import TextChannel
from .guild import Guild
... | 2.046875 | 2 |
mayan/apps/appearance/settings.py | Syunkolee9891/Mayan-EDMS | 1 | 12764948 | from __future__ import unicode_literals
from django.utils.translation import ugettext_lazy as _
from mayan.apps.smart_settings.classes import Namespace
from .literals import DEFAULT_MAXIMUM_TITLE_LENGTH
namespace = Namespace(label=_('Appearance'), name='appearance')
setting_max_title_length = namespace.add_setting... | 1.804688 | 2 |
tfmiss/training/adapt.py | shkarupa-alex/tfmiss | 1 | 12764949 | <filename>tfmiss/training/adapt.py
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import tensorflow as tf
import time
from collections import Counter
from scipy.interpolate import LinearNDInterpolator
from functools import lru_cache
de... | 2.6875 | 3 |
advertools/ad_from_string.py | JUSTIN-BOLAND/advertools | 1 | 12764950 | <gh_stars>1-10
import string
def ad_from_string(s, slots=(30, 30, 30, 90, 90, 15, 15), sep=None,
capitalize=False):
"""Convert string ``s`` to an ad by splitting it into groups of words.
Each group would have a length of at most the allowed length for that slot.
If the total length of ... | 4.0625 | 4 |