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
phi/math/backend/_backend.py
marc-gav/PhiFlow
0
4000
<filename>phi/math/backend/_backend.py from collections import namedtuple from contextlib import contextmanager from threading import Barrier from typing import List, Callable import numpy from ._dtype import DType, combine_types SolveResult = namedtuple('SolveResult', [ 'method', 'x', 'residual', 'iterations',...
<filename>phi/math/backend/_backend.py from collections import namedtuple from contextlib import contextmanager from threading import Barrier from typing import List, Callable import numpy from ._dtype import DType, combine_types SolveResult = namedtuple('SolveResult', [ 'method', 'x', 'residual', 'iterations',...
en
0.708661
A physical device that can be selected to perform backend computations. Name of the compute device. CPUs are typically called `'CPU'`. Type of device such as `'CPU'`, `'GPU'` or `'TPU'`. Maximum memory of the device that can be allocated (in bytes). -1 for n/a. Number of CPU cores or GPU multiprocessors. -1 for n/a. Fu...
2.842221
3
bpython/curtsiesfrontend/parse.py
dtrodrigues/bpython
2,168
4001
import re from curtsies.formatstring import fmtstr, FmtStr from curtsies.termformatconstants import ( FG_COLORS, BG_COLORS, colors as CURTSIES_COLORS, ) from functools import partial from ..lazyre import LazyReCompile COLORS = CURTSIES_COLORS + ("default",) CNAMES = dict(zip("krgybmcwd", COLORS)) # hack...
import re from curtsies.formatstring import fmtstr, FmtStr from curtsies.termformatconstants import ( FG_COLORS, BG_COLORS, colors as CURTSIES_COLORS, ) from functools import partial from ..lazyre import LazyReCompile COLORS = CURTSIES_COLORS + ("default",) CNAMES = dict(zip("krgybmcwd", COLORS)) # hack...
en
0.742617
# hack for finding the "inverse" Returns FmtStr constructor for a bpython-style color code Returns a FmtStr object from a bpython-formatted colored string # this isn't according to spec as I understand it # TODO figure out why boldness isn't based on presence of \x02 # hack for finding the "inverse" (?P<colormarker>\x0...
2.522608
3
sarpy/io/general/nitf_elements/tres/unclass/BANDSA.py
pressler-vsc/sarpy
1
4002
<reponame>pressler-vsc/sarpy # -*- coding: utf-8 -*- from ..tre_elements import TREExtension, TREElement __classification__ = "UNCLASSIFIED" __author__ = "<NAME>" class BAND(TREElement): def __init__(self, value): super(BAND, self).__init__() self.add_field('BANDPEAK', 's', 5, value) sel...
# -*- coding: utf-8 -*- from ..tre_elements import TREExtension, TREElement __classification__ = "UNCLASSIFIED" __author__ = "<NAME>" class BAND(TREElement): def __init__(self, value): super(BAND, self).__init__() self.add_field('BANDPEAK', 's', 5, value) self.add_field('BANDLBOUND', 's'...
en
0.769321
# -*- coding: utf-8 -*-
2.220846
2
ktrain/graph/learner.py
husmen/ktrain
1,013
4003
from ..imports import * from .. import utils as U from ..core import GenLearner class NodeClassLearner(GenLearner): """ ``` Main class used to tune and train Keras models for node classification Main parameters are: model (Model): A compiled instance of keras.engine.training.Model train_dat...
from ..imports import * from .. import utils as U from ..core import GenLearner class NodeClassLearner(GenLearner): """ ``` Main class used to tune and train Keras models for node classification Main parameters are: model (Model): A compiled instance of keras.engine.training.Model train_dat...
en
0.763768
``` Main class used to tune and train Keras models for node classification Main parameters are: model (Model): A compiled instance of keras.engine.training.Model train_data (Iterator): a Iterator instance for training set val_data (Iterator): A Iterator instance for validation set ``` ``` ...
2.884221
3
VegaZero2VegaLite.py
Thanksyy/Vega-Zero
5
4004
__author__ = "<NAME>" import json import pandas class VegaZero2VegaLite(object): def __init__(self): pass def parse_vegaZero(self, vega_zero): self.parsed_vegaZero = { 'mark': '', 'data': '', 'encoding': { 'x': '', 'y': { ...
__author__ = "<NAME>" import json import pandas class VegaZero2VegaLite(object): def __init__(self): pass def parse_vegaZero(self, vega_zero): self.parsed_vegaZero = { 'mark': '', 'data': '', 'encoding': { 'x': '', 'y': { ...
en
0.750747
# replace 'and' -- 'or' # ’=‘ in SQL --to--> ’==‘ in Vega-Lite # each = '&' or '|' # only consider this case: '%a%' # only single filter condition # assign some vega-zero keywords to the VegaLiteSpec object # it seems that the group will be performed by VegaLite defaultly, in our cases.
2.988262
3
utils/dancer.py
kmzbrnoI/ac-python
0
4005
"""Library for executing user-defined dance.""" import logging from typing import Any, Dict, Optional, Callable import datetime import ac import ac.blocks from ac import ACs, AC JC = Dict[str, Any] class DanceStartException(Exception): pass class Step: """Base class for all specific dance steps.""" ...
"""Library for executing user-defined dance.""" import logging from typing import Any, Dict, Optional, Callable import datetime import ac import ac.blocks from ac import ACs, AC JC = Dict[str, Any] class DanceStartException(Exception): pass class Step: """Base class for all specific dance steps.""" ...
en
0.81087
Library for executing user-defined dance. Base class for all specific dance steps. Process jc 'name'. If processed already, skip processing and continue. Delay any time. Wait for specific state of any block. See examples below. This AC executes predefined steps. # type: ignore
2.637551
3
praw/models/reddit/mixins/reportable.py
zachwylde00/praw
38
4006
<gh_stars>10-100 """Provide the ReportableMixin class.""" from ....const import API_PATH class ReportableMixin: """Interface for RedditBase classes that can be reported.""" def report(self, reason): """Report this object to the moderators of its subreddit. :param reason: The reason for repor...
"""Provide the ReportableMixin class.""" from ....const import API_PATH class ReportableMixin: """Interface for RedditBase classes that can be reported.""" def report(self, reason): """Report this object to the moderators of its subreddit. :param reason: The reason for reporting. Ra...
en
0.7603
Provide the ReportableMixin class. Interface for RedditBase classes that can be reported. Report this object to the moderators of its subreddit. :param reason: The reason for reporting. Raises :class:`.APIException` if ``reason`` is longer than 100 characters. Example usage: ...
2.757044
3
defense/jpeg_compress.py
TrustworthyDL/LeBA
19
4007
def _jpeg_compression(im): assert torch.is_tensor(im) im = ToPILImage()(im) savepath = BytesIO() im.save(savepath, 'JPEG', quality=75) im = Image.open(savepath) im = ToTensor()(im) return im
def _jpeg_compression(im): assert torch.is_tensor(im) im = ToPILImage()(im) savepath = BytesIO() im.save(savepath, 'JPEG', quality=75) im = Image.open(savepath) im = ToTensor()(im) return im
none
1
2.53273
3
mellon/factories/filesystem/file.py
LaudateCorpus1/mellon
5
4008
<reponame>LaudateCorpus1/mellon import collections import os.path from zope import component from zope import interface from zope.component.factory import Factory from sparc.configuration import container import mellon @interface.implementer(mellon.IByteMellonFile) class MellonByteFileFromFilePathAndConfig(object): ...
import collections import os.path from zope import component from zope import interface from zope.component.factory import Factory from sparc.configuration import container import mellon @interface.implementer(mellon.IByteMellonFile) class MellonByteFileFromFilePathAndConfig(object): def __init__(self, file_p...
en
0.268955
Init Args: config: sparc.configuration.container.ISparcAppPyContainerConfiguration provider with mellon.factories.filesystem[configure.yaml:FileSystemDir] and mellon[configure.yaml:MellonSnippet] entries. #get interface-assigned s...
2.083489
2
dltb/thirdparty/datasource/__init__.py
CogSciUOS/DeepLearningToolbox
2
4009
<gh_stars>1-10 """Predefined Datasources. """ # toolbox imports from ...datasource import Datasource Datasource.register_instance('imagenet-val', __name__ + '.imagenet', 'ImageNet', section='val') # section='train' Datasource.register_instance('dogsandcats', __name__ + '.dogsandcats', ...
"""Predefined Datasources. """ # toolbox imports from ...datasource import Datasource Datasource.register_instance('imagenet-val', __name__ + '.imagenet', 'ImageNet', section='val') # section='train' Datasource.register_instance('dogsandcats', __name__ + '.dogsandcats', ...
en
0.484569
Predefined Datasources. # toolbox imports # section='train'
1.752405
2
tests/test_results.py
babinyurii/RECAN
7
4010
<reponame>babinyurii/RECAN # -*- coding: utf-8 -*- """ Created on Tue Oct 22 15:58:44 2019 @author: babin """ posits_def = [251, 501, 751, 1001, 1251, 1501, 1751, 2001, 2251, 2501, 2751, 3001, 3215] dist_whole_align_ref = {'AB048704.1_genotype_C_': [0.88, 0.938, 0.914, 0.886, 0.89, 0.908, 0.938, 0.9...
# -*- coding: utf-8 -*- """ Created on Tue Oct 22 15:58:44 2019 @author: babin """ posits_def = [251, 501, 751, 1001, 1251, 1501, 1751, 2001, 2251, 2501, 2751, 3001, 3215] dist_whole_align_ref = {'AB048704.1_genotype_C_': [0.88, 0.938, 0.914, 0.886, 0.89, 0.908, 0.938, 0.948, 0.948, 0.886, 0.8...
en
0.808555
# -*- coding: utf-8 -*- Created on Tue Oct 22 15:58:44 2019 @author: babin
1.425331
1
lxmls/readers/simple_data_set.py
SimonSuster/lxmls-toolkit
1
4011
import numpy as np # This class generates a 2D dataset with two classes, "positive" and "negative". # Each class follows a Gaussian distribution. class SimpleDataSet(): ''' A simple two dimentional dataset for visualization purposes. The date set contains points from two gaussians with mean u_i and std_i''' d...
import numpy as np # This class generates a 2D dataset with two classes, "positive" and "negative". # Each class follows a Gaussian distribution. class SimpleDataSet(): ''' A simple two dimentional dataset for visualization purposes. The date set contains points from two gaussians with mean u_i and std_i''' d...
en
0.765766
# This class generates a 2D dataset with two classes, "positive" and "negative". # Each class follows a Gaussian distribution. A simple two dimentional dataset for visualization purposes. The date set contains points from two gaussians with mean u_i and std_i # number of examples of "positive" class # number of example...
3.396599
3
set1/c06_attack_repeating_key_xor.py
kangtastic/cryptopals
1
4012
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Break repeating-key XOR # # It is officially on, now. # # This challenge isn't conceptually hard, but it involves actual # error-prone coding. The other challenges in this set are there to bring # you up to speed. This one is there to qualify you. If you can do t...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Break repeating-key XOR # # It is officially on, now. # # This challenge isn't conceptually hard, but it involves actual # error-prone coding. The other challenges in this set are there to bring # you up to speed. This one is there to qualify you. If you can do t...
en
0.912147
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Break repeating-key XOR # # It is officially on, now. # # This challenge isn't conceptually hard, but it involves actual # error-prone coding. The other challenges in this set are there to bring # you up to speed. This one is there to qualify you. If you can do t...
3.679234
4
c2nl/models/transformer.py
kopf-yhs/ncscos
22
4013
import torch import torch.nn as nn import torch.nn.functional as f from prettytable import PrettyTable from c2nl.modules.char_embedding import CharEmbedding from c2nl.modules.embeddings import Embeddings from c2nl.modules.highway import Highway from c2nl.encoders.transformer import TransformerEncoder from c2nl.decoder...
import torch import torch.nn as nn import torch.nn.functional as f from prettytable import PrettyTable from c2nl.modules.char_embedding import CharEmbedding from c2nl.modules.embeddings import Embeddings from c2nl.modules.highway import Highway from c2nl.encoders.transformer import TransformerEncoder from c2nl.decoder...
en
0.52787
# at least one of word or char embedding options should be True # B x P x d # B x P x f # B x P x d+f # B x P x d+f # B x P x d # B x P x f # B x P x d+f # B x P x d+f # used in inference time # B x seq_len x h # B x seq_len x nlayers x h # Following (https://arxiv.org/pdf/1808.07913.pdf), we split decoder # To accompl...
1.92915
2
cattle/plugins/docker/delegate.py
cjellick/python-agent
8
4014
import logging from cattle import Config from cattle.utils import reply, popen from .compute import DockerCompute from cattle.agent.handler import BaseHandler from cattle.progress import Progress from cattle.type_manager import get_type, MARSHALLER from . import docker_client import subprocess import os import time ...
import logging from cattle import Config from cattle.utils import reply, popen from .compute import DockerCompute from cattle.agent.handler import BaseHandler from cattle.progress import Progress from cattle.type_manager import get_type, MARSHALLER from . import docker_client import subprocess import os import time ...
en
0.704104
# Sleep and try again if missing
1.896255
2
bitraider/strategy.py
ehickox2012/bitraider
2
4015
import sys import pytz #import xml.utils.iso8601 import time import numpy from datetime import date, datetime, timedelta from matplotlib import pyplot as plt from exchange import cb_exchange as cb_exchange from exchange import CoinbaseExchangeAuth from abc import ABCMeta, abstractmethod class strategy(object): """...
import sys import pytz #import xml.utils.iso8601 import time import numpy from datetime import date, datetime, timedelta from matplotlib import pyplot as plt from exchange import cb_exchange as cb_exchange from exchange import CoinbaseExchangeAuth from abc import ABCMeta, abstractmethod class strategy(object): """...
en
0.717355
#import xml.utils.iso8601 `strategy` defines an abstract base strategy class. Minimum required to create a strategy is a file with a class which inherits from strategy containing a backtest_strategy function. As a bonus, strategy includes utility functions like calculate_historic_data. Constructor for an abstract strat...
3.40437
3
neural-networks.py
PacktPublishing/Python-Deep-Learning-for-Beginners-
7
4016
<filename>neural-networks.py import numpy as np # Perceptron def predict_perceptron(inputs, weights): if np.dot(inputs, weights) > 0: return 1 else: return 0 def predict_perceptron_proper(inputs, weights): def step_function(input): return 1 if input > 0 else 0 def linear_mode...
<filename>neural-networks.py import numpy as np # Perceptron def predict_perceptron(inputs, weights): if np.dot(inputs, weights) > 0: return 1 else: return 0 def predict_perceptron_proper(inputs, weights): def step_function(input): return 1 if input > 0 else 0 def linear_mode...
en
0.405554
# Perceptron
3.598567
4
biggan_discovery/orojar_discover.py
andreasjansson/OroJaR
47
4017
""" Learns a matrix of Z-Space directions using a pre-trained BigGAN Generator. Modified from train.py in the PyTorch BigGAN repo. """ import os from tqdm import tqdm import torch import torch.nn as nn import torch.optim import utils import train_fns from sync_batchnorm import patch_replication_callback from torch.u...
""" Learns a matrix of Z-Space directions using a pre-trained BigGAN Generator. Modified from train.py in the PyTorch BigGAN repo. """ import os from tqdm import tqdm import torch import torch.nn as nn import torch.optim import utils import train_fns from sync_batchnorm import patch_replication_callback from torch.u...
en
0.830409
Learns a matrix of Z-Space directions using a pre-trained BigGAN Generator. Modified from train.py in the PyTorch BigGAN repo. This is simply a wrapper class to compute the OroJaR efficiently over several GPUs # The main training file. Config is a dictionary specifying the configuration # of this training run. # Downlo...
2.347137
2
file_importer0.py
Alva789ro/Regional-Comprehensive-Economic-Partnership-RCEP-Economic-Default-Risk-Analysis
1
4018
import xlsxwriter import pandas as pd import numpy as np import mysql.connector australia=pd.read_excel(r'\Users\jesica\Desktop\RCEP_economic_analysis.xlsx', sheet_name='Australia') brunei=pd.read_excel(r'\Users\jesica\Desktop\RCEP_economic_analysis.xlsx', sheet_name='Brunei') cambodia=pd.read_excel(r'\Users\jesica\De...
import xlsxwriter import pandas as pd import numpy as np import mysql.connector australia=pd.read_excel(r'\Users\jesica\Desktop\RCEP_economic_analysis.xlsx', sheet_name='Australia') brunei=pd.read_excel(r'\Users\jesica\Desktop\RCEP_economic_analysis.xlsx', sheet_name='Brunei') cambodia=pd.read_excel(r'\Users\jesica\De...
en
0.377304
mydb = mysql.connector.connect( host = "localhost", user = "root", passwd = "", database = "" ) mycursor = mydb.cursor() sqlformula1 = "INSERT INTO australia VALUES(%s, %s, %s, %s, %s, %s, %s, %s)" for a, b, c, d, e, f, g, h in zip(australia['Year'], australia['RGDP'], australia['NGDP'], australia['GD...
2.246032
2
packer/resources/bootstrap_node.py
VIOOH/nile
4
4019
#!/usr/bin/env python3 import os import re import glob import boto3 import requests import subprocess from time import sleep AWS_REGION = os.environ['AWS_REGION'] DEPLOY_UUID = os.environ['DEPLOY_UUID'] SERVICE_NAME = os.environ['SERVICE_NAME'] MOUNT_POINT = "/var/lib/" + SERVICE_NAME...
#!/usr/bin/env python3 import os import re import glob import boto3 import requests import subprocess from time import sleep AWS_REGION = os.environ['AWS_REGION'] DEPLOY_UUID = os.environ['DEPLOY_UUID'] SERVICE_NAME = os.environ['SERVICE_NAME'] MOUNT_POINT = "/var/lib/" + SERVICE_NAME...
en
0.374695
#!/usr/bin/env python3 # Wait to ensure device is attached # p_partprobe = subprocess.Popen('partprobe'.split(' '), stdout=subprocess.PIPE) # stdout, stderr = p_partprobe.communicate() # print(stdout) # print(stderr) # uses: DEPLOY_UUID, TAG_KEY # uses: MOUNT_POINT, SERVICE_NAME, DEPLOY_UUID, TAG_KEY # uses: NIC_IP
2.028274
2
parsers/srum_parser.py
otoriocyber/Chronos
12
4020
import csv import datetime import random import os from parsers.parser_base import ParserBase FILE_TIME_EPOCH = datetime.datetime(1601, 1, 1) FILE_TIME_MICROSECOND = 10 def filetime_to_epoch_datetime(file_time): if isinstance(file_time, int): microseconds_since_file_time_epoch = file_time / FILE_TIME_MIC...
import csv import datetime import random import os from parsers.parser_base import ParserBase FILE_TIME_EPOCH = datetime.datetime(1601, 1, 1) FILE_TIME_MICROSECOND = 10 def filetime_to_epoch_datetime(file_time): if isinstance(file_time, int): microseconds_since_file_time_epoch = file_time / FILE_TIME_MIC...
none
1
2.331956
2
tests/csrf_tests/test_context_processor.py
Yoann-Vie/esgi-hearthstone
0
4021
from django.http import HttpRequest from django.middleware.csrf import _compare_salted_tokens as equivalent_tokens from django.template.context_processors import csrf from django.test import SimpleTestCase class TestContextProcessor(SimpleTestCase): def test_force_token_to_string(self): request ...
from django.http import HttpRequest from django.middleware.csrf import _compare_salted_tokens as equivalent_tokens from django.template.context_processors import csrf from django.test import SimpleTestCase class TestContextProcessor(SimpleTestCase): def test_force_token_to_string(self): request ...
none
1
2.324888
2
python/das/types.py
marza-animation-planet/das
4
4022
<filename>python/das/types.py import sys import das import traceback class ReservedNameError(Exception): def __init__(self, name): super(ReservedNameError, self).__init__("'%s' is a reserved name" % name) class VersionError(Exception): def __init__(self, msg=None, current_version=None, required_version=...
<filename>python/das/types.py import sys import das import traceback class ReservedNameError(Exception): def __init__(self, name): super(ReservedNameError, self).__init__("'%s' is a reserved name" % name) class VersionError(Exception): def __init__(self, msg=None, current_version=None, required_version=...
en
0.726032
# Always re-raise exception # run self validation first (container validation) # Skip global validaton # Funny, we need to declare *args here, but at the time we reach # the core of the method, tuple is already created # Maybe because tuple is immutable? # def __contains__(self, y): # try: # _v = self._adapt_v...
2.401783
2
track.py
AliabbasMerchant/fileTrackAndBackup
6
4023
#! /usr/bin/python3 from help import * import time # short-forms are used, so as to reduce the .json file size # t : type - d or f # d : directory # f : file # ts : timestamp # dirs : The dictionary containing info about directory contents # time : edit time of the file/folder # s : size of the file/folder # p : full ...
#! /usr/bin/python3 from help import * import time # short-forms are used, so as to reduce the .json file size # t : type - d or f # d : directory # f : file # ts : timestamp # dirs : The dictionary containing info about directory contents # time : edit time of the file/folder # s : size of the file/folder # p : full ...
en
0.352676
#! /usr/bin/python3 # short-forms are used, so as to reduce the .json file size # t : type - d or f # d : directory # f : file # ts : timestamp # dirs : The dictionary containing info about directory contents # time : edit time of the file/folder # s : size of the file/folder # p : full path of the file/folder # n : na...
2.705058
3
clang/tools/scan-build-py/libscanbuild/analyze.py
Kvarnefalk/llvm-project
1
4024
<filename>clang/tools/scan-build-py/libscanbuild/analyze.py<gh_stars>1-10 # -*- coding: utf-8 -*- # Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. # See https://llvm.org/LICENSE.txt for license information. # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception """ This module implemen...
<filename>clang/tools/scan-build-py/libscanbuild/analyze.py<gh_stars>1-10 # -*- coding: utf-8 -*- # Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. # See https://llvm.org/LICENSE.txt for license information. # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception """ This module implemen...
en
0.841132
# -*- coding: utf-8 -*- # Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. # See https://llvm.org/LICENSE.txt for license information. # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception This module implements the 'scan-build' command API. To run the static analyzer against a build i...
1.988493
2
tableborder.py
PIRXrav/pyhack
0
4025
<gh_stars>0 #!/usr/bin/env python3 # pylint: disable=C0103 # pylint: disable=R0902 # pylint: disable=R0903 # pylint: disable=R0913 """ Définie la classe TableBorder """ class TableBorder: """ Facillite l'usage de l'UNICODE """ def __init__(self, top_left, top_split, top_right, ...
#!/usr/bin/env python3 # pylint: disable=C0103 # pylint: disable=R0902 # pylint: disable=R0903 # pylint: disable=R0913 """ Définie la classe TableBorder """ class TableBorder: """ Facillite l'usage de l'UNICODE """ def __init__(self, top_left, top_split, top_right, mi...
fr
0.362801
#!/usr/bin/env python3 # pylint: disable=C0103 # pylint: disable=R0902 # pylint: disable=R0903 # pylint: disable=R0913 Définie la classe TableBorder Facillite l'usage de l'UNICODE Constructeur
2.64941
3
app/urls.py
tkf2019/Vue-Django-SAST-Search
0
4026
<gh_stars>0 from django.conf.urls import url from . import views urlpatterns = [ url(r'^register/', views.register), url(r'^login/', views.login), url(r'logout/', views.logout), url(r'search/', views.search) ]
from django.conf.urls import url from . import views urlpatterns = [ url(r'^register/', views.register), url(r'^login/', views.login), url(r'logout/', views.logout), url(r'search/', views.search) ]
none
1
1.595269
2
custom_components/hasl/sensor.py
Ziqqo/hasl-platform
0
4027
#!/usr/bin/python # -*- coding: utf-8 -*- """Simple service for SL (Storstockholms Lokaltrafik).""" import datetime import json import logging from datetime import timedelta import homeassistant.helpers.config_validation as cv import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA from ho...
#!/usr/bin/python # -*- coding: utf-8 -*- """Simple service for SL (Storstockholms Lokaltrafik).""" import datetime import json import logging from datetime import timedelta import homeassistant.helpers.config_validation as cv import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA from ho...
en
0.685498
#!/usr/bin/python # -*- coding: utf-8 -*- Simple service for SL (Storstockholms Lokaltrafik). # Keys used in the configuration. # Default values for configuration. # Defining the configuration schema. # API Keys Setup the sensors. Trafic Situation Sensor. Return the name of the sensor. Return the icon for the frontend....
1.940315
2
simbad_tools.py
ishivvers/astro
1
4028
""" A quick library to deal with searching simbad for info about a SN and parsing the results. Author: <NAME>, <EMAIL>, 2014 example SIMBAD uri query: http://simbad.u-strasbg.fr/simbad/sim-id?output.format=ASCII&Ident=sn%201998S """ import re from urllib2 import urlopen def get_SN_info( name ): """ Querie...
""" A quick library to deal with searching simbad for info about a SN and parsing the results. Author: <NAME>, <EMAIL>, 2014 example SIMBAD uri query: http://simbad.u-strasbg.fr/simbad/sim-id?output.format=ASCII&Ident=sn%201998S """ import re from urllib2 import urlopen def get_SN_info( name ): """ Querie...
en
0.736947
A quick library to deal with searching simbad for info about a SN and parsing the results. Author: <NAME>, <EMAIL>, 2014 example SIMBAD uri query: http://simbad.u-strasbg.fr/simbad/sim-id?output.format=ASCII&Ident=sn%201998S Queries simbad for SN coords, redshift, and host galaxy. If redshift is not given for S...
3.154911
3
robots/environments.py
StanfordASL/soft-robot-control
5
4029
import os from math import cos from math import sin import Sofa.Core from splib.numerics import Quat, Vec3 from sofacontrol import measurement_models path = os.path.dirname(os.path.abspath(__file__)) class TemplateEnvironment: def __init__(self, name='Template', rayleighMass=0.1, rayleighStiffness=0.1, dt=0.01...
import os from math import cos from math import sin import Sofa.Core from splib.numerics import Quat, Vec3 from sofacontrol import measurement_models path = os.path.dirname(os.path.abspath(__file__)) class TemplateEnvironment: def __init__(self, name='Template', rayleighMass=0.1, rayleighStiffness=0.1, dt=0.01...
en
0.57657
# set-up solvers # default # Without premultiplication with dt # Option 1: # Option 2: Equivalent to option 1 (we believe) # self.robot.addObject('MechanicalObject', src='@loader') # Gives a mass to the model # Add a TetrahedronFEMForceField componant which implement an elastic material model solved using the Finite # ...
2.102496
2
default.py
SimonPreissner/get-shifty
0
4030
""" This file contains meta information and default configurations of the project """ RSC_YEARS = [1660, 1670, 1680, 1690, 1700, 1710, 1720, 1730, 1740, 1750, 1760, 1770, 1780, 1790, 1800, 1810, 1820, 1830, 1840, 1850, 1860, 1870, 1880, 1890, 1900, 1910, 1920] # cf. Chapter 4....
""" This file contains meta information and default configurations of the project """ RSC_YEARS = [1660, 1670, 1680, 1690, 1700, 1710, 1720, 1730, 1740, 1750, 1760, 1770, 1780, 1790, 1800, 1810, 1820, 1830, 1840, 1850, 1860, 1870, 1880, 1890, 1900, 1910, 1920] # cf. Chapter 4....
en
0.674842
This file contains meta information and default configurations of the project # cf. Chapter 4.4.1 of the thesis # Alternatives # parameters passed to the GWOT object # 'euclidian', # 'mean', 'whiten', 'whiten_zca' # 'max', 'median' # #TODO fill in the rest of the options in the comments # 'csls', ... # 'custom', 'zipf'...
1.652773
2
generate_training_data_drb.py
SimonTopp/Graph-WaveNet
0
4031
<reponame>SimonTopp/Graph-WaveNet from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import argparse import numpy as np import os import pandas as pd import util import os.path import pandas as pd import n...
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import argparse import numpy as np import os import pandas as pd import util import os.path import pandas as pd import numpy as np import yaml import xa...
en
0.600793
scale the data so it has a standard deviation of 1 and a mean of zero :param dataset: [xr dataset] input or output data :param std: [xr dataset] standard deviation if scaling test data with dims :param mean: [xr dataset] mean if scaling test data with dims :return: scaled data with original dims # a...
2.75891
3
Phase-1/Python Basic 1/Day-3.py
CodedLadiesInnovateTech/python-challenges
11
4032
<reponame>CodedLadiesInnovateTech/python-challenges <<<<<<< HEAD """ 1. Write a Python program to print the documents (syntax, description etc.) of Python built-in function(s). Sample function : abs() Expected Result : abs(number) -> number Return the absolute value of the argument. ...
<<<<<<< HEAD """ 1. Write a Python program to print the documents (syntax, description etc.) of Python built-in function(s). Sample function : abs() Expected Result : abs(number) -> number Return the absolute value of the argument. Tools: help function 2. Write a Python program to p...
en
0.732932
1. Write a Python program to print the documents (syntax, description etc.) of Python built-in function(s). Sample function : abs() Expected Result : abs(number) -> number Return the absolute value of the argument. Tools: help function 2. Write a Python program to print the calendar...
4.767434
5
tests/python/metaclass_inheritance.py
gmgunter/pyre
25
4033
<filename>tests/python/metaclass_inheritance.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- # # <NAME>. aïvázis # orthologue # (c) 1998-2021 all rights reserved # # """ When a metaclass understands the extra keywords that can be passed during class declaration, it has to override all these to accommodate the chang...
<filename>tests/python/metaclass_inheritance.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- # # <NAME>. aïvázis # orthologue # (c) 1998-2021 all rights reserved # # """ When a metaclass understands the extra keywords that can be passed during class declaration, it has to override all these to accommodate the chang...
en
0.83108
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # <NAME>. aïvázis # orthologue # (c) 1998-2021 all rights reserved # # When a metaclass understands the extra keywords that can be passed during class declaration, it has to override all these to accommodate the change in signature # main # end of file
2.934571
3
cs101/module8/8-1/chroma1.py
idsdlab/basicai_sp21
1
4034
from cs1media import * import math def dist(c1, c2): r1, g1, b1 = c1 r2, g2, b2 = c2 return math.sqrt((r1-r2)**2 + (g1-g2)**2 + (b1-b2)**2) def chroma(img, key, threshold): w, h = img.size() for y in range(h): for x in range(w): p = img.get(x, y) if dist(p, key) < threshold: img.set...
from cs1media import * import math def dist(c1, c2): r1, g1, b1 = c1 r2, g2, b2 = c2 return math.sqrt((r1-r2)**2 + (g1-g2)**2 + (b1-b2)**2) def chroma(img, key, threshold): w, h = img.size() for y in range(h): for x in range(w): p = img.get(x, y) if dist(p, key) < threshold: img.set...
none
1
3.396655
3
wfirst_stars/mklc.py
RuthAngus/wfirst_stars
0
4035
import numpy as np import scipy import scipy.io import pylab import numpy import glob import pyfits def mklc(t, nspot=200, incl=(scipy.pi)*5./12., amp=1., tau=30.5, p=10.0): diffrot = 0. ''' This is a simplified version of the class-based routines in spot_model.py. It generates a light curves for dark, p...
import numpy as np import scipy import scipy.io import pylab import numpy import glob import pyfits def mklc(t, nspot=200, incl=(scipy.pi)*5./12., amp=1., tau=30.5, p=10.0): diffrot = 0. ''' This is a simplified version of the class-based routines in spot_model.py. It generates a light curves for dark, p...
en
0.840359
This is a simplified version of the class-based routines in spot_model.py. It generates a light curves for dark, point like spots with no limb-darkening. Parameters: nspot = desired number of spots present on star at any one time amp = desired light curve amplitude tau = characteris...
2.618161
3
bin/sort.py
pelavarre/pybashish
4
4036
<filename>bin/sort.py #!/usr/bin/env python3 """ usage: sort.py [-h] sort lines options: -h, --help show this help message and exit quirks: sorts tabs as different than spaces sorts some spaces ending a line as different than none ending a line examples: Oh no! No examples disclosed!! 💥 💔 💥 """ # FIXME...
<filename>bin/sort.py #!/usr/bin/env python3 """ usage: sort.py [-h] sort lines options: -h, --help show this help message and exit quirks: sorts tabs as different than spaces sorts some spaces ending a line as different than none ending a line examples: Oh no! No examples disclosed!! 💥 💔 💥 """ # FIXME...
en
0.798646
#!/usr/bin/env python3 usage: sort.py [-h] sort lines options: -h, --help show this help message and exit quirks: sorts tabs as different than spaces sorts some spaces ending a line as different than none ending a line examples: Oh no! No examples disclosed!! 💥 💔 💥 # FIXME: doc -k$N,$N and -n and maybe ...
3.207767
3
davan/http/service/telldus/tdtool.py
davandev/davanserver
0
4037
<reponame>davandev/davanserver<gh_stars>0 #!/usr/bin/env python # -*- coding: utf-8 -*- import sys, getopt, httplib, urllib, json, os import oauth.oauth as oauth import datetime from configobj import ConfigObj import logging global logger logger = logging.getLogger(os.path.basename(__file__)) import davan.util.appli...
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys, getopt, httplib, urllib, json, os import oauth.oauth as oauth import datetime from configobj import ConfigObj import logging global logger logger = logging.getLogger(os.path.basename(__file__)) import davan.util.application_logger as log_manager #insert your ...
en
0.339509
#!/usr/bin/env python # -*- coding: utf-8 -*- #insert your own public_key and private_key
2.249626
2
ichnaea/data/export.py
rajreet/ichnaea
348
4038
from collections import defaultdict import json import re import time from urllib.parse import urlparse import uuid import boto3 import boto3.exceptions import botocore.exceptions import markus import redis.exceptions import requests import requests.exceptions from sqlalchemy import select import sqlalchemy.exc from ...
from collections import defaultdict import json import re import time from urllib.parse import urlparse import uuid import boto3 import boto3.exceptions import botocore.exceptions import markus import redis.exceptions import requests import requests.exceptions from sqlalchemy import select import sqlalchemy.exc from ...
en
0.780739
The incoming queue contains the data collected in the web application. It is the single entrypoint from which all other data pipelines get their data. It distributes the data into the configured export queues, checks those queues and if they contain enough or old enough data schedules an async expo...
2.174272
2
test/inference_correctness/dcn_multi_hot.py
x-y-z/HugeCTR
130
4039
<filename>test/inference_correctness/dcn_multi_hot.py import hugectr from mpi4py import MPI solver = hugectr.CreateSolver(model_name = "dcn", max_eval_batches = 1, batchsize_eval = 16384, batchsize = 16384, ...
<filename>test/inference_correctness/dcn_multi_hot.py import hugectr from mpi4py import MPI solver = hugectr.CreateSolver(model_name = "dcn", max_eval_batches = 1, batchsize_eval = 16384, batchsize = 16384, ...
none
1
1.85315
2
bindings/pydrake/systems/perception.py
RobotLocomotion/drake-python3.7
2
4040
<reponame>RobotLocomotion/drake-python3.7 import numpy as np from pydrake.common.value import AbstractValue from pydrake.math import RigidTransform from pydrake.perception import BaseField, Fields, PointCloud from pydrake.systems.framework import LeafSystem def _TransformPoints(points_Ci, X_CiSi): # Make homogen...
import numpy as np from pydrake.common.value import AbstractValue from pydrake.math import RigidTransform from pydrake.perception import BaseField, Fields, PointCloud from pydrake.systems.framework import LeafSystem def _TransformPoints(points_Ci, X_CiSi): # Make homogeneous copy of points. points_h_Ci = np....
en
0.795661
# Make homogeneous copy of points. # Need manual broadcasting. .. pydrake_system:: name: PointCloudConcatenation input_ports: - point_cloud_CiSi_id0 - X_FCi_id0 - ... - point_cloud_CiSi_idN - X_FCi_idN output_ports: - point_cloud_FS A system that ...
2.304374
2
experiments/db_test.py
mit-ll/CATAN
15
4041
<gh_stars>10-100 #!/usr/bin/env python """ @author <NAME> © 2015 Massachusetts Institute of Technology """ import argparse import random import catan.db from catan.data import NodeMessage # test data STATUS_LIST = ['ok', 'injured', 'deceased'] # nodes def gen_nodes(n, db, start_lat, stop_lat, start_long, stop_long...
#!/usr/bin/env python """ @author <NAME> © 2015 Massachusetts Institute of Technology """ import argparse import random import catan.db from catan.data import NodeMessage # test data STATUS_LIST = ['ok', 'injured', 'deceased'] # nodes def gen_nodes(n, db, start_lat, stop_lat, start_long, stop_long): assert n ...
en
0.701928
#!/usr/bin/env python @author <NAME> © 2015 Massachusetts Institute of Technology # test data # nodes # generate n random nodes, centered around Cambridge # random lat, long # node_id, gps_lat, gps_long, gps_acc, path, timestamp # people Generates n people, random male/female ratio between 5 and 90 years of age # open...
2.861026
3
Medium/200.py
Hellofafar/Leetcode
6
4042
<gh_stars>1-10 # ------------------------------ # 200. Number of Islands # # Description: # Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid...
# ------------------------------ # 200. Number of Islands # # Description: # Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrou...
en
0.629582
# ------------------------------ # 200. Number of Islands # # Description: # Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surroun...
3.942081
4
tests/formatters/fseventsd.py
SamuelePilleri/plaso
0
4043
#!/usr/bin/env python # -*- coding: utf-8 -*- """Tests for the fseventsd record event formatter.""" from __future__ import unicode_literals import unittest from plaso.formatters import fseventsd from tests.formatters import test_lib class FseventsdFormatterTest(test_lib.EventFormatterTestCase): """Tests for the...
#!/usr/bin/env python # -*- coding: utf-8 -*- """Tests for the fseventsd record event formatter.""" from __future__ import unicode_literals import unittest from plaso.formatters import fseventsd from tests.formatters import test_lib class FseventsdFormatterTest(test_lib.EventFormatterTestCase): """Tests for the...
en
0.602035
#!/usr/bin/env python # -*- coding: utf-8 -*- Tests for the fseventsd record event formatter. Tests for the fseventsd record event formatter. Tests the initialization. Tests the GetFormatStringAttributeNames function. # TODO: add test for GetSources.
2.480531
2
train.py
Farzin-Negahbani/PathoNet
0
4044
from keras.callbacks import ModelCheckpoint,Callback,LearningRateScheduler,TensorBoard from keras.models import load_model import random import numpy as np from scipy import misc import gc from keras.optimizers import Adam from imageio import imread from datetime import datetime import os import json import models from...
from keras.callbacks import ModelCheckpoint,Callback,LearningRateScheduler,TensorBoard from keras.models import load_model import random import numpy as np from scipy import misc import gc from keras.optimizers import Adam from imageio import imread from datetime import datetime import os import json import models from...
none
1
2.036933
2
tests/chainer_tests/functions_tests/array_tests/test_flatten.py
mingxiaoh/chainer-v3
7
4045
import unittest import numpy import chainer from chainer import cuda from chainer import functions from chainer import gradient_check from chainer import testing from chainer.testing import attr @testing.parameterize(*testing.product({ 'shape': [(3, 4), ()], 'dtype': [numpy.float16, numpy.float32, numpy.flo...
import unittest import numpy import chainer from chainer import cuda from chainer import functions from chainer import gradient_check from chainer import testing from chainer.testing import attr @testing.parameterize(*testing.product({ 'shape': [(3, 4), ()], 'dtype': [numpy.float16, numpy.float32, numpy.flo...
none
1
2.58771
3
categories/migrations/0001_initial.py
snoop2head/exercise_curation_django
3
4046
# Generated by Django 3.0.3 on 2020-03-24 09:59 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('exercises', '0018_photo_file'), ] operations = [ migrations.CreateModel( na...
# Generated by Django 3.0.3 on 2020-03-24 09:59 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('exercises', '0018_photo_file'), ] operations = [ migrations.CreateModel( na...
en
0.747411
# Generated by Django 3.0.3 on 2020-03-24 09:59
1.778413
2
src/metarl/envs/dm_control/dm_control_env.py
neurips2020submission11699/metarl
2
4047
<filename>src/metarl/envs/dm_control/dm_control_env.py<gh_stars>1-10 from dm_control import suite from dm_control.rl.control import flatten_observation from dm_env import StepType import gym import numpy as np from metarl.envs import Step from metarl.envs.dm_control.dm_control_viewer import DmControlViewer class DmC...
<filename>src/metarl/envs/dm_control/dm_control_env.py<gh_stars>1-10 from dm_control import suite from dm_control.rl.control import flatten_observation from dm_env import StepType import gym import numpy as np from metarl.envs import Step from metarl.envs.dm_control.dm_control_viewer import DmControlViewer class DmC...
en
0.482278
Binding for `dm_control <https://arxiv.org/pdf/1801.00690.pdf>`_ # pylint: disable=inconsistent-return-statements
2.299811
2
python_modules/lakehouse/lakehouse/snowflake_table.py
vatervonacht/dagster
3
4048
from dagster import check from .house import Lakehouse from .table import create_lakehouse_table_def class SnowflakeLakehouse(Lakehouse): def __init__(self): pass def hydrate(self, _context, _table_type, _table_metadata, table_handle, _dest_metadata): return None def materialize(self, c...
from dagster import check from .house import Lakehouse from .table import create_lakehouse_table_def class SnowflakeLakehouse(Lakehouse): def __init__(self): pass def hydrate(self, _context, _table_type, _table_metadata, table_handle, _dest_metadata): return None def materialize(self, c...
none
1
2.264205
2
pype/plugins/maya/publish/validate_look_no_default_shaders.py
tokejepsen/pype
0
4049
<reponame>tokejepsen/pype from maya import cmds import pyblish.api import pype.api import pype.maya.action class ValidateLookNoDefaultShaders(pyblish.api.InstancePlugin): """Validate if any node has a connection to a default shader. This checks whether the look has any members of: - lambert1 - initi...
from maya import cmds import pyblish.api import pype.api import pype.maya.action class ValidateLookNoDefaultShaders(pyblish.api.InstancePlugin): """Validate if any node has a connection to a default shader. This checks whether the look has any members of: - lambert1 - initialShadingGroup - initi...
en
0.846313
Validate if any node has a connection to a default shader. This checks whether the look has any members of: - lambert1 - initialShadingGroup - initialParticleSE - particleCloud1 If any of those is present it will raise an error. A look is not allowed to have any of the "default" shaders pr...
2.57053
3
data_science_app/app.py
Johne-DuChene/data_science_learning_app
0
4050
<gh_stars>0 from flask import Flask # initialize the app app = Flask(__name__) # execute iris function at /iris route @app.route("/iris") def iris(): from sklearn.datasets import load_iris from sklearn.linear_model import LogisticRegression X, y = load_iris(return_X_y=True) clf = LogisticRegression( ...
from flask import Flask # initialize the app app = Flask(__name__) # execute iris function at /iris route @app.route("/iris") def iris(): from sklearn.datasets import load_iris from sklearn.linear_model import LogisticRegression X, y = load_iris(return_X_y=True) clf = LogisticRegression( rando...
en
0.530076
# initialize the app # execute iris function at /iris route
2.758127
3
vbdiar/scoring/normalization.py
VarunSrivastava19/VBDiarization
101
4051
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (C) 2018 Brno University of Technology FIT # Author: <NAME> <<EMAIL>> # All Rights Reserved import os import logging import pickle import multiprocessing import numpy as np from sklearn.metrics.pairwise import cosine_similarity from vbdiar.features.segments...
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (C) 2018 Brno University of Technology FIT # Author: <NAME> <<EMAIL>> # All Rights Reserved import os import logging import pickle import multiprocessing import numpy as np from sklearn.metrics.pairwise import cosine_similarity from vbdiar.features.segments...
en
0.635916
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (C) 2018 Brno University of Technology FIT # Author: <NAME> <<EMAIL>> # All Rights Reserved Args: fns: speakers_dict: features_extractor: embedding_extractor: audio_dir: wav_suffix: in_rttm_dir: r...
2.038463
2
agent_based_models/abm_allelopathy/plot_data.py
mattsmart/biomodels
0
4052
<filename>agent_based_models/abm_allelopathy/plot_data.py import matplotlib.pyplot as plt import os def data_plotter(lattice_dict, datafile_dir, plot_dir): # total spaces on grid implies grid size total_cells = lattice_dict['E'][0] + lattice_dict['D_a'][0] + lattice_dict['D_b'][0] + lattice_dict['B'][0] ...
<filename>agent_based_models/abm_allelopathy/plot_data.py import matplotlib.pyplot as plt import os def data_plotter(lattice_dict, datafile_dir, plot_dir): # total spaces on grid implies grid size total_cells = lattice_dict['E'][0] + lattice_dict['D_a'][0] + lattice_dict['D_b'][0] + lattice_dict['B'][0] ...
en
0.546043
# total spaces on grid implies grid size # alternative: 20.0, 8.0
2.334128
2
azure-mgmt-network/azure/mgmt/network/v2018_10_01/models/virtual_wan_security_providers.py
JonathanGailliez/azure-sdk-for-python
1
4053
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
en
0.553409
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
1.8679
2
jsonresume_theme_stackoverflow/filters.py
flowgunso/jsonresume-theme-stackoverflow
0
4054
import datetime import re from .exceptions import ObjectIsNotADate def format_date(value, format="%d %M %Y"): regex = re.match(r"(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})", value) if regex is not None: date = datetime.date( int(regex.group("year")), int(regex.group("mont...
import datetime import re from .exceptions import ObjectIsNotADate def format_date(value, format="%d %M %Y"): regex = re.match(r"(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})", value) if regex is not None: date = datetime.date( int(regex.group("year")), int(regex.group("mont...
none
1
3.472229
3
ipec/data/core.py
wwwbbb8510/ippso
9
4055
import numpy as np import os import logging from sklearn.model_selection import train_test_split DATASET_ROOT_FOLDER = os.path.abspath('datasets') class DataLoader: train = None validation = None test = None mode = None partial_dataset = None @staticmethod def load(train_path=None, valid...
import numpy as np import os import logging from sklearn.model_selection import train_test_split DATASET_ROOT_FOLDER = os.path.abspath('datasets') class DataLoader: train = None validation = None test = None mode = None partial_dataset = None @staticmethod def load(train_path=None, valid...
en
0.588679
get training data :return: dict of (images, labels) :rtype: dict get validation data :return: dict of (images, labels) :rtype: dict get test data :return: dict of (images, labels) :rtype: dict # randomly pick partial dataset
2.619869
3
FOR/Analisador-completo/main.py
lucasf5/Python
1
4056
<filename>FOR/Analisador-completo/main.py<gh_stars>1-10 # Exercício Python 56: Desenvolva um programa que leia o nome, idade e sexo de 4 pessoas. No final do programa, mostre: a média de idade do grupo, qual é o nome do homem mais velho e quantas mulheres têm menos de 20 anos. mediaidade = '' nomelista = [] idadelista...
<filename>FOR/Analisador-completo/main.py<gh_stars>1-10 # Exercício Python 56: Desenvolva um programa que leia o nome, idade e sexo de 4 pessoas. No final do programa, mostre: a média de idade do grupo, qual é o nome do homem mais velho e quantas mulheres têm menos de 20 anos. mediaidade = '' nomelista = [] idadelista...
pt
0.973299
# Exercício Python 56: Desenvolva um programa que leia o nome, idade e sexo de 4 pessoas. No final do programa, mostre: a média de idade do grupo, qual é o nome do homem mais velho e quantas mulheres têm menos de 20 anos. # ------------------------------------------------------------------- # Adcionei todas idades em u...
3.712274
4
test/python/quantum_info/operators/test_operator.py
EnriqueL8/qiskit-terra
2
4057
<reponame>EnriqueL8/qiskit-terra<filename>test/python/quantum_info/operators/test_operator.py # -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the ...
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any...
en
0.583342
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any ...
2.291649
2
pages/feature_modal.py
jack-skerrett-bluefruit/Python-ScreenPlay
0
4058
<gh_stars>0 from selenium.webdriver.common.by import By class feature_modal: title_textbox = (By.ID, "feature-name") description_textbox = (By.ID, "description") save_button = (By.XPATH, "/html/body/app/div[3]/div[2]/div/div/div/button[1]")
from selenium.webdriver.common.by import By class feature_modal: title_textbox = (By.ID, "feature-name") description_textbox = (By.ID, "description") save_button = (By.XPATH, "/html/body/app/div[3]/div[2]/div/div/div/button[1]")
none
1
2.131076
2
liststations.py
CrookedY/AirPollutionBot
1
4059
from urllib2 import Request, urlopen, URLError import json request = Request('https://uk-air.defra.gov.uk/sos-ukair/api/v1/stations/') try: response = urlopen(request) data = response.read() except URLError, e: print 'error:', e stations= json.loads (data) #extract out station 2 stations2 = stations [7] prope...
from urllib2 import Request, urlopen, URLError import json request = Request('https://uk-air.defra.gov.uk/sos-ukair/api/v1/stations/') try: response = urlopen(request) data = response.read() except URLError, e: print 'error:', e stations= json.loads (data) #extract out station 2 stations2 = stations [7] prope...
en
0.832328
#extract out station 2 #extract ID so can be use in link #print ID #contains station properties data. Need to get to timecourse ID #ID is a key in dictionary so need to extract as a key
3.116202
3
pyfinancials/engine.py
kmiller96/PyFinancials
1
4060
<filename>pyfinancials/engine.py def hello_world(): """Tests the import.""" return "Hello world!"
<filename>pyfinancials/engine.py def hello_world(): """Tests the import.""" return "Hello world!"
en
0.527007
Tests the import.
1.443302
1
core/migrations/0002_auto_20180702_1913.py
mertyildiran/echo
5
4061
<reponame>mertyildiran/echo<gh_stars>1-10 # Generated by Django 2.0.6 on 2018-07-02 19:13 import core.models from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('core', '0001_initial'), ] operations = [ migrations.RenameField( mo...
# Generated by Django 2.0.6 on 2018-07-02 19:13 import core.models from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('core', '0001_initial'), ] operations = [ migrations.RenameField( model_name='echo', old_name='own...
en
0.693346
# Generated by Django 2.0.6 on 2018-07-02 19:13
1.87034
2
tests/test_helpers.py
ajdavis/aiohttp
1
4062
<filename>tests/test_helpers.py import pytest from unittest import mock from aiohttp import helpers import datetime def test_parse_mimetype_1(): assert helpers.parse_mimetype('') == ('', '', '', {}) def test_parse_mimetype_2(): assert helpers.parse_mimetype('*') == ('*', '*', '', {}) def test_parse_mimety...
<filename>tests/test_helpers.py import pytest from unittest import mock from aiohttp import helpers import datetime def test_parse_mimetype_1(): assert helpers.parse_mimetype('') == ('', '', '', {}) def test_parse_mimetype_2(): assert helpers.parse_mimetype('*') == ('*', '*', '', {}) def test_parse_mimety...
en
0.898726
application/json; charset=utf-8; # missing password here # 2-char str is not allowed Docstring. # Ensure we handle unquoted percent signs in redirects. # Ensure requoting doesn't break expectations.
2.413228
2
GenConfigs.py
truls/faas-profiler
0
4063
from os.path import join FAAS_ROOT="/lhome/trulsas/faas-profiler" WORKLOAD_SPECS=join(FAAS_ROOT, "specs", "workloads") #FAAS_ROOT="/home/truls/uni/phd/faas-profiler" WSK_PATH = "wsk" OPENWHISK_PATH = "/lhome/trulsas/openwhisk" #: Location of output data DATA_DIR = join(FAAS_ROOT, "..", "profiler_results") SYSTEM_CPU...
from os.path import join FAAS_ROOT="/lhome/trulsas/faas-profiler" WORKLOAD_SPECS=join(FAAS_ROOT, "specs", "workloads") #FAAS_ROOT="/home/truls/uni/phd/faas-profiler" WSK_PATH = "wsk" OPENWHISK_PATH = "/lhome/trulsas/openwhisk" #: Location of output data DATA_DIR = join(FAAS_ROOT, "..", "profiler_results") SYSTEM_CPU...
en
0.548451
#FAAS_ROOT="/home/truls/uni/phd/faas-profiler" #: Location of output data
1.469259
1
Chapter09/calc.py
LuisPereda/Learning_Python
0
4064
def sum1(a,b): try: c = a+b return c except : print "Error in sum1 function" def divide(a,b): try: c = a/b return c except : print "Error in divide function" print divide(10,0) print sum1(10,0)
def sum1(a,b): try: c = a+b return c except : print "Error in sum1 function" def divide(a,b): try: c = a/b return c except : print "Error in divide function" print divide(10,0) print sum1(10,0)
none
1
3.525509
4
radssh/hostkey.py
Eli-Tarrago/radssh
39
4065
<gh_stars>10-100 # # Copyright (c) 2014, 2016, 2018, 2020 LexisNexis Risk Data Management Inc. # # This file is part of the RadSSH software package. # # RadSSH is free software, released under the Revised BSD License. # You are permitted to use, modify, and redsitribute this software # according to the Revised BSD Lice...
# # Copyright (c) 2014, 2016, 2018, 2020 LexisNexis Risk Data Management Inc. # # This file is part of the RadSSH software package. # # RadSSH is free software, released under the Revised BSD License. # You are permitted to use, modify, and redsitribute this software # according to the Revised BSD License, a copy of wh...
en
0.83345
# # Copyright (c) 2014, 2016, 2018, 2020 LexisNexis Risk Data Management Inc. # # This file is part of the RadSSH software package. # # RadSSH is free software, released under the Revised BSD License. # You are permitted to use, modify, and redsitribute this software # according to the Revised BSD License, a copy of wh...
2.059211
2
nuke/pymmh3.py
jfpanisset/Cryptomatte
543
4066
''' pymmh3 was written by <NAME> and enhanced by <NAME>, and is placed in the public domain. The authors hereby disclaim copyright to this source code. pure python implementation of the murmur3 hash algorithm https://code.google.com/p/smhasher/wiki/MurmurHash3 This was written for the times when you do not want to c...
''' pymmh3 was written by <NAME> and enhanced by <NAME>, and is placed in the public domain. The authors hereby disclaim copyright to this source code. pure python implementation of the murmur3 hash algorithm https://code.google.com/p/smhasher/wiki/MurmurHash3 This was written for the times when you do not want to c...
en
0.721885
pymmh3 was written by <NAME> and enhanced by <NAME>, and is placed in the public domain. The authors hereby disclaim copyright to this source code. pure python implementation of the murmur3 hash algorithm https://code.google.com/p/smhasher/wiki/MurmurHash3 This was written for the times when you do not want to compi...
3.456221
3
bindings/python/tests/test_factory.py
pscff/dlite
10
4067
<reponame>pscff/dlite<gh_stars>1-10 #!/usr/bin/env python # -*- coding: utf-8 -*- import os import dlite thisdir = os.path.abspath(os.path.dirname(__file__)) class Person: def __init__(self, name, age, skills): self.name = name self.age = age self.skills = skills def __repr__(self):...
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import dlite thisdir = os.path.abspath(os.path.dirname(__file__)) class Person: def __init__(self, name, age, skills): self.name = name self.age = age self.skills = skills def __repr__(self): return 'Person(%r, %r, %r)'...
en
0.453372
#!/usr/bin/env python # -*- coding: utf-8 -*- # Print json-representation of person2 using dlite
3.112059
3
week_11_DS_N_Algorithm/03_Thr_Lecture/실습6_연속 부분 최대합.py
bky373/elice-racer-1st
1
4068
''' 연속 부분 최대합 nn개의 숫자가 주어질 때, 연속 부분을 선택하여 그 합을 최대화 하는 프로그램을 작성하시오. 예를 들어, 다음과 같이 8개의 숫자가 있다고 하자. 1 2 -4 5 3 -2 9 -10 이 때, 연속 부분이란 연속하여 숫자를 선택하는 것을 말한다. 가능한 연속 부분으로써 [1, 2, -4], [5, 3, -2, 9], [9, -10] 등이 있을 수 있다. 이 연속 부분들 중에서 가장 합이 큰 연속 부분은 [5, 3, -2, 9] 이며, 이보다 더 합을 크게 할 수는 없다. 따라서 연속 부분 최대합은 5+3+(-2)+9 = 15 이다...
''' 연속 부분 최대합 nn개의 숫자가 주어질 때, 연속 부분을 선택하여 그 합을 최대화 하는 프로그램을 작성하시오. 예를 들어, 다음과 같이 8개의 숫자가 있다고 하자. 1 2 -4 5 3 -2 9 -10 이 때, 연속 부분이란 연속하여 숫자를 선택하는 것을 말한다. 가능한 연속 부분으로써 [1, 2, -4], [5, 3, -2, 9], [9, -10] 등이 있을 수 있다. 이 연속 부분들 중에서 가장 합이 큰 연속 부분은 [5, 3, -2, 9] 이며, 이보다 더 합을 크게 할 수는 없다. 따라서 연속 부분 최대합은 5+3+(-2)+9 = 15 이다...
ko
1.000069
연속 부분 최대합 nn개의 숫자가 주어질 때, 연속 부분을 선택하여 그 합을 최대화 하는 프로그램을 작성하시오. 예를 들어, 다음과 같이 8개의 숫자가 있다고 하자. 1 2 -4 5 3 -2 9 -10 이 때, 연속 부분이란 연속하여 숫자를 선택하는 것을 말한다. 가능한 연속 부분으로써 [1, 2, -4], [5, 3, -2, 9], [9, -10] 등이 있을 수 있다. 이 연속 부분들 중에서 가장 합이 큰 연속 부분은 [5, 3, -2, 9] 이며, 이보다 더 합을 크게 할 수는 없다. 따라서 연속 부분 최대합은 5+3+(-2)+9 = 15 이다. 입...
2.816516
3
tests/test_dns.py
jensstein/mockdock
0
4069
<reponame>jensstein/mockdock #!/usr/bin/env python3 import unittest from mockdock import dns class DNSTest(unittest.TestCase): def test_build_packet(self): data = b"^4\x01\x00\x00\x01\x00\x00\x00\x00\x00\x00\x06google\x03com\x00\x00\x01\x00\x01" packet = dns.build_packet(data, "192.168.0.1") ...
#!/usr/bin/env python3 import unittest from mockdock import dns class DNSTest(unittest.TestCase): def test_build_packet(self): data = b"^4\x01\x00\x00\x01\x00\x00\x00\x00\x00\x00\x06google\x03com\x00\x00\x01\x00\x01" packet = dns.build_packet(data, "192.168.0.1") expeced_result = b"^4\x81...
fr
0.221828
#!/usr/bin/env python3
2.780838
3
tests/conftest.py
zhongnansu/es-cli
6
4070
<filename>tests/conftest.py """ Copyright 2019, Amazon Web Services Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable ...
<filename>tests/conftest.py """ Copyright 2019, Amazon Web Services Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable ...
en
0.839811
Copyright 2019, Amazon Web Services Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, sof...
2.02809
2
Cogs/ServerStats.py
Damiian1/techwizardshardware
0
4071
import asyncio import discord from datetime import datetime from operator import itemgetter from discord.ext import commands from Cogs import Nullify from Cogs import DisplayName from Cogs import UserTime from Cogs import Message def setup(bot): # Add the bot...
import asyncio import discord from datetime import datetime from operator import itemgetter from discord.ext import commands from Cogs import Nullify from Cogs import DisplayName from Cogs import UserTime from Cogs import Message def setup(bot): # Add the bot...
en
0.815187
# Add the bot and deps # Check the message and see if we should allow it - always yes. # This module doesn't need to cancel messages. # Don't count your own, Pooter Lists some info about the current or passed server. # Check if we passed another guild # We didn't find it # Get localized user time # bot_percent = "{:,g}...
2.535952
3
chess_commentary_model/transformers_model/dataset_preprocessing.py
Rseiji/TCC-2020
0
4072
<filename>chess_commentary_model/transformers_model/dataset_preprocessing.py """Métodos de preprocessamento de testes individuais """ import pandas as pd import numpy as np import math def test_1(df, seed=0): """training: balanced; test: balanced training: 80k (40k 0, 40k 1) test: 20k (10k 0, 10k...
<filename>chess_commentary_model/transformers_model/dataset_preprocessing.py """Métodos de preprocessamento de testes individuais """ import pandas as pd import numpy as np import math def test_1(df, seed=0): """training: balanced; test: balanced training: 80k (40k 0, 40k 1) test: 20k (10k 0, 10k...
en
0.710715
Métodos de preprocessamento de testes individuais training: balanced; test: balanced training: 80k (40k 0, 40k 1) test: 20k (10k 0, 10k 1) training: balanced; test: unbalanced training: 80k (40k 0, 40k 1) test: 20k (4k 0, 16k 1) training: unbalanced; test: unbalanced training: 80k ...
2.775193
3
venv/Lib/site-packages/CoolProp/constants.py
kubakoziczak/gasSteamPowerPlant
0
4073
# This file is automatically generated by the generate_constants_module.py script in wrappers/Python. # DO NOT MODIFY THE CONTENTS OF THIS FILE! from __future__ import absolute_import from . import _constants INVALID_PARAMETER = _constants.INVALID_PARAMETER igas_constant = _constants.igas_constant imolar_mass = _cons...
# This file is automatically generated by the generate_constants_module.py script in wrappers/Python. # DO NOT MODIFY THE CONTENTS OF THIS FILE! from __future__ import absolute_import from . import _constants INVALID_PARAMETER = _constants.INVALID_PARAMETER igas_constant = _constants.igas_constant imolar_mass = _cons...
en
0.505264
# This file is automatically generated by the generate_constants_module.py script in wrappers/Python. # DO NOT MODIFY THE CONTENTS OF THIS FILE!
1.214307
1
torch_datasets/samplers/balanced_batch_sampler.py
mingruimingrui/torch-datasets
0
4074
import random import torch.utils.data.sampler class BalancedBatchSampler(torch.utils.data.sampler.BatchSampler): def __init__( self, dataset_labels, batch_size=1, steps=None, n_classes=0, n_samples=2 ): """ Create a balanced batch sampler for label based...
import random import torch.utils.data.sampler class BalancedBatchSampler(torch.utils.data.sampler.BatchSampler): def __init__( self, dataset_labels, batch_size=1, steps=None, n_classes=0, n_samples=2 ): """ Create a balanced batch sampler for label based...
en
0.679254
Create a balanced batch sampler for label based datasets Args dataset_labels : Labels of every entry from a dataset (in the same sequence) batch_size : batch_size no explaination needed step_size : Number of batches to generate (if None, then dataset_size / batch_siz...
3.151266
3
ambari-common/src/main/python/resource_management/libraries/functions/get_bare_principal.py
likenamehaojie/Apache-Ambari-ZH
1,664
4075
#!/usr/bin/env python """ 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");...
#!/usr/bin/env python """ 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");...
en
0.799659
#!/usr/bin/env python 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...
2.298561
2
04/cross_validation.01.py
study-machine-learning/dongheon.shin
2
4076
<filename>04/cross_validation.01.py<gh_stars>1-10 from sklearn import svm, metrics import random import re def split(rows): data = [] labels = [] for row in rows: data.append(row[0:4]) labels.append(row[4]) return (data, labels) def calculate_score(train, test): train_data,...
<filename>04/cross_validation.01.py<gh_stars>1-10 from sklearn import svm, metrics import random import re def split(rows): data = [] labels = [] for row in rows: data.append(row[0:4]) labels.append(row[4]) return (data, labels) def calculate_score(train, test): train_data,...
none
1
2.870315
3
third_party/org_specs2.bzl
wix/wix-oss-infra
3
4077
<gh_stars>1-10 load("@wix_oss_infra//:import_external.bzl", import_external = "safe_wix_scala_maven_import_external") def dependencies(): import_external( name = "org_specs2_specs2_fp_2_12", artifact = "org.specs2:specs2-fp_2.12:4.8.3", artifact_sha256 = "777962ca58054a9ea86e294e025453ecf3...
load("@wix_oss_infra//:import_external.bzl", import_external = "safe_wix_scala_maven_import_external") def dependencies(): import_external( name = "org_specs2_specs2_fp_2_12", artifact = "org.specs2:specs2-fp_2.12:4.8.3", artifact_sha256 = "777962ca58054a9ea86e294e025453ecf394c60084c28bd61...
none
1
1.453159
1
task/w2/trenirovka/12-rivnist 2.py
beregok/pythontask
1
4078
a = int(input()) b = int(input()) c = int(input()) d = int(input()) if a == 0 and b == 0: print("INF") else: if (d - b * c / a) != 0 and (- b / a) == (- b // a): print(- b // a) else: print("NO")
a = int(input()) b = int(input()) c = int(input()) d = int(input()) if a == 0 and b == 0: print("INF") else: if (d - b * c / a) != 0 and (- b / a) == (- b // a): print(- b // a) else: print("NO")
none
1
3.536719
4
src/reg_resampler.py
atif-hassan/Regression_ReSampling
15
4079
class resampler: def __init__(self): import pandas as pd from sklearn.preprocessing import LabelEncoder from collections import Counter import numpy as np self.bins = 3 self.pd = pd self.LabelEncoder = LabelEncoder self.Counter = Counter ...
class resampler: def __init__(self): import pandas as pd from sklearn.preprocessing import LabelEncoder from collections import Counter import numpy as np self.bins = 3 self.pd = pd self.LabelEncoder = LabelEncoder self.Counter = Counter ...
en
0.865244
# This function adds classes to each sample and returns the class list as a dataframe/numpy array (as per input) # It also merges classes as and when required # If data is numpy, then convert it into pandas # Use qcut if balanced binning is required # Pandas outputs ranges after binning. Convert ranges to classes # Mer...
3.191765
3
get_data/speech_commands.py
patrick-kidger/generalised_shapelets
32
4080
<reponame>patrick-kidger/generalised_shapelets import os import pathlib import sklearn.model_selection import tarfile import torch import torchaudio import urllib.request here = pathlib.Path(__file__).resolve().parent def _split_data(tensor, stratify): # 0.7/0.15/0.15 train/val/test split (train_tensor, test...
import os import pathlib import sklearn.model_selection import tarfile import torch import torchaudio import urllib.request here = pathlib.Path(__file__).resolve().parent def _split_data(tensor, stratify): # 0.7/0.15/0.15 train/val/test split (train_tensor, testval_tensor, train_stratify, testval_strati...
en
0.901854
# 0.7/0.15/0.15 train/val/test split # for forward compatbility if they fix it # Normalization argument doesn't seem to work so we do it manually. # A few samples are shorter than the full length; for simplicity we discard them. # X is of shape (batch=34975, length=16000, channels=1) # X is of shape (batch=34975, lengt...
2.885396
3
app/endpoints/products.py
duch94/spark_crud_test
0
4081
<reponame>duch94/spark_crud_test from datetime import datetime from typing import List from flask import Blueprint, jsonify, request, json from app.models.products import Product, Category, products_categories from app import db products_blueprint = Blueprint('products', __name__) def create_or_get_cate...
from datetime import datetime from typing import List from flask import Blueprint, jsonify, request, json from app.models.products import Product, Category, products_categories from app import db products_blueprint = Blueprint('products', __name__) def create_or_get_categories(p: dict) -> List[Category]...
en
0.455655
Func to get existing categories objects or create new otherwise :param p: payload of request :return: list of categories
2.91144
3
util/config/validators/test/test_validate_bitbucket_trigger.py
giuseppe/quay
2,027
4082
import pytest from httmock import urlmatch, HTTMock from util.config import URLSchemeAndHostname from util.config.validator import ValidatorContext from util.config.validators import ConfigValidationException from util.config.validators.validate_bitbucket_trigger import BitbucketTriggerValidator from test.fixtures i...
import pytest from httmock import urlmatch, HTTMock from util.config import URLSchemeAndHostname from util.config.validator import ValidatorContext from util.config.validators import ConfigValidationException from util.config.validators.validate_bitbucket_trigger import BitbucketTriggerValidator from test.fixtures i...
none
1
2.057448
2
Refraction.py
silkoch42/Geometric-Optics-from-QM
0
4083
<reponame>silkoch42/Geometric-Optics-from-QM # -*- coding: utf-8 -*- """ Created on Fri Mar 15 16:51:16 2019 @author: Silvan """ import numpy as np import scipy import matplotlib.pyplot as plt k=1000 n1=2.0 n2=1.0 alpha=np.pi/6.0 beta=np.arcsin(n2/n1*np.sin(alpha)) ya=1.0 xa=-ya*np.tan(alpha) ...
# -*- coding: utf-8 -*- """ Created on Fri Mar 15 16:51:16 2019 @author: Silvan """ import numpy as np import scipy import matplotlib.pyplot as plt k=1000 n1=2.0 n2=1.0 alpha=np.pi/6.0 beta=np.arcsin(n2/n1*np.sin(alpha)) ya=1.0 xa=-ya*np.tan(alpha) yb=-1.0 xb=-yb*np.tan(beta) def s(x): ...
en
0.207945
# -*- coding: utf-8 -*- Created on Fri Mar 15 16:51:16 2019 @author: Silvan #Maximum Number of subdivisions for integral calculations #plt.errorbar(x,K2/M,0.1*K2/M) #plt.text(1.1,0.5,r'$|\int_{-R}^{R}e^{i k s(x)}dx|^2$',fontsize=20) #N=20 # #dx=np.linspace(0,10,N) # #P=np.ones(N) # #for i in range(N): # print(i+1...
2.601061
3
readthedocs/docsitalia/management/commands/clear_elasticsearch.py
italia/readthedocs.org
19
4084
<reponame>italia/readthedocs.org<gh_stars>10-100 """Remove the readthedocs elasticsearch index.""" from __future__ import absolute_import from django.conf import settings from django.core.management.base import BaseCommand from elasticsearch import Elasticsearch class Command(BaseCommand): """Clear elasticsea...
"""Remove the readthedocs elasticsearch index.""" from __future__ import absolute_import from django.conf import settings from django.core.management.base import BaseCommand from elasticsearch import Elasticsearch class Command(BaseCommand): """Clear elasticsearch index.""" def handle(self, *args, **opti...
en
0.643325
Remove the readthedocs elasticsearch index. Clear elasticsearch index. handle command.
1.656461
2
train.py
vnbot2/BigGAN-PyTorch
0
4085
""" BigGAN: The Authorized Unofficial PyTorch release Code by <NAME> and <NAME> This code is an unofficial reimplementation of "Large-Scale GAN Training for High Fidelity Natural Image Synthesis," by <NAME>, <NAME>, and <NAME> (arXiv 1809.11096). Let's go. """ import datetime import time import torc...
""" BigGAN: The Authorized Unofficial PyTorch release Code by <NAME> and <NAME> This code is an unofficial reimplementation of "Large-Scale GAN Training for High Fidelity Natural Image Synthesis," by <NAME>, <NAME>, and <NAME> (arXiv 1809.11096). Let's go. """ import datetime import time import torc...
en
0.848216
BigGAN: The Authorized Unofficial PyTorch release Code by <NAME> and <NAME> This code is an unofficial reimplementation of "Large-Scale GAN Training for High Fidelity Natural Image Synthesis," by <NAME>, <NAME>, and <NAME> (arXiv 1809.11096). Let's go. # IMG_SIZE = 64 # IMG_SIZE_2 = IMG_SIZE * 2 # U...
2.43992
2
geocamUtil/tempfiles.py
geocam/geocamUtilWeb
4
4086
<reponame>geocam/geocamUtilWeb<gh_stars>1-10 # __BEGIN_LICENSE__ #Copyright (c) 2015, United States Government, as represented by the #Administrator of the National Aeronautics and Space Administration. #All rights reserved. # __END_LICENSE__ import os import time import random import shutil from glob import glob im...
# __BEGIN_LICENSE__ #Copyright (c) 2015, United States Government, as represented by the #Administrator of the National Aeronautics and Space Administration. #All rights reserved. # __END_LICENSE__ import os import time import random import shutil from glob import glob import traceback import sys from geocamUtil im...
en
0.892245
# __BEGIN_LICENSE__ #Copyright (c) 2015, United States Government, as represented by the #Administrator of the National Aeronautics and Space Administration. #All rights reserved. # __END_LICENSE__
1.923968
2
Ex1:Tests/ex2.py
Lludion/Exercises-SE
0
4087
# Ce fichier contient (au moins) cinq erreurs. # Instructions: # - tester jusqu'à atteindre 100% de couverture; # - corriger les bugs;" # - envoyer le diff ou le dépôt git par email.""" import hypothesis from hypothesis import given, settings from hypothesis.strategies import integers, lists class BinHeap: #st...
# Ce fichier contient (au moins) cinq erreurs. # Instructions: # - tester jusqu'à atteindre 100% de couverture; # - corriger les bugs;" # - envoyer le diff ou le dépôt git par email.""" import hypothesis from hypothesis import given, settings from hypothesis.strategies import integers, lists class BinHeap: #st...
fr
0.410245
# Ce fichier contient (au moins) cinq erreurs. # Instructions: # - tester jusqu'à atteindre 100% de couverture; # - corriger les bugs;" # - envoyer le diff ou le dépôt git par email.""" #structure de tas binaires d'entiers #initialise un tas binaire d'entiers avec un element 0 #taille de la liste heapList (invariant...
3.563407
4
python/snewpy/snowglobes.py
svalder/snewpy
0
4088
<gh_stars>0 # -*- coding: utf-8 -*- """The ``snewpy.snowglobes`` module contains functions for interacting with SNOwGLoBES. `SNOwGLoBES <https://github.com/SNOwGLoBES/snowglobes>`_ can estimate detected event rates from a given input supernova neutrino flux. It supports many different neutrino detectors, detector mate...
# -*- coding: utf-8 -*- """The ``snewpy.snowglobes`` module contains functions for interacting with SNOwGLoBES. `SNOwGLoBES <https://github.com/SNOwGLoBES/snowglobes>`_ can estimate detected event rates from a given input supernova neutrino flux. It supports many different neutrino detectors, detector materials and in...
en
0.75036
# -*- coding: utf-8 -*- The ``snewpy.snowglobes`` module contains functions for interacting with SNOwGLoBES. `SNOwGLoBES <https://github.com/SNOwGLoBES/snowglobes>`_ can estimate detected event rates from a given input supernova neutrino flux. It supports many different neutrino detectors, detector materials and inter...
2.568571
3
rlcycle/dqn_base/loss.py
cyoon1729/Rlcycle
128
4089
from typing import List, Tuple from omegaconf import DictConfig import torch import torch.nn as nn import torch.nn.functional as F from rlcycle.common.abstract.loss import Loss class DQNLoss(Loss): """Compute double DQN loss""" def __init__(self, hyper_params: DictConfig, use_cuda: bool): Loss.__in...
from typing import List, Tuple from omegaconf import DictConfig import torch import torch.nn as nn import torch.nn.functional as F from rlcycle.common.abstract.loss import Loss class DQNLoss(Loss): """Compute double DQN loss""" def __init__(self, hyper_params: DictConfig, use_cuda: bool): Loss.__in...
en
0.398257
Compute double DQN loss Compute quantile regression loss Compute C51 loss
2.337731
2
scripts/gap_filling_viewer.py
raphischer/probgf
3
4090
<gh_stars>1-10 """viewer application which allows to interactively view spatio-temporal gap filling results""" import os import argparse from datetime import datetime, timedelta from tkinter import Canvas, Tk, Button, RAISED, DISABLED, SUNKEN, NORMAL import numpy as np from PIL import Image, ImageTk import probgf.media...
"""viewer application which allows to interactively view spatio-temporal gap filling results""" import os import argparse from datetime import datetime, timedelta from tkinter import Canvas, Tk, Button, RAISED, DISABLED, SUNKEN, NORMAL import numpy as np from PIL import Image, ImageTk import probgf.media as media cla...
en
0.731141
viewer application which allows to interactively view spatio-temporal gap filling results # setup images # width of each displayed image # masked full images # unmasked full images # text labels and logos # image timeline # images and buttons # full image width # images for visualization # bind buttons and keys
2.68058
3
paypal/pro/tests.py
pdfcrowd/django-paypal
1
4091
<gh_stars>1-10 #!/usr/bin/python # -*- coding: utf-8 -*- from django.conf import settings from django.core.handlers.wsgi import WSGIRequest from django.forms import ValidationError from django.http import QueryDict from django.test import TestCase from django.test.client import Client from paypal.pro.fields import Cre...
#!/usr/bin/python # -*- coding: utf-8 -*- from django.conf import settings from django.core.handlers.wsgi import WSGIRequest from django.forms import ValidationError from django.http import QueryDict from django.test import TestCase from django.test.client import Client from paypal.pro.fields import CreditCardField fr...
en
0.373435
#!/usr/bin/python # -*- coding: utf-8 -*- # Used to generate request objects. # """Dummy class for testing PayPalWPP.""" # responses = { # # @@@ Need some reals data here. # "DoDirectPayment": """ack=Success&timestamp=2009-03-12T23%3A52%3A33Z&l_severitycode0=Error&l_shortmessage0=Security+error&...
2.17433
2
Hackerrank_Bot_Saves_Princess.py
madhurgupta96/Algorithmic-Journey
0
4092
# -*- coding: utf-8 -*- """ Created on Mon Dec 7 19:46:40 2020 @author: Intel """ def displayPathtoPrincess(n,grid): me_i=n//2 me_j=n//2 for i in range(n): if 'p' in grid[i]: pe_i=i for j in range(n): if 'p'==grid[i][j]: pe...
# -*- coding: utf-8 -*- """ Created on Mon Dec 7 19:46:40 2020 @author: Intel """ def displayPathtoPrincess(n,grid): me_i=n//2 me_j=n//2 for i in range(n): if 'p' in grid[i]: pe_i=i for j in range(n): if 'p'==grid[i][j]: pe...
en
0.721303
# -*- coding: utf-8 -*- Created on Mon Dec 7 19:46:40 2020 @author: Intel
3.692683
4
gelviz/basic.py
HiDiHlabs/gelviz
0
4093
<gh_stars>0 import matplotlib.pyplot as plt import pybedtools import pandas as pnd import numpy as np import tabix import matplotlib.ticker as ticker from matplotlib.patches import Rectangle from matplotlib.patches import Arrow from matplotlib.path import Path from matplotlib.patches import PathPatch import matplotlib....
import matplotlib.pyplot as plt import pybedtools import pandas as pnd import numpy as np import tabix import matplotlib.ticker as ticker from matplotlib.patches import Rectangle from matplotlib.patches import Arrow from matplotlib.path import Path from matplotlib.patches import PathPatch import matplotlib.cm as cm imp...
en
0.587636
Function for plotting gene structures, i.e. introns exons of genes. :param genes_bed: :class:`pybedtools.BedTool` object containing TX start, and TX end of genes. :type genes_bed: :class:`pybedtools.BedTool` :param exons_bed: :class:`pybedtools.BedTool` object containing exons of genes. ...
2.580891
3
toc/fsa/fsa.py
djrochford/toc
0
4094
<filename>toc/fsa/fsa.py<gh_stars>0 """ File containing DFA and NFA public classes """ import collections.abc from itertools import product, chain, combinations from string import printable from typing import ( AbstractSet, Container, FrozenSet, Iterable, List, Mapping, MutableMapping, O...
<filename>toc/fsa/fsa.py<gh_stars>0 """ File containing DFA and NFA public classes """ import collections.abc from itertools import product, chain, combinations from string import printable from typing import ( AbstractSet, Container, FrozenSet, Iterable, List, Mapping, MutableMapping, O...
en
0.860103
File containing DFA and NFA public classes Output a GNFA equivalent to `self` with one less state in it. A nondeterministic finite automaton class. Takes three keyword arguments: - `transition_function`: Mapping[Tuple[State, Symbol], AbstractSet[State]] - `start_state`: State - `accept_states`: AbstractS...
2.673539
3
Numbers/Roman Number Generator/tests.py
fossabot/IdeaBag2-Solutions
10
4095
<reponame>fossabot/IdeaBag2-Solutions<filename>Numbers/Roman Number Generator/tests.py #!/usr/bin/env python3 import unittest from roman_number_generator import arabic_to_roman class Test(unittest.TestCase): def _start_arabic_to_roman(self): self.assertRaises(ValueError, arabic_to_roman, 4000) s...
Number Generator/tests.py #!/usr/bin/env python3 import unittest from roman_number_generator import arabic_to_roman class Test(unittest.TestCase): def _start_arabic_to_roman(self): self.assertRaises(ValueError, arabic_to_roman, 4000) self.assertEqual(arabic_to_roman(4), "IV") self.assert...
fr
0.221828
#!/usr/bin/env python3
3.35965
3
modules/moduleBase.py
saintaardvark/glouton-satnogs-data-downloader
0
4096
from infrastructure.satnogClient import SatnogClient import os class ModuleBase: def __init__(self, working_dir): self.working_dir = working_dir def runAfterDownload(self, file_name, full_path, observation): raise NotImplementedError()
from infrastructure.satnogClient import SatnogClient import os class ModuleBase: def __init__(self, working_dir): self.working_dir = working_dir def runAfterDownload(self, file_name, full_path, observation): raise NotImplementedError()
none
1
1.960945
2
oregano_plugins/fusion/server.py
MrNaif2018/Oregano
0
4097
<reponame>MrNaif2018/Oregano #!/usr/bin/env python3 # # Oregano - a lightweight Ergon client # CashFusion - an advanced coin anonymizer # # Copyright (C) 2020 <NAME> # # Permission is hereby granted, free of charge, to any person # obtaining a copy of this software and associated documentation files # (the "Software"),...
#!/usr/bin/env python3 # # Oregano - a lightweight Ergon client # CashFusion - an advanced coin anonymizer # # Copyright (C) 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 with...
en
0.912131
#!/usr/bin/env python3 # # Oregano - a lightweight Ergon client # CashFusion - an advanced coin anonymizer # # Copyright (C) 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 with...
1.578609
2
Excercici4Package/ex4.py
jtorrenth/CienciaDades
0
4098
<gh_stars>0 import matplotlib.pyplot as plt def countvalues(dataframe, subject): # Filtrem i tractem el dataset economydf = filtrar(dataframe, "economy") # el printem printar(economydf, subject) # Filtrem ara per subject infected i ho desem en un altre df infectedf = filtrar(dataframe, "infe...
import matplotlib.pyplot as plt def countvalues(dataframe, subject): # Filtrem i tractem el dataset economydf = filtrar(dataframe, "economy") # el printem printar(economydf, subject) # Filtrem ara per subject infected i ho desem en un altre df infectedf = filtrar(dataframe, "infected") #...
ca
0.944866
# Filtrem i tractem el dataset # el printem # Filtrem ara per subject infected i ho desem en un altre df # Calculem els percentatjes # Els printem # Printem a la consola els valors # Finalment, grafiquem # Cal tancar el grafic per a seguir amb l'execució # Afegim els valors en funció del samplesize a dues noves columne...
3.449601
3
build/rules.bzl
filmil/bazel-ebook
9
4099
<gh_stars>1-10 # Copyright (C) 2020 Google Inc. # # This file has been licensed under Apache 2.0 license. Please see the LICENSE # file at the root of the repository. # Build rules for building ebooks. # This is the container CONTAINER = "filipfilmar/ebook-buildenv:1.1" # Use this for quick local runs. #CONTAINER =...
# Copyright (C) 2020 Google Inc. # # This file has been licensed under Apache 2.0 license. Please see the LICENSE # file at the root of the repository. # Build rules for building ebooks. # This is the container CONTAINER = "filipfilmar/ebook-buildenv:1.1" # Use this for quick local runs. #CONTAINER = "ebook-builden...
en
0.596982
# Copyright (C) 2020 Google Inc. # # This file has been licensed under Apache 2.0 license. Please see the LICENSE # file at the root of the repository. # Build rules for building ebooks. # This is the container # Use this for quick local runs. #CONTAINER = "ebook-buildenv:local" # Returns the docker_run script invocat...
2.434261
2