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 |
|---|---|---|---|---|---|---|---|---|---|---|
setup.py | pnxenopoulos/soccer-data-gen | 0 | 2400 | from setuptools import setup, find_packages
setup(
name="soccergen",
version="0.1",
packages=find_packages(),
# Project uses reStructuredText, so ensure that the docutils get
# installed or upgraded on the target machine
install_requires=["gfootball>=2.8",],
# metadata to display on PyPI
... | from setuptools import setup, find_packages
setup(
name="soccergen",
version="0.1",
packages=find_packages(),
# Project uses reStructuredText, so ensure that the docutils get
# installed or upgraded on the target machine
install_requires=["gfootball>=2.8",],
# metadata to display on PyPI
... | en | 0.633926 | # Project uses reStructuredText, so ensure that the docutils get # installed or upgraded on the target machine # metadata to display on PyPI # project home page, if any | 1.387941 | 1 |
metaspace/engine/sm/engine/tests/test_fdr.py | METASPACE2020/METASPACE | 0 | 2401 | from itertools import product
from unittest.mock import patch
import pytest
import numpy as np
import pandas as pd
from pandas.util.testing import assert_frame_equal
from sm.engine.annotation.fdr import FDR, run_fdr_ranking
from sm.engine.formula_parser import format_modifiers
FDR_CONFIG = {'decoy_sample_size': 2}
... | from itertools import product
from unittest.mock import patch
import pytest
import numpy as np
import pandas as pd
from pandas.util.testing import assert_frame_equal
from sm.engine.annotation.fdr import FDR, run_fdr_ranking
from sm.engine.formula_parser import format_modifiers
FDR_CONFIG = {'decoy_sample_size': 2}
... | en | 0.714975 | # total number varies because different (formula, modifier) pairs may receive the same (formula, decoy_modifier) pair # total number varies because different (formula, modifier) pairs may receive the same (formula, decoy_modifier) pair | 1.937603 | 2 |
tests/__init__.py | acarl005/plotille | 2 | 2402 | from logging import getLogger
getLogger('flake8').propagate = False
| from logging import getLogger
getLogger('flake8').propagate = False
| none | 1 | 1.233666 | 1 | |
umigame/nlp/labelling.py | penguinwang96825/Umigame | 0 | 2403 | <reponame>penguinwang96825/Umigame
import math
import numpy as np
import pandas as pd
def fixed_time_horizon(df, column='close', lookback=20):
"""
Fixed-time Horizon
As it relates to finance, virtually all ML papers label observations using the fixed-time horizon method.
Fixed-time horizon is presente... | import math
import numpy as np
import pandas as pd
def fixed_time_horizon(df, column='close', lookback=20):
"""
Fixed-time Horizon
As it relates to finance, virtually all ML papers label observations using the fixed-time horizon method.
Fixed-time horizon is presented as one of the main procedures to ... | en | 0.770981 | Fixed-time Horizon As it relates to finance, virtually all ML papers label observations using the fixed-time horizon method. Fixed-time horizon is presented as one of the main procedures to label data when it comes to processing financial time series for machine learning. Parameters ---------- ... | 3.874568 | 4 |
mayan/apps/converter/api.py | Dave360-crypto/mayan-edms | 3 | 2404 | from __future__ import absolute_import
import hashlib
import logging
import os
from django.utils.encoding import smart_str
from common.conf.settings import TEMPORARY_DIRECTORY
from common.utils import fs_cleanup
from .exceptions import OfficeConversionError, UnknownFileFormat
from .literals import (DEFAULT_PAGE_NUM... | from __future__ import absolute_import
import hashlib
import logging
import os
from django.utils.encoding import smart_str
from common.conf.settings import TEMPORARY_DIRECTORY
from common.utils import fs_cleanup
from .exceptions import OfficeConversionError, UnknownFileFormat
from .literals import (DEFAULT_PAGE_NUM... | en | 0.659338 | # Recycle the already detected mimetype | 1.916389 | 2 |
LogisticRegression/learn.py | ValYouW/DeepLearningCourse | 0 | 2405 | <reponame>ValYouW/DeepLearningCourse
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import utils
def plot_data(x_mat, y, db_x, db_y):
plt.figure()
plt.title('Data')
admitted = (y == 1).flatten()
rejected = (y == 0).flatten()
# plot decision boundary
plt.pl... | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import utils
def plot_data(x_mat, y, db_x, db_y):
plt.figure()
plt.title('Data')
admitted = (y == 1).flatten()
rejected = (y == 0).flatten()
# plot decision boundary
plt.plot(db_x, db_y)
# plot admitted... | en | 0.848184 | # plot decision boundary # plot admitted # plot rejected # data is: exam 1 score, exam 2 score, bool whether admitted # exam scores # admitted or not # normalize input (input has large values which causes sigmoid to always be 1 or 0) # add intercept # Learn model # predict for student # Predict on train set # calc deci... | 3.379582 | 3 |
ignite/handlers/time_profilers.py | iamhardikat11/ignite | 4,119 | 2406 | import functools
from collections import OrderedDict
from typing import Any, Callable, Dict, List, Mapping, Sequence, Tuple, Union, cast
import torch
from ignite.engine import Engine, EventEnum, Events
from ignite.handlers.timing import Timer
class BasicTimeProfiler:
"""
BasicTimeProfiler can be used to pro... | import functools
from collections import OrderedDict
from typing import Any, Callable, Dict, List, Mapping, Sequence, Tuple, Union, cast
import torch
from ignite.engine import Engine, EventEnum, Events
from ignite.handlers.timing import Timer
class BasicTimeProfiler:
"""
BasicTimeProfiler can be used to pro... | en | 0.462993 | BasicTimeProfiler can be used to profile the handlers, events, data loading and data processing times. Examples: .. code-block:: python from ignite.handlers import BasicTimeProfiler trainer = Engine(train_updater) # Create an object of the profiler and attach an e... | 2.520118 | 3 |
bellmanford.py | asmodehn/aiokraken | 0 | 2407 | <gh_stars>0
"""
Bellman Ford Arbitrage implementation over websocket API.
"""
from __future__ import annotations
from collections import namedtuple
from datetime import datetime
from decimal import Decimal
from math import log
import pandas as pd
import numpy as np
import asyncio
import typing
from aiokraken.model.a... | """
Bellman Ford Arbitrage implementation over websocket API.
"""
from __future__ import annotations
from collections import namedtuple
from datetime import datetime
from decimal import Decimal
from math import log
import pandas as pd
import numpy as np
import asyncio
import typing
from aiokraken.model.assetpair imp... | en | 0.666766 | Bellman Ford Arbitrage implementation over websocket API. # For required pairs, get ticket updates # TODO : we need to unify iterable of pairs somehow... # TODO : build price matrix # retrieve the actual pair # TODO : pick the right fee depending on total traded volume ! # TODO : 2 levels : # - slow updates with wide ... | 2.330116 | 2 |
custom_components/snowtire/__init__.py | borys-kupar/smart-home | 128 | 2408 | #
# Copyright (c) 2020, Andrey "Limych" Khrolenok <<EMAIL>>
# Creative Commons BY-NC-SA 4.0 International Public License
# (see LICENSE.md or https://creativecommons.org/licenses/by-nc-sa/4.0/)
#
"""
The Snowtire binary sensor.
For more details about this platform, please refer to the documentation at
https://githu... | #
# Copyright (c) 2020, Andrey "Limych" Khrolenok <<EMAIL>>
# Creative Commons BY-NC-SA 4.0 International Public License
# (see LICENSE.md or https://creativecommons.org/licenses/by-nc-sa/4.0/)
#
"""
The Snowtire binary sensor.
For more details about this platform, please refer to the documentation at
https://githu... | en | 0.731302 | # # Copyright (c) 2020, Andrey "Limych" Khrolenok <<EMAIL>> # Creative Commons BY-NC-SA 4.0 International Public License # (see LICENSE.md or https://creativecommons.org/licenses/by-nc-sa/4.0/) # The Snowtire binary sensor. For more details about this platform, please refer to the documentation at https://github.co... | 0.939961 | 1 |
tests/test_bayes_classifier.py | manishgit138/pomegranate | 3,019 | 2409 | from __future__ import (division)
from pomegranate import *
from pomegranate.io import DataGenerator
from pomegranate.io import DataFrameGenerator
from nose.tools import with_setup
from nose.tools import assert_almost_equal
from nose.tools import assert_equal
from nose.tools import assert_not_equal
from nose.tools im... | from __future__ import (division)
from pomegranate import *
from pomegranate.io import DataGenerator
from pomegranate.io import DataFrameGenerator
from nose.tools import with_setup
from nose.tools import assert_almost_equal
from nose.tools import assert_equal
from nose.tools import assert_not_equal
from nose.tools im... | none | 1 | 1.959077 | 2 | |
ks_engine/variable_scoring.py | FilippoRanza/ks.py | 2 | 2410 | #! /usr/bin/python
from .solution import Solution
try:
import gurobipy
except ImportError:
print("Gurobi not found: error ignored to allow tests")
def variable_score_factory(sol: Solution, base_kernel: dict, config: dict):
if config.get("VARIABLE_RANKING"):
output = VariableRanking(sol, base_ker... | #! /usr/bin/python
from .solution import Solution
try:
import gurobipy
except ImportError:
print("Gurobi not found: error ignored to allow tests")
def variable_score_factory(sol: Solution, base_kernel: dict, config: dict):
if config.get("VARIABLE_RANKING"):
output = VariableRanking(sol, base_ker... | fr | 0.245098 | #! /usr/bin/python | 2.370379 | 2 |
src/fetchcode/vcs/pip/_internal/utils/entrypoints.py | quepop/fetchcode | 7 | 2411 | <gh_stars>1-10
import sys
from fetchcode.vcs.pip._internal.cli.main import main
from fetchcode.vcs.pip._internal.utils.typing import MYPY_CHECK_RUNNING
if MYPY_CHECK_RUNNING:
from typing import Optional, List
def _wrapper(args=None):
# type: (Optional[List[str]]) -> int
"""Central wrapper for all old en... | import sys
from fetchcode.vcs.pip._internal.cli.main import main
from fetchcode.vcs.pip._internal.utils.typing import MYPY_CHECK_RUNNING
if MYPY_CHECK_RUNNING:
from typing import Optional, List
def _wrapper(args=None):
# type: (Optional[List[str]]) -> int
"""Central wrapper for all old entrypoints.
... | en | 0.925367 | # type: (Optional[List[str]]) -> int Central wrapper for all old entrypoints. Historically pip has had several entrypoints defined. Because of issues arising from PATH, sys.path, multiple Pythons, their interactions, and most of them having a pip installed, users suffer every time an entrypoint gets mo... | 2.09156 | 2 |
Support/Make_Documentation.py | bvbohnen/x4-projects | 24 | 2412 | <filename>Support/Make_Documentation.py
'''
Support for generating documentation readmes for the extensions.
Extracts from decorated lua block comments and xml comments.
'''
from pathlib import Path
from lxml import etree
import sys
from itertools import chain
project_dir = Path(__file__).resolve().parents[1]
# Set ... | <filename>Support/Make_Documentation.py
'''
Support for generating documentation readmes for the extensions.
Extracts from decorated lua block comments and xml comments.
'''
from pathlib import Path
from lxml import etree
import sys
from itertools import chain
project_dir = Path(__file__).resolve().parents[1]
# Set ... | en | 0.758304 | Support for generating documentation readmes for the extensions. Extracts from decorated lua block comments and xml comments. # Set up an import from the customizer for some text processing. #from Framework.Make_Documentation import Get_BB_Text # Grab the project specifications. # Update all of the content.xml files. #... | 2.478148 | 2 |
Chapter 2 - Variables & Data Types/05_pr_set_add_two_no.py | alex-dsouza777/Python-Basics | 0 | 2413 | #Addition of two numbers
a = 30
b = 17
print("Sum of a and b is",a + b) | #Addition of two numbers
a = 30
b = 17
print("Sum of a and b is",a + b) | en | 0.92883 | #Addition of two numbers | 3.644998 | 4 |
curso 1/04 - caixa de texto/a4.py | andersonssh/aprendendo-pyqt5 | 0 | 2414 | <reponame>andersonssh/aprendendo-pyqt5<filename>curso 1/04 - caixa de texto/a4.py
import sys
from PyQt5.QtWidgets import (QApplication,
QMainWindow,
QPushButton,
QToolTip,
QLabel,
... | 1/04 - caixa de texto/a4.py
import sys
from PyQt5.QtWidgets import (QApplication,
QMainWindow,
QPushButton,
QToolTip,
QLabel,
QLineEdit)
from PyQt5 import QtGui
class Janel... | es | 0.272951 | # botoes # forma 1 # forma 2 | 2.978394 | 3 |
pdf2write.py | codeunik/stylus_labs_write_pdf_importer | 0 | 2415 | import base64
import os
import sys
import PyPDF2
svg = '''<svg id="write-document" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<rect id="write-doc-background" width="100%" height="100%" fill="#808080"/>
<defs id="write-defs">
<script type="text/writeconfig">
<int name="docFormatVer... | import base64
import os
import sys
import PyPDF2
svg = '''<svg id="write-document" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<rect id="write-doc-background" width="100%" height="100%" fill="#808080"/>
<defs id="write-defs">
<script type="text/writeconfig">
<int name="docFormatVer... | en | 0.276309 | <svg id="write-document" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> <rect id="write-doc-background" width="100%" height="100%" fill="#808080"/> <defs id="write-defs"> <script type="text/writeconfig"> <int name="docFormatVersion" value="2" /> <int name="pageColor" value="-1" /> ... | 2.695582 | 3 |
py_headless_daw/project/having_parameters.py | hq9000/py-headless-daw | 22 | 2416 | from typing import Dict, List, cast
from py_headless_daw.project.parameter import Parameter, ParameterValueType, ParameterRangeType
class HavingParameters:
def __init__(self):
self._parameters: Dict[str, Parameter] = {}
super().__init__()
def has_parameter(self, name: str) -> bool:
... | from typing import Dict, List, cast
from py_headless_daw.project.parameter import Parameter, ParameterValueType, ParameterRangeType
class HavingParameters:
def __init__(self):
self._parameters: Dict[str, Parameter] = {}
super().__init__()
def has_parameter(self, name: str) -> bool:
... | en | 0.214864 | # noinspection PyTypeChecker | 2.697872 | 3 |
wasatch/ROI.py | adiravishankara/Wasatch.PY | 9 | 2417 | ##
# This class encapsulates a Region Of Interest, which may be either horizontal
# (pixels) or vertical (rows/lines).
class ROI:
def __init__(self, start, end):
self.start = start
self.end = end
self.len = end - start + 1
def valid(self):
return self.start >= 0 and self.start ... | ##
# This class encapsulates a Region Of Interest, which may be either horizontal
# (pixels) or vertical (rows/lines).
class ROI:
def __init__(self, start, end):
self.start = start
self.end = end
self.len = end - start + 1
def valid(self):
return self.start >= 0 and self.start ... | en | 0.553622 | ## # This class encapsulates a Region Of Interest, which may be either horizontal # (pixels) or vertical (rows/lines). | 3.104935 | 3 |
examples/python/oled_ssd1327.py | whpenner/upm | 1 | 2418 | #!/usr/bin/python
# Author: <NAME> <<EMAIL>>
# Copyright (c) 2015 Intel Corporation.
#
# 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 ... | #!/usr/bin/python
# Author: <NAME> <<EMAIL>>
# Copyright (c) 2015 Intel Corporation.
#
# 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 ... | en | 0.750802 | #!/usr/bin/python # Author: <NAME> <<EMAIL>> # Copyright (c) 2015 Intel Corporation. # # 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 ... | 1.528666 | 2 |
digital_image_processing/algorithms/edge_detection_algorithms/threshold/adaptive_thresholding_methods/__init__.py | juansdev/digital_image_processing | 1 | 2419 | from .bernsen import bernsen_thresholding_method
from .bradley_roth import bradley_thresholding_method
from .contrast import contrast_thresholding_method
from .feng import feng_thresholding_method
from .gaussian import threshold_value_gaussian
from .johannsen import johannsen_thresholding_method
from .kapur import kapu... | from .bernsen import bernsen_thresholding_method
from .bradley_roth import bradley_thresholding_method
from .contrast import contrast_thresholding_method
from .feng import feng_thresholding_method
from .gaussian import threshold_value_gaussian
from .johannsen import johannsen_thresholding_method
from .kapur import kapu... | none | 1 | 1.222073 | 1 | |
data/train/python/be1d04203f18e6f16b60a723e614122b48a08671celeryconfig.py | harshp8l/deep-learning-lang-detection | 84 | 2420 | <filename>data/train/python/be1d04203f18e6f16b60a723e614122b48a08671celeryconfig.py
import os
from kombu import Queue, Exchange
## Broker settings.
BROKER_URL = os.getenv('BROKER_URL', 'amqp://guest:guest@localhost:5672')
#BROKER_URL = "amqp://guest:guest@localhost:5672/"
#BROKER_URL = os.getenv('BROKER_URL', 'redis:/... | <filename>data/train/python/be1d04203f18e6f16b60a723e614122b48a08671celeryconfig.py
import os
from kombu import Queue, Exchange
## Broker settings.
BROKER_URL = os.getenv('BROKER_URL', 'amqp://guest:guest@localhost:5672')
#BROKER_URL = "amqp://guest:guest@localhost:5672/"
#BROKER_URL = os.getenv('BROKER_URL', 'redis:/... | en | 0.428884 | ## Broker settings. #BROKER_URL = "amqp://guest:guest@localhost:5672/" #BROKER_URL = os.getenv('BROKER_URL', 'redis://guest@localhost:6379') #BROKER_HOST = "localhost" #BROKER_PORT = 27017 #BROKER_TRANSPORT = 'mongodb' #BROKER_VHOST = 'celery' # Queue('aws_uploads', routing_key='video.uploads'), #CELERY_RESULT_BACKE... | 1.614519 | 2 |
timesheet.py | dgollub/timesheet-google-thingy | 0 | 2421 | # -*- coding: utf-8 -*-
#
#
from __future__ import print_function
import csv
import os
import re
import sys
import arrow
from gsheets import Sheets
CURRENT_PATH = os.path.abspath(os.path.dirname(os.path.realpath(__file__)))
DEBUG = os.environ.get('DEBUG', "0") == "1"
AS_CSV = os.environ.get('CSV', "0") == "1"
COL... | # -*- coding: utf-8 -*-
#
#
from __future__ import print_function
import csv
import os
import re
import sys
import arrow
from gsheets import Sheets
CURRENT_PATH = os.path.abspath(os.path.dirname(os.path.realpath(__file__)))
DEBUG = os.environ.get('DEBUG', "0") == "1"
AS_CSV = os.environ.get('CSV', "0") == "1"
COL... | en | 0.801596 | # -*- coding: utf-8 -*- # # # includes lunch # does not include lunch #quickstart") # find the row with the first column that has today's date in it #if max_cols >= COL_NOTES: # print("No notes/tasks entered yet.") # return None # check the previous Friday entry (if today is not Friday), to see what work from hom... | 2.577773 | 3 |
league/game.py | Orpheon/All-in | 0 | 2422 | <gh_stars>0
import numpy as np
import pickle
import treys
import constants
FULL_DECK = np.array(treys.Deck.GetFullDeck())
class GameEngine:
def __init__(self, BATCH_SIZE, INITIAL_CAPITAL, SMALL_BLIND, BIG_BLIND, logger):
self.BATCH_SIZE = BATCH_SIZE
self.INITIAL_CAPITAL = INITIAL_CAPITAL
self.SMALL_BL... | import numpy as np
import pickle
import treys
import constants
FULL_DECK = np.array(treys.Deck.GetFullDeck())
class GameEngine:
def __init__(self, BATCH_SIZE, INITIAL_CAPITAL, SMALL_BLIND, BIG_BLIND, logger):
self.BATCH_SIZE = BATCH_SIZE
self.INITIAL_CAPITAL = INITIAL_CAPITAL
self.SMALL_BLIND = SMALL_... | en | 0.796183 | # Pre-flop # Flop # Turn # River # Showdown # Get everyone who has the best hand and among which pots will be split # Get the number of times each pot will be split # Split and distribute the money :param players: [Player] :param prev_round_investment: np.ndarray(batchsize, n_players) = int :param folded: np.nd... | 2.508782 | 3 |
cms/admin/views.py | miloprice/django-cms | 0 | 2423 | # -*- coding: utf-8 -*-
from cms.models import Page, Title, CMSPlugin, Placeholder
from cms.utils import get_language_from_request
from django.http import Http404
from django.shortcuts import get_object_or_404
def revert_plugins(request, version_id, obj):
from reversion.models import Version
version = get_obj... | # -*- coding: utf-8 -*-
from cms.models import Page, Title, CMSPlugin, Placeholder
from cms.utils import get_language_from_request
from django.http import Http404
from django.shortcuts import get_object_or_404
def revert_plugins(request, version_id, obj):
from reversion.models import Version
version = get_obj... | en | 0.837084 | # -*- coding: utf-8 -*- #page = obj #Page.objects.get(pk=obj.pk) # admin has already created the placeholders/ get them instead # connect plugins to the correct placeholder | 1.953043 | 2 |
delete.py | lvwuyunlifan/crop | 0 | 2424 | <reponame>lvwuyunlifan/crop
import os
from PIL import Image, ImageFilter
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
# import seaborn as sns
import pandas as pd
import numpy as np
import random
train_path = './AgriculturalDisease_trainingset/'
valid_path = './AgriculturalDisease_validationset/'
... | import os
from PIL import Image, ImageFilter
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
# import seaborn as sns
import pandas as pd
import numpy as np
import random
train_path = './AgriculturalDisease_trainingset/'
valid_path = './AgriculturalDisease_validationset/'
def genImage(gpath, datatyp... | en | 0.135123 | # import seaborn as sns # 统计生成的图片数量 # 生成图片label # for imagefile in imagelist: # im_detail = im.filter(ImageFilter.DETAIL) # 细节增强 # label = label.append(label_gen_pd) # 将生成的图片label加入原先的label # label['label'] = label[['label']].astype('int64') # 转化为int64 # print(label) # label_gen_p = pd.DataFrame(label_gen_dict) # la... | 2.839031 | 3 |
数据分析/matplotlib/03.demo.py | likedeke/python-spider-study | 1 | 2425 | <gh_stars>1-10
# - - - - - - - - - - -
# @author like
# @since 2021-02-23 11:08
# @email <EMAIL>
# 十点到十二点的气温变化
from matplotlib import pyplot as plt
from matplotlib import rc
from matplotlib import font_manager
import random
x = range(0, 120)
y = [random.randint(20, 35) for i in range(120)]
plt.figure(figsize=(20, ... | # - - - - - - - - - - -
# @author like
# @since 2021-02-23 11:08
# @email <EMAIL>
# 十点到十二点的气温变化
from matplotlib import pyplot as plt
from matplotlib import rc
from matplotlib import font_manager
import random
x = range(0, 120)
y = [random.randint(20, 35) for i in range(120)]
plt.figure(figsize=(20, 8), dpi=80)
pl... | zh | 0.188056 | # - - - - - - - - - - - # @author like # @since 2021-02-23 11:08 # @email <EMAIL> # 十点到十二点的气温变化 # 中文字体 # SimHei # chFont = font_manager.FontProperties(fname="C:/Windows/Fonts/SIMHEI.TTF") # 刻度相关设置 # 添加描述信息 | 3.242693 | 3 |
testing/vcs/test_vcs_isoline_labels.py | xylar/cdat | 62 | 2426 | import os, sys, cdms2, vcs, vcs.testing.regression as regression
dataset = cdms2.open(os.path.join(vcs.sample_data,"clt.nc"))
data = dataset("clt")
canvas = regression.init()
isoline = canvas.createisoline()
isoline.label="y"
texts=[]
colors = []
for i in range(10):
text = canvas.createtext()
text.color = 50 +... | import os, sys, cdms2, vcs, vcs.testing.regression as regression
dataset = cdms2.open(os.path.join(vcs.sample_data,"clt.nc"))
data = dataset("clt")
canvas = regression.init()
isoline = canvas.createisoline()
isoline.label="y"
texts=[]
colors = []
for i in range(10):
text = canvas.createtext()
text.color = 50 +... | en | 0.708138 | # First test using isoline.text[...].color # Now set isoline.linecolors and test again. # Now set isoline.textcolors and test again. | 2.214307 | 2 |
src/Python_version/ICE_py36.py | ds-utilities/ICE | 2 | 2427 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Mon Mar 5 05:47:03 2018
@author: zg
"""
import numpy as np
#from scipy import io
import scipy.io
#import pickle
from sklearn.model_selection import StratifiedKFold
#import sklearn
from scipy.sparse import spdiags
from scipy.spatial import distance
#impo... | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Mon Mar 5 05:47:03 2018
@author: zg
"""
import numpy as np
#from scipy import io
import scipy.io
#import pickle
from sklearn.model_selection import StratifiedKFold
#import sklearn
from scipy.sparse import spdiags
from scipy.spatial import distance
#impo... | en | 0.562771 | #!/usr/bin/env python2 # -*- coding: utf-8 -*- Created on Mon Mar 5 05:47:03 2018 @author: zg #from scipy import io #import pickle #import sklearn #import matplotlib.pyplot as plt #from sklearn import metrics #import FuzzyRwrBagging as frb #from joblib import Parallel, delayed #import multiprocessing % the random wal... | 2.499986 | 2 |
xc/common/utils/prjxray_routing_import.py | FireFox317/symbiflow-arch-defs | 1 | 2428 | <reponame>FireFox317/symbiflow-arch-defs<filename>xc/common/utils/prjxray_routing_import.py
#!/usr/bin/env python3
""" Imports 7-series routing fabric to the rr graph.
For ROI configurations, this also connects the synthetic IO tiles to the routing
node specified.
Rough structure:
Add rr_nodes for CHANX and CHANY fr... | #!/usr/bin/env python3
""" Imports 7-series routing fabric to the rr graph.
For ROI configurations, this also connects the synthetic IO tiles to the routing
node specified.
Rough structure:
Add rr_nodes for CHANX and CHANY from the database. IPIN and OPIN rr_nodes
should already be present from the input rr_graph.
... | en | 0.717452 | #!/usr/bin/env python3 Imports 7-series routing fabric to the rr graph. For ROI configurations, this also connects the synthetic IO tiles to the routing node specified. Rough structure: Add rr_nodes for CHANX and CHANY from the database. IPIN and OPIN rr_nodes should already be present from the input rr_graph. Cre... | 1.901749 | 2 |
testing/onQuest/longClusters/m67/OLD-analyseEBLSSTm67.py | andrewbowen19/ClusterEclipsingBinaries | 0 | 2429 | #########################
#########################
# Need to account for limit in input period
#########################
#########################
# Baseline M67 long script -- NO crowding
# New script copied from quest - want to take p and ecc from each population (all, obs, rec) and put them into separate file
# Do... | #########################
#########################
# Need to account for limit in input period
#########################
#########################
# Baseline M67 long script -- NO crowding
# New script copied from quest - want to take p and ecc from each population (all, obs, rec) and put them into separate file
# Do... | en | 0.586491 | ######################### ######################### # Need to account for limit in input period ######################### ######################### # Baseline M67 long script -- NO crowding # New script copied from quest - want to take p and ecc from each population (all, obs, rec) and put them into separate file # Doi... | 2.04495 | 2 |
CondTools/BeamSpot/test/BeamSpotRcdPrinter_cfg.py | ckamtsikis/cmssw | 13 | 2430 | <filename>CondTools/BeamSpot/test/BeamSpotRcdPrinter_cfg.py
import FWCore.ParameterSet.Config as cms
import os
process = cms.Process("summary")
process.MessageLogger = cms.Service( "MessageLogger",
debugModules = cms.untracked.vstring( "*" ),
c... | <filename>CondTools/BeamSpot/test/BeamSpotRcdPrinter_cfg.py
import FWCore.ParameterSet.Config as cms
import os
process = cms.Process("summary")
process.MessageLogger = cms.Service( "MessageLogger",
debugModules = cms.untracked.vstring( "*" ),
c... | en | 0.311298 | ### 2018 Prompt ### 2017 ReReco #process.BeamSpotRcdPrinter.tagName = "BeamSpotObjects_LumiBased_v4_offline" #process.BeamSpotRcdPrinter.startIOV = 1275820035276801 #process.BeamSpotRcdPrinter.endIOV = 1316235677532161 ### 2018 ABC ReReco #process.BeamSpotRcdPrinter.tagName = "BeamSpotObjects_LumiBased_v4_offline" ... | 1.445169 | 1 |
django/authentication/api/urls.py | NAVANEETHA-BS/Django-Reactjs-Redux-Register-login-logout-Homepage--Project | 2 | 2431 | from django.urls import path
from rest_framework_simplejwt.views import (
TokenObtainPairView,
TokenRefreshView,
TokenVerifyView
)
urlpatterns = [
path('obtain/', TokenObtainPairView.as_view(), name='token_obtain_pair'),
path('refresh/', TokenRefreshView.as_view(), name='token_refresh'),
path('... | from django.urls import path
from rest_framework_simplejwt.views import (
TokenObtainPairView,
TokenRefreshView,
TokenVerifyView
)
urlpatterns = [
path('obtain/', TokenObtainPairView.as_view(), name='token_obtain_pair'),
path('refresh/', TokenRefreshView.as_view(), name='token_refresh'),
path('... | none | 1 | 1.801729 | 2 | |
yue/core/explorer/ftpsource.py | nsetzer/YueMusicPlayer | 0 | 2432 | <filename>yue/core/explorer/ftpsource.py
from ftplib import FTP,error_perm, all_errors
import posixpath
from io import BytesIO,SEEK_SET
from .source import DataSource
import sys
import re
reftp = re.compile('(ssh|ftp)\:\/\/(([^@:]+)?:?([^@]+)?@)?([^:]+)(:[0-9]+)?\/(.*)')
def parseFTPurl( url ):
m = reftp.match(... | <filename>yue/core/explorer/ftpsource.py
from ftplib import FTP,error_perm, all_errors
import posixpath
from io import BytesIO,SEEK_SET
from .source import DataSource
import sys
import re
reftp = re.compile('(ssh|ftp)\:\/\/(([^@:]+)?:?([^@]+)?@)?([^:]+)(:[0-9]+)?\/(.*)')
def parseFTPurl( url ):
m = reftp.match(... | en | 0.828503 | # ftp port default docstring for FTPWriter docstring for FTPWriter # open the file there is some sort of problem with utf-8/latin-1 and ftplib storbinary must accepts a STRING, since it builds a cmd and add the CRLF to the input argument using the plus operator. the command fails when given unicode text (... | 2.574807 | 3 |
tests/engine/knowledge_base.py | roshanmaskey/plaso | 1,253 | 2433 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Tests for the knowledge base."""
import unittest
from plaso.containers import artifacts
from plaso.engine import knowledge_base
from tests import test_lib as shared_test_lib
class KnowledgeBaseTest(shared_test_lib.BaseTestCase):
"""Tests for the knowledge base.""... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Tests for the knowledge base."""
import unittest
from plaso.containers import artifacts
from plaso.engine import knowledge_base
from tests import test_lib as shared_test_lib
class KnowledgeBaseTest(shared_test_lib.BaseTestCase):
"""Tests for the knowledge base.""... | en | 0.582862 | #!/usr/bin/env python3 # -*- coding: utf-8 -*- Tests for the knowledge base. Tests for the knowledge base. # pylint: disable=protected-access Sets the user accounts in the knowledge base. Args: knowledge_base_object (KnowledgeBase): knowledge base. users (list[dict[str,str])): users. Tests the codepage... | 1.917507 | 2 |
Problems/Dynamic Programming/140. Word Break II.py | BYJRK/LeetCode-Solutions | 0 | 2434 | <filename>Problems/Dynamic Programming/140. Word Break II.py
# https://leetcode.com/problems/word-break-ii/
from typing import List
class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> List[str]:
# 做一个快速的检查,如果 s 中存在所有 word 都不包含的字母,则直接退出
set1 = set(s)
set2 = set(''.join(wor... | <filename>Problems/Dynamic Programming/140. Word Break II.py
# https://leetcode.com/problems/word-break-ii/
from typing import List
class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> List[str]:
# 做一个快速的检查,如果 s 中存在所有 word 都不包含的字母,则直接退出
set1 = set(s)
set2 = set(''.join(wor... | zh | 0.629154 | # https://leetcode.com/problems/word-break-ii/ # 做一个快速的检查,如果 s 中存在所有 word 都不包含的字母,则直接退出 # dp[i] 的意思是,子字符串 s[:i] 能以怎样的方式进行分割 # 如果是 [[]] 则表示开头 # 如果是 [None],则表示还没有访问到,或没有办法进行分割 # 如果是 [['a', 'b'], ['ab']] 则表示目前已经有两种方式拼出这个子字符串 # 如果当前子字符串无法分割,则跳过 # 将目前的所有方式全部添加到新的位置,并在每个的最后追加当前的单词 # text = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa... | 3.648441 | 4 |
neutron/tests/unit/db/test_migration.py | banhr/neutron | 1 | 2435 | <filename>neutron/tests/unit/db/test_migration.py
# Copyright 2012 New Dream Network, LLC (DreamHost)
# 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
#
# ... | <filename>neutron/tests/unit/db/test_migration.py
# Copyright 2012 New Dream Network, LLC (DreamHost)
# 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
#
# ... | en | 0.687519 | # Copyright 2012 New Dream Network, LLC (DreamHost) # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # ... | 1.793772 | 2 |
withdrawal/floor_ceiling.py | hoostus/prime-harvesting | 23 | 2436 | <filename>withdrawal/floor_ceiling.py<gh_stars>10-100
from decimal import Decimal
from .abc import WithdrawalStrategy
# Bengen's Floor-to-Ceiling, as described in McClung's Living Off Your Money
class FloorCeiling(WithdrawalStrategy):
def __init__(self, portfolio, harvest_strategy, rate=.05, floor=.9, ceiling=1.2... | <filename>withdrawal/floor_ceiling.py<gh_stars>10-100
from decimal import Decimal
from .abc import WithdrawalStrategy
# Bengen's Floor-to-Ceiling, as described in McClung's Living Off Your Money
class FloorCeiling(WithdrawalStrategy):
def __init__(self, portfolio, harvest_strategy, rate=.05, floor=.9, ceiling=1.2... | en | 0.944325 | # Bengen's Floor-to-Ceiling, as described in McClung's Living Off Your Money | 2.929908 | 3 |
20190426/6_BME280_WiFi/bme280.py | rcolistete/MicroPython_MiniCurso_ProjOrientado | 0 | 2437 | <reponame>rcolistete/MicroPython_MiniCurso_ProjOrientado
"""
MicroPython driver for Bosh BME280 temperature, pressure and humidity I2C sensor:
https://www.bosch-sensortec.com/bst/products/all_products/bme280
Authors: <NAME>, <NAME>
Version: 3.1.2 @ 2018/04
License: MIT License (https://opensource.org/licenses/MIT)
"""
... | """
MicroPython driver for Bosh BME280 temperature, pressure and humidity I2C sensor:
https://www.bosch-sensortec.com/bst/products/all_products/bme280
Authors: <NAME>, <NAME>
Version: 3.1.2 @ 2018/04
License: MIT License (https://opensource.org/licenses/MIT)
"""
import time
from ustruct import unpack, unpack_from
from... | en | 0.692356 | MicroPython driver for Bosh BME280 temperature, pressure and humidity I2C sensor: https://www.bosch-sensortec.com/bst/products/all_products/bme280 Authors: <NAME>, <NAME> Version: 3.1.2 @ 2018/04 License: MIT License (https://opensource.org/licenses/MIT) # BME280 default address # BME280_I2CADDR = 0x77 Get raw data and... | 2.980313 | 3 |
airflow/contrib/secrets/hashicorp_vault.py | colpal/airfloss | 0 | 2438 | #
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not... | #
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not... | en | 0.636416 | # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not... | 1.98014 | 2 |
Trajectory_Mining/Bag_of_Words/Comp_Corr_KD_CosDist/comp_dist_partialKD.py | AdamCoscia/eve-trajectory-mining | 0 | 2439 | <filename>Trajectory_Mining/Bag_of_Words/Comp_Corr_KD_CosDist/comp_dist_partialKD.py
# -*- coding: utf-8 -*-
"""Computes distance between killmails by text similarity.
Edit Distance Metrics
- Levenshtein Distance
- Damerau-Levenshtein Distance
- Jaro Distance
- Jaro-Winkler Distance
- Match Rating Approach Comparison
... | <filename>Trajectory_Mining/Bag_of_Words/Comp_Corr_KD_CosDist/comp_dist_partialKD.py
# -*- coding: utf-8 -*-
"""Computes distance between killmails by text similarity.
Edit Distance Metrics
- Levenshtein Distance
- Damerau-Levenshtein Distance
- Jaro Distance
- Jaro-Winkler Distance
- Match Rating Approach Comparison
... | en | 0.819667 | # -*- coding: utf-8 -*- Computes distance between killmails by text similarity. Edit Distance Metrics - Levenshtein Distance - Damerau-Levenshtein Distance - Jaro Distance - Jaro-Winkler Distance - Match Rating Approach Comparison - Hamming Distance Vector Distance Metrics - Jaccard Similarity - Cosine Distance Writ... | 2.337005 | 2 |
src/chess/utils.py | Dalkio/custom-alphazero | 0 | 2440 | import numpy as np
from itertools import product
from typing import List
from src.config import ConfigChess
from src.chess.board import Board
from src.chess.move import Move
def get_all_possible_moves() -> List[Move]:
all_possible_moves = set()
array = np.zeros((ConfigChess.board_size, ConfigChess.board_size... | import numpy as np
from itertools import product
from typing import List
from src.config import ConfigChess
from src.chess.board import Board
from src.chess.move import Move
def get_all_possible_moves() -> List[Move]:
all_possible_moves = set()
array = np.zeros((ConfigChess.board_size, ConfigChess.board_size... | en | 0.953196 | # underpromotion moves # no need to add castling moves: they have already be added with queen moves under UCI notation | 2.826725 | 3 |
multirotor.py | christymarc/mfac | 0 | 2441 | from random import gauss
class MultiRotor:
"""Simple vertical dynamics for a multirotor vehicle."""
GRAVITY = -9.81
def __init__(
self, altitude=10, velocity=0, mass=1.54, emc=10.0, dt=0.05, noise=0.1
):
"""
Args:
altitude (float): initial altitude of the vehicle... | from random import gauss
class MultiRotor:
"""Simple vertical dynamics for a multirotor vehicle."""
GRAVITY = -9.81
def __init__(
self, altitude=10, velocity=0, mass=1.54, emc=10.0, dt=0.05, noise=0.1
):
"""
Args:
altitude (float): initial altitude of the vehicle... | en | 0.716782 | Simple vertical dynamics for a multirotor vehicle. Args: altitude (float): initial altitude of the vehicle velocity (float): initial velocity of the vehicle mass (float): mass of the vehicle emc (float): electromechanical constant for the vehicle dt (float): s... | 3.588946 | 4 |
stpmex/client.py | cuenca-mx/stpmex-python | 37 | 2442 | <reponame>cuenca-mx/stpmex-python
import re
from typing import Any, ClassVar, Dict, List, NoReturn, Union
from cryptography.exceptions import UnsupportedAlgorithm
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization
from requests import Response, Session
fr... | import re
from typing import Any, ClassVar, Dict, List, NoReturn, Union
from cryptography.exceptions import UnsupportedAlgorithm
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization
from requests import Response, Session
from .exc import (
AccountDoesNo... | es | 0.897976 | # resources # Some responses are enveloped # STP regresa esta respuesta cuando se registra # una cuenta. No se levanta excepción porque # todas las cuentas pasan por este status. | 2.123698 | 2 |
aql/tests/types/aql_test_list_types.py | menify/sandbox | 0 | 2443 | import sys
import os.path
import timeit
sys.path.insert( 0, os.path.normpath(os.path.join( os.path.dirname( __file__ ), '..') ))
from aql_tests import skip, AqlTestCase, runLocalTests
from aql.util_types import UniqueList, SplitListType, List, ValueListType
#//=======================================================... | import sys
import os.path
import timeit
sys.path.insert( 0, os.path.normpath(os.path.join( os.path.dirname( __file__ ), '..') ))
from aql_tests import skip, AqlTestCase, runLocalTests
from aql.util_types import UniqueList, SplitListType, List, ValueListType
#//=======================================================... | fr | 0.383471 | #//===========================================================================// #//===========================================================================// #//===========================================================================// #//==========================================================================... | 2.434119 | 2 |
logger_application/logger.py | swatishayna/OnlineEDAAutomation | 1 | 2444 | <reponame>swatishayna/OnlineEDAAutomation<filename>logger_application/logger.py
from datetime import datetime
from src.utils import uploaded_file
import os
class App_Logger:
def __init__(self):
pass
def log(self, file_object, email, log_message, log_writer_id):
self.now = datetime.now()
... | from datetime import datetime
from src.utils import uploaded_file
import os
class App_Logger:
def __init__(self):
pass
def log(self, file_object, email, log_message, log_writer_id):
self.now = datetime.now()
self.date = self.now.date()
self.current_time = self.now.strftime("%H:... | none | 1 | 3.081333 | 3 | |
metasync/params.py | dstarikov/metavault | 1 | 2445 | # config params
KB = 1024
MB = 1024*KB
GB = 1024*MB
# name of meta root dir
META_DIR = ".metasync"
# batching time for daemon
SYNC_WAIT = 3
# blob size
BLOB_UNIT = 32*MB
# Increase of Paxos proposal number
PAXOS_PNUM_INC = 10
# authentication directory
import os
AUTH_DIR = os.path.join(os.path.expanduser("~"), "... | # config params
KB = 1024
MB = 1024*KB
GB = 1024*MB
# name of meta root dir
META_DIR = ".metasync"
# batching time for daemon
SYNC_WAIT = 3
# blob size
BLOB_UNIT = 32*MB
# Increase of Paxos proposal number
PAXOS_PNUM_INC = 10
# authentication directory
import os
AUTH_DIR = os.path.join(os.path.expanduser("~"), "... | en | 0.584463 | # config params # name of meta root dir # batching time for daemon # blob size # Increase of Paxos proposal number # authentication directory | 1.425633 | 1 |
py/tests/test_valid_parentheses.py | Dragonway/LeetCode | 0 | 2446 | import unittest
from py.tests.utils import test
from py import valid_parentheses as vp
class TestValidParentheses(unittest.TestCase):
@test(vp.Solution.is_valid)
def test_valid_parentheses(self) -> None:
test("()", result=True)
test("()[]{}", result=True)
test("(]", ... | import unittest
from py.tests.utils import test
from py import valid_parentheses as vp
class TestValidParentheses(unittest.TestCase):
@test(vp.Solution.is_valid)
def test_valid_parentheses(self) -> None:
test("()", result=True)
test("()[]{}", result=True)
test("(]", ... | none | 1 | 3.151062 | 3 | |
hitnet/hitnet.py | AchintyaSrivastava/HITNET-Stereo-Depth-estimation | 38 | 2447 | <reponame>AchintyaSrivastava/HITNET-Stereo-Depth-estimation
import tensorflow as tf
import numpy as np
import time
import cv2
from hitnet.utils_hitnet import *
drivingStereo_config = CameraConfig(0.546, 1000)
class HitNet():
def __init__(self, model_path, model_type=ModelType.eth3d, camera_config=drivingStereo_con... | import tensorflow as tf
import numpy as np
import time
import cv2
from hitnet.utils_hitnet import *
drivingStereo_config = CameraConfig(0.546, 1000)
class HitNet():
def __init__(self, model_path, model_type=ModelType.eth3d, camera_config=drivingStereo_config):
self.fps = 0
self.timeLastPrediction = time.time(... | en | 0.828289 | # Initialize model # Wrap frozen graph to ConcreteFunctions # Perform inference on the image # Shape (1, None, None, 2) # Shape (1, None, None, 6) | 2.291946 | 2 |
fobi_custom/plugins/form_elements/fields/intercept/household_tenure/fobi_form_elements.py | datamade/just-spaces | 6 | 2448 | from django import forms
from fobi.base import FormFieldPlugin, form_element_plugin_registry
from .forms import HouseholdTenureForm
class HouseholdTenurePlugin(FormFieldPlugin):
"""HouseholdTenurePlugin."""
uid = "household_tenure"
name = "What year did you move into your current address?"
form = H... | from django import forms
from fobi.base import FormFieldPlugin, form_element_plugin_registry
from .forms import HouseholdTenureForm
class HouseholdTenurePlugin(FormFieldPlugin):
"""HouseholdTenurePlugin."""
uid = "household_tenure"
name = "What year did you move into your current address?"
form = H... | en | 0.937373 | HouseholdTenurePlugin. # Group to which the plugin belongs to | 2.148731 | 2 |
utils/scripts/OOOlevelGen/src/sprites/__init__.py | fullscreennl/monkeyswipe | 0 | 2449 | <gh_stars>0
__all__ = ['EnemyBucketWithStar',
'Nut',
'Beam',
'Enemy',
'Friend',
'Hero',
'Launcher',
'Rotor',
'SpikeyBuddy',
'Star',
'Wizard',
'EnemyEquipedRotor',
'CyclingEnemyObject',
... | __all__ = ['EnemyBucketWithStar',
'Nut',
'Beam',
'Enemy',
'Friend',
'Hero',
'Launcher',
'Rotor',
'SpikeyBuddy',
'Star',
'Wizard',
'EnemyEquipedRotor',
'CyclingEnemyObject',
'Joi... | none | 1 | 1.212242 | 1 | |
code/trainer.py | mazzaAnt/StackGAN-v2 | 1 | 2450 | <reponame>mazzaAnt/StackGAN-v2<gh_stars>1-10
from __future__ import print_function
from six.moves import range
import torchvision.transforms as transforms
import torch.backends.cudnn as cudnn
import torch
import torch.nn as nn
from torch.autograd import Variable
import torch.optim as optim
import torchvision.utils as ... | from __future__ import print_function
from six.moves import range
import torchvision.transforms as transforms
import torch.backends.cudnn as cudnn
import torch
import torch.nn as nn
from torch.autograd import Variable
import torch.optim as optim
import torchvision.utils as vutils
import numpy as np
import os
import ti... | en | 0.249643 | # ################## Shared functions ################### # batch_size * channel_num * 1 * 1 # batch_size * channel_num * num_pixels # batch_size * num_pixels * channel_num # batch_size * channel_num * channel_num # -0.5 * sum(1 + log(sigma^2) - mu^2 - sigma^2) # print('predictions', predictions.shape) # print('predict... | 1.99827 | 2 |
spletni_vmesnik.py | LeaHolc/recepcija | 1 | 2451 | from bottle import TEMPLATE_PATH, route, run, template, redirect, get, post, request, response, auth_basic, Bottle, abort, error, static_file
import bottle
import controller
from controller import dobi_parcele_za_prikaz, dobi_info_parcele, dodaj_gosta_na_rezervacijo, naredi_rezervacijo, dobi_rezervacijo_po_id, zakljuci... | from bottle import TEMPLATE_PATH, route, run, template, redirect, get, post, request, response, auth_basic, Bottle, abort, error, static_file
import bottle
import controller
from controller import dobi_parcele_za_prikaz, dobi_info_parcele, dodaj_gosta_na_rezervacijo, naredi_rezervacijo, dobi_rezervacijo_po_id, zakljuci... | zh | 0.26621 | # Preberemo lastnosti iz forme #get("") #get("") #get("") #get("") #get("") #get("") #get("") # Preberemo lastnosti iz forme #get("") #get("") #get("") #get("") #get("") | 2.39864 | 2 |
espnet/nets/pytorch_backend/transducer/initializer.py | magictron/espnet | 2 | 2452 | <filename>espnet/nets/pytorch_backend/transducer/initializer.py<gh_stars>1-10
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Parameter initialization for transducer RNN/Transformer parts."""
import six
from espnet.nets.pytorch_backend.initialization import lecun_normal_init_parameters
from espnet.nets.pytorch_bac... | <filename>espnet/nets/pytorch_backend/transducer/initializer.py<gh_stars>1-10
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Parameter initialization for transducer RNN/Transformer parts."""
import six
from espnet.nets.pytorch_backend.initialization import lecun_normal_init_parameters
from espnet.nets.pytorch_bac... | en | 0.499107 | #!/usr/bin/env python3 # -*- coding: utf-8 -*- Parameter initialization for transducer RNN/Transformer parts. Initialize transducer model. Args: model (torch.nn.Module): transducer instance args (Namespace): argument Namespace containing options | 2.396741 | 2 |
evaluate.py | adelmassimo/EM-Algorithm-for-MMPP | 0 | 2453 | <filename>evaluate.py
import model
import numpy as np
import datasetReader as df
import main
# Number of traces loaded T
T = 1
# Generate traces
traces_factory = df.DatasetFactory()
traces_factory.createDataset(T)
traces = traces_factory.traces
P0 = np.matrix("[ .02 0;"
"0 0 0.5;"
"0 0... | <filename>evaluate.py
import model
import numpy as np
import datasetReader as df
import main
# Number of traces loaded T
T = 1
# Generate traces
traces_factory = df.DatasetFactory()
traces_factory.createDataset(T)
traces = traces_factory.traces
P0 = np.matrix("[ .02 0;"
"0 0 0.5;"
"0 0... | en | 0.604151 | # Number of traces loaded T # Generate traces # P = stored_p_values[i, :, :] | 2.677535 | 3 |
Imaging/Core/Testing/Python/TestHSVToRGB.py | forestGzh/VTK | 1,755 | 2454 | #!/usr/bin/env python
import vtk
from vtk.util.misc import vtkGetDataRoot
VTK_DATA_ROOT = vtkGetDataRoot()
# Use the painter to draw using colors.
# This is not a pipeline object. It will support pipeline objects.
# Please do not use this object directly.
imageCanvas = vtk.vtkImageCanvasSource2D()
imageCanvas.SetNumb... | #!/usr/bin/env python
import vtk
from vtk.util.misc import vtkGetDataRoot
VTK_DATA_ROOT = vtkGetDataRoot()
# Use the painter to draw using colors.
# This is not a pipeline object. It will support pipeline objects.
# Please do not use this object directly.
imageCanvas = vtk.vtkImageCanvasSource2D()
imageCanvas.SetNumb... | en | 0.749574 | #!/usr/bin/env python # Use the painter to draw using colors. # This is not a pipeline object. It will support pipeline objects. # Please do not use this object directly. # r, g, b # intensity scale # saturation scale #viewer SetInputConnection [imageCanvas GetOutputPort] # --- end of script -- | 2.219491 | 2 |
kelas_2b/echa.py | barizraihan/belajarpython | 0 | 2455 | <reponame>barizraihan/belajarpython
import csv
class echa:
def werehousing(self):
with open('kelas_2b/echa.csv', 'r') as csvfile:
csv_reader = csv.reader(csvfile, delimiter=',')
for row in csv_reader:
print("menampilkan data barang:", row[0], row[1], row[2], row[... | import csv
class echa:
def werehousing(self):
with open('kelas_2b/echa.csv', 'r') as csvfile:
csv_reader = csv.reader(csvfile, delimiter=',')
for row in csv_reader:
print("menampilkan data barang:", row[0], row[1], row[2], row[3], row[4]) | none | 1 | 3.363776 | 3 | |
tests/test_handler_surface_distance.py | dyollb/MONAI | 2,971 | 2456 | # Copyright 2020 - 2021 MONAI Consortium
# 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 wri... | # Copyright 2020 - 2021 MONAI Consortium
# 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 wri... | en | 0.796948 | # Copyright 2020 - 2021 MONAI Consortium # 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 wri... | 2.072646 | 2 |
benchmarks/eval.py | rom1mouret/anoflows | 0 | 2457 | #!/usr/bin/env python3
import sys
import logging
import yaml
import pandas as pd
import numpy as np
from collections import defaultdict
from sklearn.model_selection import train_test_split
from sklearn.ensemble import IsolationForest
from sklearn.impute import SimpleImputer
from anoflows.hpo import find_best_flows
... | #!/usr/bin/env python3
import sys
import logging
import yaml
import pandas as pd
import numpy as np
from collections import defaultdict
from sklearn.model_selection import train_test_split
from sklearn.ensemble import IsolationForest
from sklearn.impute import SimpleImputer
from anoflows.hpo import find_best_flows
... | en | 0.572778 | #!/usr/bin/env python3 # random sampling # imputing # train/test split # training #flows, loss = find_best_flows(X_train, device='cpu', n_trials=1) # prediction # evaluation | 2.408091 | 2 |
pydantic/version.py | jamescurtin/pydantic | 1 | 2458 | <reponame>jamescurtin/pydantic
__all__ = ['VERSION', 'version_info']
VERSION = '1.4a1'
def version_info() -> str:
import platform
import sys
from importlib import import_module
from pathlib import Path
from .main import compiled
optional_deps = []
for p in ('typing-extensions', 'email-v... | __all__ = ['VERSION', 'version_info']
VERSION = '1.4a1'
def version_info() -> str:
import platform
import sys
from importlib import import_module
from pathlib import Path
from .main import compiled
optional_deps = []
for p in ('typing-extensions', 'email-validator', 'devtools'):
... | none | 1 | 2.257515 | 2 | |
spire/core/registry.py | siq/spire | 0 | 2459 | <filename>spire/core/registry.py
from scheme import Structure
__all__ = ('Configurable', 'Registry')
class Configurable(object):
"""A sentry class which indicates that subclasses can establish a configuration chain."""
class Registry(object):
"""The unit registry."""
dependencies = {}
schemas = {}
... | <filename>spire/core/registry.py
from scheme import Structure
__all__ = ('Configurable', 'Registry')
class Configurable(object):
"""A sentry class which indicates that subclasses can establish a configuration chain."""
class Registry(object):
"""The unit registry."""
dependencies = {}
schemas = {}
... | en | 0.871353 | A sentry class which indicates that subclasses can establish a configuration chain. The unit registry. | 2.504235 | 3 |
oslo_devsupport/model/__init__.py | berrange/oslo.devsupport | 0 | 2460 | <filename>oslo_devsupport/model/__init__.py
from .command import *
from .database import *
from .entrypoint import *
from .group import *
from .http import *
from .messaging import *
from .method import *
from .operation import *
from .stack import *
from .threads import *
| <filename>oslo_devsupport/model/__init__.py
from .command import *
from .database import *
from .entrypoint import *
from .group import *
from .http import *
from .messaging import *
from .method import *
from .operation import *
from .stack import *
from .threads import *
| none | 1 | 1.184731 | 1 | |
scripts/extract.py | nng555/fairseq | 2 | 2461 | #!/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.
"""Extracts random constraints from reference files."""
import argparse
import random
import sys
from sacrebleu imp... | #!/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.
"""Extracts random constraints from reference files."""
import argparse
import random
import sys
from sacrebleu imp... | en | 0.868198 | #!/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. Extracts random constraints from reference files. # mask out with spaces | 2.895353 | 3 |
AppImageBuilder/commands/file.py | gouchi/appimage-builder | 0 | 2462 | <filename>AppImageBuilder/commands/file.py
# Copyright 2020 <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>AppImageBuilder/commands/file.py
# Copyright 2020 <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.882815 | # Copyright 2020 <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, distribute... | 2.38982 | 2 |
text_selection/analyse_zenon_scrape.py | dainst/chronoi-corpus-processing | 0 | 2463 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import argparse
import csv
import furl
import json
import re
import sys
from collections import defaultdict
def filter_records_without_url(records: []) -> []:
return [r for r in records if any(r.get("urls"))]
def build_furl(url: str) -> furl.furl:
try:
... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import argparse
import csv
import furl
import json
import re
import sys
from collections import defaultdict
def filter_records_without_url(records: []) -> []:
return [r for r in records if any(r.get("urls"))]
def build_furl(url: str) -> furl.furl:
try:
... | en | 0.912359 | #!/usr/bin/env python3 # -*- coding: utf-8 -*- # It should be ok, to only pattern match the hosts here... # filter urls by the user-provided filter list # print unique hosts or urls, then exit # check in how many records the two given hosts co-occur, then exit # do some selection based on a url pattern, remove all non-... | 2.908499 | 3 |
src/python/twitter/pants/targets/java_antlr_library.py | wfarner/commons | 1 | 2464 | # ==================================================================================================
# Copyright 2012 Twitter, Inc.
# --------------------------------------------------------------------------------------------------
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use thi... | # ==================================================================================================
# Copyright 2012 Twitter, Inc.
# --------------------------------------------------------------------------------------------------
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use thi... | en | 0.69262 | # ================================================================================================== # Copyright 2012 Twitter, Inc. # -------------------------------------------------------------------------------------------------- # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use thi... | 1.732804 | 2 |
bigml/tests/create_pca_steps_bck.py | devs-cloud/python_ml | 0 | 2465 | # -*- coding: utf-8 -*-
#!/usr/bin/env python
#
# Copyright 2018-2020 BigML
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requi... | # -*- coding: utf-8 -*-
#!/usr/bin/env python
#
# Copyright 2018-2020 BigML
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requi... | en | 0.767232 | # -*- coding: utf-8 -*- #!/usr/bin/env python # # Copyright 2018-2020 BigML # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requi... | 2.227736 | 2 |
config.py | Pasmikh/quiz_please_bot | 0 | 2466 | <filename>config.py
days_of_week = ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday', 'Sunday']
operation = ''
options = ['Info', 'Check-in/Out', 'Edit games', 'Back']
admins = ['admin1_telegram_nickname', 'admin2_telegram_nickname']
avail_days = []
TOKEN = 'bot_<PASSWORD>'
group_id = id_of_group_chat | <filename>config.py
days_of_week = ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday', 'Sunday']
operation = ''
options = ['Info', 'Check-in/Out', 'Edit games', 'Back']
admins = ['admin1_telegram_nickname', 'admin2_telegram_nickname']
avail_days = []
TOKEN = 'bot_<PASSWORD>'
group_id = id_of_group_chat | none | 1 | 1.626503 | 2 | |
Chapter 8/sandwich-maker.py | ostin-r/automate-boring-stuff-solutions | 4 | 2467 | '''
<NAME> 2/20/21
sandwich-maker.py uses pyinputplus to validate user input for sandwich preferences
'''
import pyinputplus as ip
def get_cost(food_name):
'''gets the cost of items in sandwich_builder'''
food_dict = {
'sourdough':1.75,
'rye':2.0,
'wheat':1.50,
'white':1.25,... | '''
<NAME> 2/20/21
sandwich-maker.py uses pyinputplus to validate user input for sandwich preferences
'''
import pyinputplus as ip
def get_cost(food_name):
'''gets the cost of items in sandwich_builder'''
food_dict = {
'sourdough':1.75,
'rye':2.0,
'wheat':1.50,
'white':1.25,... | en | 0.771945 | <NAME> 2/20/21 sandwich-maker.py uses pyinputplus to validate user input for sandwich preferences gets the cost of items in sandwich_builder # toppings return 'yes' in sandwich_builder(), so I made them all cost 0.25 # saying no to a topping costs nothing | 3.951078 | 4 |
tests/core/test_headerupdater.py | My-Novel-Management/storybuilderunite | 1 | 2468 | <filename>tests/core/test_headerupdater.py
# -*- coding: utf-8 -*-
'''
HeaderUpdater class test
========================
'''
import unittest
from tests.testutils import print_testtitle, validate_with_fail
from builder.commands.scode import SCode, SCmd
from builder.containers.chapter import Chapter
from builder.contain... | <filename>tests/core/test_headerupdater.py
# -*- coding: utf-8 -*-
'''
HeaderUpdater class test
========================
'''
import unittest
from tests.testutils import print_testtitle, validate_with_fail
from builder.commands.scode import SCode, SCmd
from builder.containers.chapter import Chapter
from builder.contain... | en | 0.555048 | # -*- coding: utf-8 -*- HeaderUpdater class test ======================== # (src, expect, exp_opt) # (src, expect) # (src, expect) | 2.647287 | 3 |
dotsDB/test_vlen_datasets.py | aernesto/Lab_DotsDB_Utilities | 1 | 2469 | <gh_stars>1-10
import numpy as np
import h5py
filename = "test_vlen_datasets_np_bool.h5"
rows = [np.array([np.True_, np.False_]),
np.array([np.True_, np.True_, np.False_])]
f = h5py.File(filename, 'x') # create file, fails if exists
vlen_data_type = h5py.special_dtype(vlen=np.bool_)
dset = f.create_dataset... | import numpy as np
import h5py
filename = "test_vlen_datasets_np_bool.h5"
rows = [np.array([np.True_, np.False_]),
np.array([np.True_, np.True_, np.False_])]
f = h5py.File(filename, 'x') # create file, fails if exists
vlen_data_type = h5py.special_dtype(vlen=np.bool_)
dset = f.create_dataset("vlen_matrix",... | en | 0.284329 | # create file, fails if exists | 2.79874 | 3 |
utils.py | g4idrijs/CardiacUltrasoundPhaseEstimation | 1 | 2470 | import os, time
import numpy as np
import scipy.signal
import scipy.misc
import scipy.ndimage.filters
import matplotlib.pyplot as plt
import PIL
from PIL import ImageDraw
import angles
import cv2
import SimpleITK as sitk
def cvShowImage(imDisp, strName, strAnnotation='', textColor=(0, 0, 255),
r... | import os, time
import numpy as np
import scipy.signal
import scipy.misc
import scipy.ndimage.filters
import matplotlib.pyplot as plt
import PIL
from PIL import ImageDraw
import angles
import cv2
import SimpleITK as sitk
def cvShowImage(imDisp, strName, strAnnotation='', textColor=(0, 0, 255),
r... | en | 0.554721 | # find max number of frames # display video # resize image if requested # show image # look for "esc" key # escape # space # left arrow # right arrow # print metadata # smooth if wanted # read video frames # update progress # start timer # write video # fourcc = cv2.FOURCC(*list(codec)) # opencv 2.4 # end timer # re... | 2.41364 | 2 |
weasyl/emailer.py | akash143143/weasyl | 0 | 2471 | <filename>weasyl/emailer.py
from __future__ import absolute_import
import re
from email.mime.text import MIMEText
from smtplib import SMTP
from weasyl import define, macro
EMAIL_ADDRESS = re.compile(r"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+\Z")
def normalize_address(address):
"""
Converts an e-mai... | <filename>weasyl/emailer.py
from __future__ import absolute_import
import re
from email.mime.text import MIMEText
from smtplib import SMTP
from weasyl import define, macro
EMAIL_ADDRESS = re.compile(r"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+\Z")
def normalize_address(address):
"""
Converts an e-mai... | en | 0.829938 | Converts an e-mail address to a consistent representation. Returns None if the given address is not considered valid. Send an e-mail. `mailto` must be a normalized e-mail address to send this e-mail to. The system email will be designated as the sender. # smtp.sendmail() only converts CR and LF (produced b... | 2.998392 | 3 |
tests/test_missing_process.py | ricklupton/sphinx_probs_rdf | 1 | 2472 | <filename>tests/test_missing_process.py
import pytest
from rdflib import Graph, Namespace, Literal
from rdflib.namespace import RDF, RDFS
from sphinx_probs_rdf.directives import PROBS
SYS = Namespace("http://example.org/system/")
@pytest.mark.sphinx(
'probs_rdf', testroot='missing',
confoverrides={'probs_rdf... | <filename>tests/test_missing_process.py
import pytest
from rdflib import Graph, Namespace, Literal
from rdflib.namespace import RDF, RDFS
from sphinx_probs_rdf.directives import PROBS
SYS = Namespace("http://example.org/system/")
@pytest.mark.sphinx(
'probs_rdf', testroot='missing',
confoverrides={'probs_rdf... | none | 1 | 2.145797 | 2 | |
analysis_functionarcademix.py | thekushalpokhrel/Python_Programs_SoftDev_DataAnalysis | 0 | 2473 | <reponame>thekushalpokhrel/Python_Programs_SoftDev_DataAnalysis
#analysis function for three level game
def stat_analysis(c1,c2,c3):
#ask question for viewing analysis of game
analysis=input('\nDo you want to see your game analysis? (Yes/No) ')
if analysis=='Yes':
levels=['Level 1','Level 2','Level... | #analysis function for three level game
def stat_analysis(c1,c2,c3):
#ask question for viewing analysis of game
analysis=input('\nDo you want to see your game analysis? (Yes/No) ')
if analysis=='Yes':
levels=['Level 1','Level 2','Level 3']
#calculating the score of levels
l... | en | 0.603305 | #analysis function for three level game #ask question for viewing analysis of game #calculating the score of levels #plot bar chart #add title #set x-axis label #set y-axis label #find mean value #find median value #Mode calculation #create numPy array of values with only one mode #find unique values in array along wit... | 3.860651 | 4 |
Hello_Cone.py | TechnoTanuki/Python_BMP | 3 | 2474 | notice = """
Cone Demo
-----------------------------------
| Copyright 2022 by <NAME> |
| [<EMAIL>] |
|-----------------------------------|
| We make absolutely no warranty |
| of any kind, expressed or implied |
|-----------------------------------|
| This graphics library outputs |... | notice = """
Cone Demo
-----------------------------------
| Copyright 2022 by <NAME> |
| [<EMAIL>] |
|-----------------------------------|
| We make absolutely no warranty |
| of any kind, expressed or implied |
|-----------------------------------|
| This graphics library outputs |... | en | 0.681471 | Cone Demo
-----------------------------------
| Copyright 2022 by <NAME> |
| [<EMAIL>] |
|-----------------------------------|
| We make absolutely no warranty |
| of any kind, expressed or implied |
|-----------------------------------|
| This graphics library outputs |
| to a bitmap file. ... | 2.16724 | 2 |
analysis/training_curve_6D.py | AndrewKirby2/data_synthesis | 0 | 2475 | <reponame>AndrewKirby2/data_synthesis
""" Plot a training curve for the 6D data simulator of CT*
"""
import numpy as np
import matplotlib.pyplot as plt
from sklearn.preprocessing import StandardScaler
from sklearn.gaussian_process import GaussianProcessRegressor
from sklearn.gaussian_process.kernels import RBF, WhiteK... | """ Plot a training curve for the 6D data simulator of CT*
"""
import numpy as np
import matplotlib.pyplot as plt
from sklearn.preprocessing import StandardScaler
from sklearn.gaussian_process import GaussianProcessRegressor
from sklearn.gaussian_process.kernels import RBF, WhiteKernel, Matern
from sklearn.metrics imp... | en | 0.683566 | Plot a training curve for the 6D data simulator of CT* # create array to store results for plotting # create array of sampled regular array layouts #cand_points = regular_array_monte_carlo(10000) # create testing points # create training points # fit GP regression and calculate rmse # report rmse | 3.047212 | 3 |
website/raspac.py | tpudlik/RaspAC | 28 | 2476 | import sqlite3
import subprocess, datetime
from flask import Flask, request, session, g, redirect, url_for, \
abort, render_template, flash
from contextlib import closing
from tquery import get_latest_record
from config import *
app = Flask(__name__)
app.config.from_object(__name__)... | import sqlite3
import subprocess, datetime
from flask import Flask, request, session, g, redirect, url_for, \
abort, render_template, flash
from contextlib import closing
from tquery import get_latest_record
from config import *
app = Flask(__name__)
app.config.from_object(__name__)... | en | 0.90032 | # DB helper functions Initializes the sqlite3 database. This function must be imported and executed from the Python interpreter before the application is first run. # Auto-open and close DB when serving requests # someone's logging in # successful login # command is being issued to AC Validates and sanitizes user-... | 2.532624 | 3 |
tests/util_test.py | NLESC-JCER/pyspectra | 1 | 2477 | """Helper functions to tests."""
import numpy as np
def norm(vs: np.array) -> float:
"""Compute the norm of a vector."""
return np.sqrt(np.dot(vs, vs))
def create_random_matrix(size: int) -> np.array:
"""Create a numpy random matrix."""
return np.random.normal(size=size ** 2).reshape(size, size)
... | """Helper functions to tests."""
import numpy as np
def norm(vs: np.array) -> float:
"""Compute the norm of a vector."""
return np.sqrt(np.dot(vs, vs))
def create_random_matrix(size: int) -> np.array:
"""Create a numpy random matrix."""
return np.random.normal(size=size ** 2).reshape(size, size)
... | en | 0.659557 | Helper functions to tests. Compute the norm of a vector. Create a numpy random matrix. Create a numpy symmetric matrix. Check that the eigenvalue equation holds. | 3.264582 | 3 |
solutions/Interview-03-shu-zu-zhong-zhong-fu-de-shu-zi-lcof/03.py | leetcode-notebook/wonz | 12 | 2478 | <filename>solutions/Interview-03-shu-zu-zhong-zhong-fu-de-shu-zi-lcof/03.py<gh_stars>10-100
from typing import List
class Solution:
def findRepeatNumber(self, nums: List[int]) -> int:
# solution one: 哈希表
n = len(nums)
flag = [False for i in range(n)]
for i in range(n):
i... | <filename>solutions/Interview-03-shu-zu-zhong-zhong-fu-de-shu-zi-lcof/03.py<gh_stars>10-100
from typing import List
class Solution:
def findRepeatNumber(self, nums: List[int]) -> int:
# solution one: 哈希表
n = len(nums)
flag = [False for i in range(n)]
for i in range(n):
i... | zh | 0.568189 | # solution one: 哈希表 # solution two: 排序 # solution three: 两个萝卜一个坑 # 有重复 # 交换 | 3.575796 | 4 |
examples/test_network.py | Charles-Peeke/gwu_nn | 4 | 2479 | <reponame>Charles-Peeke/gwu_nn<gh_stars>1-10
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from gwu_nn.gwu_network import GWUNetwork
from gwu_nn.layers import Dense
from gwu_nn.activation_layers import Sigmoid
np.random.seed(8)
num_obs = 8000
# Cre... | import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from gwu_nn.gwu_network import GWUNetwork
from gwu_nn.layers import Dense
from gwu_nn.activation_layers import Sigmoid
np.random.seed(8)
num_obs = 8000
# Create our features to draw from two distinct 2D... | en | 0.740471 | # Create our features to draw from two distinct 2D normal distributions # Stack our inputs into one feature space # colors = ['red'] * num_obs + ['blue'] * num_obs # plt.figure(figsize=(12,8)) # plt.scatter(X[:, 0], X[:, 1], c = colors, alpha = 0.5) # Lets randomly split things into training and testing sets so we don'... | 3.035791 | 3 |
scattering/van_hove.py | XiaoboLinlin/scattering | 0 | 2480 | <reponame>XiaoboLinlin/scattering
import itertools as it
import numpy as np
import mdtraj as md
from progressbar import ProgressBar
from scattering.utils.utils import get_dt
from scattering.utils.constants import get_form_factor
def compute_van_hove(trj, chunk_length, water=False,
r_range=(0, 1... | import itertools as it
import numpy as np
import mdtraj as md
from progressbar import ProgressBar
from scattering.utils.utils import get_dt
from scattering.utils.constants import get_form_factor
def compute_van_hove(trj, chunk_length, water=False,
r_range=(0, 1.0), bin_width=0.005, n_bins=None,... | en | 0.63595 | Compute the partial van Hove function of a trajectory Parameters ---------- trj : mdtraj.Trajectory trajectory on which to compute the Van Hove function chunk_length : int length of time between restarting averaging water : bool use X-ray form factors for water that account ... | 2.518263 | 3 |
nn_benchmark/networks/__init__.py | QDucasse/nn_benchmark | 18 | 2481 | # -*- coding: utf-8 -*-
# nn_benchmark
# author - <NAME>
# https://github.com/QDucasse
# <EMAIL>
from __future__ import absolute_import
__all__ = ["lenet","lenet5","quant_lenet5",
"quant_cnv", "quant_tfc",
"mobilenetv1","quant_mobilenetv1",
"vggnet", "quant_vggnet",
"commo... | # -*- coding: utf-8 -*-
# nn_benchmark
# author - <NAME>
# https://github.com/QDucasse
# <EMAIL>
from __future__ import absolute_import
__all__ = ["lenet","lenet5","quant_lenet5",
"quant_cnv", "quant_tfc",
"mobilenetv1","quant_mobilenetv1",
"vggnet", "quant_vggnet",
"commo... | en | 0.527015 | # -*- coding: utf-8 -*- # nn_benchmark # author - <NAME> # https://github.com/QDucasse # <EMAIL> | 1.169783 | 1 |
Section1_Basics/contours.py | NeeharikaDva/opencv_course | 0 | 2482 | #pylint:disable=no-member
import cv2 as cv
import numpy as np
img = cv.imread('/Users/webileapp/Desktop/niharika_files/projects/opencv_course_master/Resources/Photos/cats.jpg')
cv.imshow('Cats', img)
#
blank = np.zeros(img.shape[:2], dtype='uint8')
cv.imshow('Blank', blank)
gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)... | #pylint:disable=no-member
import cv2 as cv
import numpy as np
img = cv.imread('/Users/webileapp/Desktop/niharika_files/projects/opencv_course_master/Resources/Photos/cats.jpg')
cv.imshow('Cats', img)
#
blank = np.zeros(img.shape[:2], dtype='uint8')
cv.imshow('Blank', blank)
gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)... | en | 0.354153 | #pylint:disable=no-member # # # # # | 2.818004 | 3 |
mmdet/ops/fcosr_tools/__init__.py | RangeKing/FCOSR | 38 | 2483 | from . import fcosr_tools
__all__ = ['fcosr_tools'] | from . import fcosr_tools
__all__ = ['fcosr_tools'] | none | 1 | 1.120788 | 1 | |
health_care/health_care/doctype/practitioner/practitioner.py | Jnalis/frappe-health-care | 0 | 2484 | # Copyright (c) 2022, Juve and contributors
# For license information, please see license.txt
# import frappe
from frappe.model.document import Document
class Practitioner(Document):
def before_save(self):
self.practitioner_full_name = f'{self.first_name} {self.second_name or ""}'
| # Copyright (c) 2022, Juve and contributors
# For license information, please see license.txt
# import frappe
from frappe.model.document import Document
class Practitioner(Document):
def before_save(self):
self.practitioner_full_name = f'{self.first_name} {self.second_name or ""}'
| en | 0.64678 | # Copyright (c) 2022, Juve and contributors # For license information, please see license.txt # import frappe | 1.984837 | 2 |
install-hooks.py | JustasGau/DonjinKrawler | 0 | 2485 | <reponame>JustasGau/DonjinKrawler
import sys
from os import path
import urllib; from urllib.request import urlretrieve
from subprocess import call
def install_hooks(directory):
checkstyleUrl = 'https://github.com/checkstyle/checkstyle/releases/download/checkstyle-8.36.1/checkstyle-8.36.1-all.jar'
preCommitUrl ... | import sys
from os import path
import urllib; from urllib.request import urlretrieve
from subprocess import call
def install_hooks(directory):
checkstyleUrl = 'https://github.com/checkstyle/checkstyle/releases/download/checkstyle-8.36.1/checkstyle-8.36.1-all.jar'
preCommitUrl = 'https://gist.githubusercontent.... | none | 1 | 2.349872 | 2 | |
09_MicroServer_Cookies/micro_server.py | Rockfish/PythonCourse | 0 | 2486 | """
Micro webapp based on WebOb, Jinja2, WSGI with a simple router
"""
import os
import hmac
import hashlib
import mimetypes
from wsgiref.simple_server import WSGIServer, WSGIRequestHandler
from webob import Request
from webob import Response
from jinja2 import Environment, FileSystemLoader
class MicroServer(obje... | """
Micro webapp based on WebOb, Jinja2, WSGI with a simple router
"""
import os
import hmac
import hashlib
import mimetypes
from wsgiref.simple_server import WSGIServer, WSGIRequestHandler
from webob import Request
from webob import Response
from jinja2 import Environment, FileSystemLoader
class MicroServer(obje... | en | 0.859375 | Micro webapp based on WebOb, Jinja2, WSGI with a simple router Small web server. Initializes the class and configures the paths and the Jinja2 environment so it can find and render pages. # Set up the paths and environment for Jinja. This is how it finds the templates. # Figure out what directory the server is ... | 3.13793 | 3 |
apps/addons/management/commands/jetpackers.py | clouserw/olympia | 1 | 2487 | import logging
from django.core import mail
from django.conf import settings
from django.core.management.base import BaseCommand
import amo.utils
from users.models import UserProfile
log = logging.getLogger('z.mailer')
FROM = settings.DEFAULT_FROM_EMAIL
class Command(BaseCommand):
help = "Send the email for bu... | import logging
from django.core import mail
from django.conf import settings
from django.core.management.base import BaseCommand
import amo.utils
from users.models import UserProfile
log = logging.getLogger('z.mailer')
FROM = settings.DEFAULT_FROM_EMAIL
class Command(BaseCommand):
help = "Send the email for bu... | en | 0.834909 | # whoa \ Hello Mozilla Add-ons Developer! With the final version of the Add-on SDK only a week away, we wanted to get in touch with all add-on developers who have existing SDK-based (Jetpack) add-ons. We would like you to know that going forward AMO will be auto-updating add-ons with new versions of the Add-on SDK up... | 2.040756 | 2 |
astroplan/constraints.py | edose/astroplan | 160 | 2488 | <gh_stars>100-1000
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
Specify and constraints to determine which targets are observable for
an observer.
"""
from __future__ import (absolute_import, division, print_function,
unicode_literals)
# Standard library
from abc import ... | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
Specify and constraints to determine which targets are observable for
an observer.
"""
from __future__ import (absolute_import, division, print_function,
unicode_literals)
# Standard library
from abc import ABCMeta, abstractme... | en | 0.734457 | # Licensed under a 3-clause BSD style license - see LICENSE.rst Specify and constraints to determine which targets are observable for an observer. # Standard library # Third-party # Package # needed for backward compatibility # needed for backward compatibility Make a unique key to reference this combination of ``times... | 1.865166 | 2 |
backend/views.py | Raulios/django-blog | 0 | 2489 | from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.core.urlresolvers import reverse
from django.shortcuts import render
from django.http import HttpResponseRedirect
from core.models import Po... | from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.core.urlresolvers import reverse
from django.shortcuts import render
from django.http import HttpResponseRedirect
from core.models import Po... | en | 0.968116 | # Create your views here. | 2.129731 | 2 |
tiktorch/server/session/process.py | FynnBe/tiktorch | 0 | 2490 | import dataclasses
import io
import multiprocessing as _mp
import uuid
import zipfile
from concurrent.futures import Future
from multiprocessing.connection import Connection
from typing import List, Optional, Tuple
import numpy
from tiktorch import log
from tiktorch.rpc import Shutdown
from tiktorch.rpc import mp as ... | import dataclasses
import io
import multiprocessing as _mp
import uuid
import zipfile
from concurrent.futures import Future
from multiprocessing.connection import Connection
from typing import List, Optional, Tuple
import numpy
from tiktorch import log
from tiktorch.rpc import Shutdown
from tiktorch.rpc import mp as ... | en | 0.681081 | # TODO: Test for model info # from: https://github.com/pytorch/pytorch/issues/973#issuecomment-346405667 # probably running on windows | 2.164341 | 2 |
openpype/modules/ftrack/event_handlers_server/event_del_avalon_id_from_new.py | dangerstudios/OpenPype | 0 | 2491 | from openpype.modules.ftrack.lib import BaseEvent
from openpype.modules.ftrack.lib.avalon_sync import CUST_ATTR_ID_KEY
from openpype.modules.ftrack.event_handlers_server.event_sync_to_avalon import (
SyncToAvalonEvent
)
class DelAvalonIdFromNew(BaseEvent):
'''
This event removes AvalonId from custom attri... | from openpype.modules.ftrack.lib import BaseEvent
from openpype.modules.ftrack.lib.avalon_sync import CUST_ATTR_ID_KEY
from openpype.modules.ftrack.event_handlers_server.event_sync_to_avalon import (
SyncToAvalonEvent
)
class DelAvalonIdFromNew(BaseEvent):
'''
This event removes AvalonId from custom attri... | en | 0.927259 | This event removes AvalonId from custom attributes of new entities Result: - 'Copy->Pasted' entities won't have same AvalonID as source entity Priority of this event must be less than SyncToAvalon event Register plugin. Called when used as an plugin. | 1.68258 | 2 |
tests/workflow/test_workflow_ingest_accepted_submission.py | elifesciences/elife-bot | 17 | 2492 | import unittest
import tests.settings_mock as settings_mock
from tests.activity.classes_mock import FakeLogger
from workflow.workflow_IngestAcceptedSubmission import workflow_IngestAcceptedSubmission
class TestWorkflowIngestAcceptedSubmission(unittest.TestCase):
def setUp(self):
self.workflow = workflow_I... | import unittest
import tests.settings_mock as settings_mock
from tests.activity.classes_mock import FakeLogger
from workflow.workflow_IngestAcceptedSubmission import workflow_IngestAcceptedSubmission
class TestWorkflowIngestAcceptedSubmission(unittest.TestCase):
def setUp(self):
self.workflow = workflow_I... | none | 1 | 2.579767 | 3 | |
go/token/views.py | lynnUg/vumi-go | 0 | 2493 | from urllib import urlencode
import urlparse
from django.shortcuts import Http404, redirect
from django.contrib.auth.views import logout
from django.contrib import messages
from django.core.urlresolvers import reverse
from django.contrib.auth.decorators import login_required
from vumi.utils import load_class_by_strin... | from urllib import urlencode
import urlparse
from django.shortcuts import Http404, redirect
from django.contrib.auth.views import logout
from django.contrib import messages
from django.core.urlresolvers import reverse
from django.contrib.auth.decorators import login_required
from vumi.utils import load_class_by_strin... | en | 0.875688 | # We only need the redis manager here, but it's saner to get a whole # vumi_api and not worry about all the setup magic. # If we're authorized and we're the same user_id then redirect to # where we need to be # since the token can be custom we prepend the size of the user_token # to the token being forwarded so the vie... | 2.131202 | 2 |
typogrify/templatetags/typogrify_tags.py | tylerbutler/typogrify | 0 | 2494 | from typogrify.filters import amp, caps, initial_quotes, smartypants, titlecase, typogrify, widont, TypogrifyError
from functools import wraps
from django.conf import settings
from django import template
from django.utils.safestring import mark_safe
from django.utils.encoding import force_unicode
register = template.... | from typogrify.filters import amp, caps, initial_quotes, smartypants, titlecase, typogrify, widont, TypogrifyError
from functools import wraps
from django.conf import settings
from django import template
from django.utils.safestring import mark_safe
from django.utils.encoding import force_unicode
register = template.... | en | 0.623885 | A function wrapper to make typogrify play nice with django's unicode support. | 2.273825 | 2 |
bvbabel/vmr.py | carbrock/bvbabel | 7 | 2495 | """Read, write, create Brainvoyager VMR file format."""
import struct
import numpy as np
from bvbabel.utils import (read_variable_length_string,
write_variable_length_string)
# =============================================================================
def read_vmr(filename):
"""Read... | """Read, write, create Brainvoyager VMR file format."""
import struct
import numpy as np
from bvbabel.utils import (read_variable_length_string,
write_variable_length_string)
# =============================================================================
def read_vmr(filename):
"""Read... | en | 0.619293 | Read, write, create Brainvoyager VMR file format. # ============================================================================= Read Brainvoyager VMR file. Parameters ---------- filename : string Path to file. Returns ------- header : dictionary Pre-data and post-data headers... | 3.069541 | 3 |
example/image-classification/test_score.py | Vikas-kum/incubator-mxnet | 399 | 2496 | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | en | 0.864637 | # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u... | 1.868028 | 2 |
verticapy/vcolumn.py | vertica/vertica_ml_python | 7 | 2497 | # (c) Copyright [2018-2022] Micro Focus or one of its affiliates.
# 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 applicabl... | # (c) Copyright [2018-2022] Micro Focus or one of its affiliates.
# 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 applicabl... | en | 0.442264 | # (c) Copyright [2018-2022] Micro Focus or one of its affiliates. # 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 applicabl... | 1.884349 | 2 |
booktags/flaskapp/book/views.py | MagicSword/Booktags | 0 | 2498 | <reponame>MagicSword/Booktags
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
example.py
~~~~~~~~~
A simple command line application to run flask apps.
:copyright: 2019 Miller
:license: BSD-3-Clause
"""
# Known bugs that can't be fixed here:
# - synopsis() cannot be prevented from clobbering e... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
example.py
~~~~~~~~~
A simple command line application to run flask apps.
:copyright: 2019 Miller
:license: BSD-3-Clause
"""
# Known bugs that can't be fixed here:
# - synopsis() cannot be prevented from clobbering existing
# loaded modules.
... | en | 0.568692 | #!/usr/bin/env python3 # -*- coding: utf-8 -*- example.py ~~~~~~~~~ A simple command line application to run flask apps. :copyright: 2019 Miller :license: BSD-3-Clause # Known bugs that can't be fixed here: # - synopsis() cannot be prevented from clobbering existing # loaded modules. # - If the ... | 2.147338 | 2 |
narwhallet/core/kws/http/enumerations/mediatypes.py | Snider/narwhallet | 3 | 2499 | from enum import Enum
class content_type(Enum):
# https://www.iana.org/assignments/media-types/media-types.xhtml
css = 'text/css'
gif = 'image/gif'
htm = 'text/html'
html = 'text/html'
ico = 'image/bmp'
jpg = 'image/jpeg'
jpeg = 'image/jpeg'
js = 'application/javascript'
png = ... | from enum import Enum
class content_type(Enum):
# https://www.iana.org/assignments/media-types/media-types.xhtml
css = 'text/css'
gif = 'image/gif'
htm = 'text/html'
html = 'text/html'
ico = 'image/bmp'
jpg = 'image/jpeg'
jpeg = 'image/jpeg'
js = 'application/javascript'
png = ... | en | 0.61577 | # https://www.iana.org/assignments/media-types/media-types.xhtml | 2.67477 | 3 |