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 |
|---|---|---|---|---|---|---|---|---|---|---|
tests/bytecode/mp-tests/try4.py | LabAixBidouille/micropython | 303 | 6621651 | <reponame>LabAixBidouille/micropython
try:
f()
except A:
g()
except:
h()
try:
f()
except A:
g()
except B as c:
h()
try:
f()
except A:
g()
except B as c:
h()
except:
i()
| try:
f()
except A:
g()
except:
h()
try:
f()
except A:
g()
except B as c:
h()
try:
f()
except A:
g()
except B as c:
h()
except:
i() | none | 1 | 1.939423 | 2 | |
fom/__init__.py | MichalKononenko/FoundationsOfMechanics | 0 | 6621652 | """
Library for working with symplectic geometries as defined in Abraham and
Marsden's Foundations of Mechanics. This works attempts to mirror the
definitions in the textbook as close as possible.
The :mod:`fom.interfaces` contains the API documentation, defined in the form
of Python abstract classes that have no impl... | """
Library for working with symplectic geometries as defined in Abraham and
Marsden's Foundations of Mechanics. This works attempts to mirror the
definitions in the textbook as close as possible.
The :mod:`fom.interfaces` contains the API documentation, defined in the form
of Python abstract classes that have no impl... | en | 0.938639 | Library for working with symplectic geometries as defined in Abraham and Marsden's Foundations of Mechanics. This works attempts to mirror the definitions in the textbook as close as possible. The :mod:`fom.interfaces` contains the API documentation, defined in the form of Python abstract classes that have no implemen... | 1.98686 | 2 |
register_lib.py | jacob975/TATIRP | 0 | 6621653 | #!/usr/bin/python
'''
Program:
This is a liberary program of register
Usage:
1. from register_lib import [func name] or import curvefit
2. use it in your lovely code.
Editor:
Jacob975
#################################
update log
20180628 version alpha 1
1. Remove some
'''
import numpy as np
# cal... | #!/usr/bin/python
'''
Program:
This is a liberary program of register
Usage:
1. from register_lib import [func name] or import curvefit
2. use it in your lovely code.
Editor:
Jacob975
#################################
update log
20180628 version alpha 1
1. Remove some
'''
import numpy as np
# cal... | en | 0.886475 | #!/usr/bin/python Program: This is a liberary program of register Usage: 1. from register_lib import [func name] or import curvefit 2. use it in your lovely code. Editor: Jacob975 ################################# update log 20180628 version alpha 1 1. Remove some # calculate the inner product and ... | 2.688974 | 3 |
src/awscli_login/__main__.py | kstateome/awscli-login | 0 | 6621654 | <reponame>kstateome/awscli-login
# from signal import signal, SIGINT, SIGTERM
import logging
import signal
import traceback
import sys
import os
import subprocess
import pickle
from argparse import Namespace
from datetime import datetime
from functools import wraps
import boto3
from botocore.session import Session
... | # from signal import signal, SIGINT, SIGTERM
import logging
import signal
import traceback
import sys
import os
import subprocess
import pickle
from argparse import Namespace
from datetime import datetime
from functools import wraps
import boto3
from botocore.session import Session
from daemoniker import Daemonizer... | en | 0.773662 | # from signal import signal, SIGINT, SIGTERM # duration is optional and can be set by the role; # avoid passing if not set. # TODO add retries! A decorator for exception handling and logging. # type: Exception # Write an argvector for the worker to the namespace passer # namespace_path # Use the highest available proto... | 1.640871 | 2 |
site/thicc/urls/production.py | aldenjenkins/ThiccGaming | 0 | 6621655 | <gh_stars>0
#from django.conf.urls import url
from .common import urlpatterns as common_urlpatterns
#from rest_framework_swagger.views import get_swagger_view
urlpatterns = [
] + common_urlpatterns
| #from django.conf.urls import url
from .common import urlpatterns as common_urlpatterns
#from rest_framework_swagger.views import get_swagger_view
urlpatterns = [
] + common_urlpatterns | en | 0.235939 | #from django.conf.urls import url #from rest_framework_swagger.views import get_swagger_view | 1.277766 | 1 |
tests/test_internals_filter.py | MinKPark/ptvsd | 1 | 6621656 | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE in the project root
# for license information.
import os
import pytest
import ptvsd
from ptvsd.wrapper import InternalsFilter
INTERNAL_DIR = os.path.dirname(os.path.abspath(ptvsd.__file__))
@pytest.mark.parametr... | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE in the project root
# for license information.
import os
import pytest
import ptvsd
from ptvsd.wrapper import InternalsFilter
INTERNAL_DIR = os.path.dirname(os.path.abspath(ptvsd.__file__))
@pytest.mark.parametr... | en | 0.830169 | # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See LICENSE in the project root # for license information. # File used by VS/VSC to launch ptvsd # Any file under ptvsd | 2.25665 | 2 |
main.py | sippyca/voice_interface | 0 | 6621657 | import channels, interfaces
# In production, the credentials will be obtained using load_dotenv
creds = interfaces.Credentials("192.168.1.1:1111", "username", "password")
rest_interface = (interfaces.RestInterface(creds))
def get_channel():
"""Get channel information for channel 123456 from the Rest interface.""... | import channels, interfaces
# In production, the credentials will be obtained using load_dotenv
creds = interfaces.Credentials("192.168.1.1:1111", "username", "password")
rest_interface = (interfaces.RestInterface(creds))
def get_channel():
"""Get channel information for channel 123456 from the Rest interface.""... | en | 0.763908 | # In production, the credentials will be obtained using load_dotenv Get channel information for channel 123456 from the Rest interface. | 2.579529 | 3 |
piestats/web/player_names.py | jrgp/soldat-pystats | 8 | 6621658 | import re
trailing_name_count_matcher = re.compile('(.+)\((\d+)\)$')
def remove_redundant_player_names(names):
'''
Given a list of names, remove ones with trailing (1) through (n) depending on correctness
Assumes names will be a list of strings with no duplicates. Order is preserved on return
'''
if le... | import re
trailing_name_count_matcher = re.compile('(.+)\((\d+)\)$')
def remove_redundant_player_names(names):
'''
Given a list of names, remove ones with trailing (1) through (n) depending on correctness
Assumes names will be a list of strings with no duplicates. Order is preserved on return
'''
if le... | en | 0.833286 | Given a list of names, remove ones with trailing (1) through (n) depending on correctness Assumes names will be a list of strings with no duplicates. Order is preserved on return | 3.605433 | 4 |
datapack/data/scripts/quests/154_SacrificeToSea/__init__.py | DigitalCoin1/L2SPERO | 0 | 6621659 | <reponame>DigitalCoin1/L2SPERO
# Maked by Mr. Have fun! Version 0.2
import sys
from com.l2jfrozen.gameserver.model.quest import State
from com.l2jfrozen.gameserver.model.quest import QuestState
from com.l2jfrozen.gameserver.model.quest.jython import QuestJython as JQuest
qn = "154_SacrificeToSea"
FOX_FUR_ID = 1032
FO... | # Maked by Mr. Have fun! Version 0.2
import sys
from com.l2jfrozen.gameserver.model.quest import State
from com.l2jfrozen.gameserver.model.quest import QuestState
from com.l2jfrozen.gameserver.model.quest.jython import QuestJython as JQuest
qn = "154_SacrificeToSea"
FOX_FUR_ID = 1032
FOX_FUR_YARN_ID = 1033
MAIDEN_DOL... | en | 0.843975 | # Maked by Mr. Have fun! Version 0.2 | 2.413329 | 2 |
ezntfs/__init__.py | lezgomatt/ezntfs | 13 | 6621660 | """An easy-to-use wrapper for NTFS-3G on macOS."""
__version__ = "1.1.1"
| """An easy-to-use wrapper for NTFS-3G on macOS."""
__version__ = "1.1.1"
| en | 0.481813 | An easy-to-use wrapper for NTFS-3G on macOS. | 1.038569 | 1 |
utils.py | karanvivekbhargava/vanilla-neural-network | 1 | 6621661 | import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets
from sklearn.utils import shuffle
class Net:
def __init__(self):
self.data = None
self.W = None
def feedData(self, x_train, y_train, x_valid, y_valid, x_test, y_test):
self.data = [x_train, y_train, x_vali... | import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets
from sklearn.utils import shuffle
class Net:
def __init__(self):
self.data = None
self.W = None
def feedData(self, x_train, y_train, x_valid, y_valid, x_test, y_test):
self.data = [x_train, y_train, x_vali... | en | 0.81412 | # Call bb solver # import some data to play with # we take all the features. # Subtract the mean from the data to make the training faster # convert labels to ones hot using this function Convert a list of matrices into a vector Convert a vector into a list of matrices. The returned value will have the same shape as l... | 3.080384 | 3 |
glr/train_lr.py | dlkt-review-and-empirical-evaluation/dlkt-review-and-empirical-evaluation | 0 | 6621662 | import argparse
import numpy as np
import pandas as pd
from scipy.sparse import load_npz, csr_matrix
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score as acc, roc_auc_score as auc, f1_score as f1, matthews_corrcoef as mc, \
mean_squared_error as mse, precision_score as p... | import argparse
import numpy as np
import pandas as pd
from scipy.sparse import load_npz, csr_matrix
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score as acc, roc_auc_score as auc, f1_score as f1, matthews_corrcoef as mc, \
mean_squared_error as mse, precision_score as p... | en | 0.494346 | # nll = log_loss(y, y_pred) # Load sparse dataset # Train-test split # Student-wise train-test split # First 5 columns are the original dataset, including label in column 3 # Train # Write predictions to csv # test_df[f"LR_{features_suffix}"] = y_pred_test # print('write') # test_df.to_csv(f'data/{args.dataset}/preproc... | 2.37911 | 2 |
swing/parsers.py | docker-swing/swing | 1 | 6621663 | import configparser
import os
import yaml
from .errors import InvalidConfigError, InvalidRequirementsError, InvalidChartDefinitionError
from .helpers import is_readable_dir, is_readable_file
class Config:
def __init__(self, server_url, email, password):
self.server_url = server_url
self.email = ... | import configparser
import os
import yaml
from .errors import InvalidConfigError, InvalidRequirementsError, InvalidChartDefinitionError
from .helpers import is_readable_dir, is_readable_file
class Config:
def __init__(self, server_url, email, password):
self.server_url = server_url
self.email = ... | none | 1 | 2.767723 | 3 | |
aydin/cli/test/test_cli.py | AhmetCanSolak/aydin | 78 | 6621664 | from click.testing import CliRunner
from aydin.cli.cli import cli, handle_files
from aydin.io.datasets import examples_single
from aydin.util.log.log import Log
def test_info():
Log.override_test_exclusion = True
Log.force_click_echo = True
image_path = examples_single.generic_lizard.get_path()
run... | from click.testing import CliRunner
from aydin.cli.cli import cli, handle_files
from aydin.io.datasets import examples_single
from aydin.util.log.log import Log
def test_info():
Log.override_test_exclusion = True
Log.force_click_echo = True
image_path = examples_single.generic_lizard.get_path()
run... | en | 0.622785 | # Denoise # TODO: turn this into a saveload testcase # Denoise with the pre-trained model # result = runner.invoke(cli, ['denoise', '--model-path=', '--use-model', image_path]) # assert result.exit_code == 0 # denoised = denoised.clip(0, 1) # # psnr_noisy = psnr(noisy, image) # ssim_noisy = ssim(noisy, image) # print("... | 2.049311 | 2 |
recsim/agents/layers/cluster_click_statistics.py | MontrealAI/recsim | 625 | 6621665 | <filename>recsim/agents/layers/cluster_click_statistics.py
# coding=utf-8
# coding=utf-8
# Copyright 2019 The RecSim Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://ww... | <filename>recsim/agents/layers/cluster_click_statistics.py
# coding=utf-8
# coding=utf-8
# Copyright 2019 The RecSim Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://ww... | en | 0.809967 | # coding=utf-8 # coding=utf-8 # Copyright 2019 The RecSim Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by ap... | 2.300014 | 2 |
jacoren/memory.py | kuszaj/jacoren | 1 | 6621666 | # -*- coding: utf-8 -*-
"""Utilities for memory info."""
import psutil
from collections import OrderedDict
def memory_ram(percent=False):
"""
Return memory metrics.
Function returns a OrderedDict::
{
'total': <total memory>,
'available': <available memory>,
... | # -*- coding: utf-8 -*-
"""Utilities for memory info."""
import psutil
from collections import OrderedDict
def memory_ram(percent=False):
"""
Return memory metrics.
Function returns a OrderedDict::
{
'total': <total memory>,
'available': <available memory>,
... | en | 0.625031 | # -*- coding: utf-8 -*- Utilities for memory info. Return memory metrics. Function returns a OrderedDict:: { 'total': <total memory>, 'available': <available memory>, 'used': <used memory>, 'free': <free memory>, ... }, Above fields ... | 3.067973 | 3 |
spring_cloud/commons/helpers/cache/cache_manager.py | haribo0915/Spring-Cloud-in-Python | 5 | 6621667 | <gh_stars>1-10
# -*- coding: utf-8 -*-
"""
A cache manager wrapper that supports some syntax sugar.
Usage:
value = cache_manager.get(cache_key) \
.on_cache_miss(lambda: retrieve_value(key))
"""
__author__ = "Waterball (<EMAIL>)"
__license__ = "Apache 2.0"
# standard library
from abc import ABC,... | # -*- coding: utf-8 -*-
"""
A cache manager wrapper that supports some syntax sugar.
Usage:
value = cache_manager.get(cache_key) \
.on_cache_miss(lambda: retrieve_value(key))
"""
__author__ = "Waterball (<EMAIL>)"
__license__ = "Apache 2.0"
# standard library
from abc import ABC, abstractmethod... | en | 0.75503 | # -*- coding: utf-8 -*- A cache manager wrapper that supports some syntax sugar. Usage: value = cache_manager.get(cache_key) \ .on_cache_miss(lambda: retrieve_value(key)) # standard library :param cache_miss_func: (lambda ()->value) Service Provider Interface (SPI) for basic caching. We might w... | 3.245261 | 3 |
mace/python/tools/dsp_ops.py | huuuuusy/MACE-Learn | 7 | 6621668 | <reponame>huuuuusy/MACE-Learn<filename>mace/python/tools/dsp_ops.py
# Copyright 2018 Xiaomi, Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apac... | # Copyright 2018 Xiaomi, Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | en | 0.858705 | # Copyright 2018 Xiaomi, Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or... | 1.627438 | 2 |
profile_generator/schema/schema.py | nethy/profile-generator | 0 | 6621669 | from abc import ABCMeta, abstractmethod
from collections.abc import Mapping
from typing import Any, Optional
class SchemaError(Exception, metaclass=ABCMeta):
...
class Schema(metaclass=ABCMeta):
@abstractmethod
def validate(self, data: Any) -> Optional[SchemaError]:
...
def process( # pyli... | from abc import ABCMeta, abstractmethod
from collections.abc import Mapping
from typing import Any, Optional
class SchemaError(Exception, metaclass=ABCMeta):
...
class Schema(metaclass=ABCMeta):
@abstractmethod
def validate(self, data: Any) -> Optional[SchemaError]:
...
def process( # pyli... | en | 0.50174 | # pylint: disable=no-self-use # pylint: disable=unused-argument | 2.955651 | 3 |
astropy/utils/tests/test_parsing.py | MatiasRepetto/astropy | 1 | 6621670 | <filename>astropy/utils/tests/test_parsing.py<gh_stars>1-10
# Licensed under a 3-clause BSD style license - see LICENSE.rst
import importlib
import secrets
import sys
from textwrap import dedent
import pytest
from astropy.utils.parsing import lex, yacc, _TAB_HEADER
def _docstring_canary():
"""Docstring that's ... | <filename>astropy/utils/tests/test_parsing.py<gh_stars>1-10
# Licensed under a 3-clause BSD style license - see LICENSE.rst
import importlib
import secrets
import sys
from textwrap import dedent
import pytest
from astropy.utils.parsing import lex, yacc, _TAB_HEADER
def _docstring_canary():
"""Docstring that's ... | en | 0.564862 | # Licensed under a 3-clause BSD style license - see LICENSE.rst Docstring that's here just to check for -OO. # Write Python code into the temporary directory, so that the # generated tables will also go into the temporary directory. # We use a unique suffix so that the test can be run multiple times # without weirdness... | 2.271583 | 2 |
work/tests/test_admin.py | allink/allink-apps | 1 | 6621671 | <reponame>allink/allink-apps
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib import admin
from cms.utils.urlutils import admin_reverse
from ..admin import WorkAdmin
from . import BaseWorkTest
class TestWorkAdmin(BaseWorkTest):
def test_all_translations(self):
# Ch... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib import admin
from cms.utils.urlutils import admin_reverse
from ..admin import WorkAdmin
from . import BaseWorkTest
class TestWorkAdmin(BaseWorkTest):
def test_all_translations(self):
# Check that all the available la... | en | 0.732762 | # -*- coding: utf-8 -*- # Check that all the available languages appear in `all_translations` | 2.155003 | 2 |
crop_images.py | BluePinetree/KaKR_3rd_month-Car_class_classification | 0 | 6621672 | import os
import sys
import numpy as np
import pandas as pd
from tqdm import tqdm
import matplotlib.pyplot as plt
import cv2
import PIL
# https://www.kaggle.com/tmheo74/3rd-ml-month-car-image-cropping-updated-7-10
# 데이터 경로
TRAIN_IMG_PATH = os.path.join(os.getcwd(), 'input/train')
TEST_IMG_PATH = os.path.join(os.getcw... | import os
import sys
import numpy as np
import pandas as pd
from tqdm import tqdm
import matplotlib.pyplot as plt
import cv2
import PIL
# https://www.kaggle.com/tmheo74/3rd-ml-month-car-image-cropping-updated-7-10
# 데이터 경로
TRAIN_IMG_PATH = os.path.join(os.getcwd(), 'input/train')
TEST_IMG_PATH = os.path.join(os.getcw... | ko | 0.850519 | # https://www.kaggle.com/tmheo74/3rd-ml-month-car-image-cropping-updated-7-10 # 데이터 경로 # plt.imshow(cropped_img) # plt.show() # 훈련 이미지 자르기 # 시험 이미지 자르기 | 2.745796 | 3 |
payo_anasayfa.py | cagataysarioglu/pyPasswordManager_Qt | 3 | 6621673 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'payo_anasayfa.ui'
#
# Created by: PyQt5 UI code generator 5.15.2
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
from PyQt5 imp... | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'payo_anasayfa.ui'
#
# Created by: PyQt5 UI code generator 5.15.2
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
from PyQt5 imp... | en | 0.845419 | # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'payo_anasayfa.ui' # # Created by: PyQt5 UI code generator 5.15.2 # # WARNING: Any manual changes made to this file will be lost when pyuic5 is # run again. Do not edit this file unless you know what you are doing. #000000;\n" #cfcfcf;\n" #36... | 1.754706 | 2 |
ims3d.py | R-Laurent/detection | 0 | 6621674 | <gh_stars>0
#!/usr/bin/python3
import os
import sys
import argparse
import logging
import numpy as np
import pymatgenims3d.py -r 1 naphtalene.xyz
import geometry.geometry
import graph_theory.detect_cycle
import grids.angular
import grids.geode
import interface.gaussian
# Create logger
logger = logging.getLogger('lo... | #!/usr/bin/python3
import os
import sys
import argparse
import logging
import numpy as np
import pymatgenims3d.py -r 1 naphtalene.xyz
import geometry.geometry
import graph_theory.detect_cycle
import grids.angular
import grids.geode
import interface.gaussian
# Create logger
logger = logging.getLogger('log')
logger.s... | en | 0.473627 | #!/usr/bin/python3 # Create logger # create console handler and set level to error # create file handler and set level to info # create formatter #formatter = logging.Formatter( # '%(asctime)s - %(name)s - %(levelname)s - %(message)s') # add formatter to ch # add ch to logger Returns RGB colors for each value of val... | 2.327233 | 2 |
release/stubs.min/System/Windows/Forms/__init___parts/DataGridViewCellPaintingEventArgs.py | YKato521/ironpython-stubs | 0 | 6621675 | <reponame>YKato521/ironpython-stubs
class DataGridViewCellPaintingEventArgs(HandledEventArgs):
"""
Provides data for the System.Windows.Forms.DataGridView.CellPainting event.
DataGridViewCellPaintingEventArgs(dataGridView: DataGridView,graphics: Graphics,clipBounds: Rectangle,cellBounds: Rectangle,rowIn... | class DataGridViewCellPaintingEventArgs(HandledEventArgs):
"""
Provides data for the System.Windows.Forms.DataGridView.CellPainting event.
DataGridViewCellPaintingEventArgs(dataGridView: DataGridView,graphics: Graphics,clipBounds: Rectangle,cellBounds: Rectangle,rowIndex: int,columnIndex: int,cellState:... | en | 0.457443 | Provides data for the System.Windows.Forms.DataGridView.CellPainting event.
DataGridViewCellPaintingEventArgs(dataGridView: DataGridView,graphics: Graphics,clipBounds: Rectangle,cellBounds: Rectangle,rowIndex: int,columnIndex: int,cellState: DataGridViewElementStates,value: object,formattedValue: object,errorT... | 2.394863 | 2 |
Language Proficiency/Python/Collections/Word Order/word_order.py | xuedong/hacker-rank | 1 | 6621676 | <reponame>xuedong/hacker-rank
#!/usr/bin/env python3
from collections import OrderedDict
if __name__ == "__main__":
n = int(input())
d = OrderedDict()
total = 0
for _ in range(n):
word = input()
if word in d:
d[word] += 1
else:
d[word] = 1
... | #!/usr/bin/env python3
from collections import OrderedDict
if __name__ == "__main__":
n = int(input())
d = OrderedDict()
total = 0
for _ in range(n):
word = input()
if word in d:
d[word] += 1
else:
d[word] = 1
total += 1
print(total)
... | fr | 0.221828 | #!/usr/bin/env python3 | 3.740814 | 4 |
Helper-Scripts/RGB_to_YCbCr.py | wolfdale/NSFW-ImageScanner | 0 | 6621677 | <gh_stars>0
from PIL import Image
def main():
img = Image.open('Input_Image.jpg')
ycbcr_image = Image.new('RGB', img.size, 'black')
ycbcr = convert_to_ycbcr(img)
pix = ycbcr_image.load()
for i in range(0, img.size[0]):
for j in range(0, img.size[1]):
... | from PIL import Image
def main():
img = Image.open('Input_Image.jpg')
ycbcr_image = Image.new('RGB', img.size, 'black')
ycbcr = convert_to_ycbcr(img)
pix = ycbcr_image.load()
for i in range(0, img.size[0]):
for j in range(0, img.size[1]):
pi... | en | 0.616815 | #function to Convert rgb image to ycbcr | 3.294709 | 3 |
ansible-devel/test/integration/targets/module_defaults/collections/ansible_collections/testns/testcoll/plugins/module_utils/echo_impl.py | satishcarya/ansible | 0 | 6621678 | <filename>ansible-devel/test/integration/targets/module_defaults/collections/ansible_collections/testns/testcoll/plugins/module_utils/echo_impl.py
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import json
from ansible.module_utils import basic
from ansible.module_utils.basic i... | <filename>ansible-devel/test/integration/targets/module_defaults/collections/ansible_collections/testns/testcoll/plugins/module_utils/echo_impl.py
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import json
from ansible.module_utils import basic
from ansible.module_utils.basic i... | none | 1 | 1.598118 | 2 | |
dedo/utils/init_utils.py | console-beaver/dedo | 23 | 6621679 | """
Utilities for deform sim in PyBullet.
Note: this code is for research i.e. quick experimentation; it has minimal
comments for now, but if we see further interest from the community -- we will
add further comments, unify the style, improve efficiency and add unittests.
@contactrika
"""
from pathlib import Path ... | """
Utilities for deform sim in PyBullet.
Note: this code is for research i.e. quick experimentation; it has minimal
comments for now, but if we see further interest from the community -- we will
add further comments, unify the style, improve efficiency and add unittests.
@contactrika
"""
from pathlib import Path ... | en | 0.822753 | Utilities for deform sim in PyBullet. Note: this code is for research i.e. quick experimentation; it has minimal comments for now, but if we see further interest from the community -- we will add further comments, unify the style, improve efficiency and add unittests. @contactrika # automatically converts forward sl... | 2.444787 | 2 |
sample/tests/start_tests.py | yaras/pythontemplate | 0 | 6621680 | <gh_stars>0
import unittest
from sample import start
class StartTests(unittest.TestCase):
def test_sayHello(self):
self.assertEquals('hello', start.sayHello())
if __name__ == '__main__':
unittest.main()
| import unittest
from sample import start
class StartTests(unittest.TestCase):
def test_sayHello(self):
self.assertEquals('hello', start.sayHello())
if __name__ == '__main__':
unittest.main() | none | 1 | 2.735509 | 3 | |
update-gh-pages.py | nicholasbishop/dumbmath-rs | 2 | 6621681 | #!/usr/bin/env python3
import os
import shutil
import subprocess
import tempfile
REPO = '<EMAIL>:nicholasbishop/dumbmath-rs.git'
BRANCH = 'gh-pages'
COMMIT_MSG = 'Automatic-ish rustdoc update'
def run_cmd(cmd, cwd=None):
print(' '.join(cmd))
subprocess.check_call(cmd, cwd=cwd)
def main():
run_cmd(['ca... | #!/usr/bin/env python3
import os
import shutil
import subprocess
import tempfile
REPO = '<EMAIL>:nicholasbishop/dumbmath-rs.git'
BRANCH = 'gh-pages'
COMMIT_MSG = 'Automatic-ish rustdoc update'
def run_cmd(cmd, cwd=None):
print(' '.join(cmd))
subprocess.check_call(cmd, cwd=cwd)
def main():
run_cmd(['ca... | fr | 0.221828 | #!/usr/bin/env python3 | 2.135167 | 2 |
segment/ml/models/three_dimensional/small_unet.py | yngtodd/segment | 4 | 6621682 | import torch
from torch import nn
import torch.nn.functional as F
class DoubleBlock(nn.Module):
'''(conv => BN => ReLU) * 2'''
def __init__(self, in_ch, out_ch):
super(DoubleBlock, self).__init__()
self.conv = nn.Sequential(
nn.Conv3d(in_ch, out_ch, 3, padding=1),
nn.... | import torch
from torch import nn
import torch.nn.functional as F
class DoubleBlock(nn.Module):
'''(conv => BN => ReLU) * 2'''
def __init__(self, in_ch, out_ch):
super(DoubleBlock, self).__init__()
self.conv = nn.Sequential(
nn.Conv3d(in_ch, out_ch, 3, padding=1),
nn.... | ko | 0.250293 | (conv => BN => ReLU) * 2 | 3.0752 | 3 |
control/src/path_planner.py | mnemonia/transprotobot | 0 | 6621683 | <filename>control/src/path_planner.py
import logging
import numpy as np
from sensor_interface_layer import GpsMath
from stanley_controller import State, StandleyController
class PathPlanner():
LOG = logging.getLogger('PathPlanner')
def __init__(self, gsl, sil, vil, tc, sc):
self._gsl = gsl
sel... | <filename>control/src/path_planner.py
import logging
import numpy as np
from sensor_interface_layer import GpsMath
from stanley_controller import State, StandleyController
class PathPlanner():
LOG = logging.getLogger('PathPlanner')
def __init__(self, gsl, sil, vil, tc, sc):
self._gsl = gsl
sel... | en | 0.81879 | # Initial state | 2.811194 | 3 |
mc/db/schema.py | aspuru-guzik-group/mission_control | 3 | 6621684 | from . import models # noqa
from .base import Base
metadata = Base.metadata
| from . import models # noqa
from .base import Base
metadata = Base.metadata
| none | 1 | 1.046662 | 1 | |
create_level2_dataset.py | danilobenozzo/supervised_causality_detection | 2 | 6621685 | import numpy as np
import pickle
from scipy.io import loadmat
from statsmodels.stats.stattools import durbin_watson, omni_normtest, jarque_bera
from sklearn.linear_model import LinearRegression, BayesianRidge
from sklearn.svm import SVR
from sklearn.cross_validation import cross_val_score, KFold, cross_val_predict
from... | import numpy as np
import pickle
from scipy.io import loadmat
from statsmodels.stats.stattools import durbin_watson, omni_normtest, jarque_bera
from sklearn.linear_model import LinearRegression, BayesianRidge
from sklearn.svm import SVR
from sklearn.cross_validation import cross_val_score, KFold, cross_val_predict
from... | en | 0.739808 | #from load_challenge_data import load_challenge_data Compute regression scores for a given set of 3 timeseries according to the causality structures. #added 2 dimensions to compute r2 and mse #added 2 dimensions to compute r2 and mse #len(cs_train))) #residuals #tmp_score[i_reg] = cross_val_score(reg, X, y, cv=cv, ... | 2.097483 | 2 |
mediagenerator/multidomain_media_url.py | ajith-004/django-mediagenerator | 0 | 6621686 | import os, os.path
import urlparse
from django.conf import settings
from django.core.files.storage import FileSystemStorage
count = 0
media_count=100
def rewrite_url():
media_change = getattr(settings, 'CHANGE_MEDIA_URL', False)
if (media_change):
global count
global media_count
count ... | import os, os.path
import urlparse
from django.conf import settings
from django.core.files.storage import FileSystemStorage
count = 0
media_count=100
def rewrite_url():
media_change = getattr(settings, 'CHANGE_MEDIA_URL', False)
if (media_change):
global count
global media_count
count ... | none | 1 | 2.221236 | 2 | |
__init__.py | zengljnwpu/yaspc | 0 | 6621687 | <gh_stars>0
"""Yet Another Pascal Compiler"""
# Bring in all of the public yaspc interface into this
# module.
#from __future__ import absolute_import
#from __future__ import division
#from __future__ import print_function
# import all packages from optimization
# pylint: disable=wildcard-import
#from yaspc.optimizati... | """Yet Another Pascal Compiler"""
# Bring in all of the public yaspc interface into this
# module.
#from __future__ import absolute_import
#from __future__ import division
#from __future__ import print_function
# import all packages from optimization
# pylint: disable=wildcard-import
#from yaspc.optimization import *
... | en | 0.454746 | Yet Another Pascal Compiler # Bring in all of the public yaspc interface into this # module. #from __future__ import absolute_import #from __future__ import division #from __future__ import print_function # import all packages from optimization # pylint: disable=wildcard-import #from yaspc.optimization import * # pylin... | 1.124957 | 1 |
examples/shaders.py | brianbruggeman/oogli | 3 | 6621688 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import division
import ctypes
from textwrap import dedent as dd
import numpy as np
import OpenGL
OpenGL.ERROR_CHECKING = True
import glfw
from glfw import gl
# ######################################################################
# Data
# ###############... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import division
import ctypes
from textwrap import dedent as dd
import numpy as np
import OpenGL
OpenGL.ERROR_CHECKING = True
import glfw
from glfw import gl
# ######################################################################
# Data
# ###############... | de | 0.367588 | #!/usr/bin/env python # -*- coding: utf-8 -*- # ###################################################################### # Data # ###################################################################### # gl.QUADS, # gl.PATCHES, # index for index in range(vertices.shape[0]) # 5, 2, 0, # 5, 8, 6, # Generate some colors for ... | 2.458093 | 2 |
mysql2/mysql_settings.py | arfu2016/DuReader | 0 | 6621689 | """
@Project : DuReader
@Module : mysql_settings.py
@Author : Deco [<EMAIL>]
@Created : 5/14/18 1:42 PM
@Desc :
"""
import logging
import os
import sys
import pprint
import pickle
from .mysql_connect import Mysql
from . import settings
host = settings.MYSQL.get("host")
port = settings.MYSQL.get("port"... | """
@Project : DuReader
@Module : mysql_settings.py
@Author : Deco [<EMAIL>]
@Created : 5/14/18 1:42 PM
@Desc :
"""
import logging
import os
import sys
import pprint
import pickle
from .mysql_connect import Mysql
from . import settings
host = settings.MYSQL.get("host")
port = settings.MYSQL.get("port"... | en | 0.288759 | @Project : DuReader @Module : mysql_settings.py @Author : Deco [<EMAIL>] @Created : 5/14/18 1:42 PM @Desc : # for logging # print(log_example) # print(log_data[0]) | 2.635601 | 3 |
hw/_qa/alexander_sidorov/vadim_maletski/hw06/level_04_test.py | alexander-sidorov/qap-05 | 9 | 6621690 | from datetime import date
from typing import Any
import pytest
from hw.vadim_maletski.func6 import level_04
from .common import azaza
from .common import validate_data
from .common import validate_errors
happy_data = [
pytest.param(*params, id=name)
for name, params in {
"date": [{object: date(1900,... | from datetime import date
from typing import Any
import pytest
from hw.vadim_maletski.func6 import level_04
from .common import azaza
from .common import validate_data
from .common import validate_errors
happy_data = [
pytest.param(*params, id=name)
for name, params in {
"date": [{object: date(1900,... | none | 1 | 2.391653 | 2 | |
setup.py | UniBO-PRISMLab/micro-wot-servient | 1 | 6621691 | <reponame>UniBO-PRISMLab/micro-wot-servient
from setuptools import setup, find_packages
setup(
name='embeddedWoTServient',
url='https://github.com/UniBO-PRISMLab/micro-wot-servient',
author='<NAME>',
version='0.1',
license='MIT',
description='WoT module for build TDs and executable scripts for ... | from setuptools import setup, find_packages
setup(
name='embeddedWoTServient',
url='https://github.com/UniBO-PRISMLab/micro-wot-servient',
author='<NAME>',
version='0.1',
license='MIT',
description='WoT module for build TDs and executable scripts for embedded systems',
long_description=open... | el | 0.160844 | [console_scripts] embeddedWoTServient=embeddedWoTServient:cli | 1.267502 | 1 |
leetcode/28_strStr.py | thiakx/leetcode | 0 | 6621692 | <filename>leetcode/28_strStr.py<gh_stars>0
import unittest
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
haystack_set = set(haystack)
needle_len = len(needle)
haystack_len = len(haystack)
if needle == '':
return 0
elif haystack == '' or ... | <filename>leetcode/28_strStr.py<gh_stars>0
import unittest
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
haystack_set = set(haystack)
needle_len = len(needle)
haystack_len = len(haystack)
if needle == '':
return 0
elif haystack == '' or ... | en | 0.688134 | # use a moving window | 3.538848 | 4 |
pinpayments/constants.py | MattHealy/pinpayments-python | 0 | 6621693 | <reponame>MattHealy/pinpayments-python
API_VERSION = '1'
BASE_URL = 'https://api.pin.net.au/' + API_VERSION
BASE_URL_TEST = 'https://test-api.pin.net.au/' + API_VERSION
| API_VERSION = '1'
BASE_URL = 'https://api.pin.net.au/' + API_VERSION
BASE_URL_TEST = 'https://test-api.pin.net.au/' + API_VERSION | none | 1 | 1.125178 | 1 | |
deploy/gunicorn.py | udbhav/eurorack-planner | 1 | 6621694 | import os
import sys
sys.path.append("/home/udbhav/www/django/eurorack-planner/app/source/")
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings")
# This application object is used by the development server
# as well as any WSGI server configured to use this file.
from django.core.wsgi import get_wsgi_applicat... | import os
import sys
sys.path.append("/home/udbhav/www/django/eurorack-planner/app/source/")
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings")
# This application object is used by the development server
# as well as any WSGI server configured to use this file.
from django.core.wsgi import get_wsgi_applicat... | en | 0.970782 | # This application object is used by the development server # as well as any WSGI server configured to use this file. | 1.402886 | 1 |
disbot.py | Smirf123/Disbot-Python-Bot | 0 | 6621695 | import discord
import requests
from discord.ext import commands
client = commands.AutoShardedBot(command_prefix="!")
TOKEN = "INSERTTOKENHERE"
clientid = insertclientidherenoquotes
disbottoken = "<PASSWORD>"
async def disbot():
while True:
url = f"https://disbot.top/api/v2/bot/{clientid}/update"
... | import discord
import requests
from discord.ext import commands
client = commands.AutoShardedBot(command_prefix="!")
TOKEN = "INSERTTOKENHERE"
clientid = insertclientidherenoquotes
disbottoken = "<PASSWORD>"
async def disbot():
while True:
url = f"https://disbot.top/api/v2/bot/{clientid}/update"
... | none | 1 | 2.74931 | 3 | |
apps/collection/tests/test_collection_relation.py | magocod/django_repository | 1 | 6621696 | <reponame>magocod/django_repository<gh_stars>1-10
# standard library
# import json
# local Django
from apps.category.models import Category
from apps.collection.models import Collection
from apps.collection.serializers import CollectionHeavySerializer
from apps.tag.models import Tag
from apps.tests.fixtures import Rep... | # standard library
# import json
# local Django
from apps.category.models import Category
from apps.collection.models import Collection
from apps.collection.serializers import CollectionHeavySerializer
from apps.tag.models import Tag
from apps.tests.fixtures import RepositoryTestCase
class CollectionRelationTest(Rep... | en | 0.179312 | # standard library # import json # local Django ... # oldvalues = self.serializer( # Collection.objects.get(id=1) # ) # print(response.data) # self.assertNotEqual(oldvalues.data, response.data) # print(response.data) ... # oldvalues = self.serializer( # Collection.objects.get(id=1) # ) # print(response.data) # ... | 2.261625 | 2 |
python/src/main/python/pyalink/alink/tests/pipeline/test_special_models.py | wenwei8268/Alink | 0 | 6621697 | <gh_stars>0
import unittest
import numpy as np
import pandas as pd
from pyalink.alink import *
class TestSpecialModels(unittest.TestCase):
def test_wrap_model(self):
source = CsvSourceBatchOp() \
.setSchemaStr(
"sepal_length double, sepal_width double, petal_length double, petal... | import unittest
import numpy as np
import pandas as pd
from pyalink.alink import *
class TestSpecialModels(unittest.TestCase):
def test_wrap_model(self):
source = CsvSourceBatchOp() \
.setSchemaStr(
"sepal_length double, sepal_width double, petal_length double, petal_width doubl... | none | 1 | 2.464846 | 2 | |
apps/scrapers/po10.py | tractiming/trac-gae | 3 | 6621698 | <gh_stars>1-10
import requests
from bs4 import BeautifulSoup
from datetime import datetime
from .base import Scraper
from .exceptions import NoSuchAthlete, TooManyAthletes
PO10_BASE = 'http://www.thepowerof10.info/'
PO10_SEARCH_URL = PO10_BASE + 'athletes/athleteslookup.aspx'
YEAR_ROW = 1
TITLES_ROW = 2
PERF_ROW = 3... | import requests
from bs4 import BeautifulSoup
from datetime import datetime
from .base import Scraper
from .exceptions import NoSuchAthlete, TooManyAthletes
PO10_BASE = 'http://www.thepowerof10.info/'
PO10_SEARCH_URL = PO10_BASE + 'athletes/athleteslookup.aspx'
YEAR_ROW = 1
TITLES_ROW = 2
PERF_ROW = 3
def perf_row... | en | 0.872321 | tests what row type a tr elem from perf table is given an html page returns the athlete name given an html profile page returns the bs4 performance table Scrapes the Power of 10 websites (UK athletes) gets the athlete name from power of 10 # No name = no athlete returns performances from the athlete's power of 10 page.... | 3.022284 | 3 |
6 kyu/IP Validation.py | mwk0408/codewars_solutions | 6 | 6621699 | <reponame>mwk0408/codewars_solutions
def is_valid_IP(strng):
strng=strng.split(".")
if len(strng)!=4:
return False
for i in strng:
try:
temp=int(i)
if temp<0:
return False
elif temp>255:
return False
elif temp>=0... | def is_valid_IP(strng):
strng=strng.split(".")
if len(strng)!=4:
return False
for i in strng:
try:
temp=int(i)
if temp<0:
return False
elif temp>255:
return False
elif temp>=0 and temp<=9 and len(i)>1:
... | none | 1 | 3.195564 | 3 | |
src/mock/position.py | celiakwan/kafka-taxi-booker | 1 | 6621700 | <reponame>celiakwan/kafka-taxi-booker
from random import randint
THRESHOLD = 10000000
def _mock_coordinates(min, max):
return randint(min * THRESHOLD, max * THRESHOLD) / THRESHOLD
def mock_latitude():
return _mock_coordinates(20, 30)
def mock_longitude():
return _mock_coordinates(50, 60) | from random import randint
THRESHOLD = 10000000
def _mock_coordinates(min, max):
return randint(min * THRESHOLD, max * THRESHOLD) / THRESHOLD
def mock_latitude():
return _mock_coordinates(20, 30)
def mock_longitude():
return _mock_coordinates(50, 60) | none | 1 | 2.516394 | 3 | |
tensor2struct/models/spider/spider_linking.py | chenyangh/tensor2struct-public | 69 | 6621701 | import attr
import einops
import numpy as np
import torch
from torch import nn
import torch.nn.functional as F
from tensor2struct.utils import batched_sequence
from tensor2struct.contexts import knowledge_graph
from tensor2struct.utils import registry, gumbel
from tensor2struct.modules import rat, lstm, embedders, ene... | import attr
import einops
import numpy as np
import torch
from torch import nn
import torch.nn.functional as F
from tensor2struct.utils import batched_sequence
from tensor2struct.contexts import knowledge_graph
from tensor2struct.utils import registry, gumbel
from tensor2struct.modules import rat, lstm, embedders, ene... | en | 0.571015 | Protocol: the graph is contructed based on four keys of desc: question, columns, tables **MIND THE ORDER OF SECTIONS** # build modules # for gumbel # then norm q/col/tab x1, x2: len * relation_emb_size # len * 1 * emb_size # TODO: optimize this code relation_scores: either dim_1 or dim_2 will be normalized # qc... | 2.149804 | 2 |
Codeforces/A_Anti_Light_s_Cell_Guessing.py | anubhab-code/Competitive-Programming | 0 | 6621702 | <gh_stars>0
for _ in range(int(input())):
a,b=map(int,input().split())
if a==1 and b==1:
print(0)
elif a==1 or b==1:
print(1)
else:
print(2) | for _ in range(int(input())):
a,b=map(int,input().split())
if a==1 and b==1:
print(0)
elif a==1 or b==1:
print(1)
else:
print(2) | none | 1 | 3.732288 | 4 | |
commands/__init__.py | sebiTCR/Stocks-of-Razbia | 3 | 6621703 | <reponame>sebiTCR/Stocks-of-Razbia
import typing as t
from .exc import *
from .converters import *
from .cmd_utils import *
def _long_name(name, parent):
if parent is not None:
return f"{parent.long_name} {name}"
return name
class Command:
__slots__ = ("name", "long_name", "run", "args", "usage... | import typing as t
from .exc import *
from .converters import *
from .cmd_utils import *
def _long_name(name, parent):
if parent is not None:
return f"{parent.long_name} {name}"
return name
class Command:
__slots__ = ("name", "long_name", "run", "args", "usage")
def __init__(self, func, na... | none | 1 | 2.468929 | 2 | |
winregistry/winregistry.py | michael-rolfe/winregistry | 18 | 6621704 | <gh_stars>10-100
from datetime import datetime, timedelta
from typing import Any, Optional, Union
from winreg import (
KEY_READ,
KEY_SET_VALUE,
KEY_WRITE,
ConnectRegistry,
CreateKeyEx,
DeleteKey,
DeleteValue,
EnumKey,
EnumValue,
HKEYType,
OpenKey,
QueryInfoKey,
QueryV... | from datetime import datetime, timedelta
from typing import Any, Optional, Union
from winreg import (
KEY_READ,
KEY_SET_VALUE,
KEY_WRITE,
ConnectRegistry,
CreateKeyEx,
DeleteKey,
DeleteValue,
EnumKey,
EnumValue,
HKEYType,
OpenKey,
QueryInfoKey,
QueryValueEx,
SetVa... | en | 0.383714 | # type: ignore # type: ignore # pylint: disable=unused-variable | 2.093836 | 2 |
diplomacy_research/models/draw/tests/draw_model_test_setup.py | wwongkamjan/dipnet_press | 39 | 6621705 | # ==============================================================================
# Copyright 2019 - <NAME>
#
# NOTICE: 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, ... | # ==============================================================================
# Copyright 2019 - <NAME>
#
# NOTICE: 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, ... | en | 0.635688 | # ============================================================================== # Copyright 2019 - <NAME> # # NOTICE: 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, ... | 1.96442 | 2 |
tests/test_mapper.py | jcklie/wikimapper | 69 | 6621706 | import pytest
from tests.fixtures import *
BAVARIAN_PARAMS = [
pytest.param("Stoaboog", "Q168327"),
pytest.param("Wechslkrod", "Q243242"),
pytest.param("Wickiana", "Q2567666"),
pytest.param("Ulrich_Zwingli", "Q123034"),
pytest.param("Jingstes_Gricht", "Q1821239"),
pytest.param("Sånkt_Johann_im... | import pytest
from tests.fixtures import *
BAVARIAN_PARAMS = [
pytest.param("Stoaboog", "Q168327"),
pytest.param("Wechslkrod", "Q243242"),
pytest.param("Wickiana", "Q2567666"),
pytest.param("Ulrich_Zwingli", "Q123034"),
pytest.param("Jingstes_Gricht", "Q1821239"),
pytest.param("Sånkt_Johann_im... | none | 1 | 2.444057 | 2 | |
utils/formatters.py | NicholasJohansan/EP5 | 0 | 6621707 | <gh_stars>0
def seconds_to_time(seconds):
days = (seconds // (60*60*24)), "day"
seconds %= (60*60*24)
hours = (seconds // (60*60)), "hour"
seconds %= (60*60)
minutes = (seconds // (60)), "minute"
seconds = seconds % 60, "second"
_time = []
for u, m in [days, hours, minutes, seconds]:
if u:
if u > 1:
... | def seconds_to_time(seconds):
days = (seconds // (60*60*24)), "day"
seconds %= (60*60*24)
hours = (seconds // (60*60)), "hour"
seconds %= (60*60)
minutes = (seconds // (60)), "minute"
seconds = seconds % 60, "second"
_time = []
for u, m in [days, hours, minutes, seconds]:
if u:
if u > 1:
m += "s"
... | none | 1 | 3.713325 | 4 | |
nucypher/tests/blockchain/eth/contracts/main/policy_manager/test_policy_manager.py | kanzeparov/NuCypher | 0 | 6621708 | """
This file is part of nucypher.
nucypher 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, either version 3 of the License, or
(at your option) any later version.
nucypher is distributed in the hope that it wil... | """
This file is part of nucypher.
nucypher 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, either version 3 of the License, or
(at your option) any later version.
nucypher is distributed in the hope that it wil... | en | 0.852929 | This file is part of nucypher. nucypher 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, either version 3 of the License, or (at your option) any later version. nucypher is distributed in the hope that it will be... | 1.886816 | 2 |
src/utils.py | SamadiPour/iran-ips | 33 | 6621709 | <gh_stars>10-100
import ipaddress
def save_to_file(path: str, content: str):
with open(path, "w") as fp:
fp.write(content)
def convert_to_ip_network(ip: str):
try:
return ipaddress.ip_network(ip)
except:
return None
# -- Old method to remove subnets --
# -- I will remove it whe... | import ipaddress
def save_to_file(path: str, content: str):
with open(path, "w") as fp:
fp.write(content)
def convert_to_ip_network(ip: str):
try:
return ipaddress.ip_network(ip)
except:
return None
# -- Old method to remove subnets --
# -- I will remove it when I'm sure from t... | en | 0.548403 | # -- Old method to remove subnets -- # -- I will remove it when I'm sure from the new method -- # def remove_subnet_ips(ip_list: list[ipaddress.IPv4Network]): # subset_indexes = set() # # for i in range(0, len(ip_list)): # for j in range(i + 1, len(ip_list)): # x = ip_list[i] # y... | 3.282284 | 3 |
card.py | frrmack/CallofCthulhu | 1 | 6621710 | import random as rnd
import numpy.random
poisson = numpy.random.poisson
from util import *
from layout import *
from graphics import CardImage, WoundTokenImage
class Card:
def __init__(self, name, imageFileName=None):
self.name = name
self.owner = None
self.controller = None
self.... | import random as rnd
import numpy.random
poisson = numpy.random.poisson
from util import *
from layout import *
from graphics import CardImage, WoundTokenImage
class Card:
def __init__(self, name, imageFileName=None):
self.name = name
self.owner = None
self.controller = None
self.... | en | 0.405233 | # imageFiles can be given as a string or # a sequence of strings (filenames) #-- Information #-- Actions #-- Graphics #-- Information #-- Actions # lose attachments # lose toughness # for card in self.attached: # card.image.clear() # card.image.flipCard() | 2.959853 | 3 |
easyGuiCheck.py | piotrbla/pyExamples | 0 | 6621711 | from easygui import *
msgbox("ttt", "eeee")
| from easygui import *
msgbox("ttt", "eeee")
| none | 1 | 1.286172 | 1 | |
setup.py | OdelinCharron/pycNic | 0 | 6621712 | <gh_stars>0
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
with open('README.md') as f:
readme = f.read()
with open('LICENSE') as f:
license0 = f.read()
setup(
name='pycnic',
version='0.0.1',
description='Automated quiz for mri images',
long_description=readme,
autho... | # -*- coding: utf-8 -*-
from setuptools import setup, find_packages
with open('README.md') as f:
readme = f.read()
with open('LICENSE') as f:
license0 = f.read()
setup(
name='pycnic',
version='0.0.1',
description='Automated quiz for mri images',
long_description=readme,
author='<NAME>, <... | en | 0.769321 | # -*- coding: utf-8 -*- | 1.161057 | 1 |
networkx/algorithms/shortest_paths/greedy_search.py | a-vitale/networkx | 0 | 6621713 | """Shortest paths and path lengths using the Greedy algorithm.
"""
from heapq import heappush, heappop
from itertools import count
import networkx as nx
from networkx.algorithms.shortest_paths.weighted import _weight_function
def greedy_path(G, source, target, heuristic = None, weight = "weight"):
#if source or ... | """Shortest paths and path lengths using the Greedy algorithm.
"""
from heapq import heappush, heappop
from itertools import count
import networkx as nx
from networkx.algorithms.shortest_paths.weighted import _weight_function
def greedy_path(G, source, target, heuristic = None, weight = "weight"):
#if source or ... | it | 0.936215 | Shortest paths and path lengths using the Greedy algorithm. #if source or target is not in G -> error msg #if heuristic is none -> define the default heuristic function: h = 0 #assegno a push la funzione heappush e a pop la funzione heappop. #A wieght invece assegno la funzione _weight_function(G, weight) #passando com... | 3.715657 | 4 |
Huawei2018CodeCraft-GSCPGZ/submit/predictor.py | polossk/DSML-Logs | 2 | 6621714 | # -*- coding: utf-8 -*-
import preprocessor
import regTree
import scanner
class SolidServer(object):
def __init__(self, config):
self.rest_cpu = config.cpu
self.rest_mem = config.mem
self.haveFlavors = {}
def addVM(self, flavor):
# add one virtual machine
if flavor in s... | # -*- coding: utf-8 -*-
import preprocessor
import regTree
import scanner
class SolidServer(object):
def __init__(self, config):
self.rest_cpu = config.cpu
self.rest_mem = config.mem
self.haveFlavors = {}
def addVM(self, flavor):
# add one virtual machine
if flavor in s... | en | 0.636685 | # -*- coding: utf-8 -*- # add one virtual machine # if rest resources is fit for new vm | 2.509841 | 3 |
src/langumo/configuration.py | fossabot/langumo | 7 | 6621715 | <filename>src/langumo/configuration.py
import yaml
from typing import Dict, Any
_default_configuration = {
'workspace': 'tmp',
'outputs': {
'vocabulary': 'build/vocab.txt',
'train-corpus': 'build/corpus.train.txt',
'eval-corpus': 'build/corpus.eval.txt',
},
'build': {
'... | <filename>src/langumo/configuration.py
import yaml
from typing import Dict, Any
_default_configuration = {
'workspace': 'tmp',
'outputs': {
'vocabulary': 'build/vocab.txt',
'train-corpus': 'build/corpus.train.txt',
'eval-corpus': 'build/corpus.eval.txt',
},
'build': {
'... | en | 0.113986 | # Update default configuration values. | 2.252023 | 2 |
app.py | What-to-watch/wtw-ml-model | 0 | 6621716 | import os
import threading
from surprise import dump
from training import train
from db_util import get_db_conn_url
from flask_sqlalchemy import SQLAlchemy
from flask import Flask, request
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = f"postgresql://{get_db_conn_url()}"
db = SQLAlchemy(app)
from sqla... | import os
import threading
from surprise import dump
from training import train
from db_util import get_db_conn_url
from flask_sqlalchemy import SQLAlchemy
from flask import Flask, request
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = f"postgresql://{get_db_conn_url()}"
db = SQLAlchemy(app)
from sqla... | none | 1 | 2.443059 | 2 | |
export.py | pdufter/pytorch-sgns | 0 | 6621717 |
import torch
import pickle
import os
vectors = torch.load("pts/sgns.pt")
with open("data/idx2word.dat", "rb") as fin:
vocab = pickle.load(fin)
os.makedirs("export")
with open("export/ovectors.txt", "w") as fp:
for row in vectors['embedding.ovectors.weight'].cpu().numpy():
fp.write("\t".join([str(x) for x in row]... |
import torch
import pickle
import os
vectors = torch.load("pts/sgns.pt")
with open("data/idx2word.dat", "rb") as fin:
vocab = pickle.load(fin)
os.makedirs("export")
with open("export/ovectors.txt", "w") as fp:
for row in vectors['embedding.ovectors.weight'].cpu().numpy():
fp.write("\t".join([str(x) for x in row]... | none | 1 | 2.486494 | 2 | |
PythonExercicios/ex088.py | cedricgenaro/Python | 0 | 6621718 | <reponame>cedricgenaro/Python
from random import randint
from time import sleep
import enumerator as enumerator
numeros = []
numero = 0
quant = 0
jogos = []
print('-'*30)
print(f'{"JOGA NA MEGA SENA":^30}')
print('-'*30)
quant = int(input('Quantos jogos você quer que eu sorteie? '))
print('-='*3, f'SORTEANDO {quant} JO... | from random import randint
from time import sleep
import enumerator as enumerator
numeros = []
numero = 0
quant = 0
jogos = []
print('-'*30)
print(f'{"JOGA NA MEGA SENA":^30}')
print('-'*30)
quant = int(input('Quantos jogos você quer que eu sorteie? '))
print('-='*3, f'SORTEANDO {quant} JOGOS', '-='*3)
for c in range(0... | none | 1 | 3.600544 | 4 | |
calculos.py | admelix/ejemplo-claudio | 0 | 6621719 | from sympy import *
'''
aqui puedes crear funciones que recojan resultados de la web y con ello, puedes empezar a
dividir el contenido de la web dependiendo del calculo que quieras mostrar. Un ejemplo es lo que esta abajo
Al usar latex, puedes mostrar un resultado como una imagen. El unicode, lo muestra como si fuera... | from sympy import *
'''
aqui puedes crear funciones que recojan resultados de la web y con ello, puedes empezar a
dividir el contenido de la web dependiendo del calculo que quieras mostrar. Un ejemplo es lo que esta abajo
Al usar latex, puedes mostrar un resultado como una imagen. El unicode, lo muestra como si fuera... | es | 0.956077 | aqui puedes crear funciones que recojan resultados de la web y con ello, puedes empezar a dividir el contenido de la web dependiendo del calculo que quieras mostrar. Un ejemplo es lo que esta abajo Al usar latex, puedes mostrar un resultado como una imagen. El unicode, lo muestra como si fuera en assci Tambien, en ve... | 3.386191 | 3 |
cms/atlascasestudies/migrations/0004_atlascasestudycategoryrelationship.py | rkhleics/nhs-ei.website | 1 | 6621720 | # Generated by Django 3.1.2 on 2020-11-17 18:00
from django.db import migrations, models
import django.db.models.deletion
import modelcluster.fields
class Migration(migrations.Migration):
dependencies = [
('categories', '0009_region_setting'),
('atlascasestudies', '0003_atlascasestudyregionrelat... | # Generated by Django 3.1.2 on 2020-11-17 18:00
from django.db import migrations, models
import django.db.models.deletion
import modelcluster.fields
class Migration(migrations.Migration):
dependencies = [
('categories', '0009_region_setting'),
('atlascasestudies', '0003_atlascasestudyregionrelat... | en | 0.743845 | # Generated by Django 3.1.2 on 2020-11-17 18:00 | 1.618463 | 2 |
docs/conf.py | cjw296/mush | 0 | 6621721 | # -*- coding: utf-8 -*-
import os, pkginfo, datetime
on_rtd = os.environ.get('READTHEDOCS', None) == 'True'
pkg_info = pkginfo.Develop(os.path.join(os.path.dirname(__file__),'..'))
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.intersphinx',
]
intersphinx_mapping = dict(
python = ('http://docs.pyth... | # -*- coding: utf-8 -*-
import os, pkginfo, datetime
on_rtd = os.environ.get('READTHEDOCS', None) == 'True'
pkg_info = pkginfo.Develop(os.path.join(os.path.dirname(__file__),'..'))
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.intersphinx',
]
intersphinx_mapping = dict(
python = ('http://docs.pyth... | en | 0.535605 | # -*- coding: utf-8 -*- # General # Options for HTML output # Options for LaTeX output | 1.902127 | 2 |
firestoreservice.py | tbarford/bg_streamlit_demo | 0 | 6621722 | <reponame>tbarford/bg_streamlit_demo
##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
##python3 script created by tBarford on 20220203
##
##
##File Description: Firebase Firstore Service - CRUD functions for BG golf app MVP
##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
import firebase_admin
from firebase_adm... | ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
##python3 script created by tBarford on 20220203
##
##
##File Description: Firebase Firstore Service - CRUD functions for BG golf app MVP
##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
import firebase_admin
from firebase_admin import credentials, firestore
imp... | en | 0.362089 | ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~## ##python3 script created by tBarford on 20220203 ## ## ##File Description: Firebase Firstore Service - CRUD functions for BG golf app MVP ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~## #import asyncio as io #import concurrent #instantiate firebase #self.db = firestore.As... | 2.245442 | 2 |
rfb_mc/restrictive_formula_module.py | Meterius/rfb-mc | 0 | 6621723 | from abc import ABC, abstractmethod
from typing import Generic, TypeVar, Hashable, Any, Dict, Type
from rfb_mc.types import Params
RestrictiveFormulaParams = TypeVar("RestrictiveFormulaParams", bound=Hashable)
# parameter that determines all formula generation related values
RestrictiveFormulaProperties = TypeVar("Re... | from abc import ABC, abstractmethod
from typing import Generic, TypeVar, Hashable, Any, Dict, Type
from rfb_mc.types import Params
RestrictiveFormulaParams = TypeVar("RestrictiveFormulaParams", bound=Hashable)
# parameter that determines all formula generation related values
RestrictiveFormulaProperties = TypeVar("Re... | en | 0.827305 | # parameter that determines all formula generation related values # properties of the restrictive formula that are determined by the parameters # values that parameterize a specific instance generated by the module and will be used by # the runner implementations to reconstruct the formula in the format of which ever s... | 2.731478 | 3 |
_not_in_use/tests/text_alignment_tests.py | righthan/policy_diffusion | 33 | 6621724 |
import random
import matplotlib.pyplot as plt
import time
import numpy as np
from compiler.ast import flatten
from alignment.sequence import Sequence
from alignment.vocabulary import Vocabulary
from alignment.sequencealigner import SimpleScoring, LocalSequenceAligner
from utils.general_utils import find_subsequence
fr... |
import random
import matplotlib.pyplot as plt
import time
import numpy as np
from compiler.ast import flatten
from alignment.sequence import Sequence
from alignment.vocabulary import Vocabulary
from alignment.sequencealigner import SimpleScoring, LocalSequenceAligner
from utils.general_utils import find_subsequence
fr... | en | 0.654581 | #function from python package for testing results args: a: list of words b: list of words matchScore: num mismatchScore: num gapScore: num Returns: o/w returns list of tuples with score and top alignments Description: helper function for finding alignments... | 2.795443 | 3 |
dataporten/tests/test_api.py | frafra/django-dataporten | 6 | 6621725 | <filename>dataporten/tests/test_api.py
import json
import responses
from django.test import TestCase
from ..api import usergroups, userinfo
from .utils import mock_usergroups_request, mock_userinfo_request
class TestTypes(TestCase):
""" Should hit type definitions in order to catch syntax errors """
from ..... | <filename>dataporten/tests/test_api.py
import json
import responses
from django.test import TestCase
from ..api import usergroups, userinfo
from .utils import mock_usergroups_request, mock_userinfo_request
class TestTypes(TestCase):
""" Should hit type definitions in order to catch syntax errors """
from ..... | en | 0.482835 | Should hit type definitions in order to catch syntax errors Test dataporten userinfo endpoint Test dataporten groups endpoint | 2.650389 | 3 |
main.py | SynnexMetrodata/OpenCV-CustomROI | 0 | 6621726 | <reponame>SynnexMetrodata/OpenCV-CustomROI
import cv2
import numpy
ROIEnabled = False
ROIShape = []
def createROI(event, x, y, flag, param):
global ROIEnabled, ROIShape
if ROIEnabled:
if event == cv2.EVENT_LBUTTONUP:
ROIShape.append((x,y))
def drawROI(frame, roi):
if not ROIEnabled:... | import cv2
import numpy
ROIEnabled = False
ROIShape = []
def createROI(event, x, y, flag, param):
global ROIEnabled, ROIShape
if ROIEnabled:
if event == cv2.EVENT_LBUTTONUP:
ROIShape.append((x,y))
def drawROI(frame, roi):
if not ROIEnabled:
return
start_point = ... | none | 1 | 2.581523 | 3 | |
LinInt.py | EdwardDantes/LinearInterpolation | 0 | 6621727 | # Python Program to give a Y values based on a requested X... Within the range of given (X,Y) data.
| # Python Program to give a Y values based on a requested X... Within the range of given (X,Y) data.
| en | 0.75455 | # Python Program to give a Y values based on a requested X... Within the range of given (X,Y) data. | 2.970379 | 3 |
test/scripts/geometric_shapes.py | lmontaut/hpp-fcl | 59 | 6621728 | <gh_stars>10-100
# Datas for compare_convex_box
from gepetto.corbaserver import Client
from gepetto import Quaternion
def translate (tr, t, d):
return [ tr[i] + d*t[i] for i in range(3) ] + tr[3:]
cl = Client ()
try:
cl.gui.getWindowID("fcl")
except:
cl.gui.createWindow("fcl")
cl.gui.addBox ('fcl/b0', 2,... | # Datas for compare_convex_box
from gepetto.corbaserver import Client
from gepetto import Quaternion
def translate (tr, t, d):
return [ tr[i] + d*t[i] for i in range(3) ] + tr[3:]
cl = Client ()
try:
cl.gui.getWindowID("fcl")
except:
cl.gui.createWindow("fcl")
cl.gui.addBox ('fcl/b0', 2, 2, 2, [1,0,0,0.5... | en | 0.360778 | # Datas for compare_convex_box | 2.047245 | 2 |
db_upgrade.py | aceokay/microblog | 0 | 6621729 | <gh_stars>0
# If you have database migration support, then when you are ready to release
# the new version of the app to your production server you just need to record
# a new migration, copy the migration scripts to your production server and
# run a simple script that applies the changes for you. The database upgrade... | # If you have database migration support, then when you are ready to release
# the new version of the app to your production server you just need to record
# a new migration, copy the migration scripts to your production server and
# run a simple script that applies the changes for you. The database upgrade
# can be do... | en | 0.897153 | # If you have database migration support, then when you are ready to release # the new version of the app to your production server you just need to record # a new migration, copy the migration scripts to your production server and # run a simple script that applies the changes for you. The database upgrade # can be do... | 2.159249 | 2 |
util/util.py | KoryakovDmitry/TGRNet | 55 | 6621730 | <filename>util/util.py
"""This module contains simple helper functions """
from __future__ import print_function
import torch
import torch.distributed as dist
import numpy as np
from PIL import Image
import os
import pickle
def tensor2im(input_image, imtype=np.uint8):
""""Converts a Tensor array into a numpy image... | <filename>util/util.py
"""This module contains simple helper functions """
from __future__ import print_function
import torch
import torch.distributed as dist
import numpy as np
from PIL import Image
import os
import pickle
def tensor2im(input_image, imtype=np.uint8):
""""Converts a Tensor array into a numpy image... | en | 0.646081 | This module contains simple helper functions "Converts a Tensor array into a numpy image array. Parameters: input_image (tensor) -- the input image tensor array imtype (type) -- the desired type of the converted numpy array # get the data from a variable # convert it into a numpy array # g... | 2.970401 | 3 |
PRODHAC.py | LyddonBeni/PRODACH | 0 | 6621731 | # -*- coding: utf-8 -*-
__author__ = 'LyddonBeni'
import numpy as np
from matplotlib import pyplot as plt
import scipy as sc
import numpy as np
print ("""
▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄
UNIVERSIDAD NACIONAL DE HUANCAVELICA
FACULTAD DE CIENCIA... | # -*- coding: utf-8 -*-
__author__ = 'LyddonBeni'
import numpy as np
from matplotlib import pyplot as plt
import scipy as sc
import numpy as np
print ("""
▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄
UNIVERSIDAD NACIONAL DE HUANCAVELICA
FACULTAD DE CIENCIA... | es | 0.488589 | # -*- coding: utf-8 -*- ▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄ UNIVERSIDAD NACIONAL DE HUANCAVELICA FACULTAD DE CIENCIAS DE INGENIERÍA ESCUELA ACADÉMICA PROFESIONAL DE CIVIL ▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄... | 3.506014 | 4 |
genia/utils/download.py | m-stoeckel/pyramid-nested-ner | 6 | 6621732 | <reponame>m-stoeckel/pyramid-nested-ner<filename>genia/utils/download.py<gh_stars>1-10
from oauth2client.client import GoogleCredentials
from pydrive.drive import GoogleDrive
from pydrive.auth import GoogleAuth
from google.colab import auth
if __name__ == "__main__":
auth.authenticate_user()
gauth = GoogleA... | from oauth2client.client import GoogleCredentials
from pydrive.drive import GoogleDrive
from pydrive.auth import GoogleAuth
from google.colab import auth
if __name__ == "__main__":
auth.authenticate_user()
gauth = GoogleAuth()
gauth.credentials = GoogleCredentials.get_application_default()
drive = G... | none | 1 | 2.72649 | 3 | |
placement_alg/ModifiedDijkstra.py | nigsics/dcpmtool | 3 | 6621733 | <reponame>nigsics/dcpmtool
# Copyright 2018 <NAME>
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agre... | # Copyright 2018 <NAME>
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
... | en | 0.870522 | # Copyright 2018 <NAME> # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software #... | 2.843168 | 3 |
test/scripts/sanity_test.py | bserdar/JovianDSS-KubernetesCSI | 1 | 6621734 | #!/usr/bin/python3
#from fabric.api import env, run
from fabric import Connection
import os
import vagrant
csiTestVM = "fedora29-csi-test-0.2"
def cleanVM(root):
v = vagrant.Vagrant(root=root)
print(" - Cleanig VM ", root)
try:
v.destroy()
except Exception as err:
print(err)
... | #!/usr/bin/python3
#from fabric.api import env, run
from fabric import Connection
import os
import vagrant
csiTestVM = "fedora29-csi-test-0.2"
def cleanVM(root):
v = vagrant.Vagrant(root=root)
print(" - Cleanig VM ", root)
try:
v.destroy()
except Exception as err:
print(err)
... | en | 0.182335 | #!/usr/bin/python3 #from fabric.api import env, run # Start plugin # Run tests #out = v.ssh(command="/home/vagrant/go/src/csi-test/cmd/csi-sanity/csi-sanity -ginkgo.failFast -csi.endpoint 127.0.0.1:15947") | 2.08376 | 2 |
python/pymef90/mesh/__init__.py | jeanmichelscherer/mef90 | 9 | 6621735 | <gh_stars>1-10
import sys
sys.path.append(__path__[0])
from mef90EXODUS import *
from mef90ABAQUS import *
from mef90GMSH import *
from mef90MSC import * | import sys
sys.path.append(__path__[0])
from mef90EXODUS import *
from mef90ABAQUS import *
from mef90GMSH import *
from mef90MSC import * | none | 1 | 1.238229 | 1 | |
examples/example_web_app/setup.py | aalhour/cookiecutter-aiohttp-sqlalchemy | 46 | 6621736 | <reponame>aalhour/cookiecutter-aiohttp-sqlalchemy<gh_stars>10-100
import os
try:
from setuptools import setup, find_packages
except ImportError:
from distutils.core import setup, find_packages
# Get the version
from example_web_app import __version__
def get_long_description():
readme = ""
with op... | import os
try:
from setuptools import setup, find_packages
except ImportError:
from distutils.core import setup, find_packages
# Get the version
from example_web_app import __version__
def get_long_description():
readme = ""
with open('README.md', encoding='utf-8') as readme_file:
readme =... | en | 0.653712 | # Get the version | 1.717431 | 2 |
vorpy/integration/rungekutta.py | vdods/vorpy | 3 | 6621737 | <reponame>vdods/vorpy<filename>vorpy/integration/rungekutta.py
"""
Implements explicit Runge-Kutta integration methods, of ordinary (non-error-estimating) and error-estimating types.
"""
import abc
import numpy as np
import typing
import vorpy.tensor
class RungeKutta(metaclass=abc.ABCMeta):
"""
References:
... | """
Implements explicit Runge-Kutta integration methods, of ordinary (non-error-estimating) and error-estimating types.
"""
import abc
import numpy as np
import typing
import vorpy.tensor
class RungeKutta(metaclass=abc.ABCMeta):
"""
References:
- Wikipedia RK article - https://en.wikipedia.org/wiki/Rung... | en | 0.756888 | Implements explicit Runge-Kutta integration methods, of ordinary (non-error-estimating) and error-estimating types. References: - Wikipedia RK article - https://en.wikipedia.org/wiki/Runge%E2%80%93Kutta_methods - List of RK methods - https://ipfs.io/ipfs/QmXoypizjW3WknFiJnKLwHCnL72vedxjQkDDP1mXWo6uco/wiki/L... | 2.73228 | 3 |
utils.py | Andre6o6/biometrics_project | 0 | 6621738 | <filename>utils.py
import numpy as np
import os, os.path
from skimage import io
def classify(clf, img, classes):
'''
Find image among classes that is closest to img.
'''
distances = np.array(list(map(lambda img2: clf.Distance(img, img2), classes)))
distances = distances / np.sum(distances)
... | <filename>utils.py
import numpy as np
import os, os.path
from skimage import io
def classify(clf, img, classes):
'''
Find image among classes that is closest to img.
'''
distances = np.array(list(map(lambda img2: clf.Distance(img, img2), classes)))
distances = distances / np.sum(distances)
... | en | 0.912992 | Find image among classes that is closest to img. Load and split into train (images to be recognised) and test (class samples). #random.shuffle(subj_images) # Save 1 image as an example of class # Add other images to train set ... # ... and save their class number | 2.798695 | 3 |
openstack/image/v1/image.py | sivel/python-openstacksdk | 1 | 6621739 | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under t... | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under t... | en | 0.853206 | # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under t... | 1.8402 | 2 |
api/serializers.py | Waanneek/mediasoft_test | 0 | 6621740 | <filename>api/serializers.py<gh_stars>0
from datetime import time
from rest_framework import serializers
from api.models import *
class CitySerializer(serializers.ModelSerializer):
id = serializers.IntegerField(read_only=True)
class Meta:
model = CityModel
fields = ['id', 'name']
class Stre... | <filename>api/serializers.py<gh_stars>0
from datetime import time
from rest_framework import serializers
from api.models import *
class CitySerializer(serializers.ModelSerializer):
id = serializers.IntegerField(read_only=True)
class Meta:
model = CityModel
fields = ['id', 'name']
class Stre... | none | 1 | 2.389356 | 2 | |
triple_filtering/dictionaries.py | phongnt570/large-scale-csk-extraction | 3 | 6621741 | <reponame>phongnt570/large-scale-csk-extraction<filename>triple_filtering/dictionaries.py
IGNORED_PO_PAIRS = {
("be", "seen"),
("be", "used"),
("be", "the fact"),
("be taken", "care"),
("make", "sense"),
("make", "sure"),
("make", "use"),
("pay", "attention"),
("be", " capable"),
... | IGNORED_PO_PAIRS = {
("be", "seen"),
("be", "used"),
("be", "the fact"),
("be taken", "care"),
("make", "sense"),
("make", "sure"),
("make", "use"),
("pay", "attention"),
("be", " capable"),
("be", " able"),
("come in", " size"),
("play", " an important role"),
("play... | en | 0.817959 | # NOTE: very noisy statements | 1.94071 | 2 |
dtree/displaytree.py | mgbarsky/botany_citizen | 0 | 6621742 | <filename>dtree/displaytree.py<gh_stars>0
from PIL import Image, ImageDraw
def getwidth(tree):
if tree == None: return 0
if tree.children==None: return 1
width = 0
for value in tree.children.values():
width += getwidth(value)
return width
def getdepth(tree):
if tree == None: return 0
... | <filename>dtree/displaytree.py<gh_stars>0
from PIL import Image, ImageDraw
def getwidth(tree):
if tree == None: return 0
if tree.children==None: return 1
width = 0
for value in tree.children.values():
width += getwidth(value)
return width
def getdepth(tree):
if tree == None: return 0
... | en | 0.796303 | # Get the left and right "endpoints" of this node # Draw the condition string # Draw the result if there is one # Draw a link to the branch # Draw the branch node | 2.889091 | 3 |
client/python/pycrayon/version.py | pitoupitou/crayon | 858 | 6621743 | r"""
Little utility to reveal the package version.
Place in the root dir of the package.
"""
from pkg_resources import get_distribution
__version__ = get_distribution(__name__.split('.')[0]).version
| r"""
Little utility to reveal the package version.
Place in the root dir of the package.
"""
from pkg_resources import get_distribution
__version__ = get_distribution(__name__.split('.')[0]).version
| en | 0.835573 | Little utility to reveal the package version. Place in the root dir of the package. | 1.500794 | 2 |
mapper/property_mappers.py | healyou/godville_monitor | 0 | 6621744 | from abc import ABCMeta, abstractmethod
from typing import Dict, List
def convertDictKeysToList(dict: Dict) -> List:
items: List = list()
for key, value in dict.keys():
items.append(key)
return items
def getValueOrDefaultNone(dict: Dict, key: str) -> object:
return dict.get(key, None)
# аб... | from abc import ABCMeta, abstractmethod
from typing import Dict, List
def convertDictKeysToList(dict: Dict) -> List:
items: List = list()
for key, value in dict.keys():
items.append(key)
return items
def getValueOrDefaultNone(dict: Dict, key: str) -> object:
return dict.get(key, None)
# аб... | ru | 0.996648 | # абстрактный маппер свойства из словаря # Маппер простого значения из словаря # Маппер, который для свойства вернёт None # Маппер листа объектов | 3.398466 | 3 |
aiida_sssp_workflow/calculations/wien2k_ref.py | aiidateam/aiida-sssp-workflow | 0 | 6621745 | # -*- coding: utf-8 -*-
"""
The string copy paste from WIEN2k.txt of calcDelta package version 3.1
and WIEN2K eos results for the rare-earth nitrides (Lanthanides)
"""
WIEN2K_REN_REF = """
# Rare-Earth Nitrids(REN) WIEN2K eos data (courtesy of M. Topsakal)
LaN 18.77799 122.037 4.461
CeN 16.19013 145.439 4.5... | # -*- coding: utf-8 -*-
"""
The string copy paste from WIEN2k.txt of calcDelta package version 3.1
and WIEN2K eos results for the rare-earth nitrides (Lanthanides)
"""
WIEN2K_REN_REF = """
# Rare-Earth Nitrids(REN) WIEN2K eos data (courtesy of M. Topsakal)
LaN 18.77799 122.037 4.461
CeN 16.19013 145.439 4.5... | en | 0.303248 | # -*- coding: utf-8 -*- The string copy paste from WIEN2k.txt of calcDelta package version 3.1 and WIEN2K eos results for the rare-earth nitrides (Lanthanides) # Rare-Earth Nitrids(REN) WIEN2K eos data (courtesy of M. Topsakal) LaN 18.77799 122.037 4.461 CeN 16.19013 145.439 4.513 PrN 16.33072 120.290 4... | 1.466005 | 1 |
blockchain/block.py | bajcmartinez/blockchainpy | 17 | 6621746 | <filename>blockchain/block.py
import hashlib
from api.schema.block import BlockSchema
from time import time
class Block:
def __init__(self, index, transactions, nonce, previous_hash):
"""
Constructs a new block
:param index:
:param transactions:
:param previous_hash:
... | <filename>blockchain/block.py
import hashlib
from api.schema.block import BlockSchema
from time import time
class Block:
def __init__(self, index, transactions, nonce, previous_hash):
"""
Constructs a new block
:param index:
:param transactions:
:param previous_hash:
... | en | 0.723556 | Constructs a new block :param index: :param transactions: :param previous_hash: Serializes a block into a string :return: Calculates the hash of the block :return: | 3.156212 | 3 |
AtCoder/Practice/Beginner/2-2-3/ABC007B.py | scnsh/CompetitiveProgramming | 1 | 6621747 | A = input()
if A == 'a':
print('-1')
else:
print('a')
| A = input()
if A == 'a':
print('-1')
else:
print('a')
| none | 1 | 3.784126 | 4 | |
src/stepseries/step400.py | ponoor/python-step-series | 0 | 6621748 | <filename>src/stepseries/step400.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""4 axis stepper motor driver with and Ethernet interface."""
from .stepXXX import STEPXXX
class STEP400(STEPXXX):
"""Send and receive data from a STEP400 motor driver.
Note:
It is recommended to create a default me... | <filename>src/stepseries/step400.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""4 axis stepper motor driver with and Ethernet interface."""
from .stepXXX import STEPXXX
class STEP400(STEPXXX):
"""Send and receive data from a STEP400 motor driver.
Note:
It is recommended to create a default me... | en | 0.676152 | #!/usr/bin/env python # -*- coding: utf-8 -*- 4 axis stepper motor driver with and Ethernet interface. Send and receive data from a STEP400 motor driver. Note: It is recommended to create a default message handler for this driver. Here is an example: >>> from stepseries.step400 import ... | 3.234877 | 3 |
front/definitions/exceptions.py | zhammer/morning-cd-front | 0 | 6621749 | """Several expected exceptions in the front service."""
class FrontException(Exception):
"""Base exception for front exceptions."""
class ListensError(FrontException):
"""Exception raised upon encountering an error in the listens domain."""
class MusicError(FrontException):
"""Exception raised upon en... | """Several expected exceptions in the front service."""
class FrontException(Exception):
"""Base exception for front exceptions."""
class ListensError(FrontException):
"""Exception raised upon encountering an error in the listens domain."""
class MusicError(FrontException):
"""Exception raised upon en... | en | 0.704531 | Several expected exceptions in the front service. Base exception for front exceptions. Exception raised upon encountering an error in the listens domain. Exception raised upon encountering an error in the music domain. Exception raised upon encountering an error in the sunlight domain. | 2.015136 | 2 |
projects/fizzbuzz/python/fizz_buzz.py | jthompson22/methods | 0 | 6621750 |
def fizz_buzz(num):
string = ' '
for i in range(1,num+1):
if (i%3==0 and i%5==0 and i % 7==0):
string += "fizzbuzzbazz"
#print("fizzbuzzbazz")
elif (i%3==0 and i%5==0):
string += "fizzbuzz"
#print("fizzbuzz")
elif (i%3==0 and i%7==0):
... |
def fizz_buzz(num):
string = ' '
for i in range(1,num+1):
if (i%3==0 and i%5==0 and i % 7==0):
string += "fizzbuzzbazz"
#print("fizzbuzzbazz")
elif (i%3==0 and i%5==0):
string += "fizzbuzz"
#print("fizzbuzz")
elif (i%3==0 and i%7==0):
... | ru | 0.280954 | #print("fizzbuzzbazz") #print("fizzbuzz") #print("fizzbazz") #print("buzzbazz") #print("bazz") #print("fizz") #print("buzz") #print(i) | 3.957291 | 4 |