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/attacks/class_test.py | henrik997/privacy-evaluator | 0 | 4400 | import pytest
from privacy_evaluator.attacks.sample_attack import Sample_Attack
"""
This test only test if no error is thrown when calling the function, can be removed in the future
"""
def test_sample_attack():
test = Sample_Attack(0, 0, 0)
test.perform_attack()
| import pytest
from privacy_evaluator.attacks.sample_attack import Sample_Attack
"""
This test only test if no error is thrown when calling the function, can be removed in the future
"""
def test_sample_attack():
test = Sample_Attack(0, 0, 0)
test.perform_attack()
| en | 0.779464 | This test only test if no error is thrown when calling the function, can be removed in the future | 2.559874 | 3 |
setup.py | Oli2/presto-python-client | 0 | 4401 | # 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 th... | # 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 th... | en | 0.834982 | # 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 th... | 1.482203 | 1 |
Graphs/Pie Chart.py | TausifAnsari/PyHub | 1 | 4402 | <gh_stars>1-10
import matplotlib.pyplot as graph
subject = ["Probability", "Calculas", "Discrete Mathematics", "Adv Engineering Mathematics",
"Linear Algebra", "Cryptography"]
weightage = [250,900,850,1200,290,345]
seperator = [0.05,0,0,0,0.05,0.05]
graph.title("Mathematics Topic Weightage")
graph.pie(weightage,la... | import matplotlib.pyplot as graph
subject = ["Probability", "Calculas", "Discrete Mathematics", "Adv Engineering Mathematics",
"Linear Algebra", "Cryptography"]
weightage = [250,900,850,1200,290,345]
seperator = [0.05,0,0,0,0.05,0.05]
graph.title("Mathematics Topic Weightage")
graph.pie(weightage,labels=subject,au... | none | 1 | 2.772022 | 3 | |
exercises/perform_model_selection.py | noavilk/IML.HUJI | 0 | 4403 | from __future__ import annotations
import numpy as np
import pandas as pd
from sklearn import datasets
from IMLearn.metrics import mean_square_error
from IMLearn.utils import split_train_test
from IMLearn.model_selection import cross_validate
from IMLearn.learners.regressors import PolynomialFitting, LinearRegression, ... | from __future__ import annotations
import numpy as np
import pandas as pd
from sklearn import datasets
from IMLearn.metrics import mean_square_error
from IMLearn.utils import split_train_test
from IMLearn.model_selection import cross_validate
from IMLearn.learners.regressors import PolynomialFitting, LinearRegression, ... | en | 0.649315 | Simulate data from a polynomial model and use cross-validation to select the best fitting degree Parameters ---------- n_samples: int, default=100 Number of samples to generate noise: float, default = 5 Noise level to simulate in responses # Question 1 - Generate dataset for model f(x)... | 3.045249 | 3 |
libraries/tools/media_utils.py | unfoldingWord-dev/d43-catalog | 1 | 4404 | import re
import copy
def parse_media(media, content_version, project_chapters):
"""
Converts a media object into formats usable in the catalog
:param media: the media object
:type media: dict
:param content_version: the current version of the source content
:type content_version: string
:p... | import re
import copy
def parse_media(media, content_version, project_chapters):
"""
Converts a media object into formats usable in the catalog
:param media: the media object
:type media: dict
:param content_version: the current version of the source content
:type content_version: string
:p... | en | 0.736369 | Converts a media object into formats usable in the catalog :param media: the media object :type media: dict :param content_version: the current version of the source content :type content_version: string :param project_chapters: a dictionary of project chapters :type project_chapters: dict ... | 3.014515 | 3 |
django_customflow/mixins.py | Brad19940809/django-customflow | 1 | 4405 | # -*- coding:utf-8 -*-
# create_time: 2019/8/5 16:02
# __author__ = 'brad'
from . import utils
from .tasks.base import WaitingTask, BaseTask
class WorkflowMixin(object):
"""Mixin class to make objects workflow aware.
"""
def get_workflow(self):
"""Returns the current workflow of the object.
... | # -*- coding:utf-8 -*-
# create_time: 2019/8/5 16:02
# __author__ = 'brad'
from . import utils
from .tasks.base import WaitingTask, BaseTask
class WorkflowMixin(object):
"""Mixin class to make objects workflow aware.
"""
def get_workflow(self):
"""Returns the current workflow of the object.
... | en | 0.715555 | # -*- coding:utf-8 -*- # create_time: 2019/8/5 16:02 # __author__ = 'brad' Mixin class to make objects workflow aware. Returns the current workflow of the object. Removes the workflow from the object. After this function has been called the object has no *own* workflow anymore (it might have one via its... | 2.812275 | 3 |
video_encoding/fields.py | fossabot/django-video-encoding | 164 | 4406 | from django.db.models.fields.files import (FieldFile, ImageField,
ImageFileDescriptor)
from django.utils.translation import ugettext as _
from .backends import get_backend_class
from .files import VideoFile
class VideoFileDescriptor(ImageFileDescriptor):
pass
class Vi... | from django.db.models.fields.files import (FieldFile, ImageField,
ImageFileDescriptor)
from django.utils.translation import ugettext as _
from .backends import get_backend_class
from .files import VideoFile
class VideoFileDescriptor(ImageFileDescriptor):
pass
class Vi... | en | 0.800673 | # Clear the video info cache # use FileField method # we need a real file # write `width` and `height` # Nothing to update if we have no file and not being forced to update. # get duration if file is defined # update duration # use normal FileFieldWidget for now | 2.101701 | 2 |
BST.py | boristown/leetcode | 1 | 4407 | <filename>BST.py
class BST:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
@staticmethod
def array2BST(array):
'''
array:sorted array
'''
n = len(array)
if n == 0: return None
m = n... | <filename>BST.py
class BST:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
@staticmethod
def array2BST(array):
'''
array:sorted array
'''
n = len(array)
if n == 0: return None
m = n... | en | 0.25256 | array:sorted array node:BST node | 3.653291 | 4 |
test/spec/test_spec.py | raghu1121/SLM-Lab | 1 | 4408 | <gh_stars>1-10
from flaky import flaky
from slm_lab.experiment.control import Trial
from slm_lab.experiment.monitor import InfoSpace
from slm_lab.lib import util
from slm_lab.spec import spec_util
import os
import pandas as pd
import pytest
import sys
# helper method to run all tests in test_spec
def run_trial_test(s... | from flaky import flaky
from slm_lab.experiment.control import Trial
from slm_lab.experiment.monitor import InfoSpace
from slm_lab.lib import util
from slm_lab.spec import spec_util
import os
import pandas as pd
import pytest
import sys
# helper method to run all tests in test_spec
def run_trial_test(spec_file, spec_... | en | 0.12254 | # helper method to run all tests in test_spec # ('experimental/reinforce.json', 'reinforce_conv_breakout'), # ('experimental/a2c.json', 'a2c_conv_shared_breakout'), # ('experimental/a2c.json', 'a2c_conv_separate_breakout'), # ('experimental/ppo.json', 'ppo_conv_shared_breakout'), # ('experimental/ppo.json', 'ppo_conv_s... | 1.987984 | 2 |
test/test_modify_group.py | Sfairat00/training_python | 0 | 4409 | from model.group import Group
def test_modify_group_name(app):
if app.group.count() == 0:
app.group.create(Group(name="test"))
old_groups = app.group.get_group_list()
app.group.modify_first_group(Group(name="New group"))
new_groups = app.group.get_group_list()
assert len(old_groups) == len... | from model.group import Group
def test_modify_group_name(app):
if app.group.count() == 0:
app.group.create(Group(name="test"))
old_groups = app.group.get_group_list()
app.group.modify_first_group(Group(name="New group"))
new_groups = app.group.get_group_list()
assert len(old_groups) == len... | none | 1 | 2.462553 | 2 | |
readme_metrics/MetricsMiddleware.py | readmeio/metrics-sdks-python | 2 | 4410 | <gh_stars>1-10
import io
import time
import datetime
from readme_metrics.Metrics import Metrics
from readme_metrics.MetricsApiConfig import MetricsApiConfig
from readme_metrics.ResponseInfoWrapper import ResponseInfoWrapper
from werkzeug import Request
class MetricsMiddleware:
"""Core middleware class for ReadMe... | import io
import time
import datetime
from readme_metrics.Metrics import Metrics
from readme_metrics.MetricsApiConfig import MetricsApiConfig
from readme_metrics.ResponseInfoWrapper import ResponseInfoWrapper
from werkzeug import Request
class MetricsMiddleware:
"""Core middleware class for ReadMe Metrics
A... | en | 0.851819 | Core middleware class for ReadMe Metrics Attributes: config (MetricsApiConfig): Contains the configuration settings for the running middleware instance Constructs and initializes MetricsMiddleware WSGI middleware to be passed into the currently running WSGI web server. Args: ... | 2.236233 | 2 |
kbrl.py | deekshaarya4/gymexperiments | 0 | 4411 | <filename>kbrl.py
import numpy as np
import gym
from sklearn.neighbors import NearestNeighbors
import matplotlib.pyplot as plt
import argparse
parser = argparse.ArgumentParser(description='KBRL with KNN')
parser.add_argument('--episodes', nargs='?', type=int, default=500)
parser.add_argument('--max_timesteps', nargs='... | <filename>kbrl.py
import numpy as np
import gym
from sklearn.neighbors import NearestNeighbors
import matplotlib.pyplot as plt
import argparse
parser = argparse.ArgumentParser(description='KBRL with KNN')
parser.add_argument('--episodes', nargs='?', type=int, default=500)
parser.add_argument('--max_timesteps', nargs='... | en | 0.90814 | # hyperparameters: # number of nearest neighbors # number of iterations used for training # because we don't know the state space size in continuous environments # learning-related variables # episode-related variables # first state observed # if amount of data is sufficient and values is populated (atleast one episode... | 2.936896 | 3 |
shardDesigner/shardTemplateDir/shardStemDir/log/elast.py | vinci-project/rootShard | 0 | 4412 | import elasticsearch
from elasticsearch import Elasticsearch
from elasticsearch import helpers
import time, json, datetime, os
class elalog:
def __init__(self, date):
es_host = os.getenv("ES_PORT_9200_TCP_ADDR") or '<%ELASTICIP%>'
es_port = os.getenv("ES_PORT_9200_TCP_PORT") or '9200'
sel... | import elasticsearch
from elasticsearch import Elasticsearch
from elasticsearch import helpers
import time, json, datetime, os
class elalog:
def __init__(self, date):
es_host = os.getenv("ES_PORT_9200_TCP_ADDR") or '<%ELASTICIP%>'
es_port = os.getenv("ES_PORT_9200_TCP_PORT") or '9200'
sel... | en | 0.240531 | # BLOCKS INDEX # TRANSACTIONS INDEX # BALANCE HISTORY # VALIDATOR STATISTIC | 2.544163 | 3 |
corehq/apps/sms/tests.py | dslowikowski/commcare-hq | 1 | 4413 | <reponame>dslowikowski/commcare-hq<filename>corehq/apps/sms/tests.py<gh_stars>1-10
#!/usr/bin/env python
# vim: ai ts=4 sts=4 et sw=4 encoding=utf-8
from util import clean_phone_number, clean_outgoing_sms_text
from django.test import TestCase
class UtilTestCase(TestCase):
def setUp(self):
pass
de... | #!/usr/bin/env python
# vim: ai ts=4 sts=4 et sw=4 encoding=utf-8
from util import clean_phone_number, clean_outgoing_sms_text
from django.test import TestCase
class UtilTestCase(TestCase):
def setUp(self):
pass
def testCleanPhoneNumber(self):
phone_number = " 324 23-23421241"
cl... | en | 0.321937 | #!/usr/bin/env python # vim: ai ts=4 sts=4 et sw=4 encoding=utf-8 # make sure '+' and unicode get encoded for GET properly | 2.257391 | 2 |
deepchem/models/atomic_conv.py | cjgalvin/deepchem | 3 | 4414 | __author__ = "<NAME>"
__copyright__ = "Copyright 2017, Stanford University"
__license__ = "MIT"
import sys
from deepchem.models import KerasModel
from deepchem.models.layers import AtomicConvolution
from deepchem.models.losses import L2Loss
from tensorflow.keras.layers import Input, Layer
import numpy as np
import t... | __author__ = "<NAME>"
__copyright__ = "Copyright 2017, Stanford University"
__license__ = "MIT"
import sys
from deepchem.models import KerasModel
from deepchem.models.layers import AtomicConvolution
from deepchem.models.losses import L2Loss
from tensorflow.keras.layers import Input, Layer
import numpy as np
import t... | en | 0.819066 | Initializes weights and biases to be used in a fully-connected layer. Parameters ---------- prev_layer_size: int Number of features in previous layer. size: int Number of nodes in this layer. weights: tf.Tensor, optional (Default None) Weight tensor. biases: tf.Tensor, optional (Default None) ... | 2.260856 | 2 |
dialogue-engine/test/programytest/config/brain/test_oob.py | cotobadesign/cotoba-agent-oss | 104 | 4415 | """
Copyright (c) 2020 COTOBA DESIGN, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distri... | """
Copyright (c) 2020 COTOBA DESIGN, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distri... | en | 0.703429 | Copyright (c) 2020 COTOBA DESIGN, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute... | 1.764927 | 2 |
pypad/active_skill/interfaces/orb_generator_asi.py | candyninja001/pypad | 0 | 4416 | import abc
from ...orb_attribute import OrbAttribute
# Interface for active skills that create specific orb types (whether board change, orb change, orb spawn, etc)
class OrbGeneratorASI(abc.ABC):
@abc.abstractmethod
def does_orb_generator_create_orb_attribute(self, orb_attribute: OrbAttribute) -> bool:
... | import abc
from ...orb_attribute import OrbAttribute
# Interface for active skills that create specific orb types (whether board change, orb change, orb spawn, etc)
class OrbGeneratorASI(abc.ABC):
@abc.abstractmethod
def does_orb_generator_create_orb_attribute(self, orb_attribute: OrbAttribute) -> bool:
... | en | 0.770983 | # Interface for active skills that create specific orb types (whether board change, orb change, orb spawn, etc) | 2.905927 | 3 |
setup.py | DivoK/mystery | 8 | 4417 | <filename>setup.py
"""
Core business logic for `mystery`.
This code will run when the package is being built and installed.
"""
import json
import pathlib
import random
import tempfile
import urllib.request
import typing
import setuptools
from setuptools.command.sdist import sdist
# Load the configuration file.
CONF... | <filename>setup.py
"""
Core business logic for `mystery`.
This code will run when the package is being built and installed.
"""
import json
import pathlib
import random
import tempfile
import urllib.request
import typing
import setuptools
from setuptools.command.sdist import sdist
# Load the configuration file.
CONF... | en | 0.755444 | Core business logic for `mystery`. This code will run when the package is being built and installed. # Load the configuration file. Assemble the lockfile's path. :return: lockfile path. :rtype: pathlib.Path Will be registered as a replacement for pip's 'sdist' command. Get a list of possible packages. :re... | 2.49511 | 2 |
ADMM_primal.py | CrazyIvanPro/Optimal_Transport | 2 | 4418 | <reponame>CrazyIvanPro/Optimal_Transport<filename>ADMM_primal.py<gh_stars>1-10
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# =======================================
# File Name: ADMM_primal.py
# Purpose : implementation for ADMM method
# for solving primal problem
# =======================================... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# =======================================
# File Name: ADMM_primal.py
# Purpose : implementation for ADMM method
# for solving primal problem
# =======================================
from utils import get_params
import numpy as np
import sys
def ADMM_primal(... | en | 0.530627 | #!/usr/bin/env python # -*- coding: utf-8 -*- # ======================================= # File Name: ADMM_primal.py # Purpose : implementation for ADMM method # for solving primal problem # ======================================= ADMM_primal # initialize | 2.786147 | 3 |
misc_scripts/CleanVCFparams.py | pombase/legacy-eg-loader | 0 | 4419 | <reponame>pombase/legacy-eg-loader
#!/usr/bin/python
import os
import sys
import pprint
import argparse
parser = argparse.ArgumentParser(description='Clean up the data for a given parameter')
parser.add_argument('--infile', help="Path to the VCF file", default='test.vcf')
parser.add_argument('--outfile', help="Path t... | #!/usr/bin/python
import os
import sys
import pprint
import argparse
parser = argparse.ArgumentParser(description='Clean up the data for a given parameter')
parser.add_argument('--infile', help="Path to the VCF file", default='test.vcf')
parser.add_argument('--outfile', help="Path to the new VCF file", default='test.... | en | 0.237319 | #!/usr/bin/python #fo = open('Spombe.2013-01-02.filt3c.nr57-final.snps.anno-snpeff3.cleaned3.AB325691.vcf', 'w') | 2.75945 | 3 |
create_coherency_dataset.py | UKPLab/acl20-dialogue-coherence-assessment | 12 | 4420 | import math
import os
from copy import deepcopy
from ast import literal_eval
import pandas as pd
from math import factorial
import random
from collections import Counter, defaultdict
import sys
from nltk import word_tokenize
from tqdm import tqdm, trange
import argparse
import numpy as np
import re
import csv
from skle... | import math
import os
from copy import deepcopy
from ast import literal_eval
import pandas as pd
from math import factorial
import random
from collections import Counter, defaultdict
import sys
from nltk import word_tokenize
from tqdm import tqdm, trange
import argparse
import numpy as np
import re
import csv
from skle... | en | 0.909782 | return a list of different! permuted sentences and their respective dialog acts if amount is greater than the possible amount of permutations, only the uniquely possible ones are returned #the first one is the original, which was included s.t. won't be generated df is supposed to be a pandas dataframe with colums 'act'... | 2.565158 | 3 |
tests/utils/test_clean_accounting_column.py | richardqiu/pyjanitor | 2 | 4421 | import pytest
from janitor.utils import _clean_accounting_column
@pytest.mark.utils
def test_clean_accounting_column():
test_str = "(1,000)"
assert _clean_accounting_column(test_str) == float(-1000)
@pytest.mark.utils
def test_clean_accounting_column_zeroes():
test_str = "()"
assert _clean_accounti... | import pytest
from janitor.utils import _clean_accounting_column
@pytest.mark.utils
def test_clean_accounting_column():
test_str = "(1,000)"
assert _clean_accounting_column(test_str) == float(-1000)
@pytest.mark.utils
def test_clean_accounting_column_zeroes():
test_str = "()"
assert _clean_accounti... | none | 1 | 2.484095 | 2 | |
downloadParagraph.py | icadot86/bert | 0 | 4422 | # coding=utf-8
import sys, getopt
import urllib
import requests
import requests_cache
import re
import time
from bs4 import BeautifulSoup
from requests import Session
sys.path.append("/home/taejoon1kim/BERT/my_bert")
from utils.cacheUtils import cacheExist, writeCache, readCache, getDownloadCachePath
from utils.path... | # coding=utf-8
import sys, getopt
import urllib
import requests
import requests_cache
import re
import time
from bs4 import BeautifulSoup
from requests import Session
sys.path.append("/home/taejoon1kim/BERT/my_bert")
from utils.cacheUtils import cacheExist, writeCache, readCache, getDownloadCachePath
from utils.path... | en | 0.279066 | # coding=utf-8 # desktop user-agent # mobile user-agent #headers = {"user-agent" : USER_AGENT, "cache-contorl" : "public,max-age=3600"} #headers = {"user-agent" : USER_AGENT, "cache-contorl" : "no-cache"} #s = Session() #s.headers.update(headers) #resp = s.get(URL) #print(link) #if cacheExist(cache) == False: ## 1st SE... | 2.583181 | 3 |
data_io.py | LucasChenLC/courseManager2 | 0 | 4423 | from xml.dom.minidom import Document, parse
class InfoBatch:
def __init__(self, title, pre_node_titles):
self.title = title
self.pre_node_titles = pre_node_titles
def save_data_xml(course_list, file_path):
doc = Document()
courses = doc.createElement('course_list')
doc.appendChild(co... | from xml.dom.minidom import Document, parse
class InfoBatch:
def __init__(self, title, pre_node_titles):
self.title = title
self.pre_node_titles = pre_node_titles
def save_data_xml(course_list, file_path):
doc = Document()
courses = doc.createElement('course_list')
doc.appendChild(co... | en | 0.283712 | course_list = [] course_list.append(Course('Advance Math')) course_list.append(Course('Linear Algebra')) course_list.append(Course('Procedure Oriented Programming')) course_list.append(Course('Object Oriented Programming')) course_list[-1].add_pre_course(course_list, ['Procedure Oriented Programming']) course_list.appe... | 2.961867 | 3 |
tests/rules/test_git_rm_local_modifications.py | jlandrum/theheck | 0 | 4424 | import pytest
from theheck.rules.git_rm_local_modifications import match, get_new_command
from theheck.types import Command
@pytest.fixture
def output(target):
return ('error: the following file has local modifications:\n {}\n(use '
'--cached to keep the file, or -f to force removal)').format(targe... | import pytest
from theheck.rules.git_rm_local_modifications import match, get_new_command
from theheck.types import Command
@pytest.fixture
def output(target):
return ('error: the following file has local modifications:\n {}\n(use '
'--cached to keep the file, or -f to force removal)').format(targe... | none | 1 | 2.232639 | 2 | |
application.py | statisticsnorway/microdata-data-service | 0 | 4425 | <reponame>statisticsnorway/microdata-data-service
import logging
import json_logging
import tomlkit
import uvicorn
from fastapi import FastAPI, status
from fastapi.encoders import jsonable_encoder
from fastapi.openapi.docs import (
get_redoc_html,
get_swagger_ui_html,
get_swagger_ui_oauth2_redirect_html,
)... | import logging
import json_logging
import tomlkit
import uvicorn
from fastapi import FastAPI, status
from fastapi.encoders import jsonable_encoder
from fastapi.openapi.docs import (
get_redoc_html,
get_swagger_ui_html,
get_swagger_ui_oauth2_redirect_html,
)
from fastapi.responses import JSONResponse
from f... | en | 0.734583 | Self-hosting JavaScript and CSS for docs https://fastapi.tiangolo.com/advanced/extending-openapi/#self-hosting-javascript-and-css-for-docs Customized application logger Customized request logger | 2.002176 | 2 |
graspologic/embed/n2v.py | dtborders/graspologic | 0 | 4426 | <gh_stars>0
# Copyright (c) Microsoft Corporation and contributors.
# Licensed under the MIT License.
import logging
import math
import time
from typing import Any, List, Optional, Tuple, Union
import networkx as nx
import numpy as np
from ..utils import remap_node_ids
def node2vec_embed(
graph: Union[nx.Graph... | # Copyright (c) Microsoft Corporation and contributors.
# Licensed under the MIT License.
import logging
import math
import time
from typing import Any, List, Optional, Tuple, Union
import networkx as nx
import numpy as np
from ..utils import remap_node_ids
def node2vec_embed(
graph: Union[nx.Graph, nx.DiGraph... | en | 0.783225 | # Copyright (c) Microsoft Corporation and contributors. # Licensed under the MIT License. Generates a node2vec embedding from a given graph. Will follow the word2vec algorithm to create the embedding. Parameters ---------- graph: Union[nx.Graph, nx.DiGraph] A networkx graph or digraph. A multigra... | 3.075347 | 3 |
bot.py | NotBlizzard/blizzybot | 0 | 4427 | <gh_stars>0
# bot.py
# TODO:
# organize imports
# organize
from websocket import create_connection
from threading import Thread
from battle import Battle
import commands
import traceback
import requests
import inspect
import json
from fractions import Fraction
import random
import time
import sys
im... | # bot.py
# TODO:
# organize imports
# organize
from websocket import create_connection
from threading import Thread
from battle import Battle
import commands
import traceback
import requests
import inspect
import json
from fractions import Fraction
import random
import time
import sys
import re
imp... | en | 0.784261 | # bot.py # TODO: # organize imports # organize # now the list has five elements. # new battle # lobby # battles | 2.558124 | 3 |
stRT/tdr/widgets/changes.py | Yao-14/stAnalysis | 0 | 4428 | from typing import Optional, Tuple, Union
import numpy as np
import pandas as pd
import pyvista as pv
from pyvista import DataSet, MultiBlock, PolyData, UnstructuredGrid
try:
from typing import Literal
except ImportError:
from typing_extensions import Literal
from .ddrtree import DDRTree, cal_ncenter
from .s... | from typing import Optional, Tuple, Union
import numpy as np
import pandas as pd
import pyvista as pv
from pyvista import DataSet, MultiBlock, PolyData, UnstructuredGrid
try:
from typing import Literal
except ImportError:
from typing_extensions import Literal
from .ddrtree import DDRTree, cal_ncenter
from .s... | en | 0.736838 | #################################### # Changes along a vector direction # #################################### ################################# # Changes along the model shape # ################################# # Obtain the real part of the complex argument ############################## # Changes along the branches ... | 2.20807 | 2 |
test/test_add_group.py | nkoshkina/Python_Training3 | 0 | 4429 | <filename>test/test_add_group.py<gh_stars>0
# -*- coding: utf-8 -*-
from model.group import Group
import pytest
import allure_pytest
def test_add_group(app, db, check_ui, json_groups):
group0 = json_groups
#with pytest.allure.step("Given a group list"):
old_groups = db.get_group_list()
#with pytest.all... | <filename>test/test_add_group.py<gh_stars>0
# -*- coding: utf-8 -*-
from model.group import Group
import pytest
import allure_pytest
def test_add_group(app, db, check_ui, json_groups):
group0 = json_groups
#with pytest.allure.step("Given a group list"):
old_groups = db.get_group_list()
#with pytest.all... | en | 0.544198 | # -*- coding: utf-8 -*- #with pytest.allure.step("Given a group list"): #with pytest.allure.step("When I add a group %s to the list" % group0): #assert app.group.count() == len(old_groups) + 1 #with pytest.allure.step("When the new groups list is equal old list with added group"): | 2.574969 | 3 |
cyberbrain/frame_tree.py | testinggg-art/Cyberbrain | 0 | 4430 | from __future__ import annotations
from .frame import Frame
from .generated.communication_pb2 import CursorPosition
class FrameTree:
"""A tree to store all frames. For now it's a fake implementation.
Each node in the tree represents a frame that ever exists during program execution.
Caller and callee fr... | from __future__ import annotations
from .frame import Frame
from .generated.communication_pb2 import CursorPosition
class FrameTree:
"""A tree to store all frames. For now it's a fake implementation.
Each node in the tree represents a frame that ever exists during program execution.
Caller and callee fr... | en | 0.882112 | A tree to store all frames. For now it's a fake implementation. Each node in the tree represents a frame that ever exists during program execution. Caller and callee frames are connected. Call order is preserved among callee frames of the same caller frame. Nodes are also indexed by frames' physical l... | 3.231483 | 3 |
src/otp_yubikey/models.py | moggers87/django-otp-yubikey | 0 | 4431 | from __future__ import absolute_import, division, print_function, unicode_literals
from base64 import b64decode
from binascii import hexlify, unhexlify
from struct import pack
import six
from django.db import models
from django.utils.encoding import force_text
from django_otp.models import Device
from django_otp.ut... | from __future__ import absolute_import, division, print_function, unicode_literals
from base64 import b64decode
from binascii import hexlify, unhexlify
from struct import pack
import six
from django.db import models
from django.utils.encoding import force_text
from django_otp.models import Device
from django_otp.ut... | en | 0.66061 | Represents a locally-verified YubiKey OTP :class:`~django_otp.models.Device`. .. attribute:: private_id *CharField*: The 6-byte private ID (hex-encoded). .. attribute:: key *CharField*: The 16-byte AES key shared with this YubiKey (hex-encoded). .. attribute:: session ... | 2.144313 | 2 |
v1/hsvfilter.py | gavinIRL/RHBot | 0 | 4432 | import typing
# custom data structure to hold the state of an HSV filter
class HsvFilter:
def __init__(self, hMin=None, sMin=None, vMin=None, hMax=None, sMax=None, vMax=None,
sAdd=None, sSub=None, vAdd=None, vSub=None):
self.hMin = hMin
self.sMin = sMin
self.vMin = vMin
... | import typing
# custom data structure to hold the state of an HSV filter
class HsvFilter:
def __init__(self, hMin=None, sMin=None, vMin=None, hMax=None, sMax=None, vMax=None,
sAdd=None, sSub=None, vAdd=None, vSub=None):
self.hMin = hMin
self.sMin = sMin
self.vMin = vMin
... | en | 0.898492 | # custom data structure to hold the state of an HSV filter # Putting this here out of the way as it's a chonk # For a given item string case it will return the optimal filter and the correct position to look #print("Using default filter") #print("Using enemy location filter") # This is a difficult one to separate # Thi... | 2.942263 | 3 |
glue/core/tests/test_state_objects.py | HPLegion/glue | 0 | 4433 | <reponame>HPLegion/glue
import numpy as np
from numpy.testing import assert_allclose
from echo import CallbackProperty, ListCallbackProperty
from glue.core import Data, DataCollection
from .test_state import clone
from ..state_objects import (State, StateAttributeLimitsHelper,
StateAttri... | import numpy as np
from numpy.testing import assert_allclose
from echo import CallbackProperty, ListCallbackProperty
from glue.core import Data, DataCollection
from .test_state import clone
from ..state_objects import (State, StateAttributeLimitsHelper,
StateAttributeSingleValueHelper,
... | en | 0.86994 | a: 2 b: hello flat: <CallbackList with 3 elements> nested: <CallbackList with 3 elements> <SimpleTestState a: 2 b: hello flat: <CallbackList with 3 elements> nested: <CallbackList with 3 elements> > # Changing scale mode updates the limits # When switching to custom, the last limits are retained # Make sure tha... | 2.524833 | 3 |
ecommerce_api/core/cart/exceptions.py | victormartinez/ecommerceapi | 0 | 4434 | <reponame>victormartinez/ecommerceapi
from typing import Iterable, Optional
class ProductsNotFound(Exception):
def __init__(self, product_ids: Optional[Iterable[int]] = None):
self.product_ids = product_ids or []
self.message = "One or more products are invalid."
super().__init__(self.mess... | from typing import Iterable, Optional
class ProductsNotFound(Exception):
def __init__(self, product_ids: Optional[Iterable[int]] = None):
self.product_ids = product_ids or []
self.message = "One or more products are invalid."
super().__init__(self.message) | none | 1 | 2.884846 | 3 | |
test/unit/test_record.py | jsoref/neo4j-python-driver | 0 | 4435 | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
# Copyright (c) 2002-2018 "Neo Technology,"
# Network Engine for Objects in Lund AB [http://neotechnology.com]
#
# This file is part of Neo4j.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the Li... | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
# Copyright (c) 2002-2018 "Neo Technology,"
# Network Engine for Objects in Lund AB [http://neotechnology.com]
#
# This file is part of Neo4j.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the Li... | en | 0.830815 | #!/usr/bin/env python # -*- encoding: utf-8 -*- # Copyright (c) 2002-2018 "Neo Technology," # Network Engine for Objects in Lund AB [http://neotechnology.com] # # This file is part of Neo4j. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the Lic... | 2.59935 | 3 |
tests/integration_tests/test_dashboards.py | hugocool/explainerdashboard | 1 | 4436 | <reponame>hugocool/explainerdashboard
import dash
from catboost import CatBoostClassifier, CatBoostRegressor
from xgboost import XGBClassifier, XGBRegressor
from sklearn.ensemble import RandomForestClassifier, RandomForestRegressor
from explainerdashboard.explainers import ClassifierExplainer, RegressionExplainer
f... | import dash
from catboost import CatBoostClassifier, CatBoostRegressor
from xgboost import XGBClassifier, XGBRegressor
from sklearn.ensemble import RandomForestClassifier, RandomForestRegressor
from explainerdashboard.explainers import ClassifierExplainer, RegressionExplainer
from explainerdashboard.datasets import t... | none | 1 | 2.656596 | 3 | |
code/scripts/GeneratePNG_Preview_AsIs.py | dgrechka/bengaliai-cv19 | 0 | 4437 | import tensorflow as tf
import sys
import os
from glob import glob
import png
sys.path.append(os.path.join(__file__,'..','..'))
from tfDataIngest import tfDataSetParquet as tfDsParquet
inputDataDir = sys.argv[1]
outputDir = sys.argv[2]
# test app
if __name__ == "__main__":
files = glob(os.path.join(inputDataDir... | import tensorflow as tf
import sys
import os
from glob import glob
import png
sys.path.append(os.path.join(__file__,'..','..'))
from tfDataIngest import tfDataSetParquet as tfDsParquet
inputDataDir = sys.argv[1]
outputDir = sys.argv[2]
# test app
if __name__ == "__main__":
files = glob(os.path.join(inputDataDir... | en | 0.225887 | # test app #print("Iterating...") #print(element) #print("sample name is {0}".format(sampleId)) #print(sampleIds.shape) #print(pixels.shape) # a += 1 # if a > 10: # break #print("{0} elements in the dataset".format(len(ds.))) | 2.549374 | 3 |
widgets/datepicker_ctrl/codegen.py | RSabet/wxGlade | 225 | 4438 | """\
Code generator functions for wxDatePickerCtrl objects
@copyright: 2002-2007 <NAME>
@copyright: 2014-2016 <NAME>
@copyright: 2016-2021 <NAME>
@license: MIT (see LICENSE.txt) - THIS PROGRAM COMES WITH NO WARRANTY
"""
import common, compat
import wcodegen
class PythonDatePickerCtrlGenerator(wcodegen.PythonWidgetC... | """\
Code generator functions for wxDatePickerCtrl objects
@copyright: 2002-2007 <NAME>
@copyright: 2014-2016 <NAME>
@copyright: 2016-2021 <NAME>
@license: MIT (see LICENSE.txt) - THIS PROGRAM COMES WITH NO WARRANTY
"""
import common, compat
import wcodegen
class PythonDatePickerCtrlGenerator(wcodegen.PythonWidgetC... | en | 0.707308 | \ Code generator functions for wxDatePickerCtrl objects @copyright: 2002-2007 <NAME> @copyright: 2014-2016 <NAME> @copyright: 2016-2021 <NAME> @license: MIT (see LICENSE.txt) - THIS PROGRAM COMES WITH NO WARRANTY # XXX the following needs to depend on the code generator when Phoenix is about to be supported fully: # d... | 2.376521 | 2 |
train.py | lck1201/simple-effective-3Dpose-baseline | 20 | 4439 | <reponame>lck1201/simple-effective-3Dpose-baseline<gh_stars>10-100
import pprint
import mxnet as mx
from mxnet import gluon
from mxnet import init
from lib.core.get_optimizer import *
from lib.core.metric import MPJPEMetric
from lib.core.loss import MeanSquareLoss
from lib.core.loader import JointsDataIter
from lib.n... | import pprint
import mxnet as mx
from mxnet import gluon
from mxnet import init
from lib.core.get_optimizer import *
from lib.core.metric import MPJPEMetric
from lib.core.loss import MeanSquareLoss
from lib.core.loader import JointsDataIter
from lib.network import get_net
from lib.net_module import *
from lib.utils i... | en | 0.509632 | # Parse config and mkdir output # define context # dataset, generate trainset/ validation set # network # define loss and metric # optimizer # train and valid | 1.92008 | 2 |
FastLinear/generate_memory_bank.py | WangFeng18/dino | 0 | 4440 | <filename>FastLinear/generate_memory_bank.py
import os
from tqdm import tqdm
import torch.backends.cudnn as cudnn
import torch
from datasets import ImageNetInstance, ImageNetInstanceLMDB
from torchvision import transforms
import argparse
from BaseTaskModel.task_network import get_moco_network, get_swav_network, get_sel... | <filename>FastLinear/generate_memory_bank.py
import os
from tqdm import tqdm
import torch.backends.cudnn as cudnn
import torch
from datasets import ImageNetInstance, ImageNetInstanceLMDB
from torchvision import transforms
import argparse
from BaseTaskModel.task_network import get_moco_network, get_swav_network, get_sel... | en | 0.563229 | Performs all_gather operation on the provided tensors. *** Warning ***: torch.distributed.all_gather has no gradient. # network = ResNet(50, frozen_stages=4) #args.backbone.startswith('resnet'): #args.backbone.startswith('resnet'): | 2.176735 | 2 |
tests/utils/test_mercator.py | anuragtr/fabric8-analytics-rudra | 1 | 4441 | <reponame>anuragtr/fabric8-analytics-rudra
import pytest
from rudra.utils.mercator import SimpleMercator
class TestSimpleMercator:
pom_xml_content = """
<project>
<dependencies>
<dependency>
<groupId>grp1.id</groupId>
<artifactId>art1.i... | import pytest
from rudra.utils.mercator import SimpleMercator
class TestSimpleMercator:
pom_xml_content = """
<project>
<dependencies>
<dependency>
<groupId>grp1.id</groupId>
<artifactId>art1.id</artifactId>
</dependency... | en | 0.235648 | <project> <dependencies> <dependency> <groupId>grp1.id</groupId> <artifactId>art1.id</artifactId> </dependency> <dependency> <groupId>grp2.id</groupId> <artifactId>art2.id</artifac... | 2.194163 | 2 |
tests/checks/run_performance_tests.py | stjordanis/mljar-supervised | 1,882 | 4442 | import os
import sys
import unittest
from tests.tests_bin_class.test_performance import *
if __name__ == "__main__":
unittest.main()
| import os
import sys
import unittest
from tests.tests_bin_class.test_performance import *
if __name__ == "__main__":
unittest.main()
| none | 1 | 1.195945 | 1 | |
task/CheckAllocations.py | wookiee2187/vc3-login-pod | 1 | 4443 | <gh_stars>1-10
#!/usr/bin/env python
from vc3master.task import VC3Task
class CheckAllocations(VC3Task):
'''
Plugin to do consistency/sanity checks on Allocations.
'''
def runtask(self):
'''
'''
self.log.info("Running task %s" % self.section) | #!/usr/bin/env python
from vc3master.task import VC3Task
class CheckAllocations(VC3Task):
'''
Plugin to do consistency/sanity checks on Allocations.
'''
def runtask(self):
'''
'''
self.log.info("Running task %s" % self.section) | en | 0.770606 | #!/usr/bin/env python Plugin to do consistency/sanity checks on Allocations. | 2.098112 | 2 |
django_airbrake/utils/client.py | Captricity/airbrake-django | 0 | 4444 | <gh_stars>0
import sys
import traceback
from django.conf import settings
from django.urls import resolve
from lxml import etree
from six.moves.urllib.request import urlopen, Request
class Client(object):
API_URL = '%s://airbrake.io/notifier_api/v2/notices'
ERRORS = {
403: "Cannot use SSL",
422... | import sys
import traceback
from django.conf import settings
from django.urls import resolve
from lxml import etree
from six.moves.urllib.request import urlopen, Request
class Client(object):
API_URL = '%s://airbrake.io/notifier_api/v2/notices'
ERRORS = {
403: "Cannot use SSL",
422: "Invalid X... | none | 1 | 2.015239 | 2 | |
src/spaceone/inventory/connector/snapshot.py | jean1042/plugin-azure-cloud-services | 1 | 4445 | <reponame>jean1042/plugin-azure-cloud-services
import logging
from spaceone.inventory.libs.connector import AzureConnector
from spaceone.inventory.error import *
from spaceone.inventory.error.custom import *
__all__ = ['SnapshotConnector']
_LOGGER = logging.getLogger(__name__)
class SnapshotConnector(AzureConnector)... | import logging
from spaceone.inventory.libs.connector import AzureConnector
from spaceone.inventory.error import *
from spaceone.inventory.error.custom import *
__all__ = ['SnapshotConnector']
_LOGGER = logging.getLogger(__name__)
class SnapshotConnector(AzureConnector):
def __init__(self, **kwargs):
su... | none | 1 | 2.054222 | 2 | |
docs/tutorial/context/app.py | theasylum/wired | 12 | 4446 | <gh_stars>10-100
"""
A customer walks into a store. Do the steps to interact with them:
- Get *a* (not *the*) greeter
- Interact with them
Simple wired application:
- Settings that say what punctuation to use
- Registry
- Two factories that says hello, one for the FrenchCustomer context
- A default Customer and... | """
A customer walks into a store. Do the steps to interact with them:
- Get *a* (not *the*) greeter
- Interact with them
Simple wired application:
- Settings that say what punctuation to use
- Registry
- Two factories that says hello, one for the FrenchCustomer context
- A default Customer and FrenchCustomer
... | en | 0.825487 | A customer walks into a store. Do the steps to interact with them: - Get *a* (not *the*) greeter - Interact with them Simple wired application: - Settings that say what punctuation to use - Registry - Two factories that says hello, one for the FrenchCustomer context - A default Customer and FrenchCustomer # Make... | 3.518331 | 4 |
feast/DetectionModules/ldar_program.py | GeoSensorWebLab/FEAST_PtE | 10 | 4447 | <reponame>GeoSensorWebLab/FEAST_PtE
"""
This module defines the LDARProgram class.
"""
import numpy as np
import copy
from .repair import Repair
from ..EmissionSimModules.result_classes import ResultDiscrete, ResultContinuous
class LDARProgram:
"""
An LDAR program contains one or more detection methods and o... | """
This module defines the LDARProgram class.
"""
import numpy as np
import copy
from .repair import Repair
from ..EmissionSimModules.result_classes import ResultDiscrete, ResultContinuous
class LDARProgram:
"""
An LDAR program contains one or more detection methods and one or more repair methods. Each LDAR... | en | 0.880327 | This module defines the LDARProgram class. An LDAR program contains one or more detection methods and one or more repair methods. Each LDAR program records the find and repair costs associated with all detection and repair methods in the program. The LDAR program deploys runs the action methods of each detectio... | 2.907772 | 3 |
src/CycleGAN.py | sjmoran/SIDGAN | 25 | 4448 | #Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved.
#This program is free software; you can redistribute it and/or modify it under the terms of the BSD 0-Clause License.
#This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of ... | #Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved.
#This program is free software; you can redistribute it and/or modify it under the terms of the BSD 0-Clause License.
#This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of ... | en | 0.805029 | #Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved. #This program is free software; you can redistribute it and/or modify it under the terms of the BSD 0-Clause License. #This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of ME... | 2.332895 | 2 |
application/fastapi/main.py | edson-dev/neoway | 0 | 4449 | import uvicorn
from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles
from routes import doc, api
from fastapi.templating import Jinja2Templates
from starlette.requests import Request
# configure static and templates file on jinja 2
app = FastAPI(
title=f"Technical Case",
description=f"endpoi... | import uvicorn
from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles
from routes import doc, api
from fastapi.templating import Jinja2Templates
from starlette.requests import Request
# configure static and templates file on jinja 2
app = FastAPI(
title=f"Technical Case",
description=f"endpoi... | en | 0.608041 | # configure static and templates file on jinja 2 #import factory builders and initiate # #views | 2.469387 | 2 |
civis/io/_tables.py | jsfalk/civis-python | 0 | 4450 | <filename>civis/io/_tables.py
import json
import concurrent.futures
import csv
from os import path
import io
import logging
import os
import shutil
from tempfile import TemporaryDirectory
import warnings
import zlib
import gzip
import zipfile
from civis import APIClient
from civis._utils import maybe_get_random_name
... | <filename>civis/io/_tables.py
import json
import concurrent.futures
import csv
from os import path
import io
import logging
import os
import shutil
from tempfile import TemporaryDirectory
import warnings
import zlib
import gzip
import zipfile
from civis import APIClient
from civis._utils import maybe_get_random_name
... | en | 0.614054 | Read data from a Civis table. Parameters ---------- table : str Name of table, including schema, in the database. E.g. ``'my_schema.my_table'``. Schemas or tablenames with periods must be double quoted, e.g. ``'my_schema."my.table"'``. database : str or int Read data fro... | 2.206893 | 2 |
tests/unit/small_text/integrations/pytorch/test_strategies.py | chschroeder/small-text | 218 | 4451 | <reponame>chschroeder/small-text<filename>tests/unit/small_text/integrations/pytorch/test_strategies.py
import unittest
import pytest
from small_text.integrations.pytorch.exceptions import PytorchNotFoundError
try:
from small_text.integrations.pytorch.query_strategies import (
BADGE,
ExpectedGrad... | import unittest
import pytest
from small_text.integrations.pytorch.exceptions import PytorchNotFoundError
try:
from small_text.integrations.pytorch.query_strategies import (
BADGE,
ExpectedGradientLength,
ExpectedGradientLengthMaxWord)
except PytorchNotFoundError:
pass
@pytest.mark.... | none | 1 | 2.543077 | 3 | |
pymterm/colour/tango.py | stonewell/pymterm | 102 | 4452 | <gh_stars>100-1000
TANGO_PALLETE = [
'2e2e34343636',
'cccc00000000',
'4e4e9a9a0606',
'c4c4a0a00000',
'34346565a4a4',
'757550507b7b',
'060698989a9a',
'd3d3d7d7cfcf',
'555557575353',
'efef29292929',
'8a8ae2e23434',
'fcfce9e94f4f',
'72729f9fcfcf',
'adad... | TANGO_PALLETE = [
'2e2e34343636',
'cccc00000000',
'4e4e9a9a0606',
'c4c4a0a00000',
'34346565a4a4',
'757550507b7b',
'060698989a9a',
'd3d3d7d7cfcf',
'555557575353',
'efef29292929',
'8a8ae2e23434',
'fcfce9e94f4f',
'72729f9fcfcf',
'adad7f7fa8a8',
'34... | none | 1 | 2.281187 | 2 | |
user_manager/oauth/oauth2.py | voegtlel/auth-manager-backend | 0 | 4453 | from datetime import datetime, timedelta
from enum import Enum
from typing import List, Optional, Tuple, Dict, Any, Union
import time
from authlib.common.security import generate_token
from authlib.consts import default_json_headers
from authlib.oauth2 import (
OAuth2Request,
AuthorizationServer as _Authorizat... | from datetime import datetime, timedelta
from enum import Enum
from typing import List, Optional, Tuple, Dict, Any, Union
import time
from authlib.common.security import generate_token
from authlib.consts import default_json_headers
from authlib.oauth2 import (
OAuth2Request,
AuthorizationServer as _Authorizat... | en | 0.313306 | # TODO: Create HttpRequest with json in body. # exists = mongo.authorization_code_collection.count_documents( # {'client_id': request.client_id, 'nonce': nonce}, # limit=1, # ) # Must override this to set the client in the request, to make it available to authenticate_user # token_collection.update_one({'_id': ... | 1.422048 | 1 |
src/adsb/sbs/server.py | claws/adsb | 7 | 4454 | <reponame>claws/adsb
import asyncio
import datetime
import logging
import socket
from . import protocol
from typing import Tuple
from asyncio import AbstractEventLoop
logger = logging.getLogger(__name__)
class Server(object):
def __init__(
self,
host: str = "localhost",
port: int = 3... | import asyncio
import datetime
import logging
import socket
from . import protocol
from typing import Tuple
from asyncio import AbstractEventLoop
logger = logging.getLogger(__name__)
class Server(object):
def __init__(
self,
host: str = "localhost",
port: int = 30003,
backlog=... | en | 0.75148 | Start the server # type: asyncio.Server # Fetch actual port in use. This can be different from the # specified port if the port was passed as 0 which means use # an ephemeral port. Stop the server # Avoid iterating over the protocols dict which may change size # while it is being iterating over. Register a protocol ins... | 2.873655 | 3 |
src/robusta/core/model/events.py | kandahk/robusta | 0 | 4455 | <gh_stars>0
import logging
import uuid
from enum import Enum
from typing import List, Optional, Dict, Any
from dataclasses import dataclass, field
from pydantic import BaseModel
from ...integrations.scheduled.playbook_scheduler import PlaybooksScheduler
from ..reporting.base import Finding, BaseBlock
class EventTyp... | import logging
import uuid
from enum import Enum
from typing import List, Optional, Dict, Any
from dataclasses import dataclass, field
from pydantic import BaseModel
from ...integrations.scheduled.playbook_scheduler import PlaybooksScheduler
from ..reporting.base import Finding, BaseBlock
class EventType(Enum):
... | en | 0.859969 | # Right now: # 1. this is a dataclass but we need to make all fields optional in subclasses because of https://stackoverflow.com/questions/51575931/ # 2. this can't be a pydantic BaseModel because of various pydantic bugs (see https://github.com/samuelcolvin/pydantic/pull/2557) # once the pydantic PR that addresses tho... | 2.203152 | 2 |
examples/django_mongoengine/bike/models.py | pfrantz/graphene-mongo | 260 | 4456 | <filename>examples/django_mongoengine/bike/models.py
from mongoengine import Document
from mongoengine.fields import (
FloatField,
StringField,
ListField,
URLField,
ObjectIdField,
)
class Shop(Document):
meta = {"collection": "shop"}
ID = ObjectIdField()
name = StringField()
addres... | <filename>examples/django_mongoengine/bike/models.py
from mongoengine import Document
from mongoengine.fields import (
FloatField,
StringField,
ListField,
URLField,
ObjectIdField,
)
class Shop(Document):
meta = {"collection": "shop"}
ID = ObjectIdField()
name = StringField()
addres... | none | 1 | 2.520428 | 3 | |
src/tensor/tensor/movement/__init__.py | jedhsu/tensor | 0 | 4457 | from ._movement import Movement
from .path import MovementPath
from .paths import MovementPaths
| from ._movement import Movement
from .path import MovementPath
from .paths import MovementPaths
| none | 1 | 1.180534 | 1 | |
uhd_restpy/testplatform/sessions/ixnetwork/impairment/profile/fixedclassifier/fixedclassifier.py | OpenIxia/ixnetwork_restpy | 20 | 4458 | # MIT LICENSE
#
# Copyright 1997 - 2020 by IXIA Keysight
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify,... | # MIT LICENSE
#
# Copyright 1997 - 2020 by IXIA Keysight
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify,... | en | 0.691196 | # MIT LICENSE # # Copyright 1997 - 2020 by IXIA Keysight # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify,... | 1.590191 | 2 |
lantz/drivers/sacher/Sacher_EPOS.py | mtsolmn/lantz-drivers | 4 | 4459 | # sacher_epos.py, python wrapper for sacher epos motor
# <NAME> <<EMAIL>>, August 2014
#
"""
Possbily Maxon EPOS now
"""
"""
This is the actual version that works
But only in the lab32 virtual environment
"""
# from instrument import Instrument
# import qt
import ctypes
import ctypes.wintypes
import logging
import t... | # sacher_epos.py, python wrapper for sacher epos motor
# <NAME> <<EMAIL>>, August 2014
#
"""
Possbily Maxon EPOS now
"""
"""
This is the actual version that works
But only in the lab32 virtual environment
"""
# from instrument import Instrument
# import qt
import ctypes
import ctypes.wintypes
import logging
import t... | en | 0.592451 | # sacher_epos.py, python wrapper for sacher epos motor # <NAME> <<EMAIL>>, August 2014 # Possbily Maxon EPOS now This is the actual version that works But only in the lab32 virtual environment # from instrument import Instrument # import qt # from instrument import Instrument okay so we import a bunch of random stuff I... | 1.906633 | 2 |
tools/generate_lst.py | haotianliu001/HRNet-Lesion | 0 | 4460 | <filename>tools/generate_lst.py
import argparse
import os
image_dir = 'image'
label_dir = 'label'
splits = ['train', 'val', 'test']
image_dirs = [
'image/{}',
'image/{}_crop'
]
label_dirs = [
'label/{}/annotations',
'label/{}/annotations_crop',
]
def generate(root):
assert len(image_dirs) == len(... | <filename>tools/generate_lst.py
import argparse
import os
image_dir = 'image'
label_dir = 'label'
splits = ['train', 'val', 'test']
image_dirs = [
'image/{}',
'image/{}_crop'
]
label_dirs = [
'label/{}/annotations',
'label/{}/annotations_crop',
]
def generate(root):
assert len(image_dirs) == len(... | none | 1 | 2.750535 | 3 | |
examples/example.py | f-dangel/unfoldNd | 21 | 4461 | <gh_stars>10-100
"""How to use ``unfoldNd``. A comparison with ``torch.nn.Unfold``."""
# imports, make this example deterministic
import torch
import unfoldNd
torch.manual_seed(0)
# random batched RGB 32x32 image-shaped input tensor of batch size 64
inputs = torch.randn((64, 3, 32, 32))
# module hyperparameters
ke... | """How to use ``unfoldNd``. A comparison with ``torch.nn.Unfold``."""
# imports, make this example deterministic
import torch
import unfoldNd
torch.manual_seed(0)
# random batched RGB 32x32 image-shaped input tensor of batch size 64
inputs = torch.randn((64, 3, 32, 32))
# module hyperparameters
kernel_size = 3
dil... | en | 0.616796 | How to use ``unfoldNd``. A comparison with ``torch.nn.Unfold``. # imports, make this example deterministic # random batched RGB 32x32 image-shaped input tensor of batch size 64 # module hyperparameters # both modules accept the same arguments and perform the same operation # forward pass # check | 3.111326 | 3 |
src/pretix/helpers/escapejson.py | NicsTr/pretix | 1 | 4462 | from django.utils.encoding import force_str
from django.utils.functional import keep_lazy
from django.utils.safestring import SafeText, mark_safe
_json_escapes = {
ord('>'): '\\u003E',
ord('<'): '\\u003C',
ord('&'): '\\u0026',
}
_json_escapes_attr = {
ord('>'): '\\u003E',
ord('<'): '\\u003C',
... | from django.utils.encoding import force_str
from django.utils.functional import keep_lazy
from django.utils.safestring import SafeText, mark_safe
_json_escapes = {
ord('>'): '\\u003E',
ord('<'): '\\u003C',
ord('&'): '\\u0026',
}
_json_escapes_attr = {
ord('>'): '\\u003E',
ord('<'): '\\u003C',
... | en | 0.637294 | #34;', #39;', #61;', Hex encodes characters for use in a application/json type script. Hex encodes characters for use in a html attributw script. | 2.290174 | 2 |
pyxley/charts/plotly/base.py | snowind/pyxley | 2,536 | 4463 |
from ..charts import Chart
from flask import jsonify, request
_BASE_CONFIG = {
"showLink": False,
"displaylogo": False,
"modeBarButtonsToRemove": ["sendDataToCloud"]
}
class PlotlyAPI(Chart):
""" Base class for Plotly.js API
This class is used to create charts using the plotly.js api
... |
from ..charts import Chart
from flask import jsonify, request
_BASE_CONFIG = {
"showLink": False,
"displaylogo": False,
"modeBarButtonsToRemove": ["sendDataToCloud"]
}
class PlotlyAPI(Chart):
""" Base class for Plotly.js API
This class is used to create charts using the plotly.js api
... | en | 0.532595 | Base class for Plotly.js API This class is used to create charts using the plotly.js api To keep this general, this chart does not have a default method of transmitting data. Instead the user must supply a route_func method. basic line plot dataframe to json for a line plo... | 3.191559 | 3 |
pyqt/getting_started/close_window.py | CospanDesign/python | 5 | 4464 | <filename>pyqt/getting_started/close_window.py
#!/usr/bin/python
import sys
from PyQt4 import QtGui
from PyQt4 import QtCore
class Example(QtGui.QWidget):
def __init__(self):
super(Example, self).__init__()
self.initUI()
def initUI(self):
qbtn = QtGui.QPushButton('Quit', self)
qbtn.clicked.connec... | <filename>pyqt/getting_started/close_window.py
#!/usr/bin/python
import sys
from PyQt4 import QtGui
from PyQt4 import QtCore
class Example(QtGui.QWidget):
def __init__(self):
super(Example, self).__init__()
self.initUI()
def initUI(self):
qbtn = QtGui.QPushButton('Quit', self)
qbtn.clicked.connec... | ru | 0.258958 | #!/usr/bin/python | 2.922086 | 3 |
test/means/test_zero_mean.py | bdecost/gpytorch | 0 | 4465 | <gh_stars>0
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import torch
import unittest
from gpytorch.means import ZeroMean
class TestZeroMean(unittest.TestCase):
def setUp(self):
self.mean = ZeroMean()
... | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import torch
import unittest
from gpytorch.means import ZeroMean
class TestZeroMean(unittest.TestCase):
def setUp(self):
self.mean = ZeroMean()
def tes... | none | 1 | 2.529001 | 3 | |
generator/contact.py | rizzak/python_training | 0 | 4466 | <filename>generator/contact.py
import jsonpickle
import random
import string
from model.contact import Contact
import os.path
import getopt
import sys
try:
opts, args = getopt.getopt(sys.argv[1:], "n:f:", ["number of contacts", "file"])
except getopt.GetoptError as err:
getopt.usage()
sys.exit(2)
n = 5
f... | <filename>generator/contact.py
import jsonpickle
import random
import string
from model.contact import Contact
import os.path
import getopt
import sys
try:
opts, args = getopt.getopt(sys.argv[1:], "n:f:", ["number of contacts", "file"])
except getopt.GetoptError as err:
getopt.usage()
sys.exit(2)
n = 5
f... | none | 1 | 2.76974 | 3 | |
Lib/test/test_runpy.py | arvindm95/unladen-swallow | 2,293 | 4467 | # Test the runpy module
import unittest
import os
import os.path
import sys
import tempfile
from test.test_support import verbose, run_unittest, forget
from runpy import _run_code, _run_module_code, run_module
# Note: This module can't safely test _run_module_as_main as it
# runs its tests in the current process, whic... | # Test the runpy module
import unittest
import os
import os.path
import sys
import tempfile
from test.test_support import verbose, run_unittest, forget
from runpy import _run_code, _run_module_code, run_module
# Note: This module can't safely test _run_module_as_main as it
# runs its tests in the current process, whic... | en | 0.859576 | # Test the runpy module # Note: This module can't safely test _run_module_as_main as it # runs its tests in the current process, which would mess with the # real __main__ module (usually test.regrtest) # See test_cmd_line_script for a test that executes that code path # Set up the test code and expected results # Treat... | 2.593055 | 3 |
experiments/_pytorch/_grpc_server/protofiles/imagedata_pb2.py | RedisAI/benchmarks | 6 | 4468 | <gh_stars>1-10
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: imagedata.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from go... | # -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: imagedata.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf i... | en | 0.467826 | # -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: imagedata.proto # @@protoc_insertion_point(imports) # @@protoc_insertion_point(class_scope:ImageData) # @@protoc_insertion_point(class_scope:PredictionClass) # @@protoc_insertion_point(module_scope) | 1.37221 | 1 |
app/api/admin_sales/discounted.py | akashtalole/python-flask-restful-api | 3 | 4469 | <reponame>akashtalole/python-flask-restful-api<filename>app/api/admin_sales/discounted.py
from sqlalchemy import func
from flask_rest_jsonapi import ResourceList
from marshmallow_jsonapi import fields
from marshmallow_jsonapi.flask import Schema
from app.api.helpers.utilities import dasherize
from app.api.bootstrap im... | from sqlalchemy import func
from flask_rest_jsonapi import ResourceList
from marshmallow_jsonapi import fields
from marshmallow_jsonapi.flask import Schema
from app.api.helpers.utilities import dasherize
from app.api.bootstrap import api
from app.models import db
from app.models.discount_code import DiscountCode
from ... | en | 0.953052 | Discounted sales by event Provides Event name, discount code, marketer mail, count of tickets and total sales for orders grouped by status Returns sales (dictionary with total sales and ticket count) for placed, completed and pending orders Resource for sales by marketer. Jo... | 2.215295 | 2 |
spacy/lang/sr/__init__.py | g4brielvs/spaCy | 4 | 4470 | from .stop_words import STOP_WORDS
from .tokenizer_exceptions import TOKENIZER_EXCEPTIONS
from .lex_attrs import LEX_ATTRS
from ...language import Language
class SerbianDefaults(Language.Defaults):
tokenizer_exceptions = TOKENIZER_EXCEPTIONS
lex_attr_getters = LEX_ATTRS
stop_words = STOP_WORDS
class Ser... | from .stop_words import STOP_WORDS
from .tokenizer_exceptions import TOKENIZER_EXCEPTIONS
from .lex_attrs import LEX_ATTRS
from ...language import Language
class SerbianDefaults(Language.Defaults):
tokenizer_exceptions = TOKENIZER_EXCEPTIONS
lex_attr_getters = LEX_ATTRS
stop_words = STOP_WORDS
class Ser... | none | 1 | 2.199867 | 2 | |
mmdet/ops/dcn/__init__.py | TJUsym/TJU_Advanced_CV_Homework | 1,158 | 4471 | <reponame>TJUsym/TJU_Advanced_CV_Homework
from .functions.deform_conv import deform_conv, modulated_deform_conv
from .functions.deform_pool import deform_roi_pooling
from .modules.deform_conv import (DeformConv, ModulatedDeformConv,
DeformConvPack, ModulatedDeformConvPack)
from .module... | from .functions.deform_conv import deform_conv, modulated_deform_conv
from .functions.deform_pool import deform_roi_pooling
from .modules.deform_conv import (DeformConv, ModulatedDeformConv,
DeformConvPack, ModulatedDeformConvPack)
from .modules.deform_pool import (DeformRoIPooling, De... | none | 1 | 1.326008 | 1 | |
api/skill/serializer.py | zaubermaerchen/imas_cg_api | 2 | 4472 | <gh_stars>1-10
# coding: utf-8
from rest_framework import serializers
from data.models import Skill, SkillValue
class ListSerializer(serializers.ModelSerializer):
skill_value_list = serializers.SerializerMethodField(read_only=True)
class Meta:
model = Skill
fields = [
'skill_id',
... | # coding: utf-8
from rest_framework import serializers
from data.models import Skill, SkillValue
class ListSerializer(serializers.ModelSerializer):
skill_value_list = serializers.SerializerMethodField(read_only=True)
class Meta:
model = Skill
fields = [
'skill_id',
'ta... | en | 0.833554 | # coding: utf-8 | 2.261358 | 2 |
Codes/Converting_RGB_to_GreyScale.py | sichkar-valentyn/Image_processing_in_Python | 3 | 4473 | # File: Converting_RGB_to_GreyScale.py
# Description: Opening RGB image as array, converting to GreyScale and saving result into new file
# Environment: PyCharm and Anaconda environment
#
# MIT License
# Copyright (c) 2018 <NAME>
# github.com/sichkar-valentyn
#
# Reference to:
# <NAME>. Image processing in Python // Gi... | # File: Converting_RGB_to_GreyScale.py
# Description: Opening RGB image as array, converting to GreyScale and saving result into new file
# Environment: PyCharm and Anaconda environment
#
# MIT License
# Copyright (c) 2018 <NAME>
# github.com/sichkar-valentyn
#
# Reference to:
# <NAME>. Image processing in Python // Gi... | en | 0.855049 | # File: Converting_RGB_to_GreyScale.py # Description: Opening RGB image as array, converting to GreyScale and saving result into new file # Environment: PyCharm and Anaconda environment # # MIT License # Copyright (c) 2018 <NAME> # github.com/sichkar-valentyn # # Reference to: # <NAME>. Image processing in Python // Gi... | 3.848913 | 4 |
template_renderer.py | hamza-gheggad/gcp-iam-collector | 0 | 4474 | <filename>template_renderer.py<gh_stars>0
import colorsys
import json
from jinja2 import Environment, PackageLoader
import graph
def create_html(formatted_nodes, formatted_edges, role_color_map, output_name):
env = Environment(loader=PackageLoader('visualisation', '.'))
template = env.get_template('visualisa... | <filename>template_renderer.py<gh_stars>0
import colorsys
import json
from jinja2 import Environment, PackageLoader
import graph
def create_html(formatted_nodes, formatted_edges, role_color_map, output_name):
env = Environment(loader=PackageLoader('visualisation', '.'))
template = env.get_template('visualisa... | none | 1 | 2.582698 | 3 | |
powerapi/cli/tools.py | danglotb/powerapi | 0 | 4475 | <gh_stars>0
# Copyright (c) 2018, INRIA
# Copyright (c) 2018, University of Lille
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyrig... | # Copyright (c) 2018, INRIA
# Copyright (c) 2018, University of Lille
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, t... | en | 0.739433 | # Copyright (c) 2018, INRIA # Copyright (c) 2018, University of Lille # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, t... | 1.18814 | 1 |
pyxrd/mixture/models/insitu_behaviours/insitu_behaviour.py | PyXRD/pyxrd | 27 | 4476 | # coding=UTF-8
# ex:ts=4:sw=4:et=on
#
# Copyright (c) 2013, <NAME>
# All rights reserved.
# Complete license can be found in the LICENSE file.
from mvc.models.properties import StringProperty
from pyxrd.generic.io.custom_io import storables, Storable
from pyxrd.generic.models.base import DataModel
from pyxrd.refinem... | # coding=UTF-8
# ex:ts=4:sw=4:et=on
#
# Copyright (c) 2013, <NAME>
# All rights reserved.
# Complete license can be found in the LICENSE file.
from mvc.models.properties import StringProperty
from pyxrd.generic.io.custom_io import storables, Storable
from pyxrd.generic.models.base import DataModel
from pyxrd.refinem... | en | 0.568748 | # coding=UTF-8 # ex:ts=4:sw=4:et=on # # Copyright (c) 2013, <NAME> # All rights reserved. # Complete license can be found in the LICENSE file. Interface class for coding in-situ behaviour scripts. Sub-classes should override or implement the methods below. # MODEL INTEL: # Override this so it is a unique string... | 1.915494 | 2 |
1 plainProgrammingBug/start 1 plainProgrammingBug.py | vishalbelsare/SLAPP3 | 8 | 4477 | <reponame>vishalbelsare/SLAPP3<filename>1 plainProgrammingBug/start 1 plainProgrammingBug.py
# start 1 plainProgrammingBug.py
import random
def SimpleBug():
# the environment
worldXSize = 80
worldYSize = 80
# the bug
xPos = 40
yPos = 40
# the action
for i in range(100... | plainProgrammingBug/start 1 plainProgrammingBug.py
# start 1 plainProgrammingBug.py
import random
def SimpleBug():
# the environment
worldXSize = 80
worldYSize = 80
# the bug
xPos = 40
yPos = 40
# the action
for i in range(100):
xPos += randomMove()
... | en | 0.469327 | # start 1 plainProgrammingBug.py # the environment # the bug # the action # returns -1, 0, 1 with equal probability you can eliminate the randomMove() function substituting
xPos += randomMove()
yPos += randomMove()
with
xPos += random.randint(-1, 1)
yPos += random.randint(-1, 1)
... | 3.610883 | 4 |
ba5a-min-coins/money_change.py | kjco/bioinformatics-algorithms | 0 | 4478 |
money = 8074
#money = 18705
#coin_list = [24,23,21,5,3,1]
coin_list = [24,13,12,7,5,3,1]
#coin_list = map(int, open('dataset_71_8.txt').read().split(','))
d = {0:0}
for m in range(1,money+1):
min_coin = 1000000
for coin in coin_list:
if m >= coin:
if d[m-coin]+1 < min_coin:... |
money = 8074
#money = 18705
#coin_list = [24,23,21,5,3,1]
coin_list = [24,13,12,7,5,3,1]
#coin_list = map(int, open('dataset_71_8.txt').read().split(','))
d = {0:0}
for m in range(1,money+1):
min_coin = 1000000
for coin in coin_list:
if m >= coin:
if d[m-coin]+1 < min_coin:... | en | 0.324384 | #money = 18705 #coin_list = [24,23,21,5,3,1] #coin_list = map(int, open('dataset_71_8.txt').read().split(',')) #print d | 2.929998 | 3 |
examples/remove_comments.py | igordejanovic/textx-bibtex | 1 | 4479 | """
Remove comments from bib file.
"""
from textx import metamodel_for_language
from txbibtex import bibentry_str
BIB_FILE = 'references.bib'
bibfile = metamodel_for_language('bibtex').model_from_file(BIB_FILE)
# Drop line comments.
print('\n'.join([bibentry_str(e) for e in bibfile.entries
if e.__cla... | """
Remove comments from bib file.
"""
from textx import metamodel_for_language
from txbibtex import bibentry_str
BIB_FILE = 'references.bib'
bibfile = metamodel_for_language('bibtex').model_from_file(BIB_FILE)
# Drop line comments.
print('\n'.join([bibentry_str(e) for e in bibfile.entries
if e.__cla... | en | 0.911721 | Remove comments from bib file. # Drop line comments. | 2.798307 | 3 |
google-cloud-sdk/lib/surface/compute/resource_policies/create/group_placement.py | bopopescu/Social-Lite | 0 | 4480 | # -*- coding: utf-8 -*- #
# Copyright 2019 Google LLC. 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 requir... | # -*- coding: utf-8 -*- #
# Copyright 2019 Google LLC. 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 requir... | en | 0.757141 | # -*- coding: utf-8 -*- # # Copyright 2019 Google LLC. 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 requir... | 1.831849 | 2 |
paperoni/io.py | notoraptor/paperoni | 88 | 4481 | <gh_stars>10-100
import json
from .papers import Papers
from .researchers import Researchers
def ResearchersFile(filename):
"""Parse a file containing researchers."""
try:
with open(filename, "r") as file:
data = json.load(file)
except FileNotFoundError:
data = {}
return R... | import json
from .papers import Papers
from .researchers import Researchers
def ResearchersFile(filename):
"""Parse a file containing researchers."""
try:
with open(filename, "r") as file:
data = json.load(file)
except FileNotFoundError:
data = {}
return Researchers(data, ... | en | 0.842804 | Parse a file containing researchers. Parse a file containing papers. | 3.304181 | 3 |
src/lib/sd2/test_addresses.py | zachkont/sd2 | 0 | 4482 | <reponame>zachkont/sd2
#############################################################################
# Copyright (c) 2017 SiteWare Corp. All right reserved
#############################################################################
import logging
import pytest
from . import addresses
def test_pytest():
assert ... | #############################################################################
# Copyright (c) 2017 SiteWare Corp. All right reserved
#############################################################################
import logging
import pytest
from . import addresses
def test_pytest():
assert True
def test_object_e... | de | 0.780879 | ############################################################################# # Copyright (c) 2017 SiteWare Corp. All right reserved ############################################################################# | 2.140474 | 2 |
config_model.py | Asha-ai/BERT_abstractive_proj | 17 | 4483 | <filename>config_model.py
import texar.tf as tx
beam_width = 5
hidden_dim = 768
bert = {
'pretrained_model_name': 'bert-base-uncased'
}
# See https://texar.readthedocs.io/en/latest/code/modules.html#texar.tf.modules.BERTEncoder.default_hparams
bert_encoder = {}
# From https://github.com/asyml/texar/blob/413e07f... | <filename>config_model.py
import texar.tf as tx
beam_width = 5
hidden_dim = 768
bert = {
'pretrained_model_name': 'bert-base-uncased'
}
# See https://texar.readthedocs.io/en/latest/code/modules.html#texar.tf.modules.BERTEncoder.default_hparams
bert_encoder = {}
# From https://github.com/asyml/texar/blob/413e07f... | en | 0.58528 | # See https://texar.readthedocs.io/en/latest/code/modules.html#texar.tf.modules.BERTEncoder.default_hparams # From https://github.com/asyml/texar/blob/413e07f859acbbee979f274b52942edd57b335c1/examples/transformer/config_model.py#L27-L45 # with adjustments for BERT # The 'learning_rate_schedule' can have the following 3... | 2.302434 | 2 |
wishes/migrations/0005_auto_20201029_0904.py | e-elson/bd | 0 | 4484 | # Generated by Django 3.1.2 on 2020-10-29 09:04
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('wishes', '0004_auto_20201029_0857'),
]
operations = [
migrations.AlterField(
model_name='gallery',
name='image',
... | # Generated by Django 3.1.2 on 2020-10-29 09:04
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('wishes', '0004_auto_20201029_0857'),
]
operations = [
migrations.AlterField(
model_name='gallery',
name='image',
... | en | 0.850754 | # Generated by Django 3.1.2 on 2020-10-29 09:04 | 1.399538 | 1 |
undeployed/legacy/Landsat/DNtoReflectance.py | NASA-DEVELOP/dnppy | 65 | 4485 | #-------------------------------------------------------------------------------
# Name: Landsat Digital Numbers to Radiance/Reflectance
# Purpose: To convert landsat 4,5, or 7 pixel values from digital numbers
# to Radiance, Reflectance, or Temperature
# Author: <NAME> <EMAIL>
# ... | #-------------------------------------------------------------------------------
# Name: Landsat Digital Numbers to Radiance/Reflectance
# Purpose: To convert landsat 4,5, or 7 pixel values from digital numbers
# to Radiance, Reflectance, or Temperature
# Author: <NAME> <EMAIL>
# ... | en | 0.768495 | #------------------------------------------------------------------------------- # Name: Landsat Digital Numbers to Radiance/Reflectance # Purpose: To convert landsat 4,5, or 7 pixel values from digital numbers # to Radiance, Reflectance, or Temperature # Author: <NAME> <EMAIL> # ... | 3.193159 | 3 |
.modules/.theHarvester/discovery/twittersearch.py | termux-one/EasY_HaCk | 1,103 | 4486 | import string
import requests
import sys
import myparser
import re
class search_twitter:
def __init__(self, word, limit):
self.word = word.replace(' ', '%20')
self.results = ""
self.totalresults = ""
self.server = "www.google.com"
self.hostname = "www.google.com"
s... | import string
import requests
import sys
import myparser
import re
class search_twitter:
def __init__(self, word, limit):
self.word = word.replace(' ', '%20')
self.results = ""
self.totalresults = ""
self.server = "www.google.com"
self.hostname = "www.google.com"
s... | none | 1 | 3.046638 | 3 | |
scrap_instagram.py | genaforvena/nn_scrapper | 0 | 4487 | import urllib.request
import json
access_token = "<KEY>"
api_url = "https://api.instagram.com/v1"
nn_lat = 56.296504
nn_lng = 43.936059
def request(endpoint, req_params = ""):
req = api_url + endpoint + "?access_token=" + access_token + "&" + req_params
print(req)
raw_response = urllib.request.urlopen(req... | import urllib.request
import json
access_token = "<KEY>"
api_url = "https://api.instagram.com/v1"
nn_lat = 56.296504
nn_lng = 43.936059
def request(endpoint, req_params = ""):
req = api_url + endpoint + "?access_token=" + access_token + "&" + req_params
print(req)
raw_response = urllib.request.urlopen(req... | none | 1 | 3.34689 | 3 | |
tests/unit/utils/test_validators.py | kajusK/HiddenPlaces | 0 | 4488 | <reponame>kajusK/HiddenPlaces
"""Unit tests for app.validators. """
from wtforms import ValidationError
import flask
from pytest import raises
from app.utils.validators import password_rules, image_file, allowed_file
class DummyField(object):
"""Dummy field object to emulate wtforms field."""
def __init__(sel... | """Unit tests for app.validators. """
from wtforms import ValidationError
import flask
from pytest import raises
from app.utils.validators import password_rules, image_file, allowed_file
class DummyField(object):
"""Dummy field object to emulate wtforms field."""
def __init__(self, data=None, errors=(), raw_d... | en | 0.753439 | Unit tests for app.validators. Dummy field object to emulate wtforms field. Dummy form object to emulate wtforms form. Dummy file like class to emulate uploaded file handler. Runs tests again validator with valid and invalid inputs. Args: subtest: Subtests fixture. validator: Validator instance to ... | 3.071993 | 3 |
ts_eval/utils/nans.py | vshulyak/ts-eval | 1 | 4489 | <filename>ts_eval/utils/nans.py<gh_stars>1-10
import warnings
import numpy as np
def nans_in_same_positions(*arrays):
"""
Compares all provided arrays to see if they have NaNs in the same positions.
"""
if len(arrays) == 0:
return True
for arr in arrays[1:]:
if not (np.isnan(array... | <filename>ts_eval/utils/nans.py<gh_stars>1-10
import warnings
import numpy as np
def nans_in_same_positions(*arrays):
"""
Compares all provided arrays to see if they have NaNs in the same positions.
"""
if len(arrays) == 0:
return True
for arr in arrays[1:]:
if not (np.isnan(array... | en | 0.846686 | Compares all provided arrays to see if they have NaNs in the same positions. Computes nanmean without raising a warning in case of NaNs in the dataset | 2.797011 | 3 |
tests/authorization/test_searches.py | UOC/dlkit | 2 | 4490 | <gh_stars>1-10
"""Unit tests of authorization searches."""
import pytest
from ..utilities.general import is_never_authz, is_no_authz, uses_cataloging, uses_filesystem_only
from dlkit.abstract_osid.osid import errors
from dlkit.primordium.id.primitives import Id
from dlkit.primordium.type.primitives import Type
from... | """Unit tests of authorization searches."""
import pytest
from ..utilities.general import is_never_authz, is_no_authz, uses_cataloging, uses_filesystem_only
from dlkit.abstract_osid.osid import errors
from dlkit.primordium.id.primitives import Id
from dlkit.primordium.type.primitives import Type
from dlkit.runtime ... | en | 0.503334 | Unit tests of authorization searches. # From test_templates/resource.py::ResourceSearch::init_template # From test_templates/resource.py::ResourceSearch::init_template Tests for AuthorizationSearch Tests search_among_authorizations Tests order_authorization_results Tests get_authorization_search_record Tests for Author... | 2.303207 | 2 |
mechroutines/models/_flux.py | keceli/mechdriver | 1 | 4491 | <filename>mechroutines/models/_flux.py
"""
NEW: Handle flux files
"""
import autofile
def read_flux(ts_save_path, vrc_locs=(0,)):
""" Read the geometry from the filesys
"""
vrc_fs = autofile.fs.vrctst(ts_save_path)
if vrc_fs[-1].file.flux.exists(vrc_locs):
flux_str = vrc_fs[-1].file.flux.r... | <filename>mechroutines/models/_flux.py
"""
NEW: Handle flux files
"""
import autofile
def read_flux(ts_save_path, vrc_locs=(0,)):
""" Read the geometry from the filesys
"""
vrc_fs = autofile.fs.vrctst(ts_save_path)
if vrc_fs[-1].file.flux.exists(vrc_locs):
flux_str = vrc_fs[-1].file.flux.r... | en | 0.722632 | NEW: Handle flux files Read the geometry from the filesys | 2.5774 | 3 |
RandomForest/RandomForest.py | nachiket273/ML_Algo_Implemented | 7 | 4492 | import math
import numpy as np
import pandas as pd
from sklearn.base import BaseEstimator
import sys
import os
sys.path.append(os.path.abspath('../DecisionTree'))
from DecisionTree import DecisionTree
class RandomForest(BaseEstimator):
"""
Simple implementation of Random Forest.
This class has implementat... | import math
import numpy as np
import pandas as pd
from sklearn.base import BaseEstimator
import sys
import os
sys.path.append(os.path.abspath('../DecisionTree'))
from DecisionTree import DecisionTree
class RandomForest(BaseEstimator):
"""
Simple implementation of Random Forest.
This class has implementat... | en | 0.76961 | Simple implementation of Random Forest. This class has implementation for Random Forest classifier and regressor. Dataset bagging is done by simple numpy random choice with replacement. For classification the prediction is by majority vote. For regression tree the prediction is averge of all estimator p... | 3.536832 | 4 |
tests/basics/generator_pend_throw.py | iotctl/pycopy | 663 | 4493 | def gen():
i = 0
while 1:
yield i
i += 1
g = gen()
try:
g.pend_throw
except AttributeError:
print("SKIP")
raise SystemExit
print(next(g))
print(next(g))
g.pend_throw(ValueError())
v = None
try:
v = next(g)
except Exception as e:
print("raised", repr(e))
print("ret was:"... | def gen():
i = 0
while 1:
yield i
i += 1
g = gen()
try:
g.pend_throw
except AttributeError:
print("SKIP")
raise SystemExit
print(next(g))
print(next(g))
g.pend_throw(ValueError())
v = None
try:
v = next(g)
except Exception as e:
print("raised", repr(e))
print("ret was:"... | en | 0.977045 | # It's legal to pend exception in a just-started generator, just the same # as it's legal to .throw() into it. | 3.024742 | 3 |
src/UnitTypes/ProjectileModule.py | USArmyResearchLab/ARL_Battlespace | 1 | 4494 | # -*- coding: utf-8 -*-
"""
Created on Tue Dec 15 09:49:47 2020
@author: james.z.hare
"""
from src.UnitModule import UnitClass, advance
from copy import deepcopy
import math
class ProjectileClass(UnitClass):
"""
The Projectile Class
This is a subclass to the UnitClass
Virtual Functions
----... | # -*- coding: utf-8 -*-
"""
Created on Tue Dec 15 09:49:47 2020
@author: james.z.hare
"""
from src.UnitModule import UnitClass, advance
from copy import deepcopy
import math
class ProjectileClass(UnitClass):
"""
The Projectile Class
This is a subclass to the UnitClass
Virtual Functions
----... | en | 0.816606 | # -*- coding: utf-8 -*- Created on Tue Dec 15 09:49:47 2020 @author: james.z.hare The Projectile Class This is a subclass to the UnitClass Virtual Functions ----------------- - `__copy__()` to make shallow copies - `__deepcopy__(memo)` to make deep copies - `possibleActions(State)` to ide... | 3.379978 | 3 |
OOP_MiniQuiz/run_car_Level2.py | HelloYeew/helloyeew-lab-computer-programming-i | 0 | 4495 | from car import *
def compare(car1,car2):
print(car1)
print(car2)
car1 = Car("Nissan","Tiida",450000)
car2 = Car("Toyota","Vios",400000)
car3 = Car("BMW","X3",3400000)
compare(car3,car1)
compare(car1,car2) | from car import *
def compare(car1,car2):
print(car1)
print(car2)
car1 = Car("Nissan","Tiida",450000)
car2 = Car("Toyota","Vios",400000)
car3 = Car("BMW","X3",3400000)
compare(car3,car1)
compare(car1,car2) | none | 1 | 3.11069 | 3 | |
prelude/monads.py | michel-slm/python-prelude | 2 | 4496 | from abc import ABCMeta, abstractmethod
from prelude.typeclasses import Monad
from prelude.decorators import monad_eq, singleton
@monad_eq
class Either(Monad):
__metaclass__ = ABCMeta
@classmethod
def mreturn(cls, val):
return Right(val)
@abstractmethod
def __iter__(self):
pass
c... | from abc import ABCMeta, abstractmethod
from prelude.typeclasses import Monad
from prelude.decorators import monad_eq, singleton
@monad_eq
class Either(Monad):
__metaclass__ = ABCMeta
@classmethod
def mreturn(cls, val):
return Right(val)
@abstractmethod
def __iter__(self):
pass
c... | none | 1 | 2.909953 | 3 | |
Deep Sort/src/imgconverter.py | JJavier98/TFG-Dron-de-Vigilancia | 0 | 4497 | <gh_stars>0
#!/usr/bin/env python
from __future__ import print_function
import roslib
roslib.load_manifest('msgs_to_cv2')
import sys
import rospy
import cv2
from std_msgs.msg import String
from sensor_msgs.msg import Image
from cv_bridge import CvBridge, CvBridgeError
class image_converter:
def __init__(self):
... | #!/usr/bin/env python
from __future__ import print_function
import roslib
roslib.load_manifest('msgs_to_cv2')
import sys
import rospy
import cv2
from std_msgs.msg import String
from sensor_msgs.msg import Image
from cv_bridge import CvBridge, CvBridgeError
class image_converter:
def __init__(self):
self.bridge... | en | 0.532155 | #!/usr/bin/env python try: rospy.spin() except KeyboardInterrupt: print("Shutting down") cv2.destroyAllWindows() | 2.869575 | 3 |
foodx_devops_tools/azure/__init__.py | Food-X-Technologies/foodx_devops_tools | 3 | 4498 | <reponame>Food-X-Technologies/foodx_devops_tools<filename>foodx_devops_tools/azure/__init__.py
# Copyright (c) 2021 Food-X Technologies
#
# This file is part of foodx_devops_tools.
#
# You should have received a copy of the MIT License along with
# foodx_devops_tools. If not, see <https://opensource.org/licenses/MI... | # Copyright (c) 2021 Food-X Technologies
#
# This file is part of foodx_devops_tools.
#
# You should have received a copy of the MIT License along with
# foodx_devops_tools. If not, see <https://opensource.org/licenses/MIT>.
"""Azure related utilities.""" | en | 0.930452 | # Copyright (c) 2021 Food-X Technologies # # This file is part of foodx_devops_tools. # # You should have received a copy of the MIT License along with # foodx_devops_tools. If not, see <https://opensource.org/licenses/MIT>. Azure related utilities. | 0.540502 | 1 |
beartype/vale/__init__.py | posita/beartype | 0 | 4499 | #!/usr/bin/env python3
# --------------------( LICENSE )--------------------
# Copyright (c) 2014-2021 Beartype authors.
# See "LICENSE" for further details.
'''
**Beartype validators.**
This submodule publishes a PEP-compliant hierarchy of subscriptable (indexable)
classes enabling callers ... | #!/usr/bin/env python3
# --------------------( LICENSE )--------------------
# Copyright (c) 2014-2021 Beartype authors.
# See "LICENSE" for further details.
'''
**Beartype validators.**
This submodule publishes a PEP-compliant hierarchy of subscriptable (indexable)
classes enabling callers ... | en | 0.746128 | #!/usr/bin/env python3 # --------------------( LICENSE )-------------------- # Copyright (c) 2014-2021 Beartype authors. # See "LICENSE" for further details. **Beartype validators.** This submodule publishes a PEP-compliant hierarchy of subscriptable (indexable) classes enabling callers to va... | 2.090829 | 2 |