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 |
|---|---|---|---|---|---|---|
src/gan-dogs/model/loss.py | caciolai/Generative-Dog-Images-with-BigGan | 0 | 12783951 | import tensorflow as tf
from .utils import noisy_labels, smooth_fake_labels, smooth_real_labels, CONFIG
class SGANDiscriminatorLoss(tf.keras.losses.Loss):
def __init__(self):
"""Standard GAN loss for discriminator.
"""
super().__init__()
self.bce = tf.keras.losses.BinaryCrossentr... | 2.6875 | 3 |
SV_Detection/SourceCode/TestingCase/RunSniffles/RunSniffles.py | NCI-CGR/PacbioPipeline | 0 | 12783952 | import sys
import subprocess
import os
runSnifflesScript = "./call_sniffles.sh"
resultDir = "/CGF/Bioinformatics/Production/Wen/20200117_pacbio_snp_call/29461_WGS_cell_line/bam_location_ngmlr/SV/Sniffles"
class ClsSample:
def __init__(self):
self.strName = ""
self.strPath = ""
self.strBAM ... | 2.484375 | 2 |
qppwg/utils/features.py | bigpon/QPPWG | 46 | 12783953 | <filename>qppwg/utils/features.py<gh_stars>10-100
# -*- coding: utf-8 -*-
# Copyright 2020 <NAME> (Nagoya University)
# MIT License (https://opensource.org/licenses/MIT)
"""Feature-related functions."""
import numpy as np
def validate_length(x, y, hop_size=None):
""" Validate length
Args:
x (ndarr... | 2.546875 | 3 |
lib/improver/psychrometric_calculations/psychrometric_calculations.py | TomekTrzeciak/improver | 0 | 12783954 | <reponame>TomekTrzeciak/improver<filename>lib/improver/psychrometric_calculations/psychrometric_calculations.py
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# (C) British Crown Copyright 2017-2019 Met Office.
# All rights reserved.
#
# Redistribution and use in... | 1.453125 | 1 |
eactivities/models/documentation.py | lukegb/ehacktivities | 1 | 12783955 | <filename>eactivities/models/documentation.py<gh_stars>1-10
from . import Model, ArrayModel, DictModel
from eactivities.parsers.documentation import InventoryParser, KeyListsParser, RiskAssessmentParser
class Documentation(Model):
def _spawn(self, model_cls, parser_cls):
kwargs = {
'clu... | 2.5 | 2 |
dreamplace/ops/electric_potential/electric_overflow.py | Eternity666/DREAMPlace | 323 | 12783956 | ##
# @file electric_overflow.py
# @author <NAME>
# @date Aug 2018
#
import math
import numpy as np
import torch
from torch import nn
from torch.autograd import Function
from torch.nn import functional as F
import dreamplace.ops.electric_potential.electric_potential_cpp as electric_potential_cpp
import dreamplace.... | 2.125 | 2 |
mysite/polls/urls.py | Predator01/potential-adventure | 0 | 12783957 | from django.conf.urls import include, url, patterns
from polls import views
urlpatterns = [
url(r'^home/$', views.home, name='home'),
url(r'^about/$', views.about, name='about'),
]
| 1.695313 | 2 |
app/robo-advisor.py | finleycgeorgetown/Robo-Advisor | 1 | 12783958 | # app/robo_advisor.py
import csv
import os
import json
from dotenv import load_dotenv
import requests
from datetime import datetime
now = datetime.now()
datelabel = now.strftime("%d/%m/%Y %H:%M:%S")
load_dotenv()
# utility function to convert float or integer to usd-formatted string (for printing
# ... adapted fr... | 3.390625 | 3 |
modules/analyzer/save_txt.py | Kolyamba-mamba/technology-partner-search-module | 2 | 12783959 | <reponame>Kolyamba-mamba/technology-partner-search-module
import os
import sys
sys.path.append(os.path.abspath('../../mySite/mySite'))
from modules.dbActions.getTables import get_abstract_and_descr_path
from modules.helpers.saoSelector import rem, split_description
def save_text_db_to_txt(con, filename_base = 'C:/Use... | 2.40625 | 2 |
ros_comms/ros_pub.py | FabianFalck/de_niro | 7 | 12783960 | #!/usr/bin/env python
"""
Wrapper to ROS publisher.
Author: <NAME>
Date: 05/18
"""
import rospy
class ROSPublisher(object):
def __init__(self, _topic, _message_type, _queue_size=1, rate=10):
"""
ROSPublisher constructor.
:param _topic: string, ROS topic to publish on
:param _me... | 3.109375 | 3 |
simulator/front_end/src/front_end/grpc/client.py | yrrah/cs6620-fall21-intelligent-assignment-of-data-to-dedup-nodes | 1 | 12783961 | <reponame>yrrah/cs6620-fall21-intelligent-assignment-of-data-to-dedup-nodes
from __future__ import print_function
import grpc
from front_end.grpc import assignService_pb2_grpc, assignService_pb2
from front_end.grpc.assignService_pb2 import Acknowledgement
from front_end.region_creation.input_streams import HashFile
f... | 2.515625 | 3 |
PFERD/tmp_dir.py | ff781/PFERD | 0 | 12783962 | """Helper functions and classes for temporary folders."""
import logging
import shutil
from pathlib import Path
from types import TracebackType
from typing import Optional, Type
from .location import Location
LOGGER = logging.getLogger(__name__)
class TmpDir(Location):
"""A temporary folder that can create fil... | 3.5 | 4 |
dashboard/dashboard/pinpoint/models/quest/find_isolated_test.py | ravitejavalluri/catapult | 0 | 12783963 | <reponame>ravitejavalluri/catapult
# Copyright 2016 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.
import unittest
from google.appengine.ext import ndb
from google.appengine.ext import testbed
from dashboard.pinpoint.mo... | 1.78125 | 2 |
TurtleCore/PythonCode/ScrolledCanvasClass.py | FrankFK/simple-graphics-for-csharp-beginners | 0 | 12783964 | ## helper functions for Scrolled Canvas, to forward Canvas-methods
## to ScrolledCanvas class
def __methodDict(cls, _dict):
"""helper function for Scrolled Canvas"""
baseList = list(cls.__bases__)
baseList.reverse()
for _super in baseList:
__methodDict(_super, _dict)
for key, value in cls.... | 2.921875 | 3 |
Tema1/Code/Server/src/logic/UDPServer.py | SergiuDeveloper/Programare-Concurenta-si-Distribuita | 1 | 12783965 | import socket
from threading import Thread, Lock
from time import time
from .BenchmarkData import BenchmarkData
class UDPServer:
def __init__(self, host, port, benchmark_file_path, chunk_size, ack):
self.__host = host
self.__port = port
self.__running = False
self.__running_lock ... | 2.90625 | 3 |
data/scan_records.py | geoffrey0822/deepspeech.pytorch | 0 | 12783966 | <reponame>geoffrey0822/deepspeech.pytorch
import os, sys, argparse, utils, subprocess
def regenerate(src, dst, manifest, new_manifest, sample_rate,
mono, min_duration, max_duration):
if not os.path.isdir(dst):
os.mkdir(dst)
if not os.path.isfile(manifest):
print('%s not found',... | 2.578125 | 3 |
lc_classifier/features/extractors/sn_detections_extractor.py | alercebroker/late_classifier | 6 | 12783967 | from typing import Tuple
from functools import lru_cache
from ..core.base import FeatureExtractorSingleBand
import pandas as pd
import logging
class SupernovaeDetectionFeatureExtractor(FeatureExtractorSingleBand):
@lru_cache(1)
def get_features_keys_without_band(self) -> Tuple[str, ...]:
return ('del... | 2.4375 | 2 |
redditwall.py | gopal131072/Reddit-Wall | 1 | 12783968 | import praw
import config
import time
import os
#Getting OAUTH object. Configure these in config.py.
print("Trying to log in to reddit.\n")
try:
reddit = praw.Reddit(username = config.username,
password = <PASSWORD>,
client_id = config.client_id,
client_secret = conf... | 2.90625 | 3 |
mephisto/abstractions/blueprints/remote_procedure/remote_procedure_agent_state.py | VjunetXuuftofi/Mephisto | 0 | 12783969 | <filename>mephisto/abstractions/blueprints/remote_procedure/remote_procedure_agent_state.py
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from typing import List, Opt... | 2.125 | 2 |
custom_addons/purchase_order_filter/models/purchase_order_filter.py | MonwarAdeeb/Bista_Solutions | 0 | 12783970 | <gh_stars>0
from odoo import _, api, fields, models
from datetime import datetime, timedelta
class PurchaseOrderFilter(models.TransientModel):
_name = "purchase.order.filter"
_description = "Filter Class for Purchase Order"
from_date = fields.Date(
string='Date From', default=datetime.today())
... | 2.5 | 2 |
get_while_uploading.py | sunguanxiong/kinetics | 0 | 12783971 | <filename>get_while_uploading.py
import argparse
import json
import os
import ftplib
from joblib import delayed
from joblib import Parallel
def FTP_wrapper():
ftp = ftplib.FTP()
ftp.connect ("10.107.1.68")
ftp.login ("sunguanxiong", "Sgx19940210")
return ftp
def download_video(video_name, download_dir... | 2.84375 | 3 |
launchers/hosp_mob_mean.py | BidGem/WeatherPE | 2 | 12783972 | <filename>launchers/hosp_mob_mean.py<gh_stars>1-10
from weape.argv import get_data_from_xlsx
def main():
dates, pressure, hospitalizations = get_data_from_xlsx()
series = hospitalizations.mobile_mean(730)
eventuality = hospitalizations.eventuality().mobile_mean(730)
series.plot()
eventuality.plot(... | 1.914063 | 2 |
tests/ssd.py | hey-yahei/GluonConverter | 10 | 12783973 | #-*- coding: utf-8 -*-
import os
from gluoncv.model_zoo import ssd_512_mobilenet1_0_voc
import sys
sys.path.append("..")
from convert import convert_ssd_model, save_model
if __name__ == "__main__":
if not os.path.exists("tmp"):
os.mkdir("tmp")
net = ssd_512_mobilenet1_0_voc(pretrained=True)
tex... | 2.09375 | 2 |
tests/test_dataflow/multiwoz/conftest.py | luweishuang/task_oriented_dialogue_as_dataflow_synthesis | 257 | 12783974 | # Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
from typing import Any, Dict, List, Tuple
import pytest
from dataflow.multiwoz.trade_dst_utils import BeliefState
def convert_belief_dict_to_belief_state(belief_dict: Dict[str, str]) -> BeliefState:
belief_state: BeliefState = []
for... | 2.4375 | 2 |
scripts/renewable_to_emissions.py | EasyPeasyLemonSqueezy/Climate-Change | 0 | 12783975 | <gh_stars>0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import io
import os, sys
import json
import xlrd
from math import ceil, log10
from multiprocessing import Pool
from requests import get
from base64 import b64decode
from bs4 import BeautifulSoup
url = 'http://www.iea.org/statistics/statisticssearch/report/?c... | 2.46875 | 2 |
tests/scrape/test_loaders.py | gudeg-united/mishapp-ds | 0 | 12783976 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import pytest
@pytest.mark.parametrize("value, format_, expectation", [
("01-Jan-15 10:00:00 +07:00", "DD-MMM-YY HH:mm:ss Z", "2015-01-01T03:00:00+00:00"), # noqa
... | 2.328125 | 2 |
test/test_initial_setting_presenter.py | pei223/labelpt | 6 | 12783977 | <filename>test/test_initial_setting_presenter.py<gh_stars>1-10
import tempfile
from labelpt.app import is_directory_path_exist
import shutil
import unittest
class TestInitialSettingPresenter(unittest.TestCase):
def setUp(self) -> None:
self.test_dir = tempfile.mkdtemp()
def tearDown(self) -> None:
... | 2.78125 | 3 |
mould/gitignore.py | michaeljoseph/mould | 6 | 12783978 | <reponame>michaeljoseph/mould
def read_ignore(ignore_content):
return [
ignore_line
for ignore_line in ignore_content.split()
if not ignore_line.startswith('#')
]
def remove_ignores(file_paths, ignore_list):
"""
Remove files that match gitignore patterns
:param file_paths:
... | 3.203125 | 3 |
housecanary/apiclient.py | SpainTrain/hc-api-python | 18 | 12783979 | <reponame>SpainTrain/hc-api-python
from __future__ import print_function
import os
from builtins import object
from housecanary.output import ResponseOutputGenerator
from housecanary.requestclient import RequestClient
import housecanary.exceptions
import housecanary.constants as constants
from requests.auth import HTTP... | 2.90625 | 3 |
qs2/operations.py | steinarvk/numera-te-ipsum | 0 | 12783980 | from qs2 import model
import qs2.users
import qs2.validation
import datetime
import users
import decimal
import logging
import time
import qs2.logutil
import sqlalchemy
import random
import csv
import json
import pytz
import functools
from qs2 import ui
import qs2.csvexport
from qs2.timeutil import (hacky_force_timez... | 2.125 | 2 |
os_net_config/tests/test_cli.py | openstack/os-net-conf | 0 | 12783981 | # -*- coding: utf-8 -*-
# Copyright 2014 Red Hat, 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 l... | 1.84375 | 2 |
pdc_app/pdc_core_app/urls.py | PLsergent/pdc_itlink | 1 | 12783982 | from django.urls import path, include
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('protectedErr/', views.protected_error, name='protected_error'),
path('accounts/', include('django.contrib.auth.urls')),
path('auth/', include('social_django.urls', namespace='social')),... | 1.90625 | 2 |
chapter5_operations/prediction_monitoring_pattern/src/configurations.py | sudabon/ml-system-in-actions | 133 | 12783983 | import os
from logging import getLogger
from src.constants import CONSTANTS, PLATFORM_ENUM
logger = getLogger(__name__)
class PlatformConfigurations:
platform = os.getenv("PLATFORM", PLATFORM_ENUM.DOCKER.value)
if not PLATFORM_ENUM.has_value(platform):
raise ValueError(f"PLATFORM must be one of {[v.... | 2.46875 | 2 |
src/the_impossible/live/migrations/newsletter/migrations/0003_remove_subscriber_last_sent.py | micha31r/The-Impossible | 0 | 12783984 | # Generated by Django 2.2.7 on 2020-07-15 07:26
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('newsletter', '0002_auto_20200514_1518'),
]
operations = [
migrations.RemoveField(
model_name='subscriber',
name='last_sent',... | 1.328125 | 1 |
reo/migrations/0091_merge_20201228_2115.py | akuam1/REopt_Lite_API | 41 | 12783985 | # Generated by Django 2.2.13 on 2020-12-28 21:15
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('reo', '0090_absorptionchillermodel_chiller_cop'),
('reo', '0087_merge_20201228_2004'),
]
operations = [
]
| 1.273438 | 1 |
code/k_fold.py | federico-code/PedMS-Classification | 0 | 12783986 | import numpy as np
from sklearn.model_selection import StratifiedKFold
from sklearn.model_selection import LeaveOneOut
import pandas as pd
import os
import sys
from feature_selection import read_data
def leaveOneOut(df):
# target and data selection
y=df.iloc[:,-1]
X=df.iloc[:,:-1]
y=y.to_numpy()
loo = LeaveOne... | 2.671875 | 3 |
ribbon/handlers.py | silverfix/django-ribbon | 1 | 12783987 | <filename>ribbon/handlers.py
# -*- coding: utf-8 -
from __future__ import unicode_literals, division, absolute_import
import json
import stripe
from django.conf import settings
from . import models
stripe.api_key = settings.STRIPE_SECRET_KEY
def _json_dump_response(response):
return json.dumps(dict(response)... | 1.960938 | 2 |
tests/test_parse.py | assasinitachi123/extra-boolean | 0 | 12783988 | <reponame>assasinitachi123/extra-boolean
from extra_boolean import parse
def test_parse():
assert parse("1") == True
assert parse("truthy") == True
assert parse("Not Off") == True
assert parse("Not Inactive") == True
assert parse("cold") == False
assert parse("inactive") ... | 2.875 | 3 |
interprocedural_analyses/taint/test/integration/static_methods.py | skylerberg/pyre-check | 1 | 12783989 | # flake8: noqa
class StaticClass:
@staticmethod
def sink(oops):
__test_sink(oops)
def test(source):
return StaticClass.sink(source)
def run_test(source):
test(__test_source())
| 1.96875 | 2 |
net/tune_torch.py | marbleton/FPGA_MNIST | 7 | 12783990 | <reponame>marbleton/FPGA_MNIST
from __future__ import print_function, division
import numpy as np
import torch
import torch.quantization
import torch.nn as nn
import torch.optim
from util import read_np_torch, evaluate_network
from train_torch import evaluate, prepare_datasets, LEARNING_RATE, evaluate_labels, load_to... | 2.421875 | 2 |
src/202_simple_classification.py | l-chenyao/TensorFlow-tutorials-by-Yao | 0 | 12783991 | """
Dependencies:
tensorflow: 1.2.0
matplotlib
numpy
"""
import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np
tf.set_random_seed(1)
np.random.seed(1)
#fake data
n_data = np.ones((100,2))
x0 = np.random.normal(2*n_data, 1) #class0 x shape = (100, 2))
y0 = np.zeros(100) ... | 2.84375 | 3 |
main_job.py | vsantiago113/Cisco-FMC-Selenium-Boilerplate | 0 | 12783992 | from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions
from selenium.common.exceptions import NoSuchElementException, TimeoutException, ElementNotVisibleException, \
ElementNotInter... | 2.65625 | 3 |
harvester_odt/jobcontrol_jobs.py | opendatatrentino/opendata-harvester | 1 | 12783993 | """
Functions to be used as JobControl jobs
"""
from datetime import datetime
import logging
import os
from jobcontrol.globals import execution_context
from harvester.utils import (get_storage_direct,
jobcontrol_integration, report_progress)
logger = logging.getLogger('harvester_odt.pat... | 2.796875 | 3 |
contrib/remote/remote.py | fffkongress/info-beamer | 0 | 12783994 | import sys
try:
import pygame
from pygame.locals import *
except ImportError:
print "=========================="
print "You have to install pygame"
print "=========================="
raise
try:
from OSC import OSCClient, OSCMessage # provided by pyOSC
except ImportError:
print "========... | 2.765625 | 3 |
classes_clean.py | herttale/School-district-optimization | 1 | 12783995 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Sep 7 10:51:21 2018
@author: hertta
"""
from shapely.ops import cascaded_union
from copy import deepcopy
import random
from shapely.geometry import LineString
class SchoolDistr:
""" The class representing the school districts """
def _... | 2.90625 | 3 |
results/sherpa_studies/start_sherpa_frontend.py | yimengmin/wiki-cs-dataset | 30 | 12783996 | <reponame>yimengmin/wiki-cs-dataset
import sherpa
import sys
sherpa.core.Study.load_dashboard(sys.argv[1])
while True:
pass
| 1.101563 | 1 |
py2030/app.py | markkorput/py2030 | 0 | 12783997 | #!/usr/bin/env python
import time
from optparse import OptionParser
from .component_manager import ComponentManager
if __name__ == '__main__':
parser = OptionParser()
parser.add_option('-p', '--profile', dest='profile', default=None)
# parser.add_option('-f', '--file', dest='file', default=None)
parser... | 2.328125 | 2 |
galaxy/api/v2/views/collection.py | ironfroggy/galaxy | 0 | 12783998 | # (c) 2012-2019, Ansible by Red Hat
#
# This file is part of Ansible Galaxy
#
# Ansible Galaxy is free software: you can redistribute it and/or modify
# it under the terms of the Apache License as published by
# the Apache Software Foundation, either version 2 of the License, or
# (at your option) any later version.
#
... | 1.867188 | 2 |
gtfs_grading_app/forms.py | wesleyi23/gtfs_grading_application | 6 | 12783999 | <gh_stars>1-10
from django import forms
from gtfs_grading import settings
from gtfs_grading_app.models import review_category, review_widget, consistency_widget, results_capture_widget, \
gtfs_field, consistency_widget_visual_example, consistency_widget_link, score, data_selector, result, result_image, \
resu... | 2.109375 | 2 |
torchsupport/experimental/apps/fewshot.py | bobelly/torchsupport | 18 | 12784000 | from flexx import flx
from flexx import event
import os
from tornado.web import StaticFileHandler
class ScaleImageWidget(flx.Widget):
""" Display an image from a url.
The ``node`` of this widget is an
`<img> <https://developer.mozilla.org/docs/Web/HTML/Element/img>`_
wrapped in a `<div> <https://... | 3.046875 | 3 |
kernel/components/featurecalculation/vertfeaturecalculation/base_feature_calculation.py | rinceyuan/WeFe | 39 | 12784001 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2021 Tianmian Tech. 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/LI... | 1.429688 | 1 |
apps/resizer/migrations/0003_auto_20200807_0453.py | atseplyaev/django_image_resizer | 0 | 12784002 | # Generated by Django 3.1 on 2020-08-07 04:53
from django.db import migrations, models
def set_images_names(apps, schema_editor):
UploadImage = apps.get_model('resizer', 'UploadImage')
for image in UploadImage.objects.all():
image_name = image.original_image.name.split('/')[-1]
image.image_na... | 2.015625 | 2 |
migrations/versions/fa4f694e986a_created_comments.py | Amukozoberit/Pitches | 1 | 12784003 | """Created comments
Revision ID: fa4f694e986a
Revises: <KEY>
Create Date: 2021-08-16 21:48:43.079233
"""
# revision identifiers, used by Alembic.
revision = 'fa4f694e986a'
down_revision = '<KEY>'
from alembic import op
import sqlalchemy as sa
def upgrade():
# ### commands auto generated by Alembic - please ad... | 1.257813 | 1 |
statsmodels/multivariate/api.py | nikhase/statsmodels | 34 | 12784004 | <reponame>nikhase/statsmodels
from .pca import PCA
from .manova import MANOVA
from .factor import Factor, FactorResults
from .cancorr import CanCorr
from . import factor_rotation
| 0.910156 | 1 |
users/views.py | mr-star-k/Feedly | 1 | 12784005 | <reponame>mr-star-k/Feedly<filename>users/views.py
from django.http import HttpResponse,JsonResponse
from django.shortcuts import render, redirect,reverse
from django.contrib.auth import login, authenticate,logout
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_d... | 2.328125 | 2 |
tests/test_account_key.py | nichandy/flow-py-sdk | 21 | 12784006 | from unittest import TestCase
from flow_py_sdk import AccountKey, SignAlgo, HashAlgo
from flow_py_sdk.proto.flow.entities import AccountKey as ProtoAccountKey
class TestAccountKey(TestCase):
def test_rlp(self):
expected_rlp_hex = "f847b840c51c02aa382d8d382a121178de8ac97eb6a562a1008660669ab6a220c96fce76e1... | 2.6875 | 3 |
archieve/2021/day07b.py | jabra98/aoc | 0 | 12784007 | import sys; datafilepath = sys.argv[1]
pos = [ int(x) for x in open(datafilepath).read().split(',') ]
avg = sum(pos)/len(pos)
# should ideally check floor(mean)-1 and floor(mean)+1
s_low=0
s_high=0
print(avg)
for i in pos:
dif = abs(int(avg)-i)
s_low += dif*(dif+1)/2
for i in pos:
dif = abs(int(avg+1)-... | 3.234375 | 3 |
PyRamen/PyRamen.py | nomadic-me/python-homework | 0 | 12784008 | # -*- coding: UTF-8 -*-
"""PyRamen Homework Starter."""
# @TODO: Import libraries
import csv
from pathlib import Path
# @TODO: Set file paths for menu_data.csv and sales_data.csv
menu_filepath = Path('')
sales_filepath = Path('')
# @TODO: Initialize list objects to hold our menu and sales data
menu = []
sales = []
... | 3.015625 | 3 |
macro/render/page/search.py | cloudmattcloud/Macro-Explain-o-Matic | 2 | 12784009 | '''
Collection of shared tools for appengine page rendering.
'''
# My modules
from macro.render.defs import *
from macro.render.util import render_template
from macro.data.appengine.savedmacro import SavedMacroOps
# Generate a search results page.
def generate_search_page(path, terms, p... | 2.109375 | 2 |
beams/ApogeeCam.py | Yaccoub/Beams | 11 | 12784010 | import numpy as N
import win32com.client
# generate and import apogee ActiveX module
apogee_module = win32com.client.gencache.EnsureModule(
'{A2882C73-7CFB-11D4-9155-0060676644C1}', 0, 1, 0)
if apogee_module is None:
raise ImportError # prevent plugin from being imported
from win32com.client import constants ... | 2.15625 | 2 |
config.py | alexbredo/site-packages | 0 | 12784011 | <reponame>alexbredo/site-packages
# Copyright (c) 2014 <NAME>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or
# without modification, are permitted provided that the
# following conditions are met:
#
# 1. Redistributions of source code must retain the above
# copyright notice,... | 1.390625 | 1 |
classifier/upload_and_download_files.py | Creearc/Codenrock-New-Year-ML-Battle | 1 | 12784012 | <reponame>Creearc/Codenrock-New-Year-ML-Battle
import os
from flask import Flask, request, redirect, url_for
from werkzeug.utils import secure_filename
os.environ['CUDA_VISIBLE_DEVICES'] = '-1'
import tensorflow as tf
assert float(tf.__version__[:3]) >= 2.3
import tensorflow.lite as tflite
import os
import numpy as np... | 2.28125 | 2 |
python_basics/Module & packages/basic/mymodule.py | alok8765/basic_python_practicse | 0 | 12784013 | def my_func():
print("Hey i am in mymodule.py") | 1.53125 | 2 |
code/solutions/solution_05.py | DahlitzFlorian/python-basic-training | 3 | 12784014 | # This is a possible solution for exercise_05.py
def fibonacci(number):
i = 1
if number == 0:
fib = []
elif number == 1:
fib = [1]
elif number == 2:
fib = [1, 1]
elif number > 2:
fib = [1, 1]
while i < (number - 1):
fib.append(fib[i] + fib[i - 1])... | 4.1875 | 4 |
app/test/airport/test_airport_parser.py | egenerat/gae-django | 3 | 12784015 | # -*- coding: utf-8 -*-
from app.airport.airports_parsers import get_country, get_money, get_kerosene_supply, get_kerosene_capacity, \
get_engines_supply, get_planes_capacity, get_airport_name
from app.common.http_methods_unittests import get_request
from app.common.target_urls import MY_AIRPORT
import unittest
... | 2.734375 | 3 |
setup.py | yuankaihuo/MedLabel | 10 | 12784016 | <gh_stars>1-10
from __future__ import print_function
import distutils.spawn
import os.path
from setuptools import find_packages
from setuptools import setup
import shlex
import subprocess
import sys
PY3 = sys.version_info[0] == 3
PY2 = sys.version_info[0] == 2
assert PY3 or PY2
here = os.path.abspath(os.path.dirna... | 1.882813 | 2 |
deps_report/models/runtime_informations.py | MeilleursAgents/deps-report | 0 | 12784017 | <filename>deps_report/models/runtime_informations.py
from dataclasses import dataclass
from datetime import date
@dataclass
class RuntimeInformations:
name: str
current_version: str
latest_version: str
current_version_is_outdated: bool
current_version_eol_date: date
current_version_is_eol_soon... | 1.703125 | 2 |
contrib/experimental/great_expectations_experimental/expectations/expect_column_values_to_be_valid_iana_timezone.py | arunnthevapalan/great_expectations | 1 | 12784018 | <filename>contrib/experimental/great_expectations_experimental/expectations/expect_column_values_to_be_valid_iana_timezone.py<gh_stars>1-10
import json
from typing import Optional
import pytz
from great_expectations.core.expectation_configuration import ExpectationConfiguration
from great_expectations.exceptions impo... | 2.296875 | 2 |
drf_ujson/parsers.py | pasevin/drf_ujson2 | 0 | 12784019 | <filename>drf_ujson/parsers.py
from typing import Any, Mapping, Optional, Type
from django.conf import settings
from rest_framework.exceptions import ParseError
from rest_framework.parsers import BaseParser
from rest_framework.renderers import JSONRenderer, BaseRenderer
import ujson
__all__ = ["UJSONParser"]
class ... | 2.390625 | 2 |
src/pyota/core.py | msicilia/pyota | 0 | 12784020 | <filename>src/pyota/core.py<gh_stars>0
"""
Utilities dealing with decoding IOTA messages.
Reference specs:
https://github.com/iotaledger/protocol-rfcs/blob/master/text/0017-tangle-message/0017-tangle-message.md
https://github.com/luca-moser/protocol-rfcs/blob/signed-tx-payload/text/0000-transaction-payload/0000-trans... | 2.421875 | 2 |
Program skrevet i forelesninger/Video 26 studenteksempel if settning oppgave.py | MegaMilkshakes/DAT_120_all_kode | 0 | 12784021 | <filename>Program skrevet i forelesninger/Video 26 studenteksempel if settning oppgave.py<gh_stars>0
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 1 21:54:51 2021
@author: Gerry
"""
# ax^2 + bx + c = 0
# hvordan skrive opphøyd?
import math
a = int(input("Skriv inn et tall for a:"))
b = int(input("Skriv inn et ta... | 3.5 | 4 |
twitterapiv2/model/recent/public_metrics.py | Preocts/twwordmap | 1 | 12784022 | <gh_stars>1-10
from typing import Any
from typing import Dict
class PublicMetrics:
retweet_count: int
reply_count: int
like_count: int
quote_count: int
@classmethod
def build_obj(cls, obj: Dict[str, Any]) -> "PublicMetrics":
"""Build object"""
new = cls()
new.retweet_c... | 2.75 | 3 |
utils/forms.py | DevotedExuDevelopersTeam/ClanManager | 1 | 12784023 | <reponame>DevotedExuDevelopersTeam/ClanManager
from asyncio import TimeoutError, sleep
from os import remove
import disnake
from disnake import (
ButtonStyle,
Embed,
File,
Message,
MessageInteraction,
ModalInteraction,
PermissionOverwrite,
TextInputStyle,
)
from disnake.ui import Button... | 1.875 | 2 |
user.py | Gordon003/COMP3900 | 0 | 12784024 | from flask import Flask, render_template, request, session, redirect, url_for, Blueprint
from function import data_function, user_function, sort, accom_function, object_function, checker, complaint
from werkzeug.utils import secure_filename
import os
from os.path import join
user = Blueprint('user', __name__)
# LOGOU... | 2.8125 | 3 |
pqr_to_delphi.py | jbardhan/molman | 0 | 12784025 | <filename>pqr_to_delphi.py<gh_stars>0
#!/usr/bin/env python
import os, sys, subprocess, argparse, re, logging, errno
import mymm
parser = argparse.ArgumentParser(description = "This program takes a .pqr file (MEAD format only for now, meaning no chain field!) and writes a CRG and PDB file from it.", prog = sys.argv[0... | 2.40625 | 2 |
gabi.py | csanadH/poker-player-ezmoni | 0 | 12784026 | import json
class Gabi:
def myFunc(self, game, hand, cards):
print("GABI")
try:
if (hand[0]["rank"] == hand[1]["rank"]):
print("pair, returning 800")
return 800
elif (hand[0]["rank"] in "89TJQKA" and hand[1]["rank"] in "89TJQKA"):
... | 3.421875 | 3 |
apps/photos/urls.py | commtrack/commtrack-old-to-del | 1 | 12784027 | <gh_stars>1-10
from django.conf.urls.defaults import *
import settings
image_path = settings.RAPIDSMS_APPS['photos']['image_path']
urlpatterns = patterns('',
(r'^photos/?$', 'photos.views.recent'),
(r'^photo/(?P<photo_id>\d+)/?$', 'photos.views.show'),
(r'^%s/(?P<path>.*)$' % image_... | 1.710938 | 2 |
train.py | vanAmsterdam/CauseEffectPairs | 0 | 12784028 | from torch.tensor import Tensor
from tqdm import tqdm
# from torch.nn import NeuralNet
# from torch.nn.loss import Loss, MSE
# from torch.optim import Optimizer, SGD
# from data import DataIterator, BatchIterator
def train(model, num_epochs, x, target, loss_fn, optimizer, gradient_clip = None):
for i in tqdm(ran... | 2.59375 | 3 |
tests/messages_data/mime_emails/raw_email7.py | unqx/imap_tools | 344 | 12784029 | <gh_stars>100-1000
import datetime
from imap_tools import EmailAddress
DATA = dict(
subject='testing',
from_='<EMAIL>',
to=('<EMAIL>',),
cc=(),
bcc=(),
reply_to=(),
date=datetime.datetime(2005, 6, 6, 22, 21, 22, tzinfo=datetime.timezone(datetime.timedelta(0, 7200))),
date_str='Mon, 6 Ju... | 2.03125 | 2 |
angular_scaffold/management/commands/helpers/_generate_debugger.py | juanfe/django-angular-scaffold | 4 | 12784030 | <reponame>juanfe/django-angular-scaffold<filename>angular_scaffold/management/commands/helpers/_generate_debugger.py
import os
import hashlib
def generate_debugger(directory, password):
m = hashlib.md5()
m.update(password)
password_hash = m.hexdigest()
logger_file = os.path.join(directory, 'assets', 'a... | 2.25 | 2 |
src/konfetti/exceptions.py | samarcan/konfetti | 23 | 12784031 | class KonfettiError(Exception):
"""Common error for all errors in `konfetti`."""
class MissingError(AttributeError, KonfettiError):
"""Config option is missing in the given settings module."""
# Should be inherited from AttributeError because tools like Celery rely
# on this behavior
class Settings... | 2.515625 | 3 |
setup.py | abrammer/windspharm | 56 | 12784032 | """Build and install the windspharm package."""
# Copyright (c) 2012-2018 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights... | 1.796875 | 2 |
tests/test_cli/test_predict.py | jspaaks/vak | 1 | 12784033 | """tests for vak.cli.predict module"""
import pytest
import vak.cli.predict
import vak.config
import vak.constants
import vak.paths
from . import cli_asserts
from ..test_core.test_predict import predict_output_matches_expected
@pytest.mark.parametrize(
"audio_format, spect_format, annot_format",
[
(... | 2.125 | 2 |
ch02/question_3.py | dhrey112/IntroToPython_Deitel | 0 | 12784034 | <filename>ch02/question_3.py<gh_stars>0
"""3. 2.3 (Fill in the missing code) Replace *** in the following code with a
statement that will print a message like 'Congratulations! Your
grade of 91 earns you an A in this course'. Your
statement should print the value stored in the variable grade:"""
grade = int(input('Ent... | 3.96875 | 4 |
47 - Distinct primes factors/distinct.py | jamtot/PyProjectEuler | 0 | 12784035 | <filename>47 - Distinct primes factors/distinct.py
def primegen():
primes = [2,3]
yield 2
yield 3
num = 3
while True:
prime = True
num+=2
for p in primes:
if num%p==0:
prime = False
break
if prime:
primes.append(... | 3.578125 | 4 |
player/management/commands/gendata.py | jacebrowning/virtualboombox | 4 | 12784036 | <filename>player/management/commands/gendata.py
from datetime import timedelta
from contextlib import suppress
from django.core.management.base import BaseCommand
from django.contrib.auth.models import User
from django.db.utils import IntegrityError
from django.utils import timezone
from player.models import Account,... | 2.4375 | 2 |
proplot/rctools.py | stefraynaud/proplot | 0 | 12784037 | <filename>proplot/rctools.py
#!/usr/bin/env python3
"""
A special object named `~proplot.rctools.rc`, belonging to the
`~proplot.rctools.rc_configurator` class, is created on import.
This is your one-stop shop for changing global settings belonging to any of
the following three categories.
1. Builtin matplotlib `rcPar... | 2.0625 | 2 |
ImageAlgoKD/ImageAlgoKD_kernel_cuda.py | ZihengChen/ImageAlgorithm | 6 | 12784038 | <filename>ImageAlgoKD/ImageAlgoKD_kernel_cuda.py
## cuda
import pycuda.driver as cuda
import pycuda.autoinit
from pycuda.compiler import SourceModule
mod = SourceModule("""
// 1.1 get rho
__global__ void rho_cuda( float *d_rho,
float *d_Points, float *d_wPoints,
... | 2.453125 | 2 |
scrapelin/__init__.py | MichaelYusko/scrapelin | 0 | 12784039 | <reponame>MichaelYusko/scrapelin<filename>scrapelin/__init__.py
"""
:copyright: <NAME> a.k.a <NAME>
:license: MIT, see LICENSE for more details.
"""
| 1.109375 | 1 |
modules/zabbix_send.py | yakumo-saki/megacli_to_zabbix | 1 | 12784040 | import json
import logging
import config as cfg
from modules.zabbix_sender import send_to_zabbix
logger = logging.getLogger(__name__)
"""zabbixにDevice LLDデータを送信します。
result = {"/dev/sda": {"model": EXAMPLE SSD 250, "POWER_CYCLE": 123 ...}}
@param result 送信するデータ
@param discoveryKey zabbix discovery key. ex) megacli.... | 2.359375 | 2 |
fnx/prep.py | hoefkensj/portal | 0 | 12784041 | <gh_stars>0
#!/usr/bin/env python
import os
import os
import shutil
import lib
import lib.lib
src='$HOME/.bashrc'
def prep_src(src,**k):
"""
:param src:
:param k:
:return:
"""
#this needs to be don before actually creating the propsdict as they arent done automaticly
if "~" in src or '$' in src:
src=os.pa... | 2.28125 | 2 |
doctor/command.py | jhauberg/gitdoctor | 1 | 12784042 | # coding=utf-8
"""
Provides a common interface for executing commands.
"""
import sys
import subprocess
import doctor.report as report
from doctor.report import supports_color
def get_argv(cmd: str) -> list:
""" Return a list of arguments from a fully-formed command line. """
return cmd.strip().split(' '... | 3.140625 | 3 |
code/examples/02-gpio/stepper_ULN2003.py | yuanyanhui/intro-upy-esp32 | 0 | 12784043 | """
Drive stepper motor 28BYJ-48 using ULN2003
"""
from machine import Pin
from time import sleep_ms
# define pins for ULN2003
IN1 = Pin(16, Pin.OUT)
IN2 = Pin(17, Pin.OUT)
IN3 = Pin(5, Pin.OUT)
IN4 = Pin(18, Pin.OUT)
# half-step mode
# counter clockwise step sequence
seq_ccw = [[1, 0, 0, 0],
[1, 1, 0, 0... | 3.21875 | 3 |
POPGEN/make_correct_snp_file_from_snp_file.py | Hammarn/Scripts | 0 | 12784044 | <filename>POPGEN/make_correct_snp_file_from_snp_file.py
#!/usr/bin/env python
import pandas as pd
import argparse
import sys
import pdb
def read_input(input_file, header):
if not header:
DF = pd.read_csv(input_file[0], sep = "\s+" , header = None)
if header:
DF = pd.read_csv(input_file[0], sep... | 2.96875 | 3 |
python/examples/test_simple_race.py | ziyuli/XWorld | 83 | 12784045 | <filename>python/examples/test_simple_race.py
#!/usr/bin/python
from py_simulator import Simulator
from random import randint
if __name__ == "__main__":
options = {
"pause_screen": False,
"window_width": 480,
"window_height": 480,
"track_type": "straight",
"track_width": 20... | 3.40625 | 3 |
sparse_causal_model_learner_rl/test_learner.py | sergeivolodin/causality-disentanglement-rl | 2 | 12784046 | import vectorincrement
import os
import gin
import sparse_causal_model_learner_rl.learners.rl_learner as learner
import sparse_causal_model_learner_rl.learners.abstract_learner as abstract_learner
import sparse_causal_model_learner_rl.config as config
import pytest
from sparse_causal_model_learner_rl.sacred_gin_... | 1.875 | 2 |
python_developer_tools/python/obj_utils.py | carlsummer/python_developer_tools | 32 | 12784047 | # !/usr/bin/env python
# -- coding: utf-8 --
# @Author zengxiaohui
# Datatime:4/29/2021 8:38 PM
# @File:obj_utils
from python_developer_tools.python.string_utils import str_is_null
def obj_is_null(obj):
"""判断对象是否为空"""
if obj is None:
return True
if isinstance(obj, list) and len(obj) == 0:
... | 2.375 | 2 |
teach/migrations/0003_auto_20191027_1008.py | rajk-apps/teach | 0 | 12784048 | <filename>teach/migrations/0003_auto_20191027_1008.py
# Generated by Django 2.2.6 on 2019-10-27 10:08
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('teach', '0002_remove_course_additional_lecture_content'),
]
operations = [
migrations.... | 1.65625 | 2 |
Autoclock.py | Ryushane/ryuscript | 0 | 12784049 | from selenium import webdriver
from selenium.webdriver import ActionChains
import time
# 自动小程序打卡脚本
if __name__ == '__main__':
#这里改成你的统一认证用户名和密码
user_name = 'xxx'
pwd = '<PASSWORD>'
# 加上这两句话不打开浏览器
option = webdriver.ChromeOptions()
#option.add_argument('headless') # 设置option
... | 3 | 3 |
tests/test_day7.py | ghallberg/advent2020 | 0 | 12784050 | <filename>tests/test_day7.py
from advent2020 import day7 as d
test_input_1 = [
"light red bags contain 1 bright white bag, 2 muted yellow bags.",
"dark orange bags contain 3 bright white bags, 4 muted yellow bags.",
"bright white bags contain 1 shiny gold bag.",
"muted yellow bags contain 2 shiny gold ... | 2.828125 | 3 |