max_stars_repo_path stringlengths 4 286 | max_stars_repo_name stringlengths 5 119 | max_stars_count int64 0 191k | id stringlengths 1 7 | content stringlengths 6 1.03M | content_cleaned stringlengths 6 1.03M | language stringclasses 111
values | language_score float64 0.03 1 | comments stringlengths 0 556k | edu_score float64 0.32 5.03 | edu_int_score int64 0 5 |
|---|---|---|---|---|---|---|---|---|---|---|
advent/days/day16/day.py | RuedigerLudwig/advent2021 | 0 | 6623951 | from __future__ import annotations
import abc
from math import prod
from typing import Generator, Iterator
from advent.common import utils
day_num = 16
def part1(lines: Iterator[str]) -> int:
bit = Packet.from_str(next(lines))
return bit.get_version_sum()
def part2(lines: Iterator[str]) -> int:
bit =... | from __future__ import annotations
import abc
from math import prod
from typing import Generator, Iterator
from advent.common import utils
day_num = 16
def part1(lines: Iterator[str]) -> int:
bit = Packet.from_str(next(lines))
return bit.get_version_sum()
def part2(lines: Iterator[str]) -> int:
bit =... | none | 1 | 2.621989 | 3 | |
ocradmin/ocrtasks/testutils.py | mikesname/ocropodium | 1 | 6623952 | """
Utils for testing the Ocr Task wrapper.
"""
from celery.contrib.abortable import AbortableTask
from decorators import register_handlers
@register_handlers
class TestTask(AbortableTask):
"""
Dummy task for running tests on.
"""
name = "testing.test"
max_retries = None
def run(self, a, b,... | """
Utils for testing the Ocr Task wrapper.
"""
from celery.contrib.abortable import AbortableTask
from decorators import register_handlers
@register_handlers
class TestTask(AbortableTask):
"""
Dummy task for running tests on.
"""
name = "testing.test"
max_retries = None
def run(self, a, b,... | en | 0.702823 | Utils for testing the Ocr Task wrapper. Dummy task for running tests on. | 2.217952 | 2 |
regex_builder/constants.py | Zomatree/regex-builder | 3 | 6623953 | ANY_CHAR = "."
WHITESPACE = "\\s"
NON_WHITESPACE = "\\S"
DIGIT = "\\d"
NON_DIGIT = "\\D"
WORD_CHAR = "\\w"
NON_WORD_CHAR = "\\W"
NEWLINE = "\\n"
TAB = "\\t"
NULL_CHAR = "\\0"
| ANY_CHAR = "."
WHITESPACE = "\\s"
NON_WHITESPACE = "\\S"
DIGIT = "\\d"
NON_DIGIT = "\\D"
WORD_CHAR = "\\w"
NON_WORD_CHAR = "\\W"
NEWLINE = "\\n"
TAB = "\\t"
NULL_CHAR = "\\0"
| none | 1 | 1.4834 | 1 | |
SCC/local_automation/subscribe_constant.py | Coder-Pham/SCC_application | 0 | 6623954 | <filename>SCC/local_automation/subscribe_constant.py<gh_stars>0
import paho.mqtt.subscribe as mqtts
import paho.mqtt.client as mqtt
import config
import psycopg2
import psycopg2.extras
import random, threading, json
import calendar
import time
# ====================================================
# MQTT Settings
mqtt... | <filename>SCC/local_automation/subscribe_constant.py<gh_stars>0
import paho.mqtt.subscribe as mqtts
import paho.mqtt.client as mqtt
import config
import psycopg2
import psycopg2.extras
import random, threading, json
import calendar
import time
# ====================================================
# MQTT Settings
mqtt... | en | 0.6139 | # ==================================================== # MQTT Settings # ==================================================== # MQTT In action # ==================================================== # PostgreSQL Settings # Print PostgreSQL Connection properties # Print PostgreSQL version # Change temperature and humidit... | 2.587594 | 3 |
pomidor/pomidor_exceptions.py | symon-storozhenko/pomidor | 1 | 6623955 | from selenium.webdriver.support.color import Colors
pomidor = 'Pomidor'
class PomidorKeyDoesNotExist(Exception):
"""PomidorCantRunOneBrowserInstanceInParallel Exception"""
def __init__(self, key):
self.key = key
def __repr__(self):
return f'{Colors.FAIL}\n{pomidor}ERROR\nKeyboard key {s... | from selenium.webdriver.support.color import Colors
pomidor = 'Pomidor'
class PomidorKeyDoesNotExist(Exception):
"""PomidorCantRunOneBrowserInstanceInParallel Exception"""
def __init__(self, key):
self.key = key
def __repr__(self):
return f'{Colors.FAIL}\n{pomidor}ERROR\nKeyboard key {s... | en | 0.442567 | PomidorCantRunOneBrowserInstanceInParallel Exception PomidorCantRunOneBrowserInstanceInParallel Exception Pomidor syntax error class: more actions than objects PomidorDataFeedNoAngleKeysProvidedException #name_field\n{Colors.ENDC}' PPomidorDataFeedNoCSVFileProvidedException Pomidor syntax error class: more actions than... | 2.89895 | 3 |
flightaware2columbus/geo_distance.py | KenMercusLai/FlightAware2columbus | 0 | 6623956 | #!/usr/bin/python3
from math import sin, asin, cos, radians, fabs, sqrt
EARTH_RADIUS = 6371 # 地球平均半径,6371km
def hav(theta):
s = sin(theta / 2)
return s * s
def get_distance_hav(lat0, lng0, lat1, lng1):
"""用haversine公式计算球面两点间的距离."""
# 经纬度转换成弧度
lat0 = radians(lat0)
lat1 = radians(l... | #!/usr/bin/python3
from math import sin, asin, cos, radians, fabs, sqrt
EARTH_RADIUS = 6371 # 地球平均半径,6371km
def hav(theta):
s = sin(theta / 2)
return s * s
def get_distance_hav(lat0, lng0, lat1, lng1):
"""用haversine公式计算球面两点间的距离."""
# 经纬度转换成弧度
lat0 = radians(lat0)
lat1 = radians(l... | zh | 0.790623 | #!/usr/bin/python3 # 地球平均半径,6371km 用haversine公式计算球面两点间的距离. # 经纬度转换成弧度 | 3.442067 | 3 |
model_codes/liver.py | Sarth6961/Health-app--based-on-Un-17-Guidelines | 0 | 6623957 | <reponame>Sarth6961/Health-app--based-on-Un-17-Guidelines
import numpy as np
import pandas as pd
from sklearn import ensemble
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score, classification_report, confusion_matrix
import joblib
patients=pd.read_csv('../data/indian_liver... | import numpy as np
import pandas as pd
from sklearn import ensemble
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score, classification_report, confusion_matrix
import joblib
patients=pd.read_csv('../data/indian_liver_patient.csv')
patients['Gender']=patients['Gender'].apply... | none | 1 | 2.824535 | 3 | |
analysis/scripts/project_functions.py | data301-2021-summer2/project-group6-project | 0 | 6623958 | <filename>analysis/scripts/project_functions.py
import pandas as pd
import numpy as np
import seaborn as sns
import pandas_profiling as pf
import matplotlib.pyplot as plt
path='../data/raw/adult.data'
def load_and_process(path):
# Method Chain 1 (Load data and deal with missing data)
df1 = (
pd.read_... | <filename>analysis/scripts/project_functions.py
import pandas as pd
import numpy as np
import seaborn as sns
import pandas_profiling as pf
import matplotlib.pyplot as plt
path='../data/raw/adult.data'
def load_and_process(path):
# Method Chain 1 (Load data and deal with missing data)
df1 = (
pd.read_... | en | 0.70319 | # Method Chain 1 (Load data and deal with missing data) # Method Chain 2 (Create new columns, drop others, and do processing) # Make sure to return the latest dataframe | 3.007687 | 3 |
dataset.py | navigator8972/vae_dyn | 4 | 6623959 | <reponame>navigator8972/vae_dyn
import numpy as np
class DataSets(object):
pass
class DataSet(object):
def __init__(self, data, labels=None):
if labels is not None:
#check consistency
assert data.shape[0]==labels.shape[0], (
'data.shape: %s labels.shape: %s' % (data.shape... | import numpy as np
class DataSets(object):
pass
class DataSet(object):
def __init__(self, data, labels=None):
if labels is not None:
#check consistency
assert data.shape[0]==labels.shape[0], (
'data.shape: %s labels.shape: %s' % (data.shape,
... | en | 0.687118 | #check consistency #goahead Return the next `batch_size` examples from this data set. # Finished epoch # Shuffle the data # Start next epoch | 3.056996 | 3 |
standardised_logging/__init__.py | srbry/standardised-logging | 0 | 6623960 | <reponame>srbry/standardised-logging
from .handler import ImmutableContextError, StandardisedLogHandler
from .logger import LogLevelException, StandardisedLogger
__all__ = [
"StandardisedLogger",
"StandardisedLogHandler",
"ImmutableContextError",
"LogLevelException",
]
| from .handler import ImmutableContextError, StandardisedLogHandler
from .logger import LogLevelException, StandardisedLogger
__all__ = [
"StandardisedLogger",
"StandardisedLogHandler",
"ImmutableContextError",
"LogLevelException",
] | none | 1 | 1.527238 | 2 | |
Command.py | NaraMish/Python- | 0 | 6623961 | <reponame>NaraMish/Python-
#!/usr/bin/python3
#wifi hotspot enabler
import os
os.system('cls')
print('\n\n\n\n\n')
print('Nexus Wifi Hotspot Enabler')
print('(c)2021 Nexus Group.All right reserved.')
print()
cmd='0'
while cmd != '3' :
print('1-Start Hotspot')
print('2-Stop Hotspot')
print('3... | #!/usr/bin/python3
#wifi hotspot enabler
import os
os.system('cls')
print('\n\n\n\n\n')
print('Nexus Wifi Hotspot Enabler')
print('(c)2021 Nexus Group.All right reserved.')
print()
cmd='0'
while cmd != '3' :
print('1-Start Hotspot')
print('2-Stop Hotspot')
print('3-exit')
cmd=input('Ple... | zh | 0.155782 | #!/usr/bin/python3 #wifi hotspot enabler | 3.179178 | 3 |
src/nlp/text_parsing.py | Hazoom/covid19 | 1 | 6623962 | from typing import List
import spacy
from nlp import blingfire_sentence_splitter
__CACHE = {}
def parse_texts(texts: List[str]):
return get_nlp_parser().pipe(texts)
def parse_text(text: str):
return get_nlp_parser()(text)
def get_nlp_parser():
if 'nlp' not in __CACHE:
print("Loading NLP mode... | from typing import List
import spacy
from nlp import blingfire_sentence_splitter
__CACHE = {}
def parse_texts(texts: List[str]):
return get_nlp_parser().pipe(texts)
def parse_text(text: str):
return get_nlp_parser()(text)
def get_nlp_parser():
if 'nlp' not in __CACHE:
print("Loading NLP mode... | none | 1 | 2.790142 | 3 | |
helix/matching/matcher.py | ckrivacic/helix_matcher | 2 | 6623963 | <filename>helix/matching/matcher.py
'''
Create bins or match a query protein.
Usage:
matcher.py bin <helix_dataframe> [options]
matcher.py match <match_workspace> [options]
options:
--local, -l Run locally
--tasks=NUM, -j Run on the cluster using SGE. Argument should be # of
tasks per dataframe... | <filename>helix/matching/matcher.py
'''
Create bins or match a query protein.
Usage:
matcher.py bin <helix_dataframe> [options]
matcher.py match <match_workspace> [options]
options:
--local, -l Run locally
--tasks=NUM, -j Run on the cluster using SGE. Argument should be # of
tasks per dataframe... | en | 0.586934 | Create bins or match a query protein. Usage: matcher.py bin <helix_dataframe> [options] matcher.py match <match_workspace> [options] options: --local, -l Run locally --tasks=NUM, -j Run on the cluster using SGE. Argument should be # of tasks per dataframe. --length, -e Bin by length ... | 2.593081 | 3 |
auto_trainer/callbacks/test_wandb.py | WPI-MMR/learning_experiments | 0 | 6623964 | <gh_stars>0
import unittest
from unittest import mock
import importlib
import sys
class TestWandbEvalAndRecord(unittest.TestCase):
def setUp(self):
# TODO: Create a parent test case that encompasses this W&B mocking logic
if 'wandb' in sys.modules:
import wandb
del wandb
self.mock_env = m... | import unittest
from unittest import mock
import importlib
import sys
class TestWandbEvalAndRecord(unittest.TestCase):
def setUp(self):
# TODO: Create a parent test case that encompasses this W&B mocking logic
if 'wandb' in sys.modules:
import wandb
del wandb
self.mock_env = mock.MagicMoc... | en | 0.823675 | # TODO: Create a parent test case that encompasses this W&B mocking logic # Create an episode with length 10 | 2.482316 | 2 |
packages/w3af/w3af/core/data/parsers/doc/swf.py | ZooAtmosphereGroup/HelloPackages | 3 | 6623965 | <reponame>ZooAtmosphereGroup/HelloPackages
"""
swf.py
Copyright 2006 <NAME>
This file is part of w3af, http://w3af.org/ .
w3af is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation version 2 of the License.
w3af is d... | """
swf.py
Copyright 2006 <NAME>
This file is part of w3af, http://w3af.org/ .
w3af is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation version 2 of the License.
w3af is distributed in the hope that it will be usef... | en | 0.847311 | swf.py Copyright 2006 <NAME> This file is part of w3af, http://w3af.org/ . w3af is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation version 2 of the License. w3af is distributed in the hope that it will be useful, ... | 2.020983 | 2 |
mooc_scraper/pipelines.py | ralphqq/MOOCScraper | 0 | 6623966 | # -*- coding: utf-8 -*-
from sqlalchemy.dialects.postgresql import insert
from sqlalchemy.orm import sessionmaker
from class_central.models import db_connect, create_opencourse_table, OpenCourse
class MoocScraperPipeline(object):
def process_item(self, item, spider):
item.setdefault('course', None)
... | # -*- coding: utf-8 -*-
from sqlalchemy.dialects.postgresql import insert
from sqlalchemy.orm import sessionmaker
from class_central.models import db_connect, create_opencourse_table, OpenCourse
class MoocScraperPipeline(object):
def process_item(self, item, spider):
item.setdefault('course', None)
... | en | 0.769321 | # -*- coding: utf-8 -*- | 2.473372 | 2 |
bale/__main__.py | kianahmadian/bale-bot | 2 | 6623967 | import sys
def main():
print("Pyhton-Bale-Bot By <NAME>")
print("Python Version: ", sys.version)
if __name__ == '__main__':
main()
| import sys
def main():
print("Pyhton-Bale-Bot By <NAME>")
print("Python Version: ", sys.version)
if __name__ == '__main__':
main()
| none | 1 | 1.736442 | 2 | |
geometry_tools/__init__.py | gitter-badger/neuromorpho | 9 | 6623968 | """ Geometry tools """
__version__ = '0.0.1a0'
| """ Geometry tools """
__version__ = '0.0.1a0'
| en | 0.619272 | Geometry tools | 0.97231 | 1 |
leetcode/Leetcode 54. Spiral Matrix.py | agarun/algorithms | 0 | 6623969 | <filename>leetcode/Leetcode 54. Spiral Matrix.py
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
m = len(matrix[0])
n = len(matrix)
# boundaries
top = 0
bottom = n - 1
left = 0
right = m - 1
out = []
curr_dir = "r... | <filename>leetcode/Leetcode 54. Spiral Matrix.py
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
m = len(matrix[0])
n = len(matrix)
# boundaries
top = 0
bottom = n - 1
left = 0
right = m - 1
out = []
curr_dir = "r... | en | 0.867373 | # boundaries | 3.773998 | 4 |
src/MatrixVisualisation.py | Handterpret/Infrared_Analysis | 0 | 6623970 | <filename>src/MatrixVisualisation.py
import numpy as np
import argparse
import os
import matplotlib.pyplot as plt
parser = argparse.ArgumentParser()
parser.add_argument("--input", default=".", help="Input folder with data to plot")
parser.add_argument("--output", default="./viz", help="Output folder for images")
arg... | <filename>src/MatrixVisualisation.py
import numpy as np
import argparse
import os
import matplotlib.pyplot as plt
parser = argparse.ArgumentParser()
parser.add_argument("--input", default=".", help="Input folder with data to plot")
parser.add_argument("--output", default="./viz", help="Output folder for images")
arg... | none | 1 | 2.910083 | 3 | |
catalog/bindings/gmd/md_medium_type.py | NIVANorge/s-enda-playground | 0 | 6623971 | <filename>catalog/bindings/gmd/md_medium_type.py
from dataclasses import dataclass, field
from typing import List, Optional
from bindings.gmd.abstract_object_type import AbstractObjectType
from bindings.gmd.character_string_property_type import CharacterStringPropertyType
from bindings.gmd.integer_property_type import ... | <filename>catalog/bindings/gmd/md_medium_type.py
from dataclasses import dataclass, field
from typing import List, Optional
from bindings.gmd.abstract_object_type import AbstractObjectType
from bindings.gmd.character_string_property_type import CharacterStringPropertyType
from bindings.gmd.integer_property_type import ... | en | 0.891154 | Information about the media on which the data can be distributed. | 2.048244 | 2 |
titan/react_state_pkg/stateprovider/props.py | mnieber/moonleap | 0 | 6623972 | <gh_stars>0
import os
from moonleap.typespec.get_member_field_spec import get_member_field_spec
from moonleap.utils.case import l0
from moonleap.utils.inflect import plural
from titan.react_pkg.component.resources import get_component_base_url
from titan.react_pkg.pkg.get_chain import (
ExtractItemFromItem,
Ex... | import os
from moonleap.typespec.get_member_field_spec import get_member_field_spec
from moonleap.utils.case import l0
from moonleap.utils.inflect import plural
from titan.react_pkg.component.resources import get_component_base_url
from titan.react_pkg.pkg.get_chain import (
ExtractItemFromItem,
ExtractItemLis... | it | 0.356793 | # noqa: E501 | 1.788465 | 2 |
sitator/site_descriptors/SOAP.py | ahzeeshan/sitator | 0 | 6623973 |
import numpy as np
from abc import ABCMeta, abstractmethod
from sitator.SiteNetwork import SiteNetwork
from sitator.SiteTrajectory import SiteTrajectory
try:
import quippy as qp
from quippy import descriptors
except ImportError:
raise ImportError("Quippy with GAP is required for using SOAP descriptors.")... |
import numpy as np
from abc import ABCMeta, abstractmethod
from sitator.SiteNetwork import SiteNetwork
from sitator.SiteTrajectory import SiteTrajectory
try:
import quippy as qp
from quippy import descriptors
except ImportError:
raise ImportError("Quippy with GAP is required for using SOAP descriptors.")... | en | 0.836132 | # From https://github.com/tqdm/tqdm/issues/506#issuecomment-373126698 Abstract base class for computing SOAP vectors in a SiteNetwork. SOAP computations are *not* thread-safe; use one SOAP object per thread. :param int tracer_atomic_number: The atomic number of the tracer. :param list environment: The ato... | 2.256482 | 2 |
src/declarativeTask3/ld_GUI_adjust_sound_volumes.py | labdoyon/declarativeTask3 | 0 | 6623974 | import sys
import pickle
import os
from expyriment import control, misc, design, stimuli, io
from expyriment.misc import constants
from expyriment.misc._timer import get_time
from declarativeTask3.config import debug, windowMode, windowSize, classPictures, sounds, \
bgColor, arrow, textSize, textColor, cardColor,... | import sys
import pickle
import os
from expyriment import control, misc, design, stimuli, io
from expyriment.misc import constants
from expyriment.misc._timer import get_time
from declarativeTask3.config import debug, windowMode, windowSize, classPictures, sounds, \
bgColor, arrow, textSize, textColor, cardColor,... | en | 0.720387 | # Check WindowMode and Resolution # Get arguments - experiment name and subject # Save experiment name # Save Subject Code # 0. Starting Experiment # Add sync info # Create Mouse instance # Log mouse # Hide cursor # Create blank screen # 1. PLOT INTERFACE # 2. WAIT FOR TTL # Saving sounds adjustment: (this script is su... | 1.931413 | 2 |
setup.py | Raijeku/qmeans | 0 | 6623975 | <filename>setup.py
"""Module including package metadata"""
from setuptools import setup
with open("README.md", 'r', encoding="utf-8") as f:
long_description = f.read()
setup(
name='qmeans',
version='0.1.1',
description='Q-Means algorithm implementation using Qiskit compatible with Scikit-Learn.',
lic... | <filename>setup.py
"""Module including package metadata"""
from setuptools import setup
with open("README.md", 'r', encoding="utf-8") as f:
long_description = f.read()
setup(
name='qmeans',
version='0.1.1',
description='Q-Means algorithm implementation using Qiskit compatible with Scikit-Learn.',
lic... | en | 0.794808 | Module including package metadata | 1.333227 | 1 |
hard-gists/931984/snippet.py | jjhenkel/dockerizeme | 21 | 6623976 | #!/usr/bin/env python
import MySQLdb
import os, sys
import pprint
pp = pprint.PrettyPrinter()
mysql_host = "localhost"
mysql_user = "dbusername"
mysql_pass = "<PASSWORD>"
mysql_db = "powerdns"
#ClientIP, ClientMac, host-decl-name
if (len(sys.argv) > 1):
command = sys.argv[1]
clientIP = sys.argv[2]
clientMac = ... | #!/usr/bin/env python
import MySQLdb
import os, sys
import pprint
pp = pprint.PrettyPrinter()
mysql_host = "localhost"
mysql_user = "dbusername"
mysql_pass = "<PASSWORD>"
mysql_db = "powerdns"
#ClientIP, ClientMac, host-decl-name
if (len(sys.argv) > 1):
command = sys.argv[1]
clientIP = sys.argv[2]
clientMac = ... | en | 0.291083 | #!/usr/bin/env python #ClientIP, ClientMac, host-decl-name # pp.pprint(cursor.__dict__) #pp.pprint(cursor.__dict__) #pp.pprint(cursor.__dict__) | 2.36292 | 2 |
utils/helper_functions.py | Sunnigen/pywave-function-collapse | 2 | 6623977 | <filename>utils/helper_functions.py
from collections import Counter
from math import sqrt
import random
import string
from numpy.random import choice as WeightedChoice
def distance_value(p0, p1, range_val):
dist = sqrt(((p0[0] - p1[0]) ** 2) + ((p0[1] - p1[1]) ** 2))
dist_modifier = range_val - dist
# pr... | <filename>utils/helper_functions.py
from collections import Counter
from math import sqrt
import random
import string
from numpy.random import choice as WeightedChoice
def distance_value(p0, p1, range_val):
dist = sqrt(((p0[0] - p1[0]) ** 2) + ((p0[1] - p1[1]) ** 2))
dist_modifier = range_val - dist
# pr... | en | 0.551135 | # print('Distance from origin: (%s, %s), to area: (%s, %s) is %s' % (p1[0], p1[1], p0[0], p0[1], dist)) # print('range_val = %s' % range_val) # print('dist_modifier = %s' % dist_modifier) # North, East, South, West <-- directions # 0, 1, 2, 3 <-- indexes # return index with opposite direction # return 'south' # retur... | 3.554475 | 4 |
lib/utils_plots.py | octaviomtz/Growing-Neural-Cellular-Automata | 0 | 6623978 | import os
import numpy as np
import matplotlib.pyplot as plt
import wandb
from lib.utils_vis import SamplePool, to_alpha_1ch, to_rgb_1ch
def visualize_batch(x0, x, save=True, text=''):
plt.style.use("Solarize_Light2")
vis0 = to_rgb_1ch(x0)
vis1 = to_rgb_1ch(x)
# vis0 = x0[...,0]
# vis1 = x[...,0]
... | import os
import numpy as np
import matplotlib.pyplot as plt
import wandb
from lib.utils_vis import SamplePool, to_alpha_1ch, to_rgb_1ch
def visualize_batch(x0, x, save=True, text=''):
plt.style.use("Solarize_Light2")
vis0 = to_rgb_1ch(x0)
vis1 = to_rgb_1ch(x)
# vis0 = x0[...,0]
# vis1 = x[...,0]
... | en | 0.418877 | # vis0 = x0[...,0] # vis1 = x[...,0] # %% PLOT MAX INTENSITY AND MSE # print(f'target={np.shape(t)}{np.unique(t[...,1])} seed={np.shape(s)}{np.unique(s)}') | 2.600944 | 3 |
amnesia/modules/file/model.py | silenius/amnesia | 4 | 6623979 | <filename>amnesia/modules/file/model.py
# -*- coding: utf-8 -*-
# pylint: disable=E1101
import os.path
from hashids import Hashids
from amnesia.modules.content import Content
class File(Content):
def feed(self, **kwargs):
for c in ('file_size', 'mime_id', 'original_name'):
if c in kwargs:... | <filename>amnesia/modules/file/model.py
# -*- coding: utf-8 -*-
# pylint: disable=E1101
import os.path
from hashids import Hashids
from amnesia.modules.content import Content
class File(Content):
def feed(self, **kwargs):
for c in ('file_size', 'mime_id', 'original_name'):
if c in kwargs:... | en | 0.455158 | # -*- coding: utf-8 -*- # pylint: disable=E1101 | 2.289096 | 2 |
Table_3_6.py | Jonghyun-Kim-73/SAMG_Project | 0 | 6623980 | import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
class table_3_6(QWidget):
qss = """
QWidget {
background: rgb(221, 221, 221);
border : 0px solid;
}
QPushButton{
background-color: r... | import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
class table_3_6(QWidget):
qss = """
QWidget {
background: rgb(221, 221, 221);
border : 0px solid;
}
QPushButton{
background-color: r... | ko | 0.14888 | QWidget { background: rgb(221, 221, 221); border : 0px solid; } QPushButton{ background-color: rgb(221,221,221); border: 1px solid rgb(0,0,0); font-size: 14pt; font-weight: bold ... | 2.339239 | 2 |
Section 2/source/federated_learning_for_image_classification.py | PacktPublishing/Federated-Learning-with-TensorFlow | 11 | 6623981 | # -*- coding: utf-8 -*-
# Based on the original code example:
# https://www.tensorflow.org/federated/tutorials/federated_learning_for_image_classification
# Simplified, added an example of random client sampling.
import collections
import numpy as np
np.random.seed(0)
import tensorflow as tf
from tensorflow.python.ke... | # -*- coding: utf-8 -*-
# Based on the original code example:
# https://www.tensorflow.org/federated/tutorials/federated_learning_for_image_classification
# Simplified, added an example of random client sampling.
import collections
import numpy as np
np.random.seed(0)
import tensorflow as tf
from tensorflow.python.ke... | en | 0.845743 | # -*- coding: utf-8 -*- # Based on the original code example: # https://www.tensorflow.org/federated/tutorials/federated_learning_for_image_classification # Simplified, added an example of random client sampling. # Loading simulation data # This is only needed to create the "federated" ver of the model # Training # Cre... | 3.05324 | 3 |
yproblem/__init__.py | DarioBojanjac/effective_2D | 1 | 6623982 | from .yproblem import Yproblem
from .utils import save_field_plots, save_pvd
| from .yproblem import Yproblem
from .utils import save_field_plots, save_pvd
| none | 1 | 0.989021 | 1 | |
tests/behavior/test.py | iblech/autopiper | 50 | 6623983 | <reponame>iblech/autopiper
#!/usr/bin/env python3
import os.path
import re
import sys
import tempfile
import subprocess
VERBOSE = 1
def run(exe, args):
sub = subprocess.Popen(executable = exe, args = args,
stdin=None, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = sub.communicat... | #!/usr/bin/env python3
import os.path
import re
import sys
import tempfile
import subprocess
VERBOSE = 1
def run(exe, args):
sub = subprocess.Popen(executable = exe, args = args,
stdin=None, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = sub.communicate()
retcode = sub.wait(... | en | 0.52521 | #!/usr/bin/env python3 # command types # define a port on the DUT # advance to a given cycle # write an input to the DUT # expect a given value on a given output from the DUT #5; clock = 1; cycle_counter = cycle_counter + 1; #5; clock = 0; end\n\n") #5; reset = 0; #5;\n") #%d;\n" % ((c.cycle - cur_cycle) * 10)) #10;\n"... | 2.880659 | 3 |
microci/web/ui.py | linkdd/microci | 4 | 6623984 | # -*- coding: utf-8 -*-
from flask import Blueprint, render_template, abort
from microci.web.jobs import fetch as fetch_jobs, serialize as serialize_job
from microci.model.job import JobStatus
from microci.web import db
blueprint = Blueprint('ui', __name__)
@blueprint.errorhandler(404)
def not_found(e):
retur... | # -*- coding: utf-8 -*-
from flask import Blueprint, render_template, abort
from microci.web.jobs import fetch as fetch_jobs, serialize as serialize_job
from microci.model.job import JobStatus
from microci.web import db
blueprint = Blueprint('ui', __name__)
@blueprint.errorhandler(404)
def not_found(e):
retur... | en | 0.769321 | # -*- coding: utf-8 -*- | 2.250262 | 2 |
src/randomwalk.py | Hilbert1024/sim2nd | 5 | 6623985 | # -*- coding: utf-8 -*-
"""
Created on Thu Feb 13 22:29:50 2020
@author: Hilbert1024
"""
import numpy as np
import random
class RandomWalk(object):
"""
Simulate a random walk series by given transition matrix.
Parameters
----------
graph : networkx.classes.graph.Graph
A graph in networkx... | # -*- coding: utf-8 -*-
"""
Created on Thu Feb 13 22:29:50 2020
@author: Hilbert1024
"""
import numpy as np
import random
class RandomWalk(object):
"""
Simulate a random walk series by given transition matrix.
Parameters
----------
graph : networkx.classes.graph.Graph
A graph in networkx... | en | 0.778886 | # -*- coding: utf-8 -*- Created on Thu Feb 13 22:29:50 2020 @author: Hilbert1024 Simulate a random walk series by given transition matrix. Parameters ---------- graph : networkx.classes.graph.Graph A graph in networkx. transMat : dict The dictionary includes node:prob and edge:prob. ... | 3.573456 | 4 |
tests/test_okopf.py | naydyonov/allrucodes | 0 | 6623986 | <filename>tests/test_okopf.py
import unittest
from allrucodes import OKOPFCodes
class TestOKSMCodes(unittest.TestCase):
def test_full_search(self):
test_values = {'акционерного общества': '12200'}
oksm = OKOPFCodes()
for value, code in test_values.items():
se... | <filename>tests/test_okopf.py
import unittest
from allrucodes import OKOPFCodes
class TestOKSMCodes(unittest.TestCase):
def test_full_search(self):
test_values = {'акционерного общества': '12200'}
oksm = OKOPFCodes()
for value, code in test_values.items():
se... | none | 1 | 3.036717 | 3 | |
simulation/code/fd/sample.py | sungcheolkim78/FDclassifieR | 3 | 6623987 | <gh_stars>1-10
"""Sample rank data sets from Gaussian distributions.
This module implements Gustavo's prescription for generating synthetic
data. The data consists of a (M, N) ndarray, R, of N sample rank predictions
by M base classifiers and (N,) ndarray of true sample labels. The synthetic
rank predictions may be ... | """Sample rank data sets from Gaussian distributions.
This module implements Gustavo's prescription for generating synthetic
data. The data consists of a (M, N) ndarray, R, of N sample rank predictions
by M base classifiers and (N,) ndarray of true sample labels. The synthetic
rank predictions may be correlated by s... | en | 0.790962 | Sample rank data sets from Gaussian distributions. This module implements Gustavo's prescription for generating synthetic data. The data consists of a (M, N) ndarray, R, of N sample rank predictions by M base classifiers and (N,) ndarray of true sample labels. The synthetic rank predictions may be correlated by spec... | 3.32125 | 3 |
GUI/Basic-train/MatplotWidget/MatplotlibWidget.py | muyuuuu/PyQt-learn | 12 | 6623988 | <filename>GUI/Basic-train/MatplotWidget/MatplotlibWidget.py
#!/bin/bash
# -*- coding: UTF-8 -*-
import sys
import numpy as np
import PyQt5
# 基本控件都在这里面
from PyQt5.QtWidgets import (QApplication, QMainWindow, QDesktopWidget, QStyleFactory, QWidget,
QSizePolicy, QPushButton, QGridLayout)
fr... | <filename>GUI/Basic-train/MatplotWidget/MatplotlibWidget.py
#!/bin/bash
# -*- coding: UTF-8 -*-
import sys
import numpy as np
import PyQt5
# 基本控件都在这里面
from PyQt5.QtWidgets import (QApplication, QMainWindow, QDesktopWidget, QStyleFactory, QWidget,
QSizePolicy, QPushButton, QGridLayout)
fr... | zh | 0.215633 | #!/bin/bash # -*- coding: UTF-8 -*- # 基本控件都在这里面 # 绘图的空白界面 # 多界面绘图 # 为何要加参数 # 实现绘图类 # 封装绘图类 # self.quit_btn_2 = QPushButton() # self.quit_btn_3 = QPushButton() # self.quit_btn_2.clicked.connect(self.static) # self.quit_btn_3.clicked.connect(self.dynamic) # self.gridLayout.addWidget(self.quit_btn_2) # self.gridLayout.add... | 2.345041 | 2 |
nhs_plot.py | palfrey/autocovid | 0 | 6623989 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Heirarchical map plot for local Covid data - England
Created on Sun Oct 4 14:16:24 2020
@author: jah-photoshop
"""
print("________________________________________________________________________________")
print("Covid Local Data Map Plotter - version 1.1 -... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Heirarchical map plot for local Covid data - England
Created on Sun Oct 4 14:16:24 2020
@author: jah-photoshop
"""
print("________________________________________________________________________________")
print("Covid Local Data Map Plotter - version 1.1 -... | en | 0.62422 | #!/usr/bin/env python3 # -*- coding: utf-8 -*- Heirarchical map plot for local Covid data - England Created on Sun Oct 4 14:16:24 2020 @author: jah-photoshop #Populations: [githubcom/russss/covidtracker] #London 8908081 #South East 8852361 #South West 5605997 #East of England 6493188 #Midlands 10537679 #North East ... | 2.485391 | 2 |
pb_link/pb_client.py | NabazOwner/micropython-iot | 1 | 6623990 | # pb_client.py Run on Pyboard/STM device. Communicate with IOT server via an
# ESP8266 running esp_link.py
# Copyright (c) <NAME> 2018
# Released under the MIT licence. Full text in root of this repository.
# Communication uses I2C slave mode.
import uasyncio as asyncio
import ujson
from . import app_base
from . imp... | # pb_client.py Run on Pyboard/STM device. Communicate with IOT server via an
# ESP8266 running esp_link.py
# Copyright (c) <NAME> 2018
# Released under the MIT licence. Full text in root of this repository.
# Communication uses I2C slave mode.
import uasyncio as asyncio
import ujson
from . import app_base
from . imp... | en | 0.761389 | # pb_client.py Run on Pyboard/STM device. Communicate with IOT server via an # ESP8266 running esp_link.py # Copyright (c) <NAME> 2018 # Released under the MIT licence. Full text in root of this repository. # Communication uses I2C slave mode. # Server-side connection ID: any newline-terminated string not containing an... | 2.598488 | 3 |
djangoFiles/jeklog/urls.py | silvrwolfboy/theJekyllProject | 20 | 6623991 | from django.views.generic import TemplateView
urlpatterns = []
handler404 = TemplateView.as_view(template_name='jeklog/404.html')
handler500 = TemplateView.as_view(template_name='jeklog/500.html')
handler403 = TemplateView.as_view(template_name='jeklog/403.html')
handler400 = TemplateView.as_view(template_name='jeklo... | from django.views.generic import TemplateView
urlpatterns = []
handler404 = TemplateView.as_view(template_name='jeklog/404.html')
handler500 = TemplateView.as_view(template_name='jeklog/500.html')
handler403 = TemplateView.as_view(template_name='jeklog/403.html')
handler400 = TemplateView.as_view(template_name='jeklo... | none | 1 | 1.59685 | 2 | |
TenBasicAlgorithm.py | LikeSnooker/TenBasicAlgorithm-Python- | 0 | 6623992 | <gh_stars>0
from collections import deque
#冒泡排序
#思路很简单 每一趟循环将 最大的数 冒泡到最右端
def bubbleSort(Q):
for s in range(len(Q)-1):
for m in range(len(Q)-1):
if Q[m] > Q[m+1]:
Q[m],Q[m+1] = Q[m+1],Q[m]
return Q
print("bubbleSort:")
print(bubbleSort([8,2,7,3,9,1,4,5,6]))
#
# 快速排序
# 核心 思路 选一个基准 小的放左边 大的放右边,并对左右分别递归
#
def... | from collections import deque
#冒泡排序
#思路很简单 每一趟循环将 最大的数 冒泡到最右端
def bubbleSort(Q):
for s in range(len(Q)-1):
for m in range(len(Q)-1):
if Q[m] > Q[m+1]:
Q[m],Q[m+1] = Q[m+1],Q[m]
return Q
print("bubbleSort:")
print(bubbleSort([8,2,7,3,9,1,4,5,6]))
#
# 快速排序
# 核心 思路 选一个基准 小的放左边 大的放右边,并对左右分别递归
#
def quickSort(Q... | zh | 0.906896 | #冒泡排序 #思路很简单 每一趟循环将 最大的数 冒泡到最右端 # # 快速排序 # 核心 思路 选一个基准 小的放左边 大的放右边,并对左右分别递归 # # # 归并排序 # 假设有两个已经排序好的数组 [1,3,5,7] [2,4,6] 我们很容易将这两个数组排序 步骤为 # 选取两个数组中最小的元素,将两者之间的更小者放入新数组,直到某个数组为空, # 然后将另一个数组中的剩余元素全部放入新数组 # [1,3,5,7] # [3,4,6] # [] # ↓ # [3,5,7] # [2,4,6] # [1] # ↓ # [3,5,7] # [4,6] # [1,3] # : # # # 堆排序 利用了 堆结构 #... | 3.885751 | 4 |
writeToExcel.py | kkkelicheng/PythonExcelDemo | 0 | 6623993 | <reponame>kkkelicheng/PythonExcelDemo
import openpyxl
from openpyxl.utils import get_column_letter
# 创建一个新的工作簿
wb = openpyxl.Workbook()
# 活跃的,创建wb,应该自带一个active的表单
sheet = wb.active
# 先取3个变量
sheetName_happy2020 = "happy2020"
sheetName_first = "first"
sheetName_middle = "middle"
# change the name of sheet
print(sheet... | import openpyxl
from openpyxl.utils import get_column_letter
# 创建一个新的工作簿
wb = openpyxl.Workbook()
# 活跃的,创建wb,应该自带一个active的表单
sheet = wb.active
# 先取3个变量
sheetName_happy2020 = "happy2020"
sheetName_first = "first"
sheetName_middle = "middle"
# change the name of sheet
print(sheet.title)
sheet.title = sheetName_happy2... | zh | 0.942378 | # 创建一个新的工作簿 # 活跃的,创建wb,应该自带一个active的表单 # 先取3个变量 # change the name of sheet # 如果你不调用save ,就不会写到硬盘上面的 # wb.save("pyCreatedExcel.xlsx") # 修改xlsx 的原则: 不改变源文件,重新取一个名字去保存。防止出错,取同名会覆盖。 # 创建其他的表单 # 创建一个name为first sheet的,插在happy2020的前面,假如不指定index,会放在happy2020的后面 # 删除一个表单 # 首先获取到要删除的表单,2种方式获取,随便用一个,在readExcel中有写 # 如果你不调用save ,就不... | 3.426986 | 3 |
python_scripts/setup.py | webanpick/webanpick-master | 1 | 6623994 | <filename>python_scripts/setup.py
from setuptools import setup
setup( name='webanpickdebugnode',
version='0.1',
description='A wrapper for launching and interacting with a Webanpick Debug Node',
url='http://github.com/webanpickit/webanpick',
author='<NAME>.',
author_email='<EMAIL>',
... | <filename>python_scripts/setup.py
from setuptools import setup
setup( name='webanpickdebugnode',
version='0.1',
description='A wrapper for launching and interacting with a Webanpick Debug Node',
url='http://github.com/webanpickit/webanpick',
author='<NAME>.',
author_email='<EMAIL>',
... | en | 0.127112 | #install_requires=['webanpickapi'], | 1.319907 | 1 |
py_tdlib/constructors/search_messages.py | Mr-TelegramBot/python-tdlib | 24 | 6623995 | <reponame>Mr-TelegramBot/python-tdlib
from ..factory import Method
class searchMessages(Method):
query = None # type: "string"
offset_date = None # type: "int32"
offset_chat_id = None # type: "int53"
offset_message_id = None # type: "int53"
limit = None # type: "int32"
| from ..factory import Method
class searchMessages(Method):
query = None # type: "string"
offset_date = None # type: "int32"
offset_chat_id = None # type: "int53"
offset_message_id = None # type: "int53"
limit = None # type: "int32" | en | 0.605481 | # type: "string" # type: "int32" # type: "int53" # type: "int53" # type: "int32" | 1.857358 | 2 |
src/service/encrypted/encrypted/views.py | cs5331-group12/rest-api-development | 0 | 6623996 | <reponame>cs5331-group12/rest-api-development
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from rest_framework.response import Response
from rest_framework.decorators import api_view
@api_view(["GET"])
def root(request):
"""
Retrieve all endpoints that are implemented
"""
data = {
"status":... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from rest_framework.response import Response
from rest_framework.decorators import api_view
@api_view(["GET"])
def root(request):
"""
Retrieve all endpoints that are implemented
"""
data = {
"status": True,
"result": [
"/",
"/meta/heartbe... | en | 0.879936 | # -*- coding: utf-8 -*- Retrieve all endpoints that are implemented | 2.34671 | 2 |
pybpod_soundcard_module/module_api.py | pybpod/pybpod-gui-plugin-soundcard | 0 | 6623997 | <filename>pybpod_soundcard_module/module_api.py
import array
import math
import time
import numpy as np
from enum import Enum, IntEnum
from aenum import auto
import os
import collections
import usb.core
import usb.util
from usb.backend import libusb1 as libusb
class SampleRate(IntEnum):
"""
Enumeration for th... | <filename>pybpod_soundcard_module/module_api.py
import array
import math
import time
import numpy as np
from enum import Enum, IntEnum
from aenum import auto
import os
import collections
import usb.core
import usb.util
from usb.backend import libusb1 as libusb
class SampleRate(IntEnum):
"""
Enumeration for th... | en | 0.820666 | Enumeration for the Sample rate of the sounds in the Sound Card #: 96KHz sample rate #: 192KHz sample rate Type of the data to be send to the Sound Card #: Integer 32 bits #: Single precision float :param self: :param sound_index: Sound index in the soundcard (2 -> 31 since 0 and 1 are reserved) :param ... | 2.826815 | 3 |
fpga-rfnoc/testbenches/noc_block_channelizer_tb/shared_tools/python/fp_utils.py | pjvalla/theseus-cores | 9 | 6623998 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@author: phil
"""
import numpy as np
import binascii
# from cStringIO import StringIO
from io import StringIO
import copy
from mpmath import mp
"""
Quantization vector is of the formed fixed(N, F). Where the first value indicates the
total number of bits a... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@author: phil
"""
import numpy as np
import binascii
# from cStringIO import StringIO
from io import StringIO
import copy
from mpmath import mp
"""
Quantization vector is of the formed fixed(N, F). Where the first value indicates the
total number of bits a... | en | 0.675372 | #!/usr/bin/env python # -*- coding: utf-8 -*- @author: phil # from cStringIO import StringIO Quantization vector is of the formed fixed(N, F). Where the first value indicates the total number of bits and the second number indicates the location of the fractional point. Fast way to count 1's in a 64 bit integer. B... | 3.527373 | 4 |
pKaTool/stab_fit/myfitter.py | shambo001/peat | 3 | 6623999 | #!/usr/bin/env python
import numpy as np
import math, random
import operator, os, sys, csv
import pickle
import pylab as plt
import scipy.optimize
"""Prototype for newer fit class that allows user created
models to be added dynamically and can do multivariate fitting"""
class testdata(object):
def line(self, noi... | #!/usr/bin/env python
import numpy as np
import math, random
import operator, os, sys, csv
import pickle
import pylab as plt
import scipy.optimize
"""Prototype for newer fit class that allows user created
models to be added dynamically and can do multivariate fitting"""
class testdata(object):
def line(self, noi... | en | 0.516948 | #!/usr/bin/env python Prototype for newer fit class that allows user created models to be added dynamically and can do multivariate fitting DIY lsq Evaluate the func residuals given parameters Evaluate func and get sum sq res for given params Fit by minimizing r-squared using various algorithms #downhill simplex algori... | 3.121907 | 3 |
assemblyline/al_ui/error.py | dendisuhubdy/grokmachine | 46 | 6624000 |
from flask import Blueprint, render_template, request, redirect
from sys import exc_info
from traceback import format_tb
from urllib import quote
from al_ui.apiv3.core import make_api_response
from al_ui.config import AUDIT, AUDIT_LOG, LOGGER, config
from al_ui.helper.views import redirect_helper
from al_ui.http_exce... |
from flask import Blueprint, render_template, request, redirect
from sys import exc_info
from traceback import format_tb
from urllib import quote
from al_ui.apiv3.core import make_api_response
from al_ui.config import AUDIT, AUDIT_LOG, LOGGER, config
from al_ui.helper.views import redirect_helper
from al_ui.http_exce... | de | 0.730281 | ###################################### # Custom Error page | 2.188625 | 2 |
UCIQE.py | TongJiayan/UCIQE-python | 1 | 6624001 | <reponame>TongJiayan/UCIQE-python<gh_stars>1-10
import numpy as np
import cv2
def getUCIQE(img):
img_BGR = cv2.imread(img)
img_LAB = cv2.cvtColor(img_BGR, cv2.COLOR_BGR2LAB)
img_LAB = np.array(img_LAB,dtype=np.float64)
# Trained coefficients are c1=0.4680, c2=0.2745, c3=0.2576 according to paper.
... | import numpy as np
import cv2
def getUCIQE(img):
img_BGR = cv2.imread(img)
img_LAB = cv2.cvtColor(img_BGR, cv2.COLOR_BGR2LAB)
img_LAB = np.array(img_LAB,dtype=np.float64)
# Trained coefficients are c1=0.4680, c2=0.2745, c3=0.2576 according to paper.
coe_Metric = [0.4680, 0.2745, 0.2576]
i... | en | 0.824602 | # Trained coefficients are c1=0.4680, c2=0.2745, c3=0.2576 according to paper. # item-1 # item-2 # item-3 | 2.521069 | 3 |
.github/workflows/find_changed_files.py | yut23/Microphysics | 1 | 6624002 | <filename>.github/workflows/find_changed_files.py
import subprocess
import sys
import argparse
from contextlib import contextmanager
import os
@contextmanager
def cd(newdir):
prevdir = os.getcwd()
os.chdir(os.path.expanduser(newdir))
try:
yield
finally:
os.chdir(prevdir)
def find_file... | <filename>.github/workflows/find_changed_files.py
import subprocess
import sys
import argparse
from contextlib import contextmanager
import os
@contextmanager
def cd(newdir):
prevdir = os.getcwd()
os.chdir(os.path.expanduser(newdir))
try:
yield
finally:
os.chdir(prevdir)
def find_file... | en | 0.856699 | # see which directories contain changed files # check for the NETWORK_PROPERTIES file in each parent directory # remove networks/ # compile test_eos as well | 2.566774 | 3 |
mab/gd/schw/schwhelper.py | maartenbreddels/mab | 1 | 6624003 | from numpy import *
import numpy
import os
class SchwHelper(object):
def __init__(self):
pass
@classmethod
def getrs(cls, galaxy, dither=1, dE=False, physical=False):
logr1, logr2 = cls.logE1, cls.logE2
kpc_to_arcsec = galaxy.kpc_to_arcsec(1.)
if physical:
logrmin, logrmax = logr1-log10(kpc_to_arcsec),... | from numpy import *
import numpy
import os
class SchwHelper(object):
def __init__(self):
pass
@classmethod
def getrs(cls, galaxy, dither=1, dE=False, physical=False):
logr1, logr2 = cls.logE1, cls.logE2
kpc_to_arcsec = galaxy.kpc_to_arcsec(1.)
if physical:
logrmin, logrmax = logr1-log10(kpc_to_arcsec),... | en | 0.300815 | #orbitweights = ravel(numpy.load(filename)) #orbitweights = ravel(numpy.load(filename)) #projectedmoments = load() #print projectedmoments.shape #print mask.shape #mask = mask[:,newaxis,:] #print mask.shape #for i in range(1, projectedmoments.shape[1]): # projectedmoments[:,i,:][mask] /= projectedmoments[:,0,:][mask] | 2.470378 | 2 |
download-avocado.py | flekschas/peax-avocado | 1 | 6624004 | #!/usr/bin/env python
import argparse
import os
import sys
module_path = os.path.abspath(os.path.join("../experiments"))
if module_path not in sys.path:
sys.path.append(module_path)
from utils import download_file
parser = argparse.ArgumentParser(description="Peax-Avocado")
parser.add_argument("chrom", help="ch... | #!/usr/bin/env python
import argparse
import os
import sys
module_path = os.path.abspath(os.path.join("../experiments"))
if module_path not in sys.path:
sys.path.append(module_path)
from utils import download_file
parser = argparse.ArgumentParser(description="Peax-Avocado")
parser.add_argument("chrom", help="ch... | ru | 0.26433 | #!/usr/bin/env python | 2.678633 | 3 |
labs/03_neural_recsys/movielens_paramsearch.py | soufiomario/labs-Deep-learning | 1,398 | 6624005 | from math import floor, ceil
from time import time
from pathlib import Path
from zipfile import ZipFile
from urllib.request import urlretrieve
from contextlib import contextmanager
import random
from pprint import pprint
import json
import numpy as np
import pandas as pd
import joblib
from sklearn.model_selection impo... | from math import floor, ceil
from time import time
from pathlib import Path
from zipfile import ZipFile
from urllib.request import urlretrieve
from contextlib import contextmanager
import random
from pprint import pprint
import json
import numpy as np
import pandas as pd
import joblib
from sklearn.model_selection impo... | en | 0.835132 | # sample n_samples out of n_samples with replacement # Create a single threaded TF session for this Python thread: # parallelism is leveraged at a coarser level with dask # graph=tf.Graph(), # graph-level deterministic weights init #%d:" % split_idx) # Transactional results saving to avoid file corruption on ctrl-c # S... | 2.220467 | 2 |
wsm/backend/asyncwhois/cache.py | Rayologist/windows-sshd-manager | 9 | 6624006 | <filename>wsm/backend/asyncwhois/cache.py
from .base import BaseCacheHandler, Action, Kind
import json
from ..services import (
get_whois,
create_whois,
get_whois_by_ip,
update_whois_by_ip,
get_cache_by_ip,
)
class IPWhoisCacheHandler(BaseCacheHandler):
async def create(self, action: Action):
... | <filename>wsm/backend/asyncwhois/cache.py
from .base import BaseCacheHandler, Action, Kind
import json
from ..services import (
get_whois,
create_whois,
get_whois_by_ip,
update_whois_by_ip,
get_cache_by_ip,
)
class IPWhoisCacheHandler(BaseCacheHandler):
async def create(self, action: Action):
... | none | 1 | 2.147803 | 2 | |
db_folder/sqldatabase.py | TheXer/Skaut-discord-bot | 16 | 6624007 | <filename>db_folder/sqldatabase.py<gh_stars>10-100
from os import getenv
import mysql.connector
from dotenv import load_dotenv
load_dotenv("password.env")
USER = getenv("USER_DATABASE")
PASSWORD = getenv("PASSWORD")
HOST = getenv("HOST")
DATABASE = getenv("DATABASE")
class SQLDatabase:
"""
Small wrapper fo... | <filename>db_folder/sqldatabase.py<gh_stars>10-100
from os import getenv
import mysql.connector
from dotenv import load_dotenv
load_dotenv("password.env")
USER = getenv("USER_DATABASE")
PASSWORD = getenv("PASSWORD")
HOST = getenv("HOST")
DATABASE = getenv("DATABASE")
class SQLDatabase:
"""
Small wrapper fo... | en | 0.655866 | Small wrapper for mysql.connector, so I can use magic with statement. Because readibility counts! Query of database. Returns list tuples from database. :param query: str :param val: Optional :return: list of tuples Execute your values and commit them. Or not. Your decision. :param query:... | 2.839571 | 3 |
vnpy_spreadtrading/backtesting.py | noranhe/vnpy_spreadtrading | 0 | 6624008 | from collections import defaultdict
from datetime import date, datetime
from typing import Callable, Type, Dict, List, Optional
from functools import partial
import numpy as np
from pandas import DataFrame
import plotly.graph_objects as go
from plotly.subplots import make_subplots
from vnpy.trader.constant import (
... | from collections import defaultdict
from datetime import date, datetime
from typing import Callable, Type, Dict, List, Optional
from functools import partial
import numpy as np
from pandas import DataFrame
import plotly.graph_objects as go
from plotly.subplots import make_subplots
from vnpy.trader.constant import (
... | en | 0.705554 | Output message of backtesting engine. Clear all data of last backtesting. # Use the first [days] of history data for initializing strategy # Use the rest of history data for running backtesting # Add trade data into daily reuslt. # Calculate daily result by iteration. # Generate dataframe # Check DataFrame input exteri... | 2.281944 | 2 |
src/pyastroapi/api/urls.py | rjfarmer/pyAstroApi | 0 | 6624009 | # SPDX-License-Identifier: BSD-3-Clause
import typing as t
# https://ui.adsabs.harvard.edu/help/api/api-docs.html
base_url = "https://api.adsabs.harvard.edu/v1"
urls = {
"search": {
"search": "/search/query",
"bigquery": "/search/bigquery",
},
# Stored search
"stored": {
"sea... | # SPDX-License-Identifier: BSD-3-Clause
import typing as t
# https://ui.adsabs.harvard.edu/help/api/api-docs.html
base_url = "https://api.adsabs.harvard.edu/v1"
urls = {
"search": {
"search": "/search/query",
"bigquery": "/search/bigquery",
},
# Stored search
"stored": {
"sea... | en | 0.519995 | # SPDX-License-Identifier: BSD-3-Clause # https://ui.adsabs.harvard.edu/help/api/api-docs.html # Stored search # Libraries # Add, remove, delete, update # New, view # Export # Metrics # Author # Citations # Classic # Objects # Oracle # Reference # Resolver # Notifications # Visualtions | 1.741044 | 2 |
setup.py | mwalpole/baywheels-py-demo | 0 | 6624010 | <gh_stars>0
from glob import glob
from os.path import basename
from os.path import splitext
from setuptools import find_packages
from setuptools import setup
setup(
name="baywheels",
packages=find_packages('src'),
package_dir={'': 'src'},
py_modules=[splitext(basename(path))[0] for path in glob('src... | from glob import glob
from os.path import basename
from os.path import splitext
from setuptools import find_packages
from setuptools import setup
setup(
name="baywheels",
packages=find_packages('src'),
package_dir={'': 'src'},
py_modules=[splitext(basename(path))[0] for path in glob('src/*.py')],
) | none | 1 | 1.876842 | 2 | |
Python/Basic Data Types/nested_lists.py | abivilion/Hackerank-Solutions- | 0 | 6624011 | lis = [] # main list
n = int(input()) # no number of students
# sub list into main list
for i in range(n):
sl = []
name = input()
sl.append(name)
marks = float(input())
sl.append(marks)
lis.append(sl)
# number list
num_l = []
for x in range(n):
num_l.append(lis[x][1])
... | lis = [] # main list
n = int(input()) # no number of students
# sub list into main list
for i in range(n):
sl = []
name = input()
sl.append(name)
marks = float(input())
sl.append(marks)
lis.append(sl)
# number list
num_l = []
for x in range(n):
num_l.append(lis[x][1])
... | en | 0.727856 | # main list # no number of students # sub list into main list # number list # print(num_l) # applying min algorithm from here # second min value name get | 3.466274 | 3 |
Calcul Numeric (CN)/Laborator/Laborator 12/lab12.py | DLarisa/FMI-Materials-BachelorDegree | 4 | 6624012 | # -*- coding: utf-8 -*-
"""
Created on Mon Jan 4 09:58:31 2021
@author: Larisa
"""
import numpy as np
import sympy as sym
import matplotlib.pyplot as plt
import math
### Proceduri -> Ex1
def difFinProg(X, Y):
"""
x oarecare -> f'(x) = (f(x+h) - f(x)) / h
pt discretizare ... | # -*- coding: utf-8 -*-
"""
Created on Mon Jan 4 09:58:31 2021
@author: Larisa
"""
import numpy as np
import sympy as sym
import matplotlib.pyplot as plt
import math
### Proceduri -> Ex1
def difFinProg(X, Y):
"""
x oarecare -> f'(x) = (f(x+h) - f(x)) / h
pt discretizare ... | ro | 0.612302 | # -*- coding: utf-8 -*- Created on Mon Jan 4 09:58:31 2021
@author: Larisa ### Proceduri -> Ex1 x oarecare -> f'(x) = (f(x+h) - f(x)) / h
pt discretizare xi -> f'(xi) = (f(xi+1) - f(xi)) / (xi+1 - xi), unde
xi + 1 => nodul i + 1 al vectorului x x oarecare -> f'(x) = (f(x) - f(x-h)) / h
... | 2.997828 | 3 |
setup.py | dskprt/botnolib | 3 | 6624013 | import setuptools
setuptools.setup(name="fastcord",
version="0.3.1",
description="another discord api wrapper for writing bots",
author="dskprt",
url="https://github.com/dskprt/fastcord",
packages=[ "fastcord", "fastcord.utils", "fastcord.objects", "fastcord.command" ],
classifiers = [
... | import setuptools
setuptools.setup(name="fastcord",
version="0.3.1",
description="another discord api wrapper for writing bots",
author="dskprt",
url="https://github.com/dskprt/fastcord",
packages=[ "fastcord", "fastcord.utils", "fastcord.objects", "fastcord.command" ],
classifiers = [
... | none | 1 | 1.245092 | 1 | |
yt_shared/yt_shared/models/yt_dlp.py | tropicoo/yt-dlp-bot | 2 | 6624014 | import datetime
import sqlalchemy as sa
from sqlalchemy import func
from yt_shared.db import Base
class YTDLP(Base):
__tablename__ = 'yt_dlp'
id = sa.Column(sa.Integer, autoincrement=True, primary_key=True, nullable=False)
current_version = sa.Column(sa.String, nullable=False)
updated_at = sa.Colu... | import datetime
import sqlalchemy as sa
from sqlalchemy import func
from yt_shared.db import Base
class YTDLP(Base):
__tablename__ = 'yt_dlp'
id = sa.Column(sa.Integer, autoincrement=True, primary_key=True, nullable=False)
current_version = sa.Column(sa.String, nullable=False)
updated_at = sa.Colu... | none | 1 | 2.375127 | 2 | |
integration/examples/python/rkt-control/main.py | gbuzogany/rockette | 4 | 6624015 | <filename>integration/examples/python/rkt-control/main.py<gh_stars>1-10
import json
import rkt_pb2
import socket
from RocketteClient import RocketteClient
config_file = 'config.json'
if __name__ == '__main__':
with open(config_file) as data_file:
config = json.load(data_file)
rkt = RocketteClient(config)
hos... | <filename>integration/examples/python/rkt-control/main.py<gh_stars>1-10
import json
import rkt_pb2
import socket
from RocketteClient import RocketteClient
config_file = 'config.json'
if __name__ == '__main__':
with open(config_file) as data_file:
config = json.load(data_file)
rkt = RocketteClient(config)
hos... | none | 1 | 2.663062 | 3 | |
pytokapi/__init__.py | cryptosbyte/PyTokAPI | 0 | 6624016 | import requests
"""
More information at https://pypi.org/project/pytokapi
"""
__version__ = "1.0.0"
class TikTok:
def __init__(self):
""" TikTok API Wrapper """
pass
def getInfo(self, url : str):
req = requests.get(f"https://www.tiktok.com/oembed?url={url}").json()
if ("status_msg" in req):
... | import requests
"""
More information at https://pypi.org/project/pytokapi
"""
__version__ = "1.0.0"
class TikTok:
def __init__(self):
""" TikTok API Wrapper """
pass
def getInfo(self, url : str):
req = requests.get(f"https://www.tiktok.com/oembed?url={url}").json()
if ("status_msg" in req):
... | en | 0.69477 | More information at https://pypi.org/project/pytokapi TikTok API Wrapper # Basic Video Information # These would be the average key of the object in a response # Video Information # Usage for websites # Video Size & URL | 3.509059 | 4 |
ROBOT_MOTOMAN.py | BrendonVaz/MotoManRobotTCPUDPCommands | 0 | 6624017 | <reponame>BrendonVaz/MotoManRobotTCPUDPCommands
import os
import sys
import time
import socket
import threading
import math
import struct
class rob():
def __init__(self, PARENT=0, dbg = 0):
self.PAR = PARENT
self.dbg = dbg
self.com1 = 'CONNECT Robot_access\r' #host control request
self.com2 ... | import os
import sys
import time
import socket
import threading
import math
import struct
class rob():
def __init__(self, PARENT=0, dbg = 0):
self.PAR = PARENT
self.dbg = dbg
self.com1 = 'CONNECT Robot_access\r' #host control request
self.com2 = 'HOSTCTRL_REQUEST ' #command header
sel... | en | 0.333759 | #host control request #command header #robot IP #robot tcp port number #robot udp port number #socket lock flag to make sure only one message at one time #~ ----------------------------------------------------------------------------------------------------------------------------------------- #~ TCP COMMANDS #~ ------... | 2.63083 | 3 |
script/Run_KLEE.py | kupl/HOMI_public | 6 | 6624018 | from multiprocessing import Process
import signal
import os
import sys
import random
import json
import argparse
import datetime
start_time = datetime.datetime.now()
configs = {
'script_path': os.path.abspath(os.getcwd()),
'top_dir': os.path.abspath('../experiments/'),
'build_dir': os.path.abspath('../... | from multiprocessing import Process
import signal
import os
import sys
import random
import json
import argparse
import datetime
start_time = datetime.datetime.now()
configs = {
'script_path': os.path.abspath(os.getcwd()),
'top_dir': os.path.abspath('../experiments/'),
'build_dir': os.path.abspath('../... | en | 0.469283 | # Follow the symbolic arguments in KLEE paper. (https://klee.github.io/docs/coreutils-experiments/) | 1.867001 | 2 |
weather.py | wangwanglulu/pythonlecture12 | 0 | 6624019 | import requests
url = "http://t.weather.sojson.com/api/weather/city/101020100"
r = requests.get(url)
print(r.status_code)
response_dict = r.json()
f = response_dict['data']
ff = f['forecast']
ff_today = ff[0]
ff_1 = ff[1]
ff_2 = ff[2]
def show(day):
for x in day:
print(x +': ' + str(day[x]))
print('\... | import requests
url = "http://t.weather.sojson.com/api/weather/city/101020100"
r = requests.get(url)
print(r.status_code)
response_dict = r.json()
f = response_dict['data']
ff = f['forecast']
ff_today = ff[0]
ff_1 = ff[1]
ff_2 = ff[2]
def show(day):
for x in day:
print(x +': ' + str(day[x]))
print('\... | none | 1 | 3.246659 | 3 | |
save_weight_in_mat.py | ifgovh/loss-landscape | 1 | 6624020 | """
Calculate and visualize the loss surface.
Usage example:
>> python plot_surface.py --x=-1:1:101 --y=-1:1:101 --model resnet56 --cuda
"""
import argparse
import copy
import h5py
import torch
import time
import socket
import os
import sys
import numpy as np
import torchvision
import torch.nn as nn
import... | """
Calculate and visualize the loss surface.
Usage example:
>> python plot_surface.py --x=-1:1:101 --y=-1:1:101 --model resnet56 --cuda
"""
import argparse
import copy
import h5py
import torch
import time
import socket
import os
import sys
import numpy as np
import torchvision
import torch.nn as nn
import... | en | 0.156347 | Calculate and visualize the loss surface. Usage example: >> python plot_surface.py --x=-1:1:101 --y=-1:1:101 --model resnet56 --cuda ############################################################### # MAIN ############################################################### # data parameters ... | 2.853926 | 3 |
salescleanup.py | jlat07/PandasDataTypes | 1 | 6624021 | import pandas as pd
import numpy as np
def convert_currency(val):
"""
$125,000.00 -> 125000.00
Convert the string number value to a float
- Remove $
- Remove commas
- Convert to float type
"""
new_val = val.replace(',','').replace('$', '')
return float(new_val)
def convert_perce... | import pandas as pd
import numpy as np
def convert_currency(val):
"""
$125,000.00 -> 125000.00
Convert the string number value to a float
- Remove $
- Remove commas
- Convert to float type
"""
new_val = val.replace(',','').replace('$', '')
return float(new_val)
def convert_perce... | en | 0.351606 | $125,000.00 -> 125000.00 Convert the string number value to a float - Remove $ - Remove commas - Convert to float type Convert the percentage string to an actual floating point percent # Should output something like: # (base) Aeneid:notebooks kristofer$ python3 ./salescleanup.py # Customer Number ... | 3.777267 | 4 |
MoleculeACE/benchmark/models/__init__.py | molML/MoleculeACE | 9 | 6624022 | from MoleculeACE.benchmark.models.model import Model
from MoleculeACE.benchmark.models.load_model import load_model
from MoleculeACE.benchmark.models.train_model import train_model
| from MoleculeACE.benchmark.models.model import Model
from MoleculeACE.benchmark.models.load_model import load_model
from MoleculeACE.benchmark.models.train_model import train_model
| none | 1 | 1.000663 | 1 | |
AutoMouse/automouse.py | yyFFans/DemoPractises | 0 | 6624023 | <gh_stars>0
# -*- coding: utf-8 -*-
import pyautogui
import time
pyautogui.FAILSAFE = False
screenshot = pyautogui.screenshot
pngLocate = pyautogui.locateOnScreen
def click(x,y):
pyautogui.moveTo(x,y)
pyautogui.click()
def get_button_center_from_screen(button_png,png_path='pics'):
screen = screens... | # -*- coding: utf-8 -*-
import pyautogui
import time
pyautogui.FAILSAFE = False
screenshot = pyautogui.screenshot
pngLocate = pyautogui.locateOnScreen
def click(x,y):
pyautogui.moveTo(x,y)
pyautogui.click()
def get_button_center_from_screen(button_png,png_path='pics'):
screen = screenshot("screen.... | zh | 0.970613 | # -*- coding: utf-8 -*- #找不到button #是否正在加载中 #检查是否初始画面需要跳过 #检查是否已经启用自动 #运行监测,是否结束,以及中间存在需要跳过,结束则开启下一次 每5s检测一次 #start 闯关 | 3.109181 | 3 |
cryptkeeper/quarry/node/icodrops.py | CMoncur/cryptkeeper | 0 | 6624024 | """ ICODrops Excavator """
# Core Dependencies
from datetime import datetime
# External Dependencies
from bs4 import BeautifulSoup
# Internal Dependencies
from cryptkeeper.quarry.excavator import Excavator
from cryptkeeper.db.librarian import Librarian
import cryptkeeper.db.schema.icodrops as Schema
import cryptkeep... | """ ICODrops Excavator """
# Core Dependencies
from datetime import datetime
# External Dependencies
from bs4 import BeautifulSoup
# Internal Dependencies
from cryptkeeper.quarry.excavator import Excavator
from cryptkeeper.db.librarian import Librarian
import cryptkeeper.db.schema.icodrops as Schema
import cryptkeep... | en | 0.820157 | ICODrops Excavator # Core Dependencies # External Dependencies # Internal Dependencies # Sanitization Functions Ensures ICODrops entry contains all data needed to be stored # Scraping Functions Scrapes ICO description from ICODrops listing Scrapes ICO end date from ICODrops listing # Return nothing in event string is s... | 2.765731 | 3 |
pulling-repos/filters.py | IliadisVictor/deep-learning-applications-research | 0 | 6624025 | from bs4 import BeautifulSoup
import requests
# Input the full name of the repository with the slash and the amount of contributors
# you want to see if it exceeds , True if it does False if it doesn't None if something went wrong
# with the scraping
# WARNING , these tools do not use the official API that is safer bu... | from bs4 import BeautifulSoup
import requests
# Input the full name of the repository with the slash and the amount of contributors
# you want to see if it exceeds , True if it does False if it doesn't None if something went wrong
# with the scraping
# WARNING , these tools do not use the official API that is safer bu... | en | 0.909496 | # Input the full name of the repository with the slash and the amount of contributors # you want to see if it exceeds , True if it does False if it doesn't None if something went wrong # with the scraping # WARNING , these tools do not use the official API that is safer but much slower. # looking for the link that corr... | 3.512286 | 4 |
aoc11.py | juestr/aoc-2021 | 0 | 6624026 | <gh_stars>0
#!/usr/bin/env python3
import numpy as np
from scipy.ndimage import correlate
with open('aoc11_input.txt') as f:
a = np.genfromtxt(f, delimiter=1, dtype=np.int_)
NBKERNEL = np.array(
[[1, 1, 1],
[1, 0, 1],
[1, 1, 1]])
def step(a):
a += 1
active = np.ones_like(a, dtype=np.boo... | #!/usr/bin/env python3
import numpy as np
from scipy.ndimage import correlate
with open('aoc11_input.txt') as f:
a = np.genfromtxt(f, delimiter=1, dtype=np.int_)
NBKERNEL = np.array(
[[1, 1, 1],
[1, 0, 1],
[1, 1, 1]])
def step(a):
a += 1
active = np.ones_like(a, dtype=np.bool_)
whil... | fr | 0.221828 | #!/usr/bin/env python3 | 2.739568 | 3 |
kaifa/select_11.py | AluuLL/initial-exper_python | 0 | 6624027 | #/usr/bin/python3
# -*- coding: utf-8 -*-
import sys
import getopt
import re
from itertools import *
import time
import json
import csv
import codecs
import random as r
import time
import random
import pandas as pd
##此程序用来将csv文件转成json格式
| #/usr/bin/python3
# -*- coding: utf-8 -*-
import sys
import getopt
import re
from itertools import *
import time
import json
import csv
import codecs
import random as r
import time
import random
import pandas as pd
##此程序用来将csv文件转成json格式
| zh | 0.59504 | #/usr/bin/python3 # -*- coding: utf-8 -*- ##此程序用来将csv文件转成json格式 | 1.881587 | 2 |
leetcode/1351-Count-Negative-Numbers-in-a-Sorted-Matrix/binary-search.py | cc13ny/all-in | 1 | 6624028 | <filename>leetcode/1351-Count-Negative-Numbers-in-a-Sorted-Matrix/binary-search.py
class Solution:
def countNegatives(self, grid: List[List[int]]) -> int:
res = 0
nrows, ncols = len(grid), len(grid[0])
start_l, start_r = 0, nrows - 1
for i in range(ncols - 1, -1, -1):
l,... | <filename>leetcode/1351-Count-Negative-Numbers-in-a-Sorted-Matrix/binary-search.py
class Solution:
def countNegatives(self, grid: List[List[int]]) -> int:
res = 0
nrows, ncols = len(grid), len(grid[0])
start_l, start_r = 0, nrows - 1
for i in range(ncols - 1, -1, -1):
l,... | none | 1 | 3.397755 | 3 | |
egrul/worker.py | ServerHack-The-First-Law-Of-Robotics/data_engineering | 0 | 6624029 | <filename>egrul/worker.py
from aiohttp import ClientSession
from asyncio import sleep
from logging import getLogger
from os.path import join
from base.worker import Worker
from base.data_objects import INNTask
from .data_objects import EgrulResult
logger = getLogger(__name__)
class EgrulWorker(Worker):
def __in... | <filename>egrul/worker.py
from aiohttp import ClientSession
from asyncio import sleep
from logging import getLogger
from os.path import join
from base.worker import Worker
from base.data_objects import INNTask
from .data_objects import EgrulResult
logger = getLogger(__name__)
class EgrulWorker(Worker):
def __in... | ru | 0.996376 | # гвоорит серверу "дядя, начни готовить для меня вот этот файл" # проверяет, готов ли файл. Статус может быть "wait" и "ready" | 2.395889 | 2 |
UpstreamTracker/ParseData.py | mcgov/Linux-CommA | 2 | 6624030 | # Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
import logging
from datetime import datetime
from typing import List, Optional, Set
import Util.Config
from DatabaseDriver.DatabaseDriver import DatabaseDriver
from DatabaseDriver.SqlClasses import PatchData
from Util.Tracking import get_filename... | # Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
import logging
from datetime import datetime
from typing import List, Optional, Set
import Util.Config
from DatabaseDriver.DatabaseDriver import DatabaseDriver
from DatabaseDriver.SqlClasses import PatchData
from Util.Tracking import get_filename... | en | 0.881341 | # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. # Filter description by removing blank and unwanted lines # TODO: Maybe just `return not line.lower().startswith(ignore_phrases)`? Look at all commits in the given repo and handle based on distro. repo: Git.Repo object of the repository where... | 2.378995 | 2 |
provider.py | AndrzejR/beeminder-integrations | 1 | 6624031 | """This is the main executable of the provider job.
Gets the data from the sources and upserts into the DCM.
"""
import logging
import toggl, db, habitica
from datetime import date, timedelta
from time import sleep
DATE_RANGE = 3
LOG_DIR = './logs/provider_'
LOG_DATE = str(date.today().isoformat().replace('-', ''))
... | """This is the main executable of the provider job.
Gets the data from the sources and upserts into the DCM.
"""
import logging
import toggl, db, habitica
from datetime import date, timedelta
from time import sleep
DATE_RANGE = 3
LOG_DIR = './logs/provider_'
LOG_DATE = str(date.today().isoformat().replace('-', ''))
... | en | 0.942041 | This is the main executable of the provider job. Gets the data from the sources and upserts into the DCM. # horrible hack; as it turns out I can't just get the data grouped per day for a date range # and there is a limit of 1 API call per second in Toggl | 2.349739 | 2 |
login_gui.py | Sourabh-12354/Login_Page-Design-Gui-By-Python | 0 | 6624032 | <filename>login_gui.py
from tkinter import *
from PIL import Image, ImageTk
import hashlib
import pymysql as mysql
from tkinter import messagebox
window = Tk()
window.geometry("800x500+300+100")
window.minsize(800, 500)
window.maxsize(800, 500)
window.title("SOUHARDO")
window.iconbitmap("C:\Python\login_icons... | <filename>login_gui.py
from tkinter import *
from PIL import Image, ImageTk
import hashlib
import pymysql as mysql
from tkinter import messagebox
window = Tk()
window.geometry("800x500+300+100")
window.minsize(800, 500)
window.maxsize(800, 500)
window.title("SOUHARDO")
window.iconbitmap("C:\Python\login_icons... | en | 0.208555 | #global valu #display window | 3.066149 | 3 |
proxyapp/views.py | eugenechia95/whaleproxy | 1 | 6624033 | <reponame>eugenechia95/whaleproxy<filename>proxyapp/views.py
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponse, HttpResponseRedirect
import requests
from django.views.decorators.cache import cache_page
from django.core.cache import cache
from... | from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponse, HttpResponseRedirect
import requests
from django.views.decorators.cache import cache_page
from django.core.cache import cache
from django import http
from django.conf import settings
import... | en | 0.568351 | # Create your views here. # needs to be unique # time in seconds for cache to be valid #GET Request returns dictionary of all whale instances # returns None if no key-value pair #url = 'https://whalemarket.saleswhale.io/whales' #urlheaders = {} #urlheaders['Authorization'] = '<KEY>' #response = requests.get(url, header... | 2.067898 | 2 |
Chal01/Chal01Part2.py | CasparovJR/AOC2021 | 0 | 6624034 | with open("./Chal01.txt", "r") as f:
l = []
s = 0
before = 0
after = 0
increased = 0
for i in f.readlines():
s = int(i.split()[0])
l.append(s)
if len(l) == 3:
after = sum(l)
l.pop(0)
if after > before and before != 0:
... | with open("./Chal01.txt", "r") as f:
l = []
s = 0
before = 0
after = 0
increased = 0
for i in f.readlines():
s = int(i.split()[0])
l.append(s)
if len(l) == 3:
after = sum(l)
l.pop(0)
if after > before and before != 0:
... | none | 1 | 3.272004 | 3 | |
tests/test_long_refresh_token_views.py | doordash/django-rest-framework-jwt-refresh-token | 0 | 6624035 | from django.contrib.auth import get_user_model
from django.core.urlresolvers import reverse
from refreshtoken.models import RefreshToken
from rest_framework import status
from rest_framework.test import APITestCase
from rest_framework_jwt import utils
from .urls import urlpatterns # noqa
User = get_user_model()
cl... | from django.contrib.auth import get_user_model
from django.core.urlresolvers import reverse
from refreshtoken.models import RefreshToken
from rest_framework import status
from rest_framework.test import APITestCase
from rest_framework_jwt import utils
from .urls import urlpatterns # noqa
User = get_user_model()
cl... | en | 0.881924 | # noqa # client_id is missing | 2.303371 | 2 |
send-GTFS-rt-to-GeoEvent/GTFS-rt-to-GeoEvent.py | d-wasserman/public-transit-tools | 130 | 6624036 | <gh_stars>100-1000
# Copyright 2015 Esri
#
# 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... | # Copyright 2015 Esri
#
# 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 ... | en | 0.823147 | # Copyright 2015 Esri # # 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 ... | 2.691779 | 3 |
extensions/games.py | xxori/PeepoBot | 0 | 6624037 | <filename>extensions/games.py
'''
MIT License
Copyright (c) 2020 <NAME> & <NAME>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to us... | <filename>extensions/games.py
'''
MIT License
Copyright (c) 2020 <NAME> & <NAME>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to us... | en | 0.766033 | MIT License Copyright (c) 2020 <NAME> & <NAME> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, d... | 3.018894 | 3 |
formation/xml.py | mardukbp/Formation | 71 | 6624038 | <filename>formation/xml.py
"""
XML utilities for handling formation design files
"""
# ======================================================================= #
# Copyright (c) 2020 Hoverset Group. #
# ======================================================================= #
import ... | <filename>formation/xml.py
"""
XML utilities for handling formation design files
"""
# ======================================================================= #
# Copyright (c) 2020 Hoverset Group. #
# ======================================================================= #
import ... | en | 0.628366 | XML utilities for handling formation design files # ======================================================================= # # Copyright (c) 2020 Hoverset Group. # # ======================================================================= # Base xml converter class. Contains utility... | 2.43202 | 2 |
multiplayer-rl/mprl/utility_services/worker/console.py | oslumbers/pipeline-psro | 26 | 6624039 | import json
import logging
import time
import grpc
from google.protobuf.empty_pb2 import Empty
from minio import Minio
from mprl.utility_services.cloud_storage import DEFAULT_LOCAL_SAVE_PATH
from mprl.utility_services.protobuf.population_server_pb2 import ManagerStats
from mprl.utility_services.worker.base_interface ... | import json
import logging
import time
import grpc
from google.protobuf.empty_pb2 import Empty
from minio import Minio
from mprl.utility_services.cloud_storage import DEFAULT_LOCAL_SAVE_PATH
from mprl.utility_services.protobuf.population_server_pb2 import ManagerStats
from mprl.utility_services.worker.base_interface ... | none | 1 | 1.926658 | 2 | |
model/DHS_RCL.py | lartpang/DHSNet-PyTorch | 3 | 6624040 | import torch
import torch.nn as nn
class RCL_Module(nn.Module):
def __init__(self, in_channels):
super(RCL_Module, self).__init__()
self.conv1 = nn.Conv2d(in_channels, 64, 1)
self.sigmoid = nn.Sigmoid()
self.conv2 = nn.Conv2d(65, 64, 3, padding=1)
self.relu = nn.ReLU()
... | import torch
import torch.nn as nn
class RCL_Module(nn.Module):
def __init__(self, in_channels):
super(RCL_Module, self).__init__()
self.conv1 = nn.Conv2d(in_channels, 64, 1)
self.sigmoid = nn.Sigmoid()
self.conv2 = nn.Conv2d(65, 64, 3, padding=1)
self.relu = nn.ReLU()
... | zh | 0.934939 | RCL模块的正向传播 :param x: 来自前面卷积网络的特征图, 因为通道数不唯一, 所以使用额外参数in_channels制定 :param smr: 来自上一级得到的预测掩膜图, 通道数为1 :return: RCL模块输出的预测掩膜图 # in_channelx1x1x64 # 合并来自前一级的预测掩膜和对应前期卷积特征图, 并进行融合 # 在RCL中, 使用求和的方式对共享特征和输出不同的时间步的特征结合 | 2.845731 | 3 |
workers/shutdown_worker.py | DRvader/Gcloud-preemtible-trainer | 0 | 6624041 | #!/usr/bin/python3
from google.cloud import firestore
import json
import os
import requests
def main():
if os.isfile(os.path.join('~/job_id')):
config = json.load(open('../config.json'))
redis_config = json.load(open('../jobServer/config.json'))
with open('~/job_id') as file:
... | #!/usr/bin/python3
from google.cloud import firestore
import json
import os
import requests
def main():
if os.isfile(os.path.join('~/job_id')):
config = json.load(open('../config.json'))
redis_config = json.load(open('../jobServer/config.json'))
with open('~/job_id') as file:
... | fr | 0.386793 | #!/usr/bin/python3 | 2.42063 | 2 |
cards/models.py | onerbs/treux | 0 | 6624042 | from django.db import models
from base.models import BaseModel
from boards.models import Board
from users.models import User
class List(BaseModel):
index = models.PositiveIntegerField()
title = models.CharField(max_length=100)
of_board = models.ForeignKey(Board, models.CASCADE, 'lists')
exports = BaseModel.expor... | from django.db import models
from base.models import BaseModel
from boards.models import Board
from users.models import User
class List(BaseModel):
index = models.PositiveIntegerField()
title = models.CharField(max_length=100)
of_board = models.ForeignKey(Board, models.CASCADE, 'lists')
exports = BaseModel.expor... | none | 1 | 2.126134 | 2 | |
third_party/chromite/lib/workqueue/tasks.py | zipated/src | 2,151 | 6624043 | # -*- coding: utf-8 -*-
# Copyright 2017 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Task manager classes for work queues."""
from __future__ import print_function
import abc
import multiprocessing
from chromi... | # -*- coding: utf-8 -*-
# Copyright 2017 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Task manager classes for work queues."""
from __future__ import print_function
import abc
import multiprocessing
from chromi... | en | 0.84233 | # -*- coding: utf-8 -*- # Copyright 2017 The Chromium OS Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. Task manager classes for work queues. Wrapper for the task handler function. Abstract base class for task management. `TaskManag... | 2.595003 | 3 |
ex06-string_lists-palindrome.py | lew18/practicepython.org-mysolutions | 0 | 6624044 | """
https://www.practicepython.org
Exercise 6: String Lists
2 chilis
Ask the user for a string and print out whether this string is a
palindrome or not. (A palindrome is a string that reads the same
forwards and backwards.)
"""
def palindrome_checker(s1):
for i in range(int(len(s1)/2)):
if s1[i] != s1[le... | """
https://www.practicepython.org
Exercise 6: String Lists
2 chilis
Ask the user for a string and print out whether this string is a
palindrome or not. (A palindrome is a string that reads the same
forwards and backwards.)
"""
def palindrome_checker(s1):
for i in range(int(len(s1)/2)):
if s1[i] != s1[le... | en | 0.768001 | https://www.practicepython.org Exercise 6: String Lists 2 chilis Ask the user for a string and print out whether this string is a palindrome or not. (A palindrome is a string that reads the same forwards and backwards.) | 4.123694 | 4 |
images/examples/nodes/kdp-node-validate-directory/validatedirectory/s3utils.py | NASA-PDS/kdp | 6 | 6624045 | <filename>images/examples/nodes/kdp-node-validate-directory/validatedirectory/s3utils.py
import os
import boto3
import fnmatch
s3 = boto3.resource('s3')
client = boto3.client('s3')
def get_matching_objects_from_s3_prefix(bucket_name, s3_prefix='', regex='*'):
"""Given an S3 prefix and regex pattern, return a lis... | <filename>images/examples/nodes/kdp-node-validate-directory/validatedirectory/s3utils.py
import os
import boto3
import fnmatch
s3 = boto3.resource('s3')
client = boto3.client('s3')
def get_matching_objects_from_s3_prefix(bucket_name, s3_prefix='', regex='*'):
"""Given an S3 prefix and regex pattern, return a lis... | en | 0.648316 | Given an S3 prefix and regex pattern, return a list of all matching objects. Given an S3 prefix and working directory, download all files under that prefix to the working directory Given an S3 prefix and working directory, download all XML files under that prefix to the working directory Push given file to s3 ... | 2.779758 | 3 |
dungeon/utils.py | bdwheele/dungeon | 0 | 6624046 | <reponame>bdwheele/dungeon
from math import floor
from random import randint, choices, choice
import re
from copy import deepcopy
"""
Miscellaneous utility functions that are useful for many things
"""
id_state = {}
def gen_id(table, seed=1, random=False, prefix=None, random_limit=4095, reserved=[]):
"""
Gene... | from math import floor
from random import randint, choices, choice
import re
from copy import deepcopy
"""
Miscellaneous utility functions that are useful for many things
"""
id_state = {}
def gen_id(table, seed=1, random=False, prefix=None, random_limit=4095, reserved=[]):
"""
Generate a per-program-run-uniq... | en | 0.811467 | Miscellaneous utility functions that are useful for many things Generate a per-program-run-unique ID either by using a random number or by incrementing a counter. optionally, a prefix can be added to the ID. When choosing a random id, a reserved list can be specified to avoid generating those ids. Generat... | 3.868978 | 4 |
envs/tests/test_breakout_env.py | MonteyMontey/deep-reinforcement-learning-sandbox | 0 | 6624047 | <filename>envs/tests/test_breakout_env.py
import numpy as np
from copy import deepcopy
import unittest
from envs.breakout_env import BreakoutEnv, Action
class TestBreakoutEnv(unittest.TestCase):
def test_step(self):
env = BreakoutEnv(15)
env.reset()
ball_pos = deepcopy(env.ball.pos)
... | <filename>envs/tests/test_breakout_env.py
import numpy as np
from copy import deepcopy
import unittest
from envs.breakout_env import BreakoutEnv, Action
class TestBreakoutEnv(unittest.TestCase):
def test_step(self):
env = BreakoutEnv(15)
env.reset()
ball_pos = deepcopy(env.ball.pos)
... | en | 0.320933 | # check ball pos # check paddle pos | 3.032465 | 3 |
search/binary.py | ashleawalker29/algorithms_python | 0 | 6624048 | <gh_stars>0
from numbers import Number
def binary_search(numbers, value, start=0, end=None):
if not numbers:
return 'Nothing to search through.'
if not value and value != 0:
return 'Nothing to search for.'
if not isinstance(value, Number):
return 'Can only search for numbers.'
... | from numbers import Number
def binary_search(numbers, value, start=0, end=None):
if not numbers:
return 'Nothing to search through.'
if not value and value != 0:
return 'Nothing to search for.'
if not isinstance(value, Number):
return 'Can only search for numbers.'
for numbe... | none | 1 | 4.119973 | 4 | |
pbootstrap.py | bnkr/pbundle | 3 | 6624049 | #!/usr/bin/python
"""Very quick bootstrapping script to avoid the need to manually make a
virtualenv."""
import subprocess
if __name__ == "__main__":
subprocess.call(['virtualenv', 'pbundle_modules'])
subprocess.call(['pbundle_modules/bin/pip', 'install',
'-e', 'git://github.com/bnkr/pbund... | #!/usr/bin/python
"""Very quick bootstrapping script to avoid the need to manually make a
virtualenv."""
import subprocess
if __name__ == "__main__":
subprocess.call(['virtualenv', 'pbundle_modules'])
subprocess.call(['pbundle_modules/bin/pip', 'install',
'-e', 'git://github.com/bnkr/pbund... | en | 0.412592 | #!/usr/bin/python Very quick bootstrapping script to avoid the need to manually make a virtualenv. #egg=pbundle']) | 1.787611 | 2 |
spider/cluster/kss/kss.py | dvdmjohnson/d3m_michigan_primitives | 1 | 6624050 | import typing
from d3m.metadata import hyperparams, base as metadata_module, params
from d3m.primitive_interfaces import base, clustering
from d3m import container, utils
import numpy as np
from scipy.linalg import orth
import os
Inputs = container.ndarray
Outputs = container.ndarray
DistanceMatrixOutput = container.n... | import typing
from d3m.metadata import hyperparams, base as metadata_module, params
from d3m.primitive_interfaces import base, clustering
from d3m import container, utils
import numpy as np
from scipy.linalg import orth
import os
Inputs = container.ndarray
Outputs = container.ndarray
DistanceMatrixOutput = container.n... | en | 0.753098 | Does clustering via the k-subspaces method. #link to file and repo @inproceedings{agarwal2004k, title={K-means projective clustering}, author={<NAME> and <NAME>}, booktitle={Proceedings of the twenty-third ACM SIGMOD-SIGACT-SIGART symposium on Principles of database systems}, pages={155--165}, year={2004}, organization... | 2.493456 | 2 |